code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.aviary.android.feather.effects;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import it.sephiroth.android.library.imagezoom.ImageViewTouchBase.OnBitmapChangedListener;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.ResultReceiver;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.RepeatableHorizontalDrawable;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.filters.MemeFilter;
import com.aviary.android.feather.library.graphics.drawable.EditableDrawable;
import com.aviary.android.feather.library.graphics.drawable.MemeTextDrawable;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.MatrixUtils;
import com.aviary.android.feather.utils.TypefaceUtils;
import com.aviary.android.feather.widget.DrawableHighlightView;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnLayoutListener;
/**
* The Class MemePanel.
*/
public class MemePanel extends AbstractContentPanel implements OnEditorActionListener, OnClickListener, OnDrawableEventListener,
OnLayoutListener {
Button editTopButton, editBottomButton;
EditText editTopText, editBottomText;
InputMethodManager mInputManager;
Canvas mCanvas;
DrawableHighlightView topHv, bottomHv;
Typeface mTypeface;
String fontName;
Button clearButtonTop, clearButtonBottom;
/**
* Instantiates a new meme panel.
*
* @param context
* the context
*/
public MemePanel( EffectContext context ) {
super( context );
ConfigService config = context.getService( ConfigService.class );
if ( config != null ) {
fontName = config.getString( R.string.feather_meme_default_font );
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
editTopButton = (Button) getOptionView().findViewById( R.id.button1 );
editBottomButton = (Button) getOptionView().findViewById( R.id.button2 );
mImageView = (ImageViewTouch) getContentView().findViewById( R.id.overlay );
editTopText = (EditText) getContentView().findViewById( R.id.invisible_text_1 );
editBottomText = (EditText) getContentView().findViewById( R.id.invisible_text_2 );
clearButtonTop = (Button) getOptionView().findViewById( R.id.clear_button_top );
clearButtonBottom = (Button) getOptionView().findViewById( R.id.clear_button_bottom );
mImageView.setDoubleTapEnabled( false );
mImageView.setScaleEnabled( false );
mImageView.setScrollEnabled( false );
createAndConfigurePreview();
mImageView.setOnBitmapChangedListener( new OnBitmapChangedListener() {
@Override
public void onBitmapChanged( Drawable drawable ) {
final Matrix mImageMatrix = mImageView.getImageViewMatrix();
float[] matrixValues = getMatrixValues( mImageMatrix );
final int height = (int) ( mBitmap.getHeight() * matrixValues[Matrix.MSCALE_Y] );
View view = getContentView().findViewById( R.id.feather_meme_dumb );
LinearLayout.LayoutParams p = (LinearLayout.LayoutParams) view.getLayoutParams();
p.height = height - 30;
view.setLayoutParams( p );
view.requestLayout();
}
} );
mImageView.setImageBitmap( mPreview, true, null );
View content = getOptionView().findViewById( R.id.content );
content.setBackgroundDrawable( RepeatableHorizontalDrawable.createFromView( content ) );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
createTypeFace();
onAddTopText();
onAddBottomText();
( (ImageViewDrawableOverlay) mImageView ).setOnDrawableEventListener( this );
( (ImageViewDrawableOverlay) mImageView ).setOnLayoutListener( this );
mInputManager = (InputMethodManager) getContext().getBaseContext().getSystemService( Context.INPUT_METHOD_SERVICE );
editTopButton.setOnClickListener( this );
editBottomButton.setOnClickListener( this );
editTopText.setVisibility( View.VISIBLE );
editBottomText.setVisibility( View.VISIBLE );
editTopText.getBackground().setAlpha( 0 );
editBottomText.getBackground().setAlpha( 0 );
clearButtonTop.setOnClickListener( this );
clearButtonBottom.setOnClickListener( this );
getContentView().setVisibility( View.VISIBLE );
contentReady();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
super.onDeactivate();
endEditView( topHv );
endEditView( bottomHv );
( (ImageViewDrawableOverlay) mImageView ).setOnDrawableEventListener( null );
( (ImageViewDrawableOverlay) mImageView ).setOnLayoutListener( null );
editTopButton.setOnClickListener( null );
editBottomButton.setOnClickListener( null );
clearButtonTop.setOnClickListener( null );
clearButtonBottom.setOnClickListener( null );
if ( mInputManager.isActive( editTopText ) ) mInputManager.hideSoftInputFromWindow( editTopText.getWindowToken(), 0 );
if ( mInputManager.isActive( editBottomText ) ) mInputManager.hideSoftInputFromWindow( editBottomText.getWindowToken(), 0 );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
mCanvas = null;
mInputManager = null;
super.onDestroy();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_meme_content, null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_meme_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
MemeFilter filter = (MemeFilter) FilterLoaderFactory.get( Filters.MEME );
flattenText( topHv, filter );
flattenText( bottomHv, filter );
MoaActionList actionList = (MoaActionList) filter.getActions().clone();
super.onGenerateResult( actionList );
}
/*
* (non-Javadoc)
*
* @see android.widget.TextView.OnEditorActionListener#onEditorAction(android.widget.TextView, int, android.view.KeyEvent)
*/
@Override
public boolean onEditorAction( TextView v, int actionId, KeyEvent event ) {
mLogger.info( "onEditorAction", v, actionId, event );
if ( v != null ) {
if ( actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED ) {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getSelectedHighlightView() != null ) {
DrawableHighlightView d = image.getSelectedHighlightView();
if ( d.getContent() instanceof EditableDrawable ) {
endEditView( d );
}
}
}
}
return false;
}
/**
* Flatten text.
*
* @param hv
* the hv
*/
private void flattenText( final DrawableHighlightView hv, final MemeFilter filter ) {
if ( hv != null ) {
hv.setHidden( true );
final Matrix mImageMatrix = mImageView.getImageViewMatrix();
float[] matrixValues = getMatrixValues( mImageMatrix );
mLogger.log( "image scaled: " + matrixValues[Matrix.MSCALE_X] );
// TODO: check this modification
final int width = (int) ( mBitmap.getWidth() );
final int height = (int) ( mBitmap.getHeight() );
final RectF cropRect = hv.getCropRectF();
final Rect rect = new Rect( (int) cropRect.left, (int) cropRect.top, (int) cropRect.right, (int) cropRect.bottom );
final MemeTextDrawable editable = (MemeTextDrawable) hv.getContent();
final int saveCount = mCanvas.save( Canvas.MATRIX_SAVE_FLAG );
// force end edit and hide the blinking cursor
editable.endEdit();
editable.invalidateSelf();
editable.setContentSize( width, height );
editable.setBounds( rect.left, rect.top, rect.right, rect.bottom );
editable.draw( mCanvas );
if ( topHv == hv ) {
filter.setTopText( (String) editable.getText(), (double) editable.getTextSize() / mBitmap.getWidth() );
filter.setTopOffset( ( cropRect.left + (double) editable.getXoff() ) / mBitmap.getWidth(),
( cropRect.top + (double) editable.getYoff() ) / mBitmap.getHeight() );
// action.setValue( "toptext", (String) editable.getText() );
// action.setValue( "topsize", (double)editable.getTextSize()/mBitmap.getWidth() );
// action.setValue( "topxoff", (cropRect.left + (double)editable.getXoff())/mBitmap.getWidth() );
// action.setValue( "topyoff", (cropRect.top + (double)editable.getYoff())/mBitmap.getHeight() );
} else {
filter.setBottomText( (String) editable.getText(), (double) editable.getTextSize() / mBitmap.getWidth() );
filter.setBottomOffset( ( cropRect.left + (double) editable.getXoff() ) / mBitmap.getWidth(),
( cropRect.top + (double) editable.getYoff() ) / mBitmap.getHeight() );
// action.setValue( "bottomtext", (String) editable.getText() );
// action.setValue( "bottomsize", (double)editable.getTextSize()/mBitmap.getWidth() );
// action.setValue( "bottomxoff", (cropRect.left + (double)editable.getXoff())/mBitmap.getWidth() );
// action.setValue( "bottomyoff", (cropRect.top + (double)editable.getYoff())/mBitmap.getHeight() );
}
filter.setTextScale( matrixValues[Matrix.MSCALE_X] );
// action.setValue( "scale", matrixValues[Matrix.MSCALE_X] );
// action.setValue( "textsize", editable.getTextSize() );
mCanvas.restoreToCount( saveCount );
mImageView.invalidate();
}
onPreviewChanged( mPreview, false );
}
/**
* Creates the and configure preview.
*/
private void createAndConfigurePreview() {
if ( ( mPreview != null ) && !mPreview.isRecycled() ) {
mPreview.recycle();
mPreview = null;
}
mPreview = BitmapUtils.copy( mBitmap, mBitmap.getConfig() );
mCanvas = new Canvas( mPreview );
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
if ( v == editTopButton ) {
onTopClick( topHv );
} else if ( v == editBottomButton ) {
onTopClick( bottomHv );
} else if ( v == clearButtonTop ) {
clearEditView( topHv );
endEditView( topHv );
} else if ( v == clearButtonBottom ) {
clearEditView( bottomHv );
endEditView( bottomHv );
}
}
/**
* In top editable text click
*
* @param view
* the view
*/
public void onTopClick( final DrawableHighlightView view ) {
mLogger.info( "onTopClick", view );
if ( view != null ) if ( view.getContent() instanceof EditableDrawable ) {
beginEditView( view );
}
}
/**
* Extract a value form the matrix
*
* @param m
* the m
* @return the matrix values
*/
public static float[] getMatrixValues( Matrix m ) {
float[] values = new float[9];
m.getValues( values );
return values;
}
/**
* Creates and places the top editable text
*/
private void onAddTopText() {
final Matrix mImageMatrix = mImageView.getImageViewMatrix();
final int width = (int) ( mBitmap.getWidth() );
final int height = (int) ( mBitmap.getHeight() );
final MemeTextDrawable text = new MemeTextDrawable( "", (float) mBitmap.getHeight() / 7.f, mTypeface );
text.setTextColor( Color.WHITE );
text.setTextStrokeColor( Color.BLACK );
text.setContentSize( width, height );
topHv = new DrawableHighlightView( mImageView, text );
topHv.setAlignModeV( DrawableHighlightView.AlignModeV.Top );
final int cropHeight = text.getIntrinsicHeight();
final int x = 0;
final int y = 0;
final Matrix matrix = new Matrix( mImageMatrix );
matrix.invert( matrix );
final float[] pts = new float[] { x, y, x + width, y + cropHeight };
MatrixUtils.mapPoints( matrix, pts );
final RectF cropRect = new RectF( pts[0], pts[1], pts[2], pts[3] );
addEditable( topHv, mImageMatrix, cropRect );
}
/**
* Create and place the bottom editable text.
*/
private void onAddBottomText() {
final Matrix mImageMatrix = mImageView.getImageViewMatrix();
final int width = (int) ( mBitmap.getWidth() );
final int height = (int) ( mBitmap.getHeight() );
final MemeTextDrawable text = new MemeTextDrawable( "", (float) mBitmap.getHeight() / 7.0f, mTypeface );
text.setTextColor( Color.WHITE );
text.setTextStrokeColor( Color.BLACK );
text.setContentSize( width, height );
bottomHv = new DrawableHighlightView( mImageView, text );
bottomHv.setAlignModeV( DrawableHighlightView.AlignModeV.Bottom );
final int cropHeight = text.getIntrinsicHeight();
final int x = 0;
final int y = 0;
final Matrix matrix = new Matrix( mImageMatrix );
matrix.invert( matrix );
final float[] pts = new float[] { x, y + height - cropHeight - ( height / 30 ), x + width, y + height - ( height / 30 ) };
MatrixUtils.mapPoints( matrix, pts );
final RectF cropRect = new RectF( pts[0], pts[1], pts[2], pts[3] );
addEditable( bottomHv, mImageMatrix, cropRect );
}
/**
* Adds the editable.
*
* @param hv
* the hv
* @param imageMatrix
* the image matrix
* @param cropRect
* the crop rect
*/
private void addEditable( DrawableHighlightView hv, Matrix imageMatrix, RectF cropRect ) {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
hv.setRotateAndScale( true );
hv.showAnchors( false );
hv.drawOutlineFill( false );
hv.drawOutlineStroke( false );
hv.setup( imageMatrix, null, cropRect, false );
hv.getOutlineFillPaint().setXfermode( new PorterDuffXfermode( android.graphics.PorterDuff.Mode.SRC_ATOP ) );
hv.setMinSize( 10 );
hv.setOutlineFillColor( new ColorStateList( new int[][]{ {android.R.attr.state_active } }, new int[]{0} ) );
hv.setOutlineStrokeColor( new ColorStateList( new int[][]{ {android.R.attr.state_active } }, new int[]{0} ) );
image.addHighlightView( hv );
}
abstract class MyTextWatcher implements TextWatcher {
public DrawableHighlightView view;
}
private final MyTextWatcher mEditTextWatcher = new MyTextWatcher() {
@Override
public void afterTextChanged( final Editable s ) {}
@Override
public void beforeTextChanged( final CharSequence s, final int start, final int count, final int after ) {}
@Override
public void onTextChanged( final CharSequence s, final int start, final int before, final int count ) {
mLogger.info( "onTextChanged", view );
if ( ( view != null ) && ( view.getContent() instanceof EditableDrawable ) ) {
final EditableDrawable editable = (EditableDrawable) view.getContent();
if ( !editable.isEditing() ) return;
editable.setText( s.toString() );
if ( topHv.equals( view ) ) {
editTopButton.setText( s );
clearButtonTop.setVisibility( s != null && s.length() > 0 ? View.VISIBLE : View.INVISIBLE );
} else if ( bottomHv.equals( view ) ) {
editBottomButton.setText( s );
clearButtonBottom.setVisibility( s != null && s.length() > 0 ? View.VISIBLE : View.INVISIBLE );
}
view.forceUpdate();
setIsChanged( true );
}
}
};
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onFocusChange(com.aviary.android.feather
* .widget.DrawableHighlightView, com.aviary.android.feather.widget.DrawableHighlightView)
*/
@Override
public void onFocusChange( DrawableHighlightView newFocus, DrawableHighlightView oldFocus ) {
mLogger.info( "onFocusChange", newFocus, oldFocus );
if ( oldFocus != null ) {
if ( newFocus == null ) {
endEditView( oldFocus );
}
}
}
/**
* Terminates an edit view.
*
* @param hv
* the hv
*/
private void endEditView( DrawableHighlightView hv ) {
EditableDrawable text = (EditableDrawable) hv.getContent();
mLogger.info( "endEditView", text.isEditing() );
if ( text.isEditing() ) {
text.endEdit();
endEditText( hv );
}
CharSequence value = text.getText();
if ( topHv.equals( hv ) ) {
editTopButton.setText( value );
clearButtonTop.setVisibility( value != null && value.length() > 0 ? View.VISIBLE : View.INVISIBLE );
} else if ( bottomHv.equals( hv ) ) {
editBottomButton.setText( value );
clearButtonBottom.setVisibility( value != null && value.length() > 0 ? View.VISIBLE : View.INVISIBLE );
}
}
/**
* Begins an edit view.
*
* @param hv
* the hv
*/
private void beginEditView( DrawableHighlightView hv ) {
mLogger.info( "beginEditView" );
final EditableDrawable text = (EditableDrawable) hv.getContent();
if ( hv == topHv ) {
endEditView( bottomHv );
} else {
endEditView( topHv );
}
if ( !text.isEditing() ) {
text.beginEdit();
beginEditText( hv );
}
}
private void clearEditView( DrawableHighlightView hv ) {
final MemeTextDrawable text = (MemeTextDrawable) hv.getContent();
text.setText( "" );
text.invalidateSelf();
hv.forceUpdate();
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onDown(com.aviary.android.feather.widget
* .DrawableHighlightView)
*/
@Override
public void onDown( DrawableHighlightView view ) {
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onMove(com.aviary.android.feather.widget
* .DrawableHighlightView)
*/
@Override
public void onMove( DrawableHighlightView view ) {}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onClick(com.aviary.android.feather.widget
* .DrawableHighlightView)
*/
@Override
public void onClick( DrawableHighlightView view ) {
if ( view != null ) {
if ( view.getContent() instanceof EditableDrawable ) {
beginEditView( view );
}
}
}
/**
* Begin edit text.
*
* @param view
* the view
*/
private void beginEditText( final DrawableHighlightView view ) {
mLogger.info( "beginEditText", view );
EditText editText = null;
if ( view == topHv ) {
editText = editTopText;
} else if ( view == bottomHv ) {
editText = editBottomText;
}
if ( editText != null ) {
mEditTextWatcher.view = null;
editText.removeTextChangedListener( mEditTextWatcher );
final EditableDrawable editable = (EditableDrawable) view.getContent();
final String oldText = (String) editable.getText();
editText.setText( oldText );
editText.setSelection( editText.length() );
editText.setImeOptions( EditorInfo.IME_ACTION_DONE );
editText.requestFocusFromTouch();
Handler handler = new Handler();
ResultReceiver receiver = new ResultReceiver( handler );
if ( !mInputManager.showSoftInput( editText, 0, receiver ) ) {
mInputManager.toggleSoftInput( InputMethodManager.SHOW_FORCED, 0 ); // TODO: verify
}
mEditTextWatcher.view = view;
editText.setOnEditorActionListener( this );
editText.addTextChangedListener( mEditTextWatcher );
( (ImageViewDrawableOverlay) mImageView ).setSelectedHighlightView( view );
( (EditableDrawable) view.getContent() ).setText( ( (EditableDrawable) view.getContent() ).getText() );
view.forceUpdate();
}
}
/**
* End edit text.
*
* @param view
* the view
*/
private void endEditText( final DrawableHighlightView view ) {
mLogger.info( "endEditText", view );
mEditTextWatcher.view = null;
EditText editText = null;
if ( view == topHv )
editText = editTopText;
else if ( view == bottomHv ) editText = editBottomText;
if ( editText != null ) {
editText.removeTextChangedListener( mEditTextWatcher );
if ( mInputManager.isActive( editText ) ) {
mInputManager.hideSoftInputFromWindow( editText.getWindowToken(), 0 );
}
editText.clearFocus();
}
mOptionView.requestFocus();
}
/**
* Creates the type face used for meme.
*/
private void createTypeFace() {
try {
mTypeface = TypefaceUtils.createFromAsset( getContext().getBaseContext().getAssets(), fontName );
} catch ( Exception e ) {
mTypeface = Typeface.DEFAULT;
}
}
@Override
public void onLayoutChanged( boolean changed, int left, int top, int right, int bottom ) {
if ( changed ) {
final Matrix mImageMatrix = mImageView.getImageViewMatrix();
float[] matrixValues = getMatrixValues( mImageMatrix );
final float w = mBitmap.getWidth();
final float h = mBitmap.getHeight();
final float scale = matrixValues[Matrix.MSCALE_X];
if ( topHv != null ) {
MemeTextDrawable text = (MemeTextDrawable) topHv.getContent();
text.setContentSize( w * scale, h * scale );
}
if ( bottomHv != null ) {
MemeTextDrawable text = (MemeTextDrawable) bottomHv.getContent();
text.setContentSize( w * scale, h * scale );
}
}
}
}
| Java |
package com.aviary.android.feather.effects;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.ExternalFilterPackDrawable;
import com.aviary.android.feather.library.content.FeatherIntent;
import com.aviary.android.feather.library.content.FeatherIntent.PluginType;
import com.aviary.android.feather.library.filters.EffectFilter;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.graphics.animation.TransformAnimation;
import com.aviary.android.feather.library.graphics.drawable.FakeBitmapDrawable;
import com.aviary.android.feather.library.moa.Moa;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.moa.MoaResult;
import com.aviary.android.feather.library.plugins.FeatherExternalPack;
import com.aviary.android.feather.library.plugins.FeatherInternalPack;
import com.aviary.android.feather.library.plugins.FeatherPack;
import com.aviary.android.feather.library.plugins.PluginManager;
import com.aviary.android.feather.library.plugins.PluginManager.ExternalPlugin;
import com.aviary.android.feather.library.plugins.PluginManager.IPlugin;
import com.aviary.android.feather.library.plugins.PluginManager.InternalPlugin;
import com.aviary.android.feather.library.plugins.UpdateType;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.services.PluginService;
import com.aviary.android.feather.library.services.PluginService.OnUpdateListener;
import com.aviary.android.feather.library.services.PluginService.PluginError;
import com.aviary.android.feather.library.services.PreferenceService;
import com.aviary.android.feather.library.tracking.Tracker;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.library.utils.UserTask;
import com.aviary.android.feather.utils.TypefaceUtils;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.HorizontalFixedListView;
import com.aviary.android.feather.widget.ImageSwitcher;
import com.aviary.android.feather.widget.SwipeView;
import com.aviary.android.feather.widget.SwipeView.OnSwipeListener;
import com.aviary.android.feather.widget.wp.CellLayout;
import com.aviary.android.feather.widget.wp.CellLayout.CellInfo;
import com.aviary.android.feather.widget.wp.Workspace;
import com.aviary.android.feather.widget.wp.WorkspaceIndicator;
/**
* The Class NativeEffectsPanel.
*/
@SuppressWarnings("deprecation")
public class NativeEffectsPanel extends AbstractContentPanel implements ViewFactory, OnUpdateListener, OnSwipeListener {
/** The current task. */
private RenderTask mCurrentTask;
/** The current selected filter label. */
private String mSelectedLabel = "undefined";
/** The current selected filter view. */
private View mSelectedView;
/** Panel is rendering. */
private volatile Boolean mIsRendering = false;
/** The small preview used for fast rendering. */
private Bitmap mSmallPreview;
private static final int PREVIEW_SCALE_FACTOR = 4;
/** enable/disable fast preview. */
private boolean enableFastPreview = false;
private PluginService mPluginService;
/** The horizontal filter list view. */
private HorizontalFixedListView mHList;
/** The main image switcher. */
private ImageSwitcher mImageSwitcher;
/** The cannister workspace. */
private Workspace mWorkspace;
/** The cannister workspace indicator. */
private WorkspaceIndicator mWorkspaceIndicator;
/** The number of workspace cols. */
private int mWorkspaceCols;
/** The number of workspace items per page. */
private int mWorkspaceItemsPerPage;
private View mWorkspaceContainer;
/** The big cannister view. */
private AbsoluteLayout mCannisterView;
/** panel is animating. */
private boolean mIsAnimating;
/** The default animation duration in. */
private int mAnimationDurationIn = 300;
/** The animation film duration in. */
private int mAnimationFilmDurationIn = 200;
private int mAnimationFilmDurationOut = 200;
private Interpolator mDecelerateInterpolator;
private boolean mExternalPacksEnabled = true;
/** create a reference to the update alert dialog. This to prevent multiple alert messages */
private AlertDialog mUpdateDialog;
private MoaActionList mActions = null;
private PreferenceService mPrefService;
private int mFilterCellWidth = 80;
private List<String> mInstalledPackages;
private View mLayoutLoader;
private static final int toastDuration = Toast.LENGTH_SHORT;
/* typeface for textviews */
Typeface mFiltersTypeface;
private static enum Status {
Null, // home
Packs, // pack display
Filters, // filters
}
/** The current panel status. */
private Status mStatus = Status.Null;
/** The previous panel status. */
private Status mPrevStatus = Status.Null;
/**
* Instantiates a new native effects panel.
*
* @param context
* the context
*/
public NativeEffectsPanel( EffectContext context ) {
super( context );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
mPluginService = getContext().getService( PluginService.class );
mPluginService.registerOnUpdateListener( this );
mPrefService = getContext().getService( PreferenceService.class );
mWorkspaceIndicator = (WorkspaceIndicator) mOptionView.findViewById( R.id.workspace_indicator );
mWorkspace = (Workspace) mOptionView.findViewById( R.id.workspace );
mWorkspace.setHapticFeedbackEnabled( false );
mWorkspace.setIndicator( mWorkspaceIndicator );
mLayoutLoader = mOptionView.findViewById( R.id.layout_loader );
mHList = (HorizontalFixedListView) getOptionView().findViewById( R.id.gallery );
mWorkspaceContainer = mOptionView.findViewById( R.id.workspace_container );
mCannisterView = (AbsoluteLayout) mOptionView.findViewById( R.id.cannister_container );
initWorkspace();
enableFastPreview = Constants.getFastPreviewEnabled();
mExternalPacksEnabled = Constants.getValueFromIntent( Constants.EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS, true );
mImageSwitcher = (ImageSwitcher) getContentView().findViewById( R.id.switcher );
mImageSwitcher.setSwitchEnabled( enableFastPreview );
mImageSwitcher.setFactory( this );
ConfigService config = getContext().getService( ConfigService.class );
String fontPack = config.getString( R.string.feather_effect_pack_font );
if ( null != fontPack && fontPack.length() > 1 ) {
try {
mFiltersTypeface = TypefaceUtils.createFromAsset( getContext().getBaseContext().getAssets(), fontPack );
} catch ( Throwable t ) {}
}
mDecelerateInterpolator = AnimationUtils.loadInterpolator( getContext().getBaseContext(), android.R.anim.decelerate_interpolator );
if ( enableFastPreview ) {
try {
mSmallPreview = Bitmap.createBitmap( mBitmap.getWidth() / PREVIEW_SCALE_FACTOR, mBitmap.getHeight() / PREVIEW_SCALE_FACTOR, Config.ARGB_8888 );
mImageSwitcher.setImageBitmap( mBitmap, true, null, Float.MAX_VALUE );
mImageSwitcher.setInAnimation( AnimationUtils.loadAnimation( getContext().getBaseContext(), android.R.anim.fade_in ) );
mImageSwitcher.setOutAnimation( AnimationUtils.loadAnimation( getContext().getBaseContext(), android.R.anim.fade_out ) );
} catch ( OutOfMemoryError e ) {
enableFastPreview = false;
mImageSwitcher.setImageBitmap( mBitmap, true, getContext().getCurrentImageViewMatrix(), Float.MAX_VALUE );
}
} else {
mImageSwitcher.setImageBitmap( mBitmap, true, getContext().getCurrentImageViewMatrix(), Float.MAX_VALUE );
}
mImageSwitcher.setAnimateFirstView( false );
mPreview = BitmapUtils.copy( mBitmap, Bitmap.Config.ARGB_8888 );
if ( mExternalPacksEnabled ) {
createFirstAnimation();
} else {
mLayoutLoader.setVisibility( View.GONE );
mWorkspaceContainer.setVisibility( View.GONE );
}
SwipeView mSwipeView = (SwipeView) getContentView().findViewById( R.id.swipeview ); // add an overlaying view that detects for
mSwipeView.setOnSwipeListener( this );
}
@Override
protected void onDispose() {
super.onDispose();
mWorkspace.setAdapter( null );
mHList.setAdapter( null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
mInstalledPackages = Collections.synchronizedList( new ArrayList<String>() );
ConfigService config = getContext().getService( ConfigService.class );
mAnimationDurationIn = config.getInteger( R.integer.feather_config_mediumAnimTime ) + 100;
mAnimationFilmDurationIn = config.getInteger( R.integer.feather_config_shortAnimTime ) + 100;
mAnimationFilmDurationOut = config.getInteger( R.integer.feather_config_shortAnimTime );
mFilterCellWidth = config.getDimensionPixelSize( R.dimen.feather_effects_cell_width );
mExternalPacksEnabled = false;
if ( mExternalPacksEnabled ) {
setStatus( Status.Packs );
} else {
startDefaultAnimation();
}
}
private void startDefaultAnimation() {
FeatherInternalPack thisPack = FeatherInternalPack.getDefault( getContext().getBaseContext() );
InternalPlugin plugin = (InternalPlugin) PluginManager.create( getContext().getBaseContext(), thisPack );
Drawable icon = plugin.getIcon( PluginType.TYPE_FILTER );
ImageView newView = new ImageView( getContext().getBaseContext() );
float destW, destH;
float iconW = icon.getIntrinsicWidth();
float iconH = icon.getIntrinsicHeight();
float iconR = iconW / iconH;
if ( getOptionView().findViewById( R.id.workspace_container ) != null ) {
destH = getOptionView().findViewById( R.id.workspace_container ).getHeight();
} else {
destH = iconH;
}
destH = Math.max( iconH, destH );
destW = destH * iconR;
Rect r = new Rect();
Point offset = new Point();
mOptionView.getChildVisibleRect( mOptionView.findViewById( R.id.RelativeLayout01 ), r, offset );
Resources res = getContext().getBaseContext().getResources();
final float shadow_offset = res.getDimensionPixelSize( R.dimen.feather_options_panel_height_shadow );
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams( (int) destW, (int) destH, 0, 0 );
newView.setLayoutParams( params );
newView.setScaleType( ImageView.ScaleType.FIT_XY );
newView.setImageDrawable( icon );
final float startX = Constants.SCREEN_WIDTH;
final float endX = Constants.SCREEN_WIDTH - ( destW / 2 );
final float startY = -r.top + offset.y - shadow_offset;
final float endY = startY;
Animation animation = new TranslateAnimation( TranslateAnimation.ABSOLUTE, startX, TranslateAnimation.ABSOLUTE, endX, TranslateAnimation.ABSOLUTE, startY, TranslateAnimation.ABSOLUTE, endY );
animation.setInterpolator( mDecelerateInterpolator );
animation.setDuration( mAnimationDurationIn / 2 );
animation.setFillEnabled( true );
animation.setFillBefore( true );
animation.setFillAfter( true );
startCannisterAnimation( newView, animation, plugin );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onProgressEnd()
*/
@Override
protected void onProgressEnd() {
if ( !enableFastPreview ) {
super.onProgressModalEnd();
} else {
super.onProgressEnd();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onProgressStart()
*/
@Override
protected void onProgressStart() {
if ( !enableFastPreview ) {
super.onProgressModalStart();
} else {
super.onProgressStart();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
if ( mIsRendering ) {
GenerateResultTask task = new GenerateResultTask();
task.execute();
} else {
onComplete( mPreview, mActions );
}
}
@Override
public void onConfigurationChanged( Configuration newConfig, Configuration oldConfig ) {
super.onConfigurationChanged( newConfig, oldConfig );
mLogger.info( "onConfigurationChanged: " + newConfig.orientation + ", " + oldConfig.orientation );
if ( newConfig.orientation != oldConfig.orientation ) {
reloadCurrentStatus();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
ViewGroup view = (ViewGroup) inflater.inflate( R.layout.feather_native_effects_panel, parent, false );
return view;
}
/*
* (non-Javadoc)
*
* @see android.widget.ViewSwitcher.ViewFactory#makeView()
*/
@Override
public View makeView() {
ImageViewTouch view = new ImageViewTouch( getContext().getBaseContext(), null );
view.setBackgroundColor( 0x00000000 );
view.setDoubleTapEnabled( false );
if ( enableFastPreview ) {
view.setScrollEnabled( false );
view.setScaleEnabled( false );
}
view.setLayoutParams( new ImageSwitcher.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
return view;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
if ( mSmallPreview != null && !mSmallPreview.isRecycled() ) mSmallPreview.recycle();
mSmallPreview = null;
super.onDestroy();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
onProgressEnd();
mPluginService.removeOnUpdateListener( this );
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#getContentDisplayMatrix()
*/
@Override
public Matrix getContentDisplayMatrix() {
return null;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onBackPressed()
*/
@Override
public boolean onBackPressed() {
if ( backHandled() ) return true;
return super.onBackPressed();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCancelled()
*/
@Override
public void onCancelled() {
killCurrentTask();
mIsRendering = false;
super.onCancelled();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#getIsChanged()
*/
@Override
public boolean getIsChanged() {
return super.getIsChanged() || mIsRendering == true;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_native_effects_content, null );
}
/**
* Kill current task.
*
* @return true, if successful
*/
boolean killCurrentTask() {
if ( mCurrentTask != null ) {
onProgressEnd();
return mCurrentTask.cancel( true );
}
return false;
}
/**
* Load effects.
*/
private void loadEffects( final InternalPlugin plugin ) {
String[] filters = plugin.listFilters();
if ( filters != null ) {
String[] listcopy = new String[filters.length + 2];
System.arraycopy( filters, 0, listcopy, 1, filters.length );
mSelectedLabel = "undefined";
mSelectedView = null;
FiltersAdapter adapter = new FiltersAdapter( getContext().getBaseContext(), R.layout.feather_filter_thumb, plugin, listcopy );
mFiltersAdapter = adapter;
mHList.setHideLastChild( true );
mHList.setAdapter( adapter );
mHList.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
if ( !view.isSelected() ) {
setSelected( view, position, (String) parent.getAdapter().getItem( position ) );
}
}
} );
}
}
FiltersAdapter mFiltersAdapter;
/**
* Render the current effect.
*
* @param tag
* the tag
*/
void renderEffect( String tag ) {
mLogger.log( "tag: " + tag );
killCurrentTask();
mCurrentTask = new RenderTask( tag );
mCurrentTask.execute();
}
int mSelectedPosition = 1;
/**
* Sets the selected.
*
* @param view
* the view
* @param position
* the position
* @param label
* the label
*/
void setSelected( View view, int position, String label ) {
mLogger.info( "setSelected: " + view + "," + position + "," + label );
mSelectedPosition = position;
if ( mSelectedView != null ) {
mSelectedView.setSelected( false );
ViewHolder holder = (ViewHolder) mSelectedView.getTag();
if ( null != holder ) {
holder.image.setAlpha( 127 );
}
}
// mSelectedIndex = position;
mSelectedLabel = label;
mSelectedView = view;
if ( view != null ) {
view.setSelected( true );
ViewHolder holder = (ViewHolder) view.getTag();
if ( null != holder ) {
holder.image.setAlpha( 255 );
}
}
// String tag = (String) mHList.getAdapter().getItem( position );
renderEffect( label );
}
/**
* The Class RenderTask.
*/
private class RenderTask extends UserTask<Void, Bitmap, Bitmap> implements OnCancelListener {
String mError;
String mEffect;
MoaResult mNativeResult;
MoaResult mSmallNativeResult;
/**
* Instantiates a new render task.
*
* @param tag
* the tag
*/
public RenderTask( final String tag ) {
mEffect = tag;
mLogger.info( "RenderTask::ctor", tag );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onPreExecute()
*/
@Override
public void onPreExecute() {
super.onPreExecute();
EffectFilter filter = (EffectFilter) FilterLoaderFactory.get( Filters.EFFECTS );
filter.setEffectName( mEffect );
filter.setBorders( Constants.getValueFromIntent( Constants.EXTRA_EFFECTS_BORDERS_ENABLED, true ) );
try {
mNativeResult = filter.prepare( mBitmap, mPreview, 1, 1 );
mActions = (MoaActionList) filter.getActions().clone();
} catch ( JSONException e ) {
mLogger.error( e.toString() );
e.printStackTrace();
mNativeResult = null;
return;
}
if ( mNativeResult == null ) return;
onProgressStart();
if ( !enableFastPreview ) {
// use the standard system modal progress dialog
// to render the effect
} else {
try {
mSmallNativeResult = filter.prepare( mBitmap, mSmallPreview, mSmallPreview.getWidth(), mSmallPreview.getHeight() );
} catch ( JSONException e ) {
e.printStackTrace();
}
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#doInBackground(Params[])
*/
@Override
public Bitmap doInBackground( final Void... params ) {
if ( isCancelled() ) return null;
if ( mNativeResult == null ) return null;
mIsRendering = true;
// rendering the small preview
if ( enableFastPreview && mSmallNativeResult != null ) {
mSmallNativeResult.execute();
if ( mSmallNativeResult.active > 0 ) {
publishProgress( mSmallNativeResult.outputBitmap );
}
}
if ( isCancelled() ) return null;
long t1, t2;
// rendering the full preview
try {
t1 = System.currentTimeMillis();
mNativeResult.execute();
t2 = System.currentTimeMillis();
} catch ( Exception exception ) {
mLogger.error( exception.getMessage() );
mError = exception.getMessage();
exception.printStackTrace();
return null;
}
if ( null != mTrackingAttributes ) {
mTrackingAttributes.put( "filterName", mEffect );
mTrackingAttributes.put( "renderTime", Long.toString( t2 - t1 ) );
}
mLogger.log( " complete. isCancelled? " + isCancelled(), mEffect );
if ( !isCancelled() ) {
return mNativeResult.outputBitmap;
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onProgressUpdate(Progress[])
*/
@Override
public void onProgressUpdate( Bitmap... values ) {
super.onProgressUpdate( values );
// we're using a FakeBitmapDrawable just to upscale the small bitmap
// to be rendered the same way as the full image
final FakeBitmapDrawable drawable = new FakeBitmapDrawable( values[0], mBitmap.getWidth(), mBitmap.getHeight() );
mImageSwitcher.setImageDrawable( drawable, true, null, Float.MAX_VALUE );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onPostExecute(java.lang.Object)
*/
@Override
public void onPostExecute( final Bitmap result ) {
super.onPostExecute( result );
if ( !isActive() ) return;
mPreview = result;
if ( result == null || mNativeResult == null || mNativeResult.active == 0 ) {
// restore the original bitmap...
mImageSwitcher.setImageBitmap( mBitmap, false, null, Float.MAX_VALUE );
if ( mError != null ) {
onGenericError( mError );
}
setIsChanged( false );
mActions = null;
} else {
if ( SystemUtils.isHoneyComb() ) {
Moa.notifyPixelsChanged( result );
}
mImageSwitcher.setImageBitmap( result, true, null, Float.MAX_VALUE );
setIsChanged( true );
}
onProgressEnd();
mIsRendering = false;
mCurrentTask = null;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onCancelled()
*/
@Override
public void onCancelled() {
super.onCancelled();
if ( mNativeResult != null ) {
mNativeResult.cancel();
}
if ( mSmallNativeResult != null ) {
mSmallNativeResult.cancel();
}
mLogger.warning( "onCancelled", mEffect );
mIsRendering = false;
}
/*
* (non-Javadoc)
*
* @see android.content.DialogInterface.OnCancelListener#onCancel(android.content.DialogInterface)
*/
@Override
public void onCancel( DialogInterface dialog ) {
cancel( true );
}
}
/**
* The Class GenerateResultTask.
*/
class GenerateResultTask extends AsyncTask<Void, Void, Void> {
/** The m progress. */
ProgressDialog mProgress = new ProgressDialog( getContext().getBaseContext() );
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setTitle( getContext().getBaseContext().getString( R.string.feather_loading_title ) );
mProgress.setMessage( getContext().getBaseContext().getString( R.string.effect_loading_message ) );
mProgress.setIndeterminate( true );
mProgress.setCancelable( false );
mProgress.show();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Void doInBackground( Void... params ) {
mLogger.info( "GenerateResultTask::doInBackground", mIsRendering );
while ( mIsRendering ) {
// mLogger.log( "waiting...." );
}
return null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Void result ) {
super.onPostExecute( result );
mLogger.info( "GenerateResultTask::onPostExecute" );
if ( getContext().getBaseActivity().isFinishing() ) return;
if ( mProgress.isShowing() ) mProgress.dismiss();
onComplete( mPreview, mActions );
}
}
class ViewHolder {
ImageView image;
TextView text;
View container;
};
/**
* The main Adapter for the film horizontal list view.
*/
class FiltersAdapter extends ArrayAdapter<String> {
private LayoutInflater mLayoutInflater;
private int mFilterResourceId;
private int mCellWidth;
private WeakReference<InternalPlugin> mPlugin;
/**
* Instantiates a new filters adapter.
*
* @param context
* the context
* @param textViewResourceId
* the text view resource id
* @param objects
* the objects
*/
public FiltersAdapter( Context context, int textViewResourceId, final InternalPlugin plugin, String[] objects ) {
super( context, textViewResourceId, objects );
mFilterResourceId = textViewResourceId;
mPlugin = new WeakReference<InternalPlugin>( plugin );
mLayoutInflater = UIUtils.getLayoutInflater();
mCellWidth = Constants.SCREEN_WIDTH / UIUtils.getScreenOptimalColumns( mFilterCellWidth );
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getCount()
*/
@Override
public int getCount() {
return super.getCount();
}
public CharSequence getFilterName( int position ) {
String item = getItem( position );
if ( null != mPlugin.get() ) {
CharSequence text = mPlugin.get().getFilterLabel( item );
return text;
} else {
return "";
}
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
View view;
ViewHolder holder;
boolean selected = false;
if ( convertView != null ) {
view = convertView;
holder = (ViewHolder) convertView.getTag();
} else {
view = mLayoutInflater.inflate( mFilterResourceId, parent, false );
holder = new ViewHolder();
holder.image = (ImageView) view.findViewById( R.id.image );
holder.text = (TextView) view.findViewById( R.id.text );
holder.container = view.findViewById( R.id.container );
view.setTag( holder );
view.setLayoutParams( new LinearLayout.LayoutParams( mCellWidth, LinearLayout.LayoutParams.MATCH_PARENT ) );
}
if ( position == 0 ) {
holder.container.setVisibility( View.INVISIBLE );
view.setBackgroundResource( R.drawable.feather_film_left );
} else if ( position > getCount() - 2 ) {
holder.container.setVisibility( View.INVISIBLE );
view.setBackgroundResource( R.drawable.feather_film_center );
} else {
holder.container.setVisibility( View.VISIBLE );
String item = getItem( position );
Drawable icon;
CharSequence text;
if ( null != mPlugin.get() ) {
icon = mPlugin.get().getFilterDrawable( item );
text = mPlugin.get().getFilterLabel( item );
} else {
icon = null;
text = "";
}
selected = item.equals( mSelectedLabel );
if ( icon != null )
holder.image.setImageDrawable( icon );
else
holder.image.setImageResource( R.drawable.feather_plugin_filter_undefined_thumb );
view.setBackgroundResource( R.drawable.feather_film_center );
holder.text.setText( text );
if ( null != mFiltersTypeface ) {
holder.text.setTypeface( mFiltersTypeface );
}
}
view.setSelected( selected );
holder.image.setAlpha( selected ? 255 : 127 );
if ( mSelectedView == null && selected ) {
mSelectedView = view;
}
return view;
}
}
/** The m cannister on click listener. */
private View.OnClickListener mCannisterOnClickListener = new View.OnClickListener() {
@Override
public void onClick( View clickView ) {
Object tag = clickView.getTag();
if ( tag == null ) {
getContext().downloadPlugin( FeatherIntent.PLUGIN_BASE_PACKAGE + "*", FeatherIntent.PluginType.TYPE_FILTER );
return;
}
if ( tag instanceof FeatherExternalPack ) {
getContext().downloadPlugin( ( (FeatherExternalPack) tag ).getPackageName(), FeatherIntent.PluginType.TYPE_FILTER );
return;
}
if ( !( tag instanceof FeatherInternalPack ) ) {
mLogger.warning( "invalid view.tag!" );
return;
}
final FeatherInternalPack featherPack = (FeatherInternalPack) tag;
final InternalPlugin plugin = (InternalPlugin) PluginManager.create( getContext().getBaseContext(), featherPack );
final ImageView image = (ImageView) clickView.findViewById( R.id.image );
final Drawable vIcon = image.getDrawable();
if ( plugin == null ) {
onGenericError( R.string.feather_effects_error_loading_pack );
return;
}
// then be sure the pack selected is valid
boolean loaded = plugin.listFilters().length > 0;
if ( !loaded ) {
onGenericError( R.string.feather_effects_error_loading_pack );
return;
}
// and finally verify the pack can be installed
// TODO: Move install external effects to a separate thread
PluginError error;
if ( plugin.isExternal() ) {
error = installPlugin( featherPack.getPackageName(), featherPack.getPluginType() );
} else {
error = PluginError.NoError;
}
if ( error != PluginError.NoError ) {
final String errorString = getError( error );
if ( error == PluginError.PluginTooOldError ) {
OnClickListener yesListener = new OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
getContext().downloadPlugin( featherPack.getPackageName(), PluginType.TYPE_FILTER );
}
};
onGenericError( errorString, R.string.feather_update, yesListener, android.R.string.cancel, null );
} else {
onGenericError( errorString );
}
return;
}
trackPackage( featherPack.getPackageName() );
float destW, destH;
float iconW = vIcon.getIntrinsicWidth();
float iconH = vIcon.getIntrinsicHeight();
float iconR = iconW / iconH;
if ( getOptionView().findViewById( R.id.workspace_container ) != null ) {
destH = getOptionView().findViewById( R.id.workspace_container ).getHeight();
} else {
destH = iconH;
}
destH = Math.max( iconH, destH );
destW = destH * iconR;
final float scalex = destW / image.getWidth();
final float scaley = destH / image.getHeight();
final float scale = Math.max( scalex, scaley );
Rect r = new Rect();
Point offset = new Point();
CellLayout cell = (CellLayout) clickView.getParent();
( (ViewGroup) mOptionView ).getChildVisibleRect( clickView, r, offset );
int top = -r.top;
top += cell.getTopPadding();
clickView.getGlobalVisibleRect( r );
ImageView newView = new ImageView( getContext().getBaseContext() );
newView.setScaleType( image.getScaleType() );
newView.setImageDrawable( vIcon );
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams( image.getWidth(), image.getHeight(), 0, 0 );
newView.setLayoutParams( params );
final float startX = r.left;
final float endX = Constants.SCREEN_WIDTH - ( (float) image.getWidth() * scale ) / 2;
final float startY = r.top + top;
final float endY = startY;
Animation animation = new TransformAnimation( TranslateAnimation.ABSOLUTE, startX, TranslateAnimation.ABSOLUTE, endX, TranslateAnimation.ABSOLUTE, startY, TranslateAnimation.ABSOLUTE, endY, 1, scale, 1, scale );
animation.setInterpolator( mDecelerateInterpolator );
animation.setDuration( mAnimationDurationIn );
animation.setFillEnabled( true );
animation.setFillBefore( true );
animation.setFillAfter( true );
startCannisterAnimation( newView, animation, plugin );
}
};
/**
* The main Adapter for the cannister workspace view.
*/
class FiltersPacksAdapter extends ArrayAdapter<FeatherPack> {
int screenId, cellId;
LayoutInflater mLayoutInflater;
boolean mInFirstLayout = true;
/** The default get more icon. */
Bitmap mShadow, mEffect, mEffectFree;
Typeface mTypeface;
/** The default get more label. */
String mGetMoreLabel;
/**
* Instantiates a new filters packs adapter.
*
* @param context
* the context
* @param resource
* the resource
* @param textViewResourceId
* the text view resource id
* @param objects
* the objects
*/
public FiltersPacksAdapter( Context context, int resource, int textViewResourceId, FeatherPack objects[] ) {
super( context, resource, textViewResourceId, objects );
screenId = resource;
cellId = textViewResourceId;
mLayoutInflater = UIUtils.getLayoutInflater();
mGetMoreLabel = context.getString( R.string.get_more );
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getCount()
*/
@Override
public int getCount() {
return (int) Math.ceil( (double) ( super.getCount() ) / mWorkspaceItemsPerPage );
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getItem(int)
*/
@Override
public FeatherPack getItem( int position ) {
if ( position < super.getCount() ) {
return super.getItem( position );
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return super.getItemId( position );
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
CellLayout view;
if ( convertView == null ) {
view = (CellLayout) mLayoutInflater.inflate( screenId, mWorkspace, false );
view.setNumCols( mWorkspaceCols );
} else {
view = (CellLayout) convertView;
}
int index = position * mWorkspaceItemsPerPage;
int count = super.getCount();
for ( int i = 0; i < mWorkspaceItemsPerPage; i++ ) {
View itemView = null;
CellInfo cellInfo = view.findVacantCell( 1, 1 );
if ( cellInfo == null ) {
itemView = view.getChildAt( i );
} else {
itemView = mLayoutInflater.inflate( cellId, parent, false );
CellLayout.LayoutParams lp = new CellLayout.LayoutParams( cellInfo.cellX, cellInfo.cellY, cellInfo.spanH, cellInfo.spanV );
view.addView( itemView, -1, lp );
}
if ( index < ( count ) ) {
final FeatherPack featherPack = getItem( index );
Drawable icon;
CharSequence label = "";
ensureBitmapTemplate();
if ( featherPack == null ) {
label = mGetMoreLabel;
icon = new ExternalFilterPackDrawable( "Get More", "AV", 6, 0xFF5fcbef, mTypeface, mShadow, mEffect );
} else {
final IPlugin plugin = PluginManager.create( getContext(), featherPack );
if ( plugin.isLocal() ) {
label = plugin.getLabel( PluginType.TYPE_FILTER );
icon = plugin.getIcon( PluginType.TYPE_FILTER );
} else {
label = plugin.getLabel( PluginType.TYPE_FILTER );
ExternalPlugin externalPlugin = (ExternalPlugin) plugin;
if ( externalPlugin.isFree() ) {
ensureBitmapTemplateFree();
icon = new ExternalFilterPackDrawable( label.toString(), externalPlugin.getShortTitle(), externalPlugin.getNumFilters(), externalPlugin.getDisplayColor(), mTypeface, mShadow, mEffectFree );
} else {
icon = new ExternalFilterPackDrawable( label.toString(), externalPlugin.getShortTitle(), externalPlugin.getNumFilters(), externalPlugin.getDisplayColor(), mTypeface, mShadow, mEffect );
}
}
}
final ImageView image = (ImageView) itemView.findViewById( R.id.image );
final TextView text = (TextView) itemView.findViewById( R.id.text );
if ( null != mFiltersTypeface ) {
text.setTypeface( mFiltersTypeface );
}
image.setImageDrawable( icon );
text.setText( label );
itemView.setTag( featherPack );
itemView.setOnClickListener( mCannisterOnClickListener );
itemView.setVisibility( View.VISIBLE );
} else {
itemView.setVisibility( View.INVISIBLE );
}
index++;
}
mInFirstLayout = false;
view.setSelected( false );
return view;
}
private void ensureBitmapTemplate() {
if ( null == mShadow ) {
mShadow = ( (BitmapDrawable) getContext().getResources().getDrawable( R.drawable.feather_external_filters_template_shadow ) ).getBitmap();
mEffect = ( (BitmapDrawable) getContext().getResources().getDrawable( R.drawable.feather_external_filters_template ) ).getBitmap();
}
if ( null == mTypeface ) {
try {
mTypeface = TypefaceUtils.createFromAsset( getContext().getAssets(), "fonts/HelveticaBold.ttf" );
} catch ( Exception e ) {
mTypeface = Typeface.DEFAULT_BOLD;
}
}
}
private void ensureBitmapTemplateFree() {
if ( null == mEffectFree ) {
mEffectFree = ( (BitmapDrawable) getContext().getResources().getDrawable( R.drawable.feather_external_filters_template_free ) ).getBitmap();
}
}
}
private void initWorkspace() {
mWorkspaceCols = getContext().getBaseContext().getResources().getInteger( R.integer.featherfilterPacksCount );
mWorkspaceItemsPerPage = mWorkspaceCols;
}
protected String getError( PluginError error ) {
int resId = R.string.feather_effects_error_loading_pack;
switch ( error ) {
case UnknownError:
resId = R.string.feather_effects_unknown_error;
break;
case PluginTooOldError:
resId = R.string.feather_effects_error_update_pack;
break;
case PluginTooNewError:
resId = R.string.feather_effects_error_update_editor;
break;
case PluginNotLoadedError:
break;
case PluginLoadError:
break;
case MethodNotFoundError:
break;
default:
break;
}
return getContext().getBaseContext().getString( resId );
}
/**
* Track only the first time the package is started
*
* @param packageName
*/
protected void trackPackage( String packageName ) {
if ( !mPrefService.containsValue( "effects." + packageName ) ) {
if ( !getContext().getBaseContext().getPackageName().equals( packageName ) ) {
mPrefService.putString( "effects." + packageName, packageName );
HashMap<String, String> map = new HashMap<String, String>();
map.put( "assetType", "effects" );
map.put( "assetID", packageName );
Tracker.recordTag( "content: purchased", map );
}
}
mTrackingAttributes.put( "packName", packageName );
}
/**
* Update installed packs.
*/
private void updateInstalledPacks( boolean animate ) {
mWorkspace.setAdapter( null );
UpdateInstalledPacksTask task = new UpdateInstalledPacksTask( animate );
task.execute();
}
/**
* Gets the installed packs.
*
* @return the installed packs
*/
private FeatherInternalPack[] getInstalledPacks() {
return mPluginService.getInstalled( getContext().getBaseContext(), FeatherIntent.PluginType.TYPE_FILTER );
}
/**
* Gets the list of all the packs available on the market
*
* @param type
* @return
*/
private FeatherExternalPack[] getAvailablePacks( final int type ) {
return mPluginService.getAvailable( type );
}
/**
* Back handled.
*
* @return true, if successful
*/
boolean backHandled() {
if ( mIsAnimating ) return true;
if ( !mExternalPacksEnabled ) return false;
killCurrentTask();
switch ( mStatus ) {
case Null:
case Packs:
return false;
case Filters:
setStatus( Status.Packs );
return true;
}
return false;
}
private void reloadCurrentStatus() {
mLogger.info( "reloadCurrentStatus" );
initWorkspace();
if ( mStatus == Status.Packs ) {
updateInstalledPacks( false );
} else if ( mStatus == Status.Filters ) {
View view = mCannisterView.getChildAt( 0 );
if ( null != view && view instanceof ImageView ) {
ImageView newView = (ImageView) view;
newView.clearAnimation();
Drawable icon = newView.getDrawable();
if ( null != icon ) {
Resources res = getContext().getBaseContext().getResources();
final float height = res.getDimension( R.dimen.feather_options_panel_height_with_shadow ) + 25;
final float offset = res.getDimension( R.dimen.feather_options_panel_height_shadow );
final float ratio = (float) icon.getIntrinsicWidth() / (float) icon.getIntrinsicHeight();
final float width = height * ratio;
final float endX = Constants.SCREEN_WIDTH - ( width / 2 );
final float endY = offset * 2;
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams( (int) width, (int) height, (int) endX, (int) endY );
newView.setLayoutParams( params );
}
}
}
}
/**
* Set the new status for this panel
*
* @param status
*/
void setStatus( Status status ) {
setStatus( status, null );
}
/**
* Change the status passing a custom object data.
*
* @param status
* the new status
* @param object
* a custom user object
*/
void setStatus( Status status, InternalPlugin plugin ) {
mLogger.error( "setStatus: " + mStatus + " >> " + status );
if ( status != mStatus ) {
mPrevStatus = mStatus;
mStatus = status;
switch ( mStatus ) {
case Null:
break;
case Packs: {
if ( mPrevStatus == Status.Null ) {
updateInstalledPacks( true );
} else if ( mPrevStatus == Status.Filters ) {
// going back, just switch visibility...
restorePacksAnimation();
}
}
break;
case Filters: {
if ( null == plugin ) {
mLogger.error( "plugin instance is null!" );
return;
}
if ( mPrevStatus == Status.Packs ) {
loadEffects( plugin );
startEffectsSliderAnimation( plugin.getLabel( PluginType.TYPE_FILTER ) );
mSelectedPosition = 0;
} else if ( mPrevStatus == Status.Null ) {
loadEffects( plugin );
startEffectsSliderAnimation( plugin.getLabel( PluginType.TYPE_FILTER ) );
}
}
break;
}
}
}
Animation mCannisterAnimationIn;
/**
* Firt animation when panel is loaded and it's ready to display the effects packs.
*/
private void startFirstAnimation() {
getHandler().postDelayed( new Runnable() {
@Override
public void run() {
postStartFirstAnimation();
}
}, 200 );
return;
}
private void postStartFirstAnimation() {
mIsAnimating = true;
if ( mWorkspace.getChildCount() < 1 ) {
getHandler().postDelayed( new Runnable() {
@Override
public void run() {
startFirstAnimation();
}
}, 10 );
return;
}
mWorkspace.setVisibility( View.VISIBLE );
mWorkspace.setCacheEnabled( true );
mWorkspace.enableChildrenCache( 0, 1 );
mWorkspace.startAnimation( mCannisterAnimationIn );
}
private void createFirstAnimation() {
mCannisterAnimationIn = AnimationUtils.loadAnimation( getContext().getBaseContext(), R.anim.feather_push_up_cannister );
mCannisterAnimationIn.setInterpolator( new DecelerateInterpolator( 0.4f ) );
mCannisterAnimationIn.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
mIsAnimating = false;
getContentView().setVisibility( View.VISIBLE );
contentReady();
mWorkspace.clearChildrenCache();
mWorkspace.setCacheEnabled( false );
mWorkspace.requestLayout();
mWorkspace.postInvalidate();
}
} );
}
private void startCannisterAnimation( View view, Animation animation, final InternalPlugin plugin ) {
mLogger.info( "startCannisterAnimation" );
mIsAnimating = true;
animation.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
// mLayoutLoader.setVisibility(View.GONE);
// setStatus( Status.Filters, plugin );
}
} );
mLayoutLoader.setVisibility(View.GONE);
setStatus( Status.Filters, plugin );
mWorkspaceContainer.setVisibility( View.INVISIBLE );
mCannisterView.removeAllViews();
// mCannisterView.addView( view );
// view.startAnimation( animation );
}
/** The slide in left animation. */
private Animation mSlideInLeftAnimation;
/** The slide out right animation. */
private Animation mSlideRightAnimation;
/**
* Restore the view of the effects packs with an animation
*/
private void restorePacksAnimation() {
mIsAnimating = true;
if ( mSlideInLeftAnimation == null ) {
mSlideInLeftAnimation = AnimationUtils.loadAnimation( getContext().getBaseContext(), R.anim.feather_slide_in_left );
mSlideInLeftAnimation.setDuration( mAnimationFilmDurationOut );
mSlideInLeftAnimation.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
mWorkspaceContainer.setVisibility( View.VISIBLE );
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
mIsAnimating = false;
}
} );
}
mWorkspaceContainer.startAnimation( mSlideInLeftAnimation );
if ( mSlideRightAnimation == null ) {
// hide effects
mSlideRightAnimation = AnimationUtils.loadAnimation( getContext().getBaseContext(), R.anim.feather_slide_out_right );
mSlideRightAnimation.setDuration( mAnimationFilmDurationOut );
mSlideRightAnimation.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
mCannisterView.removeAllViews();
mHList.setVisibility( View.INVISIBLE );
mHList.setAdapter( null );
getContext().setToolbarTitle( getContext().getCurrentEffect().labelResourceId );
// ok restore the original filter too...
mSelectedLabel = "undefined";
mSelectedView = null;
mImageSwitcher.setImageBitmap( mBitmap, false, null, Float.MAX_VALUE );
setIsChanged( false );
}
} );
}
mCannisterView.startAnimation( mSlideRightAnimation );
mHList.startAnimation( mSlideRightAnimation );
}
/**
* The effect list is loaded, animate it.
*/
private void startEffectsSliderAnimation( final CharSequence title ) {
mIsAnimating = true;
Animation animation = new TranslateAnimation( TranslateAnimation.RELATIVE_TO_SELF, 1, TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0 );
animation.setDuration( mAnimationFilmDurationIn );
animation.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
mHList.setVisibility( View.VISIBLE );
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
mIsAnimating = false;
// set the new toolbar title
if ( mExternalPacksEnabled ) {
getContext().setToolbarTitle( title );
} else {
getContentView().setVisibility( View.VISIBLE );
contentReady();
}
}
} );
mHList.startAnimation( animation );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.PluginService.OnUpdateListener#onUpdate(android.os.Bundle)
*/
@Override
public void onUpdate( Bundle delta ) {
if ( isActive() && mExternalPacksEnabled ) {
if ( mUpdateDialog != null && mUpdateDialog.isShowing() ) {
// another update alert is showing, skip new alerts
return;
}
if ( validDelta( delta ) ) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
setStatus( Status.Packs );
updateInstalledPacks( false );
}
};
mUpdateDialog = new AlertDialog.Builder( getContext().getBaseContext() ).setMessage( R.string.filter_pack_updated ).setNeutralButton( android.R.string.ok, listener ).setCancelable( false ).create();
mUpdateDialog.show();
}
}
}
/**
* bundle contains a list of all updates applications. if one meets the criteria ( is a filter apk ) then return true
*
* @param bundle
* the bundle
* @return true if bundle contains a valid filter package
*/
private boolean validDelta( Bundle bundle ) {
if ( null != bundle ) {
if ( bundle.containsKey( "delta" ) ) {
try {
@SuppressWarnings("unchecked")
ArrayList<UpdateType> updates = (ArrayList<UpdateType>) bundle.getSerializable( "delta" );
if ( null != updates ) {
for ( UpdateType update : updates ) {
if ( FeatherIntent.PluginType.isFilter( update.getPluginType() ) ) {
return true;
}
if ( FeatherIntent.ACTION_PLUGIN_REMOVED.equals( update.getAction() ) ) {
// if it's removed check against current listed packs
if ( mInstalledPackages.contains( update.getPackageName() ) ) {
return true;
}
}
}
return false;
}
} catch ( ClassCastException e ) {
return true;
}
}
}
return true;
}
/**
* Try to install the selected pack, >only if the passed resource manager contains an external app (not the current one)
*/
private PluginError installPlugin( String packagename, int pluginType ) {
if ( mPluginService.installed( packagename ) ) {
return PluginError.NoError;
}
return mPluginService.install( getContext().getBaseContext(), packagename, pluginType );
}
// updated installed package names
private class UpdateInstalledPacksTask extends AsyncTask<Void, Void, FeatherPack[]> {
private boolean mPostAnimate;
public UpdateInstalledPacksTask( boolean postAnimate ) {
mPostAnimate = postAnimate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mLayoutLoader.setVisibility( View.VISIBLE );
mWorkspace.setVisibility( View.INVISIBLE );
}
@Override
protected FeatherPack[] doInBackground( Void... params ) {
PluginService service = getContext().getService( PluginService.class );
if ( null != service ) {
while ( !service.isUpdated() ) {
try {
Thread.sleep( 50 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
FeatherPack packs[] = getInstalledPacks();
FeatherPack packs2[] = getAvailablePacks( FeatherIntent.PluginType.TYPE_FILTER );
int newLength = packs.length + packs2.length;
FeatherPack packs3[] = new FeatherPack[newLength];
System.arraycopy( packs, 0, packs3, 0, packs.length );
System.arraycopy( packs2, 0, packs3, packs.length, packs2.length );
mInstalledPackages.clear();
if ( null != packs ) {
for ( FeatherPack pack : packs ) {
if ( !mInstalledPackages.contains( pack ) ) mInstalledPackages.add( pack.getPackageName() );
}
}
return packs3;
}
return new FeatherPack[0];
}
@Override
protected void onPostExecute( FeatherPack[] result ) {
super.onPostExecute( result );
mLogger.log( "total packs: " + result.length );
FiltersPacksAdapter adapter = new FiltersPacksAdapter( getContext().getBaseContext(), R.layout.feather_workspace_screen, R.layout.feather_filter_pack, result );
mWorkspace.setAdapter( adapter );
mWorkspaceIndicator.setVisibility( mWorkspace.getTotalPages() > 1 ? View.VISIBLE : View.INVISIBLE );
mLayoutLoader.setVisibility( View.GONE );
if( mPostAnimate ){
startFirstAnimation();
} else {
mWorkspace.setVisibility( View.VISIBLE );
}
}
}
public void onSwipe( boolean leftToRight ) {
if ( mStatus.equals( Status.Filters ) ) {
Context context = getContext().getBaseContext();
int position = mSelectedPosition;
if ( position == 0 ) position = 1;
position = leftToRight ? position - 1 : position + 1;
if ( position > 0 && position < mHList.getAdapter().getCount() - 1 ) {
View view = mHList.getItemAt( position );
setSelected( view, position, (String) mHList.getAdapter().getItem( position ) );
CharSequence text = mFiltersAdapter.getFilterName( position );
Toast.makeText( context, text, toastDuration ).show();
} else {
int errorText;
if ( position < 1 ) {
errorText = R.string.feather_effects_beginning_of_list;
position += 1;
} else {
errorText = R.string.feather_effects_end_of_list;
position -= 1;
}
Toast.makeText( context, errorText, toastDuration ).show();
}
}
}
}
| Java |
package com.aviary.android.feather.effects;
import java.util.ArrayList;
import java.util.Collection;
import android.R.attr;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable;
import com.aviary.android.feather.graphics.GalleryCircleDrawable;
import com.aviary.android.feather.graphics.OverlayGalleryCheckboxDrawable;
import com.aviary.android.feather.graphics.PreviewCircleDrawable;
import com.aviary.android.feather.library.moa.MoaAction;
import com.aviary.android.feather.library.moa.MoaActionFactory;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.moa.MoaGraphicsCommandParameter;
import com.aviary.android.feather.library.moa.MoaGraphicsOperationParameter;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.AdapterView;
import com.aviary.android.feather.widget.Gallery;
import com.aviary.android.feather.widget.Gallery.OnItemsScrollListener;
import com.aviary.android.feather.widget.IToast;
import com.aviary.android.feather.widget.ImageViewTouchAndDraw;
import com.aviary.android.feather.widget.ImageViewTouchAndDraw.OnDrawPathListener;
import com.aviary.android.feather.widget.ImageViewTouchAndDraw.OnDrawStartListener;
import com.aviary.android.feather.widget.ImageViewTouchAndDraw.TouchMode;
/**
* The Class DrawingPanel.
*/
public class DrawingPanel extends AbstractContentPanel implements OnDrawStartListener, OnDrawPathListener {
/**
* The Drawin state.
*/
private enum DrawinTool {
Draw, Erase, Zoom,
};
protected ImageButton mLensButton;
protected Gallery mGallerySize;
protected Gallery mGalleryColor;
protected View mSelectedSizeView;
protected View mSelectedColorView;
protected int mSelectedColorPosition, mSelectedSizePosition = 0;
int mBrushSizes[];
int mBrushColors[];
protected int defaultOption = 0;
private int mColor = 0;
private int mSize = 10;
private int mBlur = 1;
private Paint mPaint;
private ConfigService mConfig;
private DrawinTool mSelectedTool;
IToast mToast;
PreviewCircleDrawable mCircleDrawablePreview;
// width and height of the bitmap
int mWidth, mHeight;
MoaActionList mActionList;
MoaAction mAction;
Collection<MoaGraphicsOperationParameter> mOperations;
MoaGraphicsOperationParameter mCurrentOperation;
/**
* Instantiates a new drawing panel.
*
* @param context
* the context
*/
public DrawingPanel( EffectContext context ) {
super( context );
}
/**
* Show toast preview.
*/
private void showToastPreview() {
if ( !isActive() ) return;
mToast.show();
}
/**
* Hide toast preview.
*/
private void hideToastPreview() {
if ( !isActive() ) return;
mToast.hide();
}
/**
* Update toast preview.
*
* @param size
* the size
* @param color
* the color
* @param blur
* the blur
* @param strokeOnly
* the stroke only
*/
private void updateToastPreview( int size, int color, int blur, boolean strokeOnly ) {
if ( !isActive() ) return;
mCircleDrawablePreview.setRadius( size / 2 );
mCircleDrawablePreview.setColor( color );
mCircleDrawablePreview.setBlur( blur );
mCircleDrawablePreview.setStyle( strokeOnly ? Paint.Style.STROKE : Paint.Style.FILL );
View v = mToast.getView();
v.findViewById( R.id.size_preview_image );
v.invalidate();
}
/**
* Inits the toast.
*/
private void initToast() {
mToast = IToast.make( getContext().getBaseContext(), -1 );
mCircleDrawablePreview = new PreviewCircleDrawable( 0 );
mCircleDrawablePreview.setStyle( Paint.Style.FILL );
ImageView image = (ImageView) mToast.getView().findViewById( R.id.size_preview_image );
image.setImageDrawable( mCircleDrawablePreview );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
mConfig = getContext().getService( ConfigService.class );
mBrushSizes = mConfig.getSizeArray( R.array.feather_brush_sizes );
int colors[] = mConfig.getIntArray( R.array.feather_default_colors );
mBrushColors = new int[colors.length + 2];
mBrushColors[0] = 0;
System.arraycopy( colors, 0, mBrushColors, 1, colors.length );
if ( mConfig != null ) {
mSize = mBrushSizes[0];
mColor = mBrushColors[1];
mBlur = mConfig.getInteger( R.integer.feather_brush_softValue );
}
mLensButton = (ImageButton) getContentView().findViewById( R.id.lens_button );
mGallerySize = (Gallery) getOptionView().findViewById( R.id.gallery );
mGallerySize.setCallbackDuringFling( false );
mGallerySize.setSpacing( 0 );
mGalleryColor = (Gallery) getOptionView().findViewById( R.id.gallery_color );
mGalleryColor.setCallbackDuringFling( false );
mGalleryColor.setSpacing( 0 );
mImageView = (ImageViewTouchAndDraw) getContentView().findViewById( R.id.image );
mWidth = mBitmap.getWidth();
mHeight = mBitmap.getHeight();
resetBitmap();
mSelectedColorPosition = 1;
mSelectedSizePosition = 0;
// init the actionlist
mActionList = MoaActionFactory.actionList( "draw" );
mAction = mActionList.get( 0 );
mOperations = new ArrayList<MoaGraphicsOperationParameter>();
mCurrentOperation = null;
mAction.setValue( "commands", mOperations );
initAdapter( mGallerySize, new GallerySizeAdapter( getContext().getBaseContext(), mBrushSizes ), 0 );
initAdapter( mGalleryColor, new GalleryColorAdapter( getContext().getBaseContext(), mBrushColors ), 1 );
initPaint();
}
/**
* Inits the adapter.
*
* @param gallery
* the gallery
* @param adapter
* the adapter
* @param selectedPosition
* the selected position
*/
private void initAdapter( final Gallery gallery, final BaseAdapter adapter, final int selectedPosition ) {
int height = gallery.getHeight();
if ( height < 1 ) {
gallery.getHandler().post( new Runnable() {
@Override
public void run() {
initAdapter( gallery, adapter, selectedPosition );
}
} );
return;
}
gallery.setAdapter( adapter );
gallery.setSelection( selectedPosition, false, true );
}
/**
* Reset bitmap.
*/
private void resetBitmap() {
mImageView.setImageBitmap( mBitmap, true, getContext().getCurrentImageViewMatrix(), UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
( (ImageViewTouchAndDraw) mImageView ).setDrawMode( TouchMode.DRAW );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
disableHapticIsNecessary( mGalleryColor, mGallerySize );
initToast();
mGallerySize.setOnItemsScrollListener( new OnItemsScrollListener() {
@Override
public void onScrollFinished( AdapterView<?> parent, View view, int position, long id ) {
mSize = (Integer) mGallerySize.getAdapter().getItem( position );
final boolean soft = ( (GallerySizeAdapter) mGallerySize.getAdapter() ).getIsSoft( position );
if ( soft )
mPaint.setMaskFilter( new BlurMaskFilter( mBlur, Blur.NORMAL ) );
else
mPaint.setMaskFilter( null );
updatePaint();
updateSelectedSize( view, position );
hideToastPreview();
}
@Override
public void onScrollStarted( AdapterView<?> parent, View view, int position, long id ) {
showToastPreview();
if ( getSelectedTool() == DrawinTool.Zoom ) {
setSelectedTool( DrawinTool.Draw );
}
}
@Override
public void onScroll( AdapterView<?> parent, View view, int position, long id ) {
GallerySizeAdapter adapter = (GallerySizeAdapter) parent.getAdapter();
int size = (Integer) adapter.getItem( position );
int blur = adapter.getIsSoft( position ) ? mBlur : 0;
boolean is_eraser = mGalleryColor.getSelectedItemPosition() == 0
|| mGalleryColor.getSelectedItemPosition() == mGalleryColor.getAdapter().getCount() - 1;
if ( is_eraser ) {
updateToastPreview( size, Color.WHITE, blur, true );
} else {
updateToastPreview( size, mColor, blur, false );
}
}
} );
mGalleryColor.setOnItemsScrollListener( new OnItemsScrollListener() {
@Override
public void onScrollFinished( AdapterView<?> parent, View view, int position, long id ) {
mColor = (Integer) parent.getAdapter().getItem( position );
final boolean is_eraser = position == 0 || ( position == parent.getAdapter().getCount() - 1 );
if ( is_eraser ) {
mColor = 0;
}
mPaint.setColor( mColor );
if ( getSelectedTool() == DrawinTool.Zoom ) {
if ( is_eraser )
setSelectedTool( DrawinTool.Erase );
else
setSelectedTool( DrawinTool.Draw );
} else {
if ( is_eraser && getSelectedTool() != DrawinTool.Erase )
setSelectedTool( DrawinTool.Erase );
else if ( !is_eraser && getSelectedTool() != DrawinTool.Draw ) setSelectedTool( DrawinTool.Draw );
}
updatePaint();
updateSelectedColor( view, position );
hideToastPreview();
}
@Override
public void onScrollStarted( AdapterView<?> parent, View view, int position, long id ) {
showToastPreview();
if ( getSelectedTool() == DrawinTool.Zoom ) {
setSelectedTool( DrawinTool.Draw );
}
}
@Override
public void onScroll( AdapterView<?> parent, View view, int position, long id ) {
final boolean is_eraser = position == 0 || ( position == parent.getAdapter().getCount() - 1 );
if ( is_eraser ) {
updateToastPreview( mSize, Color.WHITE, mBlur, true );
} else {
updateToastPreview( mSize, mBrushColors[position], mBlur, false );
}
}
} );
mLensButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View arg0 ) {
boolean selected = arg0.isSelected();
arg0.setSelected( !selected );
if ( arg0.isSelected() ) {
setSelectedTool( DrawinTool.Zoom );
} else {
if ( mGalleryColor.getSelectedItemPosition() == 0 ) {
setSelectedTool( DrawinTool.Erase );
} else {
setSelectedTool( DrawinTool.Draw );
}
updatePaint();
}
}
} );
setSelectedTool( DrawinTool.Draw );
updatePaint();
updateSelectedSize( (View) mGallerySize.getSelectedView(), mGallerySize.getSelectedItemPosition() );
updateSelectedColor( (View) mGalleryColor.getSelectedView(), mGalleryColor.getSelectedItemPosition() );
( (ImageViewTouchAndDraw) mImageView ).setOnDrawStartListener( this );
( (ImageViewTouchAndDraw) mImageView ).setOnDrawPathListener( this );
mLensButton.setVisibility( View.VISIBLE );
getContentView().setVisibility( View.VISIBLE );
contentReady();
}
/**
* Update selected size.
*
* @param newSelection
* the new selection
* @param position
* the position
*/
protected void updateSelectedSize( View newSelection, int position ) {
if ( mSelectedSizeView != null ) {
mSelectedSizeView.setSelected( false );
}
mSelectedSizeView = newSelection;
mSelectedSizePosition = position;
if ( mSelectedSizeView != null ) {
mSelectedSizeView = newSelection;
mSelectedSizeView.setSelected( true );
}
}
/**
* Update selected color.
*
* @param newSelection
* the new selection
* @param position
* the position
*/
protected void updateSelectedColor( View newSelection, int position ) {
if ( mSelectedColorView != null ) {
mSelectedColorView.setSelected( false );
}
mSelectedColorView = newSelection;
mSelectedColorPosition = position;
if ( mSelectedColorView != null ) {
mSelectedColorView = newSelection;
mSelectedColorView.setSelected( true );
}
}
/**
* Sets the selected tool.
*
* @param which
* the new selected tool
*/
private void setSelectedTool( DrawinTool which ) {
switch ( which ) {
case Draw:
( (ImageViewTouchAndDraw) mImageView ).setDrawMode( TouchMode.DRAW );
mPaint.setAlpha( 255 );
mPaint.setXfermode( null );
updatePaint();
break;
case Erase:
( (ImageViewTouchAndDraw) mImageView ).setDrawMode( TouchMode.DRAW );
mPaint.setXfermode( new PorterDuffXfermode( PorterDuff.Mode.CLEAR ) );
mPaint.setAlpha( 0 );
updatePaint();
break;
case Zoom:
( (ImageViewTouchAndDraw) mImageView ).setDrawMode( TouchMode.IMAGE );
break;
}
mLensButton.setSelected( which == DrawinTool.Zoom );
setPanelEnabled( which != DrawinTool.Zoom );
mSelectedTool = which;
}
/**
* Sets the panel enabled.
*
* @param value
* the new panel enabled
*/
public void setPanelEnabled( boolean value ) {
if( !isActive() ) return;
if ( value ) {
getContext().restoreToolbarTitle();
} else {
getContext().setToolbarTitle( R.string.zoom_mode );
}
mOptionView.findViewById( R.id.disable_status ).setVisibility( value ? View.INVISIBLE : View.VISIBLE );
}
/**
* Gets the selected tool.
*
* @return the selected tool
*/
private DrawinTool getSelectedTool() {
return mSelectedTool;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
( (ImageViewTouchAndDraw) mImageView ).setOnDrawStartListener( null );
( (ImageViewTouchAndDraw) mImageView ).setOnDrawPathListener( null );
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
mImageView.clear();
mToast.hide();
}
/**
* Inits the paint.
*/
private void initPaint() {
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mPaint.setFilterBitmap( false );
mPaint.setDither( true );
mPaint.setColor( mColor );
mPaint.setStrokeWidth( mSize );
mPaint.setStyle( Paint.Style.STROKE );
mPaint.setStrokeJoin( Paint.Join.ROUND );
mPaint.setStrokeCap( Paint.Cap.ROUND );
}
/**
* Update paint.
*/
private void updatePaint() {
mPaint.setStrokeWidth( mSize );
( (ImageViewTouchAndDraw) mImageView ).setPaint( mPaint );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_drawing_content, null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_drawing_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
Bitmap bitmap = null;
if ( !mBitmap.isMutable() ) {
bitmap = BitmapUtils.copy( mBitmap, mBitmap.getConfig() );
} else {
bitmap = mBitmap;
}
Canvas canvas = new Canvas( bitmap );
( (ImageViewTouchAndDraw) mImageView ).commit( canvas );
( (ImageViewTouchAndDraw) mImageView ).setImageBitmap( bitmap, false );
onComplete( bitmap, mActionList );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewTouchAndDraw.OnDrawStartListener#onDrawStart()
*/
@Override
public void onDrawStart() {
setIsChanged( true );
}
/**
* The Class GallerySizeAdapter.
*/
class GallerySizeAdapter extends BaseAdapter {
private static final int VALID_POSITION = 0;
private static final int INVALID_POSITION = 1;
/** The sizes. */
private int[] sizes;
/** The m layout inflater. */
LayoutInflater mLayoutInflater;
/** The m res. */
Resources mRes;
/** The m biggest. */
int mBiggest;
/**
* Instantiates a new gallery size adapter.
*
* @param context
* the context
* @param values
* the values
*/
public GallerySizeAdapter( Context context, int[] values ) {
mLayoutInflater = UIUtils.getLayoutInflater();
sizes = values;
mRes = getContext().getBaseContext().getResources();
mBiggest = sizes[sizes.length - 1];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return sizes.length;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem( int position ) {
return sizes[position];
}
/**
* Gets the checks if is soft.
*
* @param position
* the position
* @return the checks if is soft
*/
public boolean getIsSoft( int position ) {
return true;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return position;
}
@Override
public int getItemViewType( int position ) {
final boolean valid = position >= 0 && position < getCount();
return valid ? VALID_POSITION : INVALID_POSITION;
}
@Override
public int getViewTypeCount() {
return 2;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@SuppressWarnings("deprecation")
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
final int type = getItemViewType( position );
GalleryCircleDrawable mCircleDrawable = null;
View view;
if ( convertView == null ) {
if ( type == VALID_POSITION ) {
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGallerySize, false );
mCircleDrawable = new GalleryCircleDrawable( 1, 0 );
Drawable unselectedBackground = new OverlayGalleryCheckboxDrawable( mRes, false, mCircleDrawable, 1.0f, 0.4f );
Drawable selectedBackground = new OverlayGalleryCheckboxDrawable( mRes, true, mCircleDrawable, 1.0f, 0.4f );
StateListDrawable st = new StateListDrawable();
st.addState( new int[] { -attr.state_selected }, unselectedBackground );
st.addState( new int[] { attr.state_selected }, selectedBackground );
view.setBackgroundDrawable( st );
view.setTag( mCircleDrawable );
} else {
// use the blank view
view = mLayoutInflater.inflate( R.layout.feather_default_blank_gallery_item, mGallerySize, false );
Drawable unselectedBackground = new DefaultGalleryCheckboxDrawable( mRes, false );
view.setBackgroundDrawable( unselectedBackground );
}
} else {
view = convertView;
if ( type == VALID_POSITION ) {
mCircleDrawable = (GalleryCircleDrawable) view.getTag();
}
}
if ( type == VALID_POSITION && mCircleDrawable != null ) {
int size = (Integer) getItem( position );
float value = (float) size / mBiggest;
mCircleDrawable.update( value, 0 );
}
view.setSelected( position == mSelectedSizePosition );
return view;
}
}
/**
* The Class GalleryColorAdapter.
*/
class GalleryColorAdapter extends BaseAdapter {
private static final int VALID_POSITION = 0;
private static final int INVALID_POSITION = 1;
/** The colors. */
private int[] colors;
/** The m layout inflater. */
LayoutInflater mLayoutInflater;
/** The m res. */
Resources mRes;
/**
* Instantiates a new gallery color adapter.
*
* @param context
* the context
* @param values
* the values
*/
public GalleryColorAdapter( Context context, int[] values ) {
mLayoutInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
colors = values;
mRes = getContext().getBaseContext().getResources();
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return colors.length;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem( int position ) {
return colors[position];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return 0;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType( int position ) {
final boolean valid = position >= 0 && position < getCount();
return valid ? VALID_POSITION : INVALID_POSITION;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@SuppressWarnings("deprecation")
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
ImageView mask = null;
View rubber = null;
View view;
final int type = getItemViewType( position );
if ( convertView == null ) {
if ( type == VALID_POSITION ) {
view = mLayoutInflater.inflate( R.layout.feather_color_button, mGalleryColor, false );
Drawable unselectedBackground = new OverlayGalleryCheckboxDrawable( mRes, false, null, 1.0f, 20 );
Drawable selectedBackground = new OverlayGalleryCheckboxDrawable( mRes, true, null, 1.0f, 20 );
StateListDrawable st = new StateListDrawable();
st.addState( new int[] { -attr.state_selected }, unselectedBackground );
st.addState( new int[] { attr.state_selected }, selectedBackground );
rubber = view.findViewById( R.id.rubber );
mask = (ImageView) view.findViewById( R.id.color_mask );
view.setBackgroundDrawable( st );
} else {
// use the blank view
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGalleryColor, false );
Drawable unselectedBackground = new DefaultGalleryCheckboxDrawable( mRes, false );
view.setBackgroundDrawable( unselectedBackground );
}
} else {
view = convertView;
if ( type == VALID_POSITION ) {
rubber = view.findViewById( R.id.rubber );
mask = (ImageView) view.findViewById( R.id.color_mask );
}
}
if ( type == VALID_POSITION ) {
final int color = (Integer) getItem( position );
final boolean is_eraser = position == 0 || position == getCount() - 1;
view.setSelected( position == mSelectedColorPosition );
if ( !is_eraser ) {
LayerDrawable layer = (LayerDrawable) mask.getDrawable();
GradientDrawable shape = (GradientDrawable) layer.findDrawableByLayerId( R.id.masked );
shape.setColor( color );
mask.setVisibility( View.VISIBLE );
rubber.setVisibility( View.GONE );
} else {
mask.setVisibility( View.GONE );
rubber.setVisibility( View.VISIBLE );
}
}
return view;
}
}
@Override
public void onStart() {
final float scale = mImageView.getScale();
mCurrentOperation = new MoaGraphicsOperationParameter( mBlur, ( (float) mSize / scale ) / mWidth, mColor,
getSelectedTool() == DrawinTool.Erase ? 1 : 0 );
}
@Override
public void onMoveTo( float x, float y ) {
mCurrentOperation.addCommand( new MoaGraphicsCommandParameter( MoaGraphicsCommandParameter.COMMAND_MOVETO, x / mWidth, y
/ mHeight ) );
}
@Override
public void onLineTo( float x, float y ) {
mCurrentOperation.addCommand( new MoaGraphicsCommandParameter( MoaGraphicsCommandParameter.COMMAND_LINETO, x / mWidth, y
/ mHeight ) );
}
@Override
public void onQuadTo( float x, float y, float x1, float y1 ) {
mCurrentOperation.addCommand( new MoaGraphicsCommandParameter( MoaGraphicsCommandParameter.COMMAND_QUADTO, x / mWidth, y
/ mHeight, x1 / mWidth, y1 / mHeight ) );
}
@Override
public void onEnd() {
mOperations.add( mCurrentOperation );
}
}
| Java |
package com.aviary.android.feather.effects;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import android.R.attr;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable;
import com.aviary.android.feather.graphics.OverlayGalleryCheckboxDrawable;
import com.aviary.android.feather.library.graphics.drawable.EditableDrawable;
import com.aviary.android.feather.library.graphics.drawable.TextDrawable;
import com.aviary.android.feather.library.moa.MoaAction;
import com.aviary.android.feather.library.moa.MoaActionFactory;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.moa.MoaColorParameter;
import com.aviary.android.feather.library.moa.MoaPointParameter;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.MatrixUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.AdapterView;
import com.aviary.android.feather.widget.DrawableHighlightView;
import com.aviary.android.feather.widget.Gallery;
import com.aviary.android.feather.widget.Gallery.OnItemsScrollListener;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener;
public class TextPanel extends AbstractContentPanel implements OnDrawableEventListener, OnEditorActionListener {
abstract class MyTextWatcher implements TextWatcher {
public DrawableHighlightView view;
}
Gallery mGallery;
View mSelected;
int mSelectedPosition;
/** The available text colors. */
int[] mColors;
/** The available text stroke colors. */
int[] mStrokeColors;
/** The current selected color. */
private int mColor = 0;
/** The current selected stroke color. */
private int mStrokeColor = 0;
/** The minimum text size. */
private int minTextSize = 16;
/** The default text size. */
private int defaultTextSize = 16;
/** The text padding. */
private int textPadding = 10;
/** The drawing canvas. */
private Canvas mCanvas;
/** The android input manager. */
private InputMethodManager mInputManager;
/** The current edit text. */
private EditText mEditText;
private ConfigService config;
/** The m highlight stroke color down. */
private int mHighlightEllipse, mHighlightStrokeWidth;
private ColorStateList mHighlightFillColorStateList, mHighlightStrokeColorStateList;
/** The m edit text watcher. */
private final MyTextWatcher mEditTextWatcher = new MyTextWatcher() {
@Override
public void afterTextChanged( final Editable s ) {
mLogger.info( "afterTextChanged" );
}
@Override
public void beforeTextChanged( final CharSequence s, final int start, final int count, final int after ) {
mLogger.info( "beforeTextChanged" );
}
@Override
public void onTextChanged( final CharSequence s, final int start, final int before, final int count ) {
if ( ( view != null ) && ( view.getContent() instanceof EditableDrawable ) ) {
final EditableDrawable editable = (EditableDrawable) view.getContent();
if ( !editable.isEditing() ) return;
editable.setText( s.toString() );
view.forceUpdate();
}
}
};
/**
* Instantiates a new text panel.
*
* @param context
* the context
*/
public TextPanel( final EffectContext context ) {
super( context );
}
/**
* Begin edit and open the android soft keyboard if available
*
* @param view
* the view
*/
private void beginEdit( final DrawableHighlightView view ) {
if( null != view ){
view.setFocused( true );
}
mEditTextWatcher.view = null;
mEditText.removeTextChangedListener( mEditTextWatcher );
mEditText.setOnKeyListener( null );
final EditableDrawable editable = (EditableDrawable) view.getContent();
final String oldText = editable.isTextHint() ? "" : (String) editable.getText();
mEditText.setText( oldText );
mEditText.setSelection( mEditText.length() );
mEditText.setImeOptions( EditorInfo.IME_ACTION_DONE );
mEditText.requestFocusFromTouch();
// mInputManager.showSoftInput( mEditText, InputMethodManager.SHOW_IMPLICIT );
mInputManager.toggleSoftInput( InputMethodManager.SHOW_FORCED, 0 );
mEditTextWatcher.view = view;
mEditText.setOnEditorActionListener( this );
mEditText.addTextChangedListener( mEditTextWatcher );
mEditText.setOnKeyListener( new OnKeyListener() {
@Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
mLogger.log( "onKey: " + event );
if ( keyCode == KeyEvent.KEYCODE_DEL || keyCode == KeyEvent.KEYCODE_BACK ) {
if ( editable.isTextHint() && editable.isEditing() ) {
editable.setText( "" );
view.forceUpdate();
}
}
return false;
}
} );
}
/**
* Creates the and configure preview.
*/
private void createAndConfigurePreview() {
if ( ( mPreview != null ) && !mPreview.isRecycled() ) {
mPreview.recycle();
mPreview = null;
}
mPreview = BitmapUtils.copy( mBitmap, mBitmap.getConfig() );
mCanvas = new Canvas( mPreview );
}
/**
* End edit text and closes the android keyboard
*
* @param view
* the view
*/
private void endEdit( final DrawableHighlightView view ) {
if( null != view ){
view.setFocused( false );
view.forceUpdate();
}
mEditTextWatcher.view = null;
mEditText.removeTextChangedListener( mEditTextWatcher );
mEditText.setOnKeyListener( null );
if ( mInputManager.isActive( mEditText ) ) mInputManager.hideSoftInputFromWindow( mEditText.getWindowToken(), 0 );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( final LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_text_content, null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( final LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_text_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#getIsChanged()
*/
@Override
public boolean getIsChanged() {
return super.getIsChanged() || ( ( (ImageViewDrawableOverlay) mImageView ).getHighlightCount() > 0 );
}
/**
* Add a new editable text on the screen.
*/
private void onAddNewText() {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getHighlightCount() > 0 ) onApplyCurrent( image.getHighlightViewAt( 0 ) );
final TextDrawable text = new TextDrawable( "", defaultTextSize );
text.setTextColor( mColor );
text.setTextHint( getContext().getBaseContext().getString( R.string.enter_text_here ) );
final DrawableHighlightView hv = new DrawableHighlightView( mImageView, text );
final Matrix mImageMatrix = mImageView.getImageViewMatrix();
final int width = mImageView.getWidth();
final int height = mImageView.getHeight();
final int imageSize = Math.max( width, height );
// width/height of the sticker
int cropWidth = text.getIntrinsicWidth();
int cropHeight = text.getIntrinsicHeight();
final int cropSize = Math.max( cropWidth, cropHeight );
if ( cropSize > imageSize ) {
cropWidth = width / 2;
cropHeight = height / 2;
}
final int x = ( width - cropWidth ) / 2;
final int y = ( height - cropHeight ) / 2;
final Matrix matrix = new Matrix( mImageMatrix );
matrix.invert( matrix );
final float[] pts = new float[] { x, y, x + cropWidth, y + cropHeight };
MatrixUtils.mapPoints( matrix, pts );
final RectF cropRect = new RectF( pts[0], pts[1], pts[2], pts[3] );
final Rect imageRect = new Rect( 0, 0, width, height );
hv.setRotateAndScale( true );
hv.showDelete( false );
hv.setup( mImageMatrix, imageRect, cropRect, false );
hv.drawOutlineFill( true );
hv.drawOutlineStroke( true );
hv.setPadding( textPadding );
hv.setMinSize( minTextSize );
hv.setOutlineEllipse( mHighlightEllipse );
hv.setOutlineFillColor( mHighlightFillColorStateList );
hv.setOutlineStrokeColor( mHighlightStrokeColorStateList );
Paint stroke = hv.getOutlineStrokePaint();
stroke.setStrokeWidth( mHighlightStrokeWidth );
image.addHighlightView( hv );
// image.setSelectedHighlightView( hv );
onClick( hv );
}
/**
* apply the current text and flatten it over the image.
*/
private MoaActionList onApplyCurrent() {
final MoaActionList nullActions = MoaActionFactory.actionList();
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getHighlightCount() < 1 ) return nullActions;
final DrawableHighlightView hv = ( (ImageViewDrawableOverlay) mImageView ).getHighlightViewAt( 0 );
if ( hv != null ) {
if ( hv.getContent() instanceof EditableDrawable ) {
EditableDrawable editable = (EditableDrawable) hv.getContent();
if ( editable != null ) {
if ( editable.isTextHint() ) {
setIsChanged( false );
return nullActions;
}
}
}
return onApplyCurrent( hv );
}
return nullActions;
}
/**
* Flatten the view on the current image
*
* @param hv
* the hv
*/
private MoaActionList onApplyCurrent( final DrawableHighlightView hv ) {
MoaActionList actionList = MoaActionFactory.actionList();
if ( hv != null ) {
setIsChanged( true );
final RectF cropRect = hv.getCropRectF();
final Rect rect = new Rect( (int) cropRect.left, (int) cropRect.top, (int) cropRect.right, (int) cropRect.bottom );
final Matrix rotateMatrix = hv.getCropRotationMatrix();
final int w = mBitmap.getWidth();
final int h = mBitmap.getHeight();
final float left = cropRect.left / w;
final float top = cropRect.top / h;
final float right = cropRect.right / w;
final float bottom = cropRect.bottom / h;
final Matrix matrix = new Matrix( mImageView.getImageMatrix() );
if ( !matrix.invert( matrix ) ) mLogger.error( "unable to invert matrix" );
EditableDrawable editable = (EditableDrawable) hv.getContent();
editable.endEdit();
mImageView.invalidate();
MoaAction action = MoaActionFactory.action( "addtext" );
action.setValue( "text", (String) editable.getText() );
action.setValue( "fillcolor", new MoaColorParameter( mColor ) );
action.setValue( "outlinecolor", new MoaColorParameter( mStrokeColor ) );
action.setValue( "rotation", hv.getRotation() );
action.setValue( "topleft", new MoaPointParameter( left, top ) );
action.setValue( "bottomright", new MoaPointParameter( right, bottom ) );
actionList.add( action );
final int saveCount = mCanvas.save( Canvas.MATRIX_SAVE_FLAG );
mCanvas.concat( rotateMatrix );
hv.getContent().setBounds( rect );
hv.getContent().draw( mCanvas );
mCanvas.restoreToCount( saveCount );
mImageView.invalidate();
onClearCurrent( hv );
}
onPreviewChanged( mPreview, false );
return actionList;
}
/**
* Removes the current text
*
* @param hv
* the hv
*/
private void onClearCurrent( final DrawableHighlightView hv ) {
hv.setOnDeleteClickListener( null );
( (ImageViewDrawableOverlay) mImageView ).removeHightlightView( hv );
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onClick(com.aviary.android.feather.widget
* .DrawableHighlightView)
*/
@Override
public void onClick( final DrawableHighlightView view ) {
if ( view != null ) if ( view.getContent() instanceof EditableDrawable ) {
if( !view.getFocused() ){
beginEdit( view );
}
/*
final EditableDrawable text = (EditableDrawable) view.getContent();
if ( !text.isEditing() ) {
text.beginEdit();
beginEdit( view );
}
*/
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( final Bitmap bitmap ) {
super.onCreate( bitmap );
config = getContext().getService( ConfigService.class );
mColors = config.getIntArray( R.array.feather_text_fill_colors );
mStrokeColors = config.getIntArray( R.array.feather_text_stroke_colors );
mSelectedPosition = config.getInteger( R.integer.feather_text_selected_color );
mColor = mColors[mSelectedPosition];
mStrokeColor = mStrokeColors[mSelectedPosition];
mGallery = (Gallery) getOptionView().findViewById( R.id.gallery );
mGallery.setCallbackDuringFling( false );
mGallery.setSpacing( 0 );
mGallery.setAdapter( new GalleryAdapter( getContext().getBaseContext(), mColors ) );
mGallery.setSelection( mSelectedPosition, false, true );
mGallery.setOnItemsScrollListener( new OnItemsScrollListener() {
@Override
public void onScrollFinished( AdapterView<?> parent, View view, int position, long id ) {
updateSelection( view, position );
final int color = mColors[position];
mColor = color;
mStrokeColor = mStrokeColors[position];
updateCurrentHighlightColor();
updateColorButtonBitmap();
}
@Override
public void onScrollStarted( AdapterView<?> parent, View view, int position, long id ) {
// TODO Auto-generated method stub
}
@Override
public void onScroll( AdapterView<?> parent, View view, int position, long id ) {
// TODO Auto-generated method stub
}
} );
mEditText = (EditText) getContentView().findViewById( R.id.invisible_text );
mImageView = (ImageViewTouch) getContentView().findViewById( R.id.overlay );
mImageView.setDoubleTapEnabled( false );
createAndConfigurePreview();
updateColorButtonBitmap();
mImageView.setImageBitmap( mPreview, true, getContext().getCurrentImageViewMatrix(), UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
disableHapticIsNecessary( mGallery );
mHighlightFillColorStateList = config.getColorStateList( R.color.feather_effect_text_color_fill_selector );
mHighlightStrokeColorStateList = config.getColorStateList( R.color.feather_effect_text_color_stroke_selector );
mHighlightEllipse = config.getInteger( R.integer.feather_text_highlight_ellipse );
mHighlightStrokeWidth = config.getInteger( R.integer.feather_text_highlight_stroke_width );
minTextSize = config.getDimensionPixelSize( R.dimen.feather_text_drawable_min_size );
defaultTextSize = config.getDimensionPixelSize( R.dimen.feather_text_default_size );
defaultTextSize = Math.max( minTextSize, defaultTextSize );
textPadding = config.getInteger( R.integer.feather_text_padding );
( (ImageViewDrawableOverlay) mImageView ).setOnDrawableEventListener( this );
( (ImageViewDrawableOverlay) mImageView ).setScaleWithContent( true );
( (ImageViewDrawableOverlay) mImageView ).setForceSingleSelection( false );
mInputManager = (InputMethodManager) getContext().getBaseContext().getSystemService( Context.INPUT_METHOD_SERVICE );
mImageView.requestLayout();
updateSelection( (View) mGallery.getSelectedView(), mGallery.getSelectedItemPosition() );
contentReady();
onAddNewText();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
( (ImageViewDrawableOverlay) mImageView ).setOnDrawableEventListener( null );
endEdit( null );
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
mCanvas = null;
mInputManager = null;
super.onDestroy();
}
/**
* Update selection.
*
* @param newSelection
* the new selection
* @param position
* the position
*/
protected void updateSelection( View newSelection, int position ) {
if ( mSelected != null ) {
mSelected.setSelected( false );
}
mSelected = newSelection;
mSelectedPosition = position;
if ( mSelected != null ) {
mSelected = newSelection;
mSelected.setSelected( true );
}
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onDown(com.aviary.android.feather.widget
* .DrawableHighlightView)
*/
@Override
public void onDown( final DrawableHighlightView view ) {}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onFocusChange(com.aviary.android.feather
* .widget.DrawableHighlightView, com.aviary.android.feather.widget.DrawableHighlightView)
*/
@Override
public void onFocusChange( final DrawableHighlightView newFocus, final DrawableHighlightView oldFocus ) {
EditableDrawable text;
if ( oldFocus != null ) if ( oldFocus.getContent() instanceof EditableDrawable ) {
text = (EditableDrawable) oldFocus.getContent();
if ( text.isEditing() ) {
//text.endEdit();
endEdit( oldFocus );
}
// if ( !oldFocus.equals( newFocus ) )
// if ( text.getText().length() == 0 )
// onClearCurrent( oldFocus );
}
if ( newFocus != null ) if ( newFocus.getContent() instanceof EditableDrawable ) {
text = (EditableDrawable) newFocus.getContent();
mColor = text.getTextColor();
mStrokeColor = text.getTextStrokeColor();
updateColorButtonBitmap();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
MoaActionList actions = onApplyCurrent();
super.onGenerateResult( actions );
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageViewDrawableOverlay.OnDrawableEventListener#onMove(com.aviary.android.feather.widget
* .DrawableHighlightView)
*/
@Override
public void onMove( final DrawableHighlightView view ) {
if ( view.getContent() instanceof EditableDrawable ) if ( ( (EditableDrawable) view.getContent() ).isEditing() ) {
//( (EditableDrawable) view.getContent() ).endEdit();
endEdit( view );
}
}
/**
* Update color button bitmap.
*/
private void updateColorButtonBitmap() {}
/**
* Update current highlight color.
*/
private void updateCurrentHighlightColor() {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getSelectedHighlightView() != null ) {
final DrawableHighlightView hv = image.getSelectedHighlightView();
if ( hv.getContent() instanceof EditableDrawable ) {
( (EditableDrawable) hv.getContent() ).setTextColor( mColor );
( (EditableDrawable) hv.getContent() ).setTextStrokeColor( mStrokeColor );
mImageView.postInvalidate();
}
}
}
/*
* (non-Javadoc)
*
* @see android.widget.TextView.OnEditorActionListener#onEditorAction(android.widget.TextView, int, android.view.KeyEvent)
*/
@Override
public boolean onEditorAction( TextView v, int actionId, KeyEvent event ) {
if ( mEditText != null ) {
if ( mEditText.equals( v ) ) {
if ( actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED ) {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getSelectedHighlightView() != null ) {
DrawableHighlightView d = image.getSelectedHighlightView();
if ( d.getContent() instanceof EditableDrawable ) {
EditableDrawable text = (EditableDrawable) d.getContent();
if ( text.isEditing() ) {
//text.endEdit();
endEdit( d );
}
}
}
}
}
}
return false;
}
class GalleryAdapter extends BaseAdapter {
private final int VALID_POSITION = 0;
private final int INVALID_POSITION = 1;
private int[] colors;
Resources mRes;
LayoutInflater mLayoutInflater;
/**
* Instantiates a new gallery adapter.
*
* @param context
* the context
* @param values
* the values
*/
public GalleryAdapter( Context context, int[] values ) {
mLayoutInflater = UIUtils.getLayoutInflater();
colors = values;
mRes = getContext().getBaseContext().getResources();
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return colors.length;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem( int position ) {
return colors[position];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return 0;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType( int position ) {
final boolean valid = position >= 0 && position < getCount();
return valid ? VALID_POSITION : INVALID_POSITION;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@SuppressWarnings("deprecation")
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
final int type = getItemViewType( position );
View view;
if ( convertView == null ) {
if ( type == VALID_POSITION ) {
view = mLayoutInflater.inflate( R.layout.feather_color_button, mGallery, false );
Drawable unselectedBackground = new OverlayGalleryCheckboxDrawable( mRes, false, null, 1.0f, 20 );
Drawable selectedBackground = new OverlayGalleryCheckboxDrawable( mRes, true, null, 1.0f, 20 );
StateListDrawable st = new StateListDrawable();
st.addState( new int[] { -attr.state_selected }, unselectedBackground );
st.addState( new int[] { attr.state_selected }, selectedBackground );
view.setBackgroundDrawable( st );
} else {
// use the blank view
view = mLayoutInflater.inflate( R.layout.feather_default_blank_gallery_item, mGallery, false );
Drawable unselectedBackground = new DefaultGalleryCheckboxDrawable( mRes, false );
view.setBackgroundDrawable( unselectedBackground );
}
} else {
view = convertView;
}
if ( type == VALID_POSITION ) {
ImageView masked = (ImageView) view.findViewById( R.id.color_mask );
final int color = (Integer) getItem( position );
LayerDrawable layer = (LayerDrawable) masked.getDrawable();
GradientDrawable shape = (GradientDrawable) layer.findDrawableByLayerId( R.id.masked );
shape.setColor( color );
view.setSelected( position == mSelectedPosition );
}
return view;
}
}
}
| Java |
package com.aviary.android.feather.effects;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.R;
import com.aviary.android.feather.async_tasks.AsyncImageManager;
import com.aviary.android.feather.async_tasks.AsyncImageManager.OnImageLoadListener;
import com.aviary.android.feather.graphics.RepeatableHorizontalDrawable;
import com.aviary.android.feather.library.content.FeatherIntent;
import com.aviary.android.feather.library.content.FeatherIntent.PluginType;
import com.aviary.android.feather.library.filters.EffectFilter;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.filters.INativeFiler;
import com.aviary.android.feather.library.filters.NativeFilter;
import com.aviary.android.feather.library.graphics.drawable.FakeBitmapDrawable;
import com.aviary.android.feather.library.moa.Moa;
import com.aviary.android.feather.library.moa.MoaAction;
import com.aviary.android.feather.library.moa.MoaActionFactory;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.moa.MoaColorParameter;
import com.aviary.android.feather.library.moa.MoaResult;
import com.aviary.android.feather.library.plugins.FeatherExternalPack;
import com.aviary.android.feather.library.plugins.FeatherInternalPack;
import com.aviary.android.feather.library.plugins.FeatherPack;
import com.aviary.android.feather.library.plugins.PluginManager;
import com.aviary.android.feather.library.plugins.PluginManager.InternalPlugin;
import com.aviary.android.feather.library.plugins.UpdateType;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.services.PluginService;
import com.aviary.android.feather.library.services.PluginService.OnUpdateListener;
import com.aviary.android.feather.library.services.PluginService.PluginError;
import com.aviary.android.feather.library.services.PreferenceService;
import com.aviary.android.feather.library.tracking.Tracker;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.library.utils.UserTask;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.ArrayAdapterExtended;
import com.aviary.android.feather.widget.EffectThumbLayout;
import com.aviary.android.feather.widget.HorizontalFixedListView;
import com.aviary.android.feather.widget.ImageSwitcher;
import com.aviary.android.feather.widget.SwipeView;
import com.aviary.android.feather.widget.SwipeView.OnSwipeListener;
public class EffectsPanel extends AbstractContentPanel implements ViewFactory, OnUpdateListener, OnSwipeListener,
OnImageLoadListener {
/** Plugin type handled in this panel */
private final int mType;
/** thumbnail listview */
private HorizontalFixedListView mHList;
/** Panel is rendering. */
private volatile Boolean mIsRendering = false;
private Boolean mIsAnimating;
/** The current rendering task. */
private RenderTask mCurrentTask;
/** The small preview used for fast rendering. */
private Bitmap mSmallPreview;
private static final int PREVIEW_SCALE_FACTOR = 4;
/** enable/disable fast preview. */
private boolean mEnableFastPreview = false;
private PluginService mPluginService;
private PreferenceService mPrefService;
/** The main image switcher. */
private ImageSwitcher mImageSwitcher;
private boolean mExternalPacksEnabled = true;
/**
* A reference to the effect applied
*/
private MoaActionList mActions = null;
/**
* create a reference to the update alert dialog. This to prevent multiple alert messages
*/
private AlertDialog mUpdateDialog;
/** default width of each effect thumbnail */
private int mFilterCellWidth = 80;
private List<String> mInstalledPackages;
// thumbnail cache manager
private AsyncImageManager mImageManager;
// thumbnail for effects
private Bitmap mThumbBitmap;
// current selected thumbnail
private View mSelectedEffectView = null;
// current selected position
private int mSelectedPosition = 1;
// first position allowed in selection
private static int FIRST_POSITION = 1;
@SuppressWarnings("unused")
private SwipeView mSwipeView;
/** the effects list adapter */
private EffectsAdapter mListAdapter;
private int mAvailablePacks = 0;
private boolean mEnableEffectAnimation = false;
private Bitmap updateArrowBitmap;
// thumbnail properties
private static int mRoundedBordersPixelSize = 16;
private static int mShadowRadiusPixelSize = 4;
private static int mShadowOffsetPixelSize = 2;
private static int mRoundedBordersPaddingPixelSize = 5;
private static int mRoundedBordersStrokePixelSize = 3;
// don't display the error dialog more than once
private static boolean mUpdateErrorHandled = false;
public EffectsPanel( EffectContext context, int type ) {
super( context );
mType = type;
}
@SuppressWarnings("deprecation")
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
mImageManager = new AsyncImageManager();
mPluginService = getContext().getService( PluginService.class );
mPrefService = getContext().getService( PreferenceService.class );
mExternalPacksEnabled = Constants.getValueFromIntent( Constants.EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS, true );
mSelectedPosition = mExternalPacksEnabled ? 1 : 0;
FIRST_POSITION = mExternalPacksEnabled ? 1 : 0;
mHList = (HorizontalFixedListView) getOptionView().findViewById( R.id.list );
mHList.setOverScrollMode( View.OVER_SCROLL_ALWAYS );
mImageSwitcher = (ImageSwitcher) getContentView().findViewById( R.id.switcher );
mImageSwitcher.setSwitchEnabled( mEnableFastPreview );
mImageSwitcher.setFactory( this );
mSwipeView = (SwipeView) getContentView().findViewById( R.id.swipeview );
mPreview = BitmapUtils.copy( mBitmap, Bitmap.Config.ARGB_8888 );
// setup the main imageview based on the current configuration
if ( mEnableFastPreview ) {
try {
mSmallPreview = Bitmap.createBitmap( mBitmap.getWidth() / PREVIEW_SCALE_FACTOR, mBitmap.getHeight()
/ PREVIEW_SCALE_FACTOR, Config.ARGB_8888 );
mImageSwitcher.setImageBitmap( mBitmap, true, null, Float.MAX_VALUE );
mImageSwitcher.setInAnimation( AnimationUtils.loadAnimation( getContext().getBaseContext(), android.R.anim.fade_in ) );
mImageSwitcher.setOutAnimation( AnimationUtils.loadAnimation( getContext().getBaseContext(), android.R.anim.fade_out ) );
} catch ( OutOfMemoryError e ) {
mEnableFastPreview = false;
}
} else {
mImageSwitcher.setImageBitmap( mBitmap, true, getContext().getCurrentImageViewMatrix(), Float.MAX_VALUE );
}
mImageSwitcher.setAnimateFirstView( false );
mHList.setOnItemClickListener( new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick( android.widget.AdapterView<?> parent, View view, int position, long id ) {
if ( !view.isSelected() && isActive() ) {
int viewType = mHList.getAdapter().getItemViewType( position );
if ( viewType == EffectsAdapter.TYPE_NORMAL ) {
EffectPack item = (EffectPack) mHList.getAdapter().getItem( position );
if ( item.mStatus == PluginError.NoError ) {
setSelectedEffect( view, position );
} else {
showUpdateAlert( item.mPackageName, item.mStatus, true );
}
} else if ( viewType == EffectsAdapter.TYPE_GET_MORE_FIRST || viewType == EffectsAdapter.TYPE_GET_MORE_LAST ) {
EffectsPanel.this.getContext().searchPlugin( mType );
}
}
}
} );
View content = getOptionView().findViewById( R.id.background );
content.setBackgroundDrawable( RepeatableHorizontalDrawable.createFromView( content ) );
try {
updateArrowBitmap = BitmapFactory.decodeResource( getContext().getBaseContext().getResources(),
R.drawable.feather_update_arrow );
} catch ( Throwable t ) {}
mEnableEffectAnimation = Constants.ANDROID_SDK > android.os.Build.VERSION_CODES.GINGERBREAD && SystemUtils.getCpuMhz() > 800;
}
private void showUpdateAlert( final CharSequence packageName, final PluginError error, boolean fromUseClick ) {
if ( error != PluginError.NoError ) {
String errorString;
if( fromUseClick )
errorString = getError( error );
else
errorString = getErrors( error );
if ( error == PluginError.PluginTooOldError ) {
OnClickListener yesListener = new OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
getContext().downloadPlugin( (String) packageName, mType );
}
};
onGenericError( errorString, R.string.feather_update, yesListener, android.R.string.cancel, null );
} else if ( error == PluginError.PluginTooNewError ) {
OnClickListener yesListener = new OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
String pname = getContext().getBaseContext().getPackageName();
getContext().downloadPlugin( pname, mType );
}
};
onGenericError( errorString, R.string.feather_update, yesListener, android.R.string.cancel, null );
} else {
onGenericError( errorString );
}
return;
}
}
/**
* Create a popup alert dialog when multiple plugins need to be updated
*
* @param error
*/
private void showUpdateAlertMultiplePlugins( final PluginError error, boolean fromUserClick ) {
if ( error != PluginError.NoError ) {
final String errorString = getErrors( error );
if ( error == PluginError.PluginTooOldError ) {
OnClickListener yesListener = new OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
getContext().searchPlugin( mType );
}
};
onGenericError( errorString, R.string.feather_update, yesListener, android.R.string.cancel, null );
} else if ( error == PluginError.PluginTooNewError ) {
OnClickListener yesListener = new OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
String pname = getContext().getBaseContext().getPackageName();
getContext().downloadPlugin( pname, mType );
}
};
onGenericError( errorString, R.string.feather_update, yesListener, android.R.string.cancel, null );
} else {
onGenericError( errorString );
}
}
}
/**
*
* @param set
*/
private void showUpdateAlertMultipleItems( final String pkgname, Set<PluginError> set ) {
if( null != set ) {
final String errorString = getContext().getBaseContext().getResources().getString( R.string.feather_effects_error_update_multiple );
OnClickListener yesListener = new OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
getContext().searchOrDownloadPlugin( pkgname, mType, true );
}
};
onGenericError( errorString, R.string.feather_update, yesListener, android.R.string.cancel, null );
}
}
protected String getError( PluginError error ) {
int resId = R.string.feather_effects_error_loading_pack;
switch ( error ) {
case UnknownError:
resId = R.string.feather_effects_unknown_error;
break;
case PluginTooOldError:
resId = R.string.feather_effects_error_update_pack;
break;
case PluginTooNewError:
resId = R.string.feather_effects_error_update_editor;
break;
case PluginNotLoadedError:
break;
case PluginLoadError:
break;
case MethodNotFoundError:
break;
default:
break;
}
return getContext().getBaseContext().getString( resId );
}
protected String getErrors( PluginError error ) {
int resId = R.string.feather_effects_error_loading_packs;
switch ( error ) {
case UnknownError:
resId = R.string.feather_effects_unknown_errors;
break;
case PluginTooOldError:
resId = R.string.feather_effects_error_update_packs;
break;
case PluginTooNewError:
resId = R.string.feather_effects_error_update_editors;
break;
case PluginNotLoadedError:
case PluginLoadError:
case MethodNotFoundError:
default:
break;
}
return getContext().getBaseContext().getString( resId );
}
@Override
public void onActivate() {
super.onActivate();
ConfigService config = getContext().getService( ConfigService.class );
mFilterCellWidth = config.getDimensionPixelSize( R.dimen.feather_effects_cell_width );
mFilterCellWidth = (int) ( ( Constants.SCREEN_WIDTH / UIUtils.getScreenOptimalColumnsPixels( mFilterCellWidth ) ) );
mThumbBitmap = generateThumbnail( mBitmap, (int) ( mFilterCellWidth * 0.9 ), (int) ( mFilterCellWidth * 0.9 ) );
mInstalledPackages = Collections.synchronizedList( new ArrayList<String>() );
List<EffectPack> data = Collections.synchronizedList( new ArrayList<EffectPack>() );
mListAdapter = new EffectsAdapter( getContext().getBaseContext(), R.layout.feather_effect_thumb,
R.layout.feather_getmore_thumb, R.layout.feather_getmore_thumb_inverted, data );
mHList.setAdapter( mListAdapter );
mLogger.info( "[plugin] onActivate" );
// register for plugins updates
mPluginService.registerOnUpdateListener( this );
updateInstalledPacks( true );
// register for swipe gestures
// mSwipeView.setOnSwipeListener( this );
mRoundedBordersPixelSize = config.getDimensionPixelSize( R.dimen.feather_effects_panel_thumb_rounded_border );
mRoundedBordersPaddingPixelSize = config.getDimensionPixelSize( R.dimen.feather_effects_panel_thumb_padding );
mShadowOffsetPixelSize = config.getDimensionPixelSize( R.dimen.feather_effects_panel_thumb_shadow_offset );
mShadowRadiusPixelSize = config.getDimensionPixelSize( R.dimen.feather_effects_panel_thumb_shadow_radius );
mRoundedBordersStrokePixelSize = config.getDimensionPixelSize( R.dimen.feather_effects_panel_thumb_stroke_size );
mHList.setEdgeHeight( config.getDimensionPixelSize( R.dimen.feather_effects_panel_top_bg_height ) );
mHList.setEdgeGravityY( Gravity.BOTTOM );
mImageManager.setOnLoadCompleteListener( this );
getContentView().setVisibility( View.VISIBLE );
contentReady();
}
@Override
public void onDeactivate() {
onProgressEnd();
mPluginService.removeOnUpdateListener( this );
mImageManager.setOnLoadCompleteListener( null );
// mSwipeView.setOnSwipeListener( null );
super.onDeactivate();
}
@Override
public void onConfigurationChanged( Configuration newConfig, Configuration oldConfig ) {
mImageManager.clearCache();
super.onConfigurationChanged( newConfig, oldConfig );
}
@Override
protected void onDispose() {
if ( null != mImageManager ) {
mImageManager.clearCache();
mImageManager.shutDownNow();
}
if ( mThumbBitmap != null && !mThumbBitmap.isRecycled() ) {
mThumbBitmap.recycle();
}
mThumbBitmap = null;
if ( mSmallPreview != null && !mSmallPreview.isRecycled() ) {
mSmallPreview.recycle();
}
mSmallPreview = null;
if ( null != updateArrowBitmap ) {
updateArrowBitmap.recycle();
}
updateArrowBitmap = null;
super.onDispose();
}
@Override
protected void onGenerateResult() {
if ( mIsRendering ) {
GenerateResultTask task = new GenerateResultTask();
task.execute();
} else {
onComplete( mPreview, mActions );
}
}
@Override
protected void onProgressEnd() {
if ( !mEnableFastPreview ) {
super.onProgressModalEnd();
} else {
super.onProgressEnd();
}
}
@Override
protected void onProgressStart() {
if ( !mEnableFastPreview ) {
super.onProgressModalStart();
} else {
super.onProgressStart();
}
}
@Override
public boolean onBackPressed() {
if ( backHandled() ) return true;
return super.onBackPressed();
}
@Override
public void onCancelled() {
killCurrentTask();
mIsRendering = false;
super.onCancelled();
}
@Override
public boolean getIsChanged() {
return super.getIsChanged() || mIsRendering == true;
}
@Override
public void onSwipe( boolean leftToRight ) {
// TODO: implement this
}
@Override
public void onUpdate( Bundle delta ) {
if ( isActive() && mExternalPacksEnabled ) {
if ( mUpdateDialog != null && mUpdateDialog.isShowing() ) {
// another update alert is showing, skip new alerts
return;
}
if ( validDelta( delta ) ) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
updateInstalledPacks( true );
}
};
mUpdateDialog = new AlertDialog.Builder( getContext().getBaseContext() ).setMessage( R.string.filter_pack_updated )
.setNeutralButton( android.R.string.ok, listener ).setCancelable( false ).create();
mUpdateDialog.show();
}
}
}
@Override
public void onLoadComplete( final ImageView view, Bitmap bitmap ) {
if( !isActive() ) return;
view.setImageBitmap( bitmap );
if ( null != view && view.getParent() != null ) {
View parent = (View)view.getParent();
if( mEnableEffectAnimation ) {
if( mHList.getScrollX() == 0 ) {
if( parent.getLeft() < mHList.getRight() ){
ScaleAnimation anim = new ScaleAnimation( 0, 1, 0, 1, Animation.RELATIVE_TO_SELF, (float) 0.5, Animation.RELATIVE_TO_SELF, (float) 0.5 );
anim.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
view.setVisibility( View.VISIBLE );
}
@Override
public void onAnimationRepeat( Animation animation ) {
}
@Override
public void onAnimationEnd( Animation animation ) {
}
} );
anim.setDuration( 100 );
anim.setStartOffset( mHList.getScreenPositionForView( view ) * 100 );
view.startAnimation( anim );
view.setVisibility( View.INVISIBLE );
return;
}
}
}
view.setVisibility( View.VISIBLE );
}
}
/**
* bundle contains a list of all updates applications. if one meets the criteria ( is a filter apk ) then return true
*
* @param bundle
* the bundle
* @return true if bundle contains a valid filter package
*/
private boolean validDelta( Bundle bundle ) {
if ( null != bundle ) {
if ( bundle.containsKey( "delta" ) ) {
try {
@SuppressWarnings("unchecked")
ArrayList<UpdateType> updates = (ArrayList<UpdateType>) bundle.getSerializable( "delta" );
if ( null != updates ) {
for ( UpdateType update : updates ) {
if ( FeatherIntent.PluginType.isFilter( update.getPluginType() ) ) {
return true;
}
if ( FeatherIntent.ACTION_PLUGIN_REMOVED.equals( update.getAction() ) ) {
// if it's removed check against current listed packs
if ( mInstalledPackages.contains( update.getPackageName() ) ) {
return true;
}
}
}
return false;
}
} catch ( ClassCastException e ) {
return true;
}
}
}
return true;
}
@Override
public View makeView() {
ImageViewTouch view = new ImageViewTouch( getContext().getBaseContext(), null );
view.setBackgroundColor( 0x00000000 );
view.setDoubleTapEnabled( false );
if ( mEnableFastPreview ) {
view.setScrollEnabled( false );
view.setScaleEnabled( false );
}
view.setLayoutParams( new ImageSwitcher.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
return view;
}
@Override
protected View generateContentView( LayoutInflater inflater ) {
mEnableFastPreview = Constants.getFastPreviewEnabled();
return inflater.inflate( R.layout.feather_native_effects_content, null );
}
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_effects_panel, parent, false );
}
@Override
public Matrix getContentDisplayMatrix() {
return null;
}
protected Bitmap generateThumbnail( Bitmap input, final int width, final int height ) {
return ThumbnailUtils.extractThumbnail( input, width, height );
}
/**
* Update the installed plugins
*/
private void updateInstalledPacks( boolean invalidateList ) {
mIsAnimating = true;
// List of installed plugins available on the device
FeatherInternalPack installedPacks[];
FeatherPack availablePacks[];
if ( mExternalPacksEnabled ) {
installedPacks = mPluginService.getInstalled( getContext().getBaseContext(), mType );
availablePacks = mPluginService.getAvailable( mType );
} else {
installedPacks = new FeatherInternalPack[] { FeatherInternalPack.getDefault( getContext().getBaseContext() ) };
availablePacks = new FeatherExternalPack[] {};
}
// List of the available plugins online
mAvailablePacks = availablePacks.length;
// now try to install every plugin...
if ( invalidateList ) {
mListAdapter.clear();
mHList.setVisibility( View.INVISIBLE );
getOptionView().findViewById( R.id.layout_loader ).setVisibility( View.VISIBLE );
}
new PluginInstallTask().execute( installedPacks );
}
private void onEffectListUpdated( List<EffectPack> result, List<EffectPackError> mErrors ) {
// we had errors during installation
if ( null != mErrors && mErrors.size() > 0 ) {
if ( !mUpdateErrorHandled ) {
handleErrors( mErrors );
}
}
if ( mSelectedPosition != FIRST_POSITION ) {
setSelectedEffect( mHList.getItemAt( FIRST_POSITION ), FIRST_POSITION );
}
mHList.setVisibility( View.VISIBLE );
getOptionView().findViewById( R.id.layout_loader ).setVisibility( View.GONE );
}
private void handleErrors( List<EffectPackError> mErrors ) {
if ( mErrors == null || mErrors.size() < 1 ) return;
// first get the total number of errors
HashMap<PluginError, String> hash = new HashMap<PluginError, String>();
for ( EffectPackError item : mErrors ) {
PluginError error = item.mError;
hash.put( error, (String) item.mPackageName );
}
// now manage the different cases
// 1. just one type of error
if ( hash.size() == 1 ) {
// get the first error
EffectPackError item = mErrors.get( 0 );
if ( mErrors.size() == 1 ) {
showUpdateAlert( item.mPackageName, item.mError, false );
} else {
showUpdateAlertMultiplePlugins( item.mError, false );
}
} else {
// 2. here we must handle different errors type
showUpdateAlertMultipleItems( getContext().getBaseContext().getPackageName(), hash.keySet() );
}
mUpdateErrorHandled = true;
}
void setSelectedEffect( View view, int position ) {
String label = "original";
mSelectedPosition = position;
if ( mSelectedEffectView != null && mSelectedEffectView.isSelected() && !mSelectedEffectView.equals( view ) ) {
mSelectedEffectView.setSelected( false );
}
mSelectedEffectView = null;
if ( null != view ) {
mSelectedEffectView = view;
mSelectedEffectView.setSelected( true );
}
if ( mHList.getAdapter() != null ) {
EffectPack item = ( (EffectsAdapter) mHList.getAdapter() ).getItem( position );
if ( null != item && item.mStatus == PluginError.NoError ) {
label = (String) item.getItemAt( position );
renderEffect( label );
}
}
mHList.requestLayout();
}
private void renderEffect( String label ) {
killCurrentTask();
mCurrentTask = new RenderTask( label );
mCurrentTask.execute();
}
boolean killCurrentTask() {
if ( mCurrentTask != null ) {
onProgressEnd();
return mCurrentTask.cancel( true );
}
return false;
}
protected INativeFiler loadNativeFilter( String label ) {
switch ( mType ) {
case FeatherIntent.PluginType.TYPE_FILTER:
EffectFilter filter = (EffectFilter) FilterLoaderFactory.get( Filters.EFFECTS );
filter.setEffectName( label );
return filter;
// case FeatherIntent.PluginType.TYPE_BORDER:
// BorderFilter filter = (BorderFilter) mFilterService.load( Filters.BORDERS );
// filter.setBorderName( label );
// return filter;
default:
return null;
}
}
protected void trackPackage( String packageName ) {
if ( !mPrefService.containsValue( "plugin." + mType + "." + packageName ) ) {
if ( !getContext().getBaseContext().getPackageName().equals( packageName ) ) {
mPrefService.putString( "plugin." + mType + "." + packageName, packageName );
HashMap<String, String> map = new HashMap<String, String>();
if ( mType == FeatherIntent.PluginType.TYPE_FILTER ) {
map.put( "assetType", "effects" );
} else if ( mType == FeatherIntent.PluginType.TYPE_BORDER ) {
map.put( "assetType", "borders" );
} else if ( mType == FeatherIntent.PluginType.TYPE_STICKER ) {
map.put( "assetType", "stickers" );
} else {
map.put( "assetType", "tools" );
}
map.put( "assetID", packageName );
Tracker.recordTag( "content: purchased", map );
}
}
mTrackingAttributes.put( "packName", packageName );
}
boolean backHandled() {
if ( mIsAnimating ) return true;
killCurrentTask();
return false;
}
static class ViewHolder {
TextView text;
ImageView image;
}
class EffectsAdapter extends ArrayAdapterExtended<EffectPack> {
private int mLayoutResId;
private int mAltLayoutResId;
private int mAltLayout2ResId;
private int mCount = -1;
private List<EffectPack> mData;
private LayoutInflater mLayoutInflater;
static final int TYPE_GET_MORE_FIRST = 0;
static final int TYPE_GET_MORE_LAST = 1;
static final int TYPE_NORMAL = 2;
public EffectsAdapter( Context context, int textViewResourceId, int altViewResourceId, int altViewResource2Id,
List<EffectPack> objects ) {
super( context, textViewResourceId, objects );
mLayoutResId = textViewResourceId;
mAltLayoutResId = altViewResourceId;
mAltLayout2ResId = altViewResource2Id;
mData = objects;
mLayoutInflater = UIUtils.getLayoutInflater();
}
@Override
public int getCount() {
if ( mCount == -1 ) {
int total = 0; // first get more
for ( EffectPack pack : mData ) {
if ( null == pack ) {
total++;
continue;
}
pack.setIndex( total );
total += pack.size;
}
// return total;
mCount = total;
}
return mCount;
}
@Override
public void notifyDataSetChanged() {
mCount = -1;
super.notifyDataSetChanged();
}
@Override
public void notifyDataSetAdded() {
mCount = -1;
super.notifyDataSetAdded();
}
@Override
public void notifyDataSetRemoved() {
mCount = -1;
super.notifyDataSetRemoved();
}
@Override
public void notifyDataSetInvalidated() {
mCount = -1;
super.notifyDataSetInvalidated();
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType( int position ) {
if ( !mExternalPacksEnabled ) return TYPE_NORMAL;
EffectPack item = getItem( position );
if ( null == item ) {
if ( position == 0 )
return TYPE_GET_MORE_FIRST;
else
return TYPE_GET_MORE_LAST;
}
return TYPE_NORMAL;
}
@Override
public EffectPack getItem( int position ) {
for ( int i = 0; i < mData.size(); i++ ) {
EffectPack pack = mData.get( i );
if ( null == pack ) continue;
if ( position >= pack.index && position < pack.index + pack.size ) {
return pack;
}
}
return null;
}
@Override
public View getView( final int position, final View convertView, final ViewGroup parent ) {
View view;
ViewHolder holder = null;
int type = getItemViewType( position );
if ( convertView == null ) {
if ( type == TYPE_GET_MORE_FIRST ) {
view = mLayoutInflater.inflate( mAltLayoutResId, parent, false );
} else if ( type == TYPE_GET_MORE_LAST ) {
view = mLayoutInflater.inflate( mAltLayout2ResId, parent, false );
} else {
view = mLayoutInflater.inflate( mLayoutResId, parent, false );
holder = new ViewHolder();
holder.text = (TextView) view.findViewById( R.id.text );
holder.image = (ImageView) view.findViewById( R.id.image );
view.setTag( holder );
}
view.setLayoutParams( new EffectThumbLayout.LayoutParams( mFilterCellWidth, EffectThumbLayout.LayoutParams.MATCH_PARENT ) );
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
if ( type == TYPE_NORMAL ) {
EffectPack item = getItem( position );
holder.text.setText( item.getLabelAt( position ) );
holder.image.setImageBitmap( mThumbBitmap );
final String effectName = (String) item.getItemAt( position );
boolean selected = mSelectedPosition == position;
ThumbnailCallable executor = new ThumbnailCallable( (EffectFilter) loadNativeFilter( effectName ), effectName,
mThumbBitmap, item.mStatus == PluginError.NoError, updateArrowBitmap );
mImageManager.execute( executor, item.index + "/" + effectName, holder.image );
// holder.image.setImageResource( R.drawable.test_thumb );
view.setSelected( selected );
if ( selected ) {
mSelectedEffectView = view;
}
} else {
// get more
TextView totalText = (TextView) view.findViewById( R.id.text01 );
totalText.setText( String.valueOf( mAvailablePacks ) );
( (ViewGroup) totalText.getParent() ).setVisibility( mAvailablePacks > 0 ? View.VISIBLE : View.INVISIBLE );
}
return view;
}
}
/**
* Render the passed effect in a thumbnail
*
* @author alessandro
*
*/
static class ThumbnailCallable extends AsyncImageManager.MyCallable {
EffectFilter mFilter;
String mEffectName;
Bitmap srcBitmap;
Bitmap invalidBitmap;
boolean isValid;
public ThumbnailCallable( EffectFilter filter, String effectName, Bitmap bitmap, boolean valid, Bitmap invalid_bitmap ) {
mEffectName = effectName;
mFilter = filter;
srcBitmap = bitmap;
isValid = valid;
invalidBitmap = invalid_bitmap;
}
@Override
public Bitmap call() throws Exception {
mFilter.setBorders( false );
MoaAction action = MoaActionFactory.action( "ext-roundedborders" );
action.setValue( "padding", mRoundedBordersPaddingPixelSize );
action.setValue( "roundPx", mRoundedBordersPixelSize );
action.setValue( "strokeColor", new MoaColorParameter( 0xffa6a6a6 ) );
action.setValue( "strokeWeight", mRoundedBordersStrokePixelSize );
if ( !isValid ) {
action.setValue( "overlaycolor", new MoaColorParameter( 0x99000000 ) );
}
mFilter.getActions().add( action );
// shadow
action = MoaActionFactory.action( "ext-roundedshadow" );
action.setValue( "color", 0x99000000 );
action.setValue( "radius", mShadowRadiusPixelSize );
action.setValue( "roundPx", mRoundedBordersPixelSize );
action.setValue( "offsetx", mShadowOffsetPixelSize );
action.setValue( "offsety", mShadowOffsetPixelSize );
action.setValue( "padding", mRoundedBordersPaddingPixelSize );
mFilter.getActions().add( action );
Bitmap result = mFilter.execute( srcBitmap, null, 1, 1 );
if ( !isValid ) {
addUpdateArrow( result );
}
return result;
}
void addUpdateArrow( Bitmap bitmap ) {
if ( null != invalidBitmap && !invalidBitmap.isRecycled() ) {
final double w = Math.floor( bitmap.getWidth() * 0.75 );
final double h = Math.floor( bitmap.getHeight() * 0.75 );
final int paddingx = (int) ( bitmap.getWidth() - w ) / 2;
final int paddingy = (int) ( bitmap.getHeight() - h ) / 2;
Paint paint = new Paint( Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG );
Rect src = new Rect( 0, 0, invalidBitmap.getWidth(), invalidBitmap.getHeight() );
Rect dst = new Rect( paddingx, paddingy, paddingx + (int) w, paddingy + (int) h );
Canvas canvas = new Canvas( bitmap );
canvas.drawBitmap( invalidBitmap, src, dst, paint );
}
}
}
/**
* Install all the
*
* @author alessandro
*
*/
class PluginInstallTask extends AsyncTask<FeatherInternalPack[], Void, List<EffectPack>> {
List<EffectPackError> mErrors;
private PluginService mEffectsService;
@Override
protected void onPreExecute() {
super.onPreExecute();
mEffectsService = getContext().getService( PluginService.class );
mErrors = Collections.synchronizedList( new ArrayList<EffectPackError>() );
mImageManager.clearCache();
}
@Override
protected List<EffectPack> doInBackground( FeatherInternalPack[]... params ) {
List<EffectPack> result = Collections.synchronizedList( new ArrayList<EffectPack>() );
mInstalledPackages.clear();
if ( params[0] != null && params[0].length > 0 ) {
if ( mExternalPacksEnabled ) {
addItemToList( null );
}
}
for ( FeatherPack pack : params[0] ) {
if ( pack instanceof FeatherInternalPack ) {
InternalPlugin plugin = (InternalPlugin) PluginManager.create( getContext().getBaseContext(), pack );
PluginError status;
if ( plugin.isExternal() ) {
status = installPlugin( plugin.getPackageName(), plugin.getPluginType() );
if ( status != PluginError.NoError ) {
EffectPackError error = new EffectPackError( plugin.getPackageName(), plugin.getLabel( mType ), status );
mErrors.add( error );
// continue;
}
} else {
status = PluginError.NoError;
}
CharSequence[] filters = listPackItems( plugin );
CharSequence[] labels = listPackLabels( plugin, filters );
CharSequence title = plugin.getLabel( mType );
final EffectPack effectPack = new EffectPack( plugin.getPackageName(), title, filters, labels, status );
if( plugin.isExternal() ){
trackPackage( plugin.getPackageName() );
}
mInstalledPackages.add( plugin.getPackageName() );
if ( isActive() ) {
addItemToList( effectPack );
result.add( effectPack );
}
}
}
if ( params[0] != null && params[0].length > 0 ) {
if ( mExternalPacksEnabled ) {
addItemToList( null );
}
}
return result;
}
private void addItemToList( final EffectPack pack ) {
if ( isActive() ) {
getHandler().post( new Runnable() {
@Override
public void run() {
mListAdapter.add( pack );
}
} );
}
}
@Override
protected void onPostExecute( List<EffectPack> result ) {
super.onPostExecute( result );
onEffectListUpdated( result, mErrors );
mIsAnimating = false;
}
private CharSequence[] listPackItems( InternalPlugin plugin ) {
if ( mType == FeatherIntent.PluginType.TYPE_FILTER ) {
return plugin.listFilters();
} else if ( mType == FeatherIntent.PluginType.TYPE_BORDER ) {
return plugin.listBorders();
}
return null;
}
private CharSequence[] listPackLabels( InternalPlugin plugin, CharSequence[] items ) {
CharSequence[] labels = new String[items.length];
for ( int i = 0; i < items.length; i++ ) {
if ( mType == FeatherIntent.PluginType.TYPE_FILTER ) {
labels[i] = plugin.getFilterLabel( items[i] );
} else if ( mType == FeatherIntent.PluginType.TYPE_BORDER ) {
labels[i] = plugin.getBorderLabel( items[i] );
}
}
return labels;
}
private PluginError installPlugin( final String packagename, final int pluginType ) {
if ( mEffectsService.installed( packagename ) ) {
return PluginError.NoError;
}
return mEffectsService.install( getContext().getBaseContext(), packagename, pluginType );
}
}
class EffectPackError {
CharSequence mPackageName;
CharSequence mLabel;
PluginError mError;
public EffectPackError( CharSequence packagename, CharSequence label, PluginError error ) {
mPackageName = packagename;
mLabel = label;
mError = error;
}
}
class EffectPack {
CharSequence mPackageName;
CharSequence[] mValues;
CharSequence[] mLabels;
CharSequence mTitle;
PluginError mStatus;
int size = 0;
int index = 0;
public EffectPack( CharSequence packageName, CharSequence pakageTitle, CharSequence[] filters, CharSequence[] labels,
PluginError status ) {
mPackageName = packageName;
mValues = filters;
mLabels = labels;
mStatus = status;
mTitle = pakageTitle;
if ( null != filters ) {
size = filters.length;
}
}
public int getCount() {
return size;
}
public int getIndex() {
return index;
}
public void setIndex( int value ) {
index = value;
}
public CharSequence getItemAt( int position ) {
return mValues[position - index];
}
public CharSequence getLabelAt( int position ) {
return mLabels[position - index];
}
}
/**
* Render the selected effect
*/
private class RenderTask extends UserTask<Void, Bitmap, Bitmap> implements OnCancelListener {
String mError;
String mEffect;
MoaResult mNativeResult;
MoaResult mSmallNativeResult;
/**
* Instantiates a new render task.
*
* @param tag
* the tag
*/
public RenderTask( final String tag ) {
mEffect = tag;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onPreExecute()
*/
@Override
public void onPreExecute() {
super.onPreExecute();
final NativeFilter filter = (NativeFilter) loadNativeFilter( mEffect );
if ( mType == FeatherIntent.PluginType.TYPE_FILTER ) {
// activate borders ?
((EffectFilter) filter ).setBorders( Constants.getValueFromIntent( Constants.EXTRA_EFFECTS_BORDERS_ENABLED, true ) );
}
try {
mNativeResult = filter.prepare( mBitmap, mPreview, 1, 1 );
mActions = (MoaActionList) filter.getActions().clone();
} catch ( JSONException e ) {
mLogger.error( e.toString() );
e.printStackTrace();
mNativeResult = null;
return;
}
if ( mNativeResult == null ) return;
onProgressStart();
if ( !mEnableFastPreview ) {
// use the standard system modal progress dialog
// to render the effect
} else {
try {
mSmallNativeResult = filter.prepare( mBitmap, mSmallPreview, mSmallPreview.getWidth(), mSmallPreview.getHeight() );
} catch ( JSONException e ) {
e.printStackTrace();
}
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#doInBackground(Params[])
*/
@Override
public Bitmap doInBackground( final Void... params ) {
if ( isCancelled() ) return null;
if ( mNativeResult == null ) return null;
mIsRendering = true;
// rendering the small preview
if ( mEnableFastPreview && mSmallNativeResult != null ) {
mSmallNativeResult.execute();
if ( mSmallNativeResult.active > 0 ) {
publishProgress( mSmallNativeResult.outputBitmap );
}
}
if ( isCancelled() ) return null;
long t1, t2;
// rendering the full preview
try {
t1 = System.currentTimeMillis();
mNativeResult.execute();
t2 = System.currentTimeMillis();
} catch ( Exception exception ) {
mLogger.error( exception.getMessage() );
mError = exception.getMessage();
exception.printStackTrace();
return null;
}
if ( null != mTrackingAttributes ) {
mTrackingAttributes.put( "filterName", mEffect );
mTrackingAttributes.put( "renderTime", Long.toString( t2 - t1 ) );
}
mLogger.log( " complete. isCancelled? " + isCancelled(), mEffect );
if ( !isCancelled() ) {
return mNativeResult.outputBitmap;
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onProgressUpdate(Progress[])
*/
@Override
public void onProgressUpdate( Bitmap... values ) {
super.onProgressUpdate( values );
// we're using a FakeBitmapDrawable just to upscale the small bitmap
// to be rendered the same way as the full image
final FakeBitmapDrawable drawable = new FakeBitmapDrawable( values[0], mBitmap.getWidth(), mBitmap.getHeight() );
mImageSwitcher.setImageDrawable( drawable, true, null, Float.MAX_VALUE );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onPostExecute(java.lang.Object)
*/
@Override
public void onPostExecute( final Bitmap result ) {
super.onPostExecute( result );
if ( !isActive() ) return;
mPreview = result;
if ( result == null || mNativeResult == null || mNativeResult.active == 0 ) {
// restore the original bitmap...
mImageSwitcher.setImageBitmap( mBitmap, false, null, Float.MAX_VALUE );
if ( mError != null ) {
onGenericError( mError );
}
setIsChanged( false );
mActions = null;
} else {
if ( SystemUtils.isHoneyComb() ) {
Moa.notifyPixelsChanged( result );
}
mImageSwitcher.setImageBitmap( result, true, null, Float.MAX_VALUE );
setIsChanged( true );
}
onProgressEnd();
mIsRendering = false;
mCurrentTask = null;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.utils.UserTask#onCancelled()
*/
@Override
public void onCancelled() {
super.onCancelled();
if ( mNativeResult != null ) {
mNativeResult.cancel();
}
if ( mSmallNativeResult != null ) {
mSmallNativeResult.cancel();
}
mIsRendering = false;
}
/*
* (non-Javadoc)
*
* @see android.content.DialogInterface.OnCancelListener#onCancel(android.content.DialogInterface)
*/
@Override
public void onCancel( DialogInterface dialog ) {
cancel( true );
}
}
/**
* Used to generate the Bitmap result. If user clicks on the "Apply" button when an effect is still rendering, then starts this
* task.
*/
class GenerateResultTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgress = new ProgressDialog( getContext().getBaseContext() );
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setTitle( getContext().getBaseContext().getString( R.string.feather_loading_title ) );
mProgress.setMessage( getContext().getBaseContext().getString( R.string.effect_loading_message ) );
mProgress.setIndeterminate( true );
mProgress.setCancelable( false );
mProgress.show();
}
@Override
protected Void doInBackground( Void... params ) {
mLogger.info( "GenerateResultTask::doInBackground", mIsRendering );
while ( mIsRendering ) {
// mLogger.log( "waiting...." );
}
return null;
}
@Override
protected void onPostExecute( Void result ) {
super.onPostExecute( result );
mLogger.info( "GenerateResultTask::onPostExecute" );
if ( getContext().getBaseActivity().isFinishing() ) return;
if ( mProgress.isShowing() ) mProgress.dismiss();
onComplete( mPreview, mActions );
}
}
}
| Java |
package com.aviary.android.feather.effects;
import android.R.attr;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.CropCheckboxDrawable;
import com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable;
import com.aviary.android.feather.graphics.GalleryCircleDrawable;
import com.aviary.android.feather.graphics.PreviewCircleDrawable;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.filters.IFilter;
import com.aviary.android.feather.library.filters.SpotBrushFilter;
import com.aviary.android.feather.library.graphics.FlattenPath;
import com.aviary.android.feather.library.moa.Moa;
import com.aviary.android.feather.library.moa.MoaAction;
import com.aviary.android.feather.library.moa.MoaActionFactory;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.AdapterView;
import com.aviary.android.feather.widget.Gallery;
import com.aviary.android.feather.widget.Gallery.OnItemsScrollListener;
import com.aviary.android.feather.widget.IToast;
import com.aviary.android.feather.widget.ImageViewSpotDraw;
import com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener;
import com.aviary.android.feather.widget.ImageViewSpotDraw.TouchMode;
/**
* The Class SpotDrawPanel.
*/
public class SpotDrawPanel extends AbstractContentPanel implements OnDrawListener {
/** The brush size. */
protected int mBrushSize;
/** The filter type. */
protected Filters mFilterType;
protected Gallery mGallery;
/** The brush sizes. */
protected int[] mBrushSizes;
/** The current selected view. */
protected View mSelected;
/** The current selected position. */
protected int mSelectedPosition = 0;
protected ImageButton mLensButton;
/** The background draw thread. */
private MyHandlerThread mBackgroundDrawThread;
IToast mToast;
PreviewCircleDrawable mCircleDrawablePreview;
MoaActionList mActions = MoaActionFactory.actionList();
private int mPreviewWidth, mPreviewHeight;
/**
* Show size preview.
*
* @param size
* the size
*/
private void showSizePreview( int size ) {
if ( !isActive() ) return;
mToast.show();
updateSizePreview( size );
}
/**
* Hide size preview.
*/
private void hideSizePreview() {
if ( !isActive() ) return;
mToast.hide();
}
/**
* Update size preview.
*
* @param size
* the size
*/
private void updateSizePreview( int size ) {
if ( !isActive() ) return;
mCircleDrawablePreview.setRadius( size );
View v = mToast.getView();
v.findViewById( R.id.size_preview_image );
v.invalidate();
}
/**
* Instantiates a new spot draw panel.
*
* @param context
* the context
* @param filter_type
* the filter_type
*/
public SpotDrawPanel( EffectContext context, Filters filter_type ) {
super( context );
mFilterType = filter_type;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
mFilter = createFilter();
ConfigService config = getContext().getService( ConfigService.class );
mBrushSizes = config.getSizeArray( R.array.feather_spot_brush_sizes );
mBrushSize = mBrushSizes[0];
mLensButton = (ImageButton) getContentView().findViewById( R.id.lens_button );
mImageView = (ImageViewSpotDraw) getContentView().findViewById( R.id.image );
( (ImageViewSpotDraw) mImageView ).setBrushSize( (float) mBrushSize );
mPreview = BitmapUtils.copy( mBitmap, Config.ARGB_8888 );
mPreviewWidth = mPreview.getWidth();
mPreviewHeight = mPreview.getHeight();
mImageView.setImageBitmap( mPreview, true, getContext().getCurrentImageViewMatrix(), UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
int defaultOption = config.getInteger( R.integer.feather_spot_brush_selected_size_index );
defaultOption = Math.min( Math.max( defaultOption, 0 ), mBrushSizes.length - 1 );
mGallery = (Gallery) getOptionView().findViewById( R.id.gallery );
mGallery.setCallbackDuringFling( false );
mGallery.setSpacing( 0 );
mGallery.setOnItemsScrollListener( new OnItemsScrollListener() {
@Override
public void onScrollFinished( AdapterView<?> parent, View view, int position, long id ) {
mLogger.info( "onScrollFinished: " + position );
mBrushSize = mBrushSizes[position];
( (ImageViewSpotDraw) mImageView ).setBrushSize( (float) mBrushSize );
setSelectedTool( TouchMode.DRAW );
updateSelection( view, position );
hideSizePreview();
}
@Override
public void onScrollStarted( AdapterView<?> parent, View view, int position, long id ) {
showSizePreview( mBrushSizes[position] );
setSelectedTool( TouchMode.DRAW );
}
@Override
public void onScroll( AdapterView<?> parent, View view, int position, long id ) {
updateSizePreview( mBrushSizes[position] );
}
} );
mBackgroundDrawThread = new MyHandlerThread( "filter-thread", Thread.MIN_PRIORITY );
initAdapter();
}
/**
* Inits the adapter.
*/
private void initAdapter() {
int height = mGallery.getHeight();
if ( height < 1 ) {
mGallery.getHandler().post( new Runnable() {
@Override
public void run() {
initAdapter();
}
} );
return;
}
mGallery.setSelection( 2, false, true );
mGallery.setAdapter( new GalleryAdapter( getContext().getBaseContext(), mBrushSizes ) );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
( (ImageViewSpotDraw) mImageView ).setOnDrawStartListener( this );
mBackgroundDrawThread.start();
mBackgroundDrawThread.setRadius( (float) Math.max( 1, mBrushSizes[0] ), mPreviewWidth );
updateSelection( (View) mGallery.getSelectedView(), mGallery.getSelectedItemPosition() );
mToast = IToast.make( getContext().getBaseContext(), -1 );
mCircleDrawablePreview = new PreviewCircleDrawable( 0 );
ImageView image = (ImageView) mToast.getView().findViewById( R.id.size_preview_image );
image.setImageDrawable( mCircleDrawablePreview );
mLensButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View arg0 ) {
// boolean selected = arg0.isSelected();
setSelectedTool( ( (ImageViewSpotDraw) mImageView ).getDrawMode() == TouchMode.DRAW ? TouchMode.IMAGE : TouchMode.DRAW );
}
} );
mLensButton.setVisibility( View.VISIBLE );
contentReady();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#onDispose()
*/
@Override
protected void onDispose() {
mContentReadyListener = null;
super.onDispose();
}
/**
* Update selection.
*
* @param newSelection
* the new selection
* @param position
* the position
*/
protected void updateSelection( View newSelection, int position ) {
if ( mSelected != null ) {
mSelected.setSelected( false );
}
mSelected = newSelection;
mSelectedPosition = position;
if ( mSelected != null ) {
mSelected = newSelection;
mSelected.setSelected( true );
}
}
/**
* Sets the selected tool.
*
* @param which
* the new selected tool
*/
private void setSelectedTool( TouchMode which ) {
( (ImageViewSpotDraw) mImageView ).setDrawMode( which );
mLensButton.setSelected( which == TouchMode.IMAGE );
setPanelEnabled( which != TouchMode.IMAGE );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
( (ImageViewSpotDraw) mImageView ).setOnDrawStartListener( null );
if ( mBackgroundDrawThread != null ) {
if ( mBackgroundDrawThread.isAlive() ) {
mBackgroundDrawThread.quit();
while ( mBackgroundDrawThread.isAlive() ) {
// wait...
}
}
}
onProgressEnd();
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
mBackgroundDrawThread = null;
mImageView.clear();
mToast.hide();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCancelled()
*/
@Override
public void onCancelled() {
super.onCancelled();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener#onDrawStart(float[], int)
*/
@Override
public void onDrawStart( float[] points, int radius ) {
radius = Math.max( 1, radius );
mLogger.info( "onDrawStart. radius: " + radius );
mBackgroundDrawThread.setRadius( (float) radius, mPreviewWidth );
mBackgroundDrawThread.moveTo( points );
mBackgroundDrawThread.lineTo( points );
setIsChanged( true );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener#onDrawing(float[], int)
*/
@Override
public void onDrawing( float[] points, int radius ) {
mBackgroundDrawThread.quadTo( points );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener#onDrawEnd()
*/
@Override
public void onDrawEnd() {
// TODO: empty
mLogger.info( "onDrawEnd" );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
mLogger.info( "onGenerateResult: " + mBackgroundDrawThread.isCompleted() + ", " + mBackgroundDrawThread.isAlive() );
if ( !mBackgroundDrawThread.isCompleted() && mBackgroundDrawThread.isAlive() ) {
GenerateResultTask task = new GenerateResultTask();
task.execute();
} else {
onComplete( mPreview, mActions );
}
}
/**
* Sets the panel enabled.
*
* @param value
* the new panel enabled
*/
public void setPanelEnabled( boolean value ) {
if ( mOptionView != null ) {
if ( value != mOptionView.isEnabled() ) {
mOptionView.setEnabled( value );
if ( value ) {
getContext().restoreToolbarTitle();
} else {
getContext().setToolbarTitle( R.string.zoom_mode );
}
mOptionView.findViewById( R.id.disable_status ).setVisibility( value ? View.INVISIBLE : View.VISIBLE );
}
}
}
/**
* Prints the rect.
*
* @param rect
* the rect
* @return the string
*/
@SuppressWarnings("unused")
private String printRect( Rect rect ) {
return "( left=" + rect.left + ", top=" + rect.top + ", width=" + rect.width() + ", height=" + rect.height() + ")";
}
/**
* Creates the filter.
*
* @return the i filter
*/
protected IFilter createFilter() {
return FilterLoaderFactory.get( mFilterType );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_spotdraw_content, null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_pixelbrush_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#getContentDisplayMatrix()
*/
@Override
public Matrix getContentDisplayMatrix() {
return mImageView.getDisplayMatrix();
}
/**
* background draw thread
*/
class MyHandlerThread extends Thread {
/** The started. */
boolean started;
/** The running. */
volatile boolean running;
/** The paused. */
boolean paused;
/** The m x. */
float mX = 0;
/** The m y. */
float mY = 0;
/** The m flatten path. */
FlattenPath mFlattenPath;
/**
* Instantiates a new my handler thread.
*
* @param name
* the name
* @param priority
* the priority
*/
public MyHandlerThread( String name, int priority ) {
super( name );
setPriority( priority );
init();
}
/**
* Inits the.
*/
void init() {
mFlattenPath = new FlattenPath( 0.1 );
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#start()
*/
@Override
synchronized public void start() {
started = true;
running = true;
super.start();
}
/**
* Quit.
*/
synchronized public void quit() {
running = false;
pause();
interrupt();
};
/**
* Pause.
*/
public void pause() {
if ( !started ) throw new IllegalAccessError( "thread not started" );
paused = true;
boolean stopped = ( (SpotBrushFilter) mFilter ).stop();
mLogger.log( "pause. filter stopped: " + stopped );
}
/**
* Unpause.
*/
public void unpause() {
if ( !started ) throw new IllegalAccessError( "thread not started" );
paused = false;
}
/** The m radius. */
float mRadius = 10;
/**
* Sets the radius.
*
* @param radius
* the new radius
*/
public void setRadius( float radius, int bitmapWidth ) {
( (SpotBrushFilter) mFilter ).setRadius( radius, bitmapWidth );
mRadius = radius;
}
/**
* Move to.
*
* @param values
* the values
*/
public void moveTo( float values[] ) {
mFlattenPath.moveTo( values[0], values[1] );
mX = values[0];
mY = values[1];
}
/**
* Line to.
*
* @param values
* the values
*/
public void lineTo( float values[] ) {
mFlattenPath.lineTo( values[0], values[1] );
mX = values[0];
mY = values[1];
}
/**
* Quad to.
*
* @param values
* the values
*/
public void quadTo( float values[] ) {
mFlattenPath.quadTo( mX, mY, ( values[0] + mX ) / 2, ( values[1] + mY ) / 2 );
mX = values[0];
mY = values[1];
}
/**
* Checks if is completed.
*
* @return true, if is completed
*/
public boolean isCompleted() {
return mFlattenPath.size() == 0;
}
/**
* Queue size.
*
* @return the int
*/
public int queueSize() {
return mFlattenPath.size();
}
/**
* Gets the lerp.
*
* @param pt1
* the pt1
* @param pt2
* the pt2
* @param t
* the t
* @return the lerp
*/
public PointF getLerp( PointF pt1, PointF pt2, float t ) {
return new PointF( pt1.x + ( pt2.x - pt1.x ) * t, pt1.y + ( pt2.y - pt1.y ) * t );
}
/** The m last point. */
PointF mLastPoint;
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
while ( !started ) {}
boolean s = false;
mLogger.log( "thread.start!" );
while ( running ) {
if ( paused ) {
continue;
}
int currentSize;
currentSize = mFlattenPath.size();
if ( currentSize > 0 && !isInterrupted() ) {
if ( !s ) {
mLogger.log( "start: " + currentSize );
s = true;
onProgressStart();
}
PointF firstPoint;
firstPoint = mFlattenPath.remove();
if ( mLastPoint == null ) {
mLastPoint = firstPoint;
continue;
}
if ( firstPoint == null ) {
mLastPoint = null;
continue;
}
float currentPosition = 0;
// float length = mLastPoint.length( firstPoint.x, firstPoint.y );
float x = Math.abs( firstPoint.x - mLastPoint.x );
float y = Math.abs( firstPoint.y - mLastPoint.y );
float length = (float) Math.sqrt( x * x + y * y );
float lerp;
if ( length == 0 ) {
( (SpotBrushFilter) mFilter ).draw( firstPoint.x / mPreviewWidth, firstPoint.y / mPreviewHeight, mPreview );
try {
mActions.add( (MoaAction) ( (SpotBrushFilter) mFilter ).getActions().get( 0 ).clone() );
} catch ( CloneNotSupportedException e ) {
e.printStackTrace();
}
} else {
while ( currentPosition < length ) {
lerp = currentPosition / length;
PointF point = getLerp( mLastPoint, firstPoint, lerp );
currentPosition += mRadius;
( (SpotBrushFilter) mFilter ).draw( point.x / mPreviewWidth, point.y / mPreviewHeight, mPreview );
try {
mActions.add( (MoaAction) ( (SpotBrushFilter) mFilter ).getActions().get( 0 ).clone() );
} catch ( CloneNotSupportedException e ) {
e.printStackTrace();
}
if ( SystemUtils.isHoneyComb() ) {
// There's a bug in Honeycomb which prevent the bitmap to be updated on a glcanvas
// so we need to force it
Moa.notifyPixelsChanged( mPreview );
}
}
}
mLastPoint = firstPoint;
mImageView.postInvalidate();
} else {
if ( s ) {
mLogger.log( "end: " + currentSize );
onProgressEnd();
s = false;
}
}
}
onProgressEnd();
mLogger.log( "thread.end" );
};
};
/**
* Bottom Gallery adapter.
*
* @author alessandro
*/
class GalleryAdapter extends BaseAdapter {
private int[] sizes;
LayoutInflater mLayoutInflater;
Drawable checkbox_unselected, checkbox_selected;
Resources mRes;
/**
* Instantiates a new gallery adapter.
*
* @param context
* the context
* @param values
* the values
*/
public GalleryAdapter( Context context, int[] values ) {
mLayoutInflater = UIUtils.getLayoutInflater();
sizes = values;
mRes = getContext().getBaseContext().getResources();
checkbox_selected = mRes.getDrawable( R.drawable.feather_crop_checkbox_selected );
checkbox_unselected = mRes.getDrawable( R.drawable.feather_crop_checkbox_unselected );
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return sizes.length;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem( int position ) {
return sizes[position];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return 0;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
final boolean valid = position >= 0 && position < getCount();
GalleryCircleDrawable mCircleDrawable = null;
int biggest = sizes[sizes.length - 1];
int size = 1;
View view;
if ( convertView == null ) {
if ( valid ) {
mCircleDrawable = new GalleryCircleDrawable( 1, 0 );
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGallery, false );
StateListDrawable st = new StateListDrawable();
Drawable d1 = new CropCheckboxDrawable( mRes, false, mCircleDrawable, 0.67088f, 0.4f, 0.0f );
Drawable d2 = new CropCheckboxDrawable( mRes, true, mCircleDrawable, 0.67088f, 0.4f, 0.0f );
st.addState( new int[] { -attr.state_selected }, d1 );
st.addState( new int[] { attr.state_selected }, d2 );
view.setBackgroundDrawable( st );
view.setTag( mCircleDrawable );
} else {
// use the blank view
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGallery, false );
Drawable unselectedBackground = new DefaultGalleryCheckboxDrawable( mRes, false );
view.setBackgroundDrawable( unselectedBackground );
}
} else {
view = convertView;
if ( valid ) {
mCircleDrawable = (GalleryCircleDrawable) view.getTag();
}
}
if ( mCircleDrawable != null && valid ) {
size = sizes[position];
float value = (float) size / biggest;
mCircleDrawable.update( value, 0 );
}
view.setSelected( mSelectedPosition == position );
return view;
}
}
/**
* GenerateResultTask is used when the background draw operation is still running. Just wait until the draw operation completed.
*/
class GenerateResultTask extends AsyncTask<Void, Void, Void> {
/** The m progress. */
ProgressDialog mProgress = new ProgressDialog( getContext().getBaseContext() );
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setTitle( getContext().getBaseContext().getString( R.string.feather_loading_title ) );
mProgress.setMessage( getContext().getBaseContext().getString( R.string.effect_loading_message ) );
mProgress.setIndeterminate( true );
mProgress.setCancelable( false );
mProgress.show();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Void doInBackground( Void... params ) {
if ( mBackgroundDrawThread != null ) {
mLogger.info( "GenerateResultTask::doInBackground", mBackgroundDrawThread.isCompleted() );
while ( mBackgroundDrawThread != null && !mBackgroundDrawThread.isCompleted() ) {
mLogger.log( "waiting.... " + mBackgroundDrawThread.queueSize() );
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Void result ) {
super.onPostExecute( result );
mLogger.info( "GenerateResultTask::onPostExecute" );
if ( getContext().getBaseActivity().isFinishing() ) return;
if ( mProgress.isShowing() ) {
try {
mProgress.dismiss();
} catch ( IllegalArgumentException e ) {}
}
onComplete( mPreview, mActions );
}
}
}
| Java |
package com.aviary.android.feather.effects;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.ColorMatrixColorFilter;
import android.media.ThumbnailUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.filters.AbstractColorMatrixFilter;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.widget.Wheel;
import com.aviary.android.feather.widget.Wheel.OnScrollListener;
import com.aviary.android.feather.widget.WheelRadio;
// TODO: Auto-generated Javadoc
/**
* The Class ColorMatrixEffectPanel.
*/
public class ColorMatrixEffectPanel extends AbstractOptionPanel implements OnScrollListener {
Wheel mWheel;
WheelRadio mWheelRadio;
String mResourceName;
/**
* Instantiates a new color matrix effect panel.
*
* @param context
* the context
* @param type
* the type
* @param resourcesBaseName
* the resources base name
*/
public ColorMatrixEffectPanel( EffectContext context, Filters type, String resourcesBaseName ) {
super( context );
mFilter = FilterLoaderFactory.get( type );
if ( mFilter instanceof AbstractColorMatrixFilter ) {
mMinValue = ( (AbstractColorMatrixFilter) mFilter ).getMinValue();
mMaxValue = ( (AbstractColorMatrixFilter) mFilter ).getMaxValue();
}
mResourceName = resourcesBaseName;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
mWheel = (Wheel) getOptionView().findViewById( R.id.wheel );
mWheelRadio = (WheelRadio) getOptionView().findViewById( R.id.wheel_radio );
ConfigService config = getContext().getService( ConfigService.class );
mLivePreview = config.getBoolean( R.integer.feather_brightness_live_preview );
onCreateIcons();
}
protected void onCreateIcons() {
ImageView icon_small = (ImageView) getOptionView().findViewById( R.id.icon_small );
ImageView icon_big = (ImageView) getOptionView().findViewById( R.id.icon_big );
Resources res = getContext().getBaseContext().getResources();
if ( null != res ) {
int id = res.getIdentifier( "feather_tool_icon_" + mResourceName, "drawable", getContext().getBaseContext().getPackageName() );
if ( id > 0 ) {
Bitmap big, small;
try {
Bitmap bmp = BitmapFactory.decodeResource( res, id );
big = ThumbnailUtils.extractThumbnail( bmp, (int) ( bmp.getWidth() / 1.5 ), (int) ( bmp.getHeight() / 1.5 ) );
bmp.recycle();
small = ThumbnailUtils.extractThumbnail( big, (int) ( big.getWidth() / 1.5 ), (int) ( big.getHeight() / 1.5 ) );
} catch ( OutOfMemoryError e ) {
e.printStackTrace();
return;
}
icon_big.setImageBitmap( big );
icon_small.setImageBitmap( small );
}
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
disableHapticIsNecessary( mWheel );
int ticksCount = mWheel.getTicksCount();
mWheelRadio.setTicksNumber( ticksCount / 2, mWheel.getWheelScaleFactor() );
mWheel.setOnScrollListener( this );
// we intercept the touch event from the whole option panel
// and send it to the wheel, so it's like the wheel component
// interacts with the entire option view
getOptionView().setOnTouchListener( new OnTouchListener() {
@Override
public boolean onTouch( View v, MotionEvent event ) {
return mWheel.onTouchEvent( event );
}
} );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
getOptionView().setOnTouchListener( null );
super.onDeactivate();
mWheel.setOnScrollListener( null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_wheel_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.Wheel.OnScrollListener#onScrollStarted(com.aviary.android.feather.widget.Wheel, float,
* int)
*/
@Override
public void onScrollStarted( Wheel view, float value, int roundValue ) {}
/** The m last value. */
int mLastValue;
/** The m current real value. */
float mCurrentRealValue;
/** The m min value. */
float mMinValue = 0;
/** The m max value. */
float mMaxValue = 1;
boolean mLivePreview = false;
/**
* On apply value.
*
* @param value
* the value
*/
private void onApplyValue( float value ) {
float realValue = 1f + value;
float range = mMaxValue - mMinValue;
float perc = mMinValue + ( ( realValue / 2.0F ) * range );
mCurrentRealValue = perc;
final ColorMatrixColorFilter c = ( (AbstractColorMatrixFilter) mFilter ).apply( perc );
onPreviewChanged( c, true );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.Wheel.OnScrollListener#onScroll(com.aviary.android.feather.widget.Wheel, float, int)
*/
@Override
public void onScroll( Wheel view, float value, int roundValue ) {
mWheelRadio.setValue( value );
if ( mLivePreview ) { // we don't really want to update every frame...
if ( mLastValue != roundValue ) {
onApplyValue( mWheelRadio.getValue() );
}
mLastValue = roundValue;
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.Wheel.OnScrollListener#onScrollFinished(com.aviary.android.feather.widget.Wheel, float,
* int)
*/
@Override
public void onScrollFinished( Wheel view, float value, int roundValue ) {
mWheelRadio.setValue( value );
onApplyValue( mWheelRadio.getValue() );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
mPreview = BitmapUtils.copy( mBitmap, Config.ARGB_8888 );
AbstractColorMatrixFilter filter = (AbstractColorMatrixFilter) mFilter;
filter.execute( mBitmap, mPreview, mCurrentRealValue );
onComplete( mPreview, filter.getActions() );
}
}
| Java |
package com.aviary.android.feather.effects;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.filters.AdjustFilter;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.widget.AdjustImageView;
import com.aviary.android.feather.widget.AdjustImageView.FlipType;
import com.aviary.android.feather.widget.AdjustImageView.OnResetListener;
// TODO: Auto-generated Javadoc
/**
* The Class AdjustEffectPanel.
*/
public class AdjustEffectPanel extends AbstractContentPanel implements OnClickListener, OnResetListener {
private AdjustImageView mView;
private int animDuration = 400;
private int resetAnimDuration = 200;
boolean isClosing;
int currentStraightenPosition = 45;
static final int NEGATIVE_DIRECTION = -1;
static final int POSITIVE_DIRECTION = 1;
/** The enable3 d animation. */
boolean enable3DAnimation;
boolean enableFreeRotate;
/**
* Instantiates a new adjust effect panel.
*
* @param context
* the context
* @param adjust
* the adjust
*/
public AdjustEffectPanel( EffectContext context, Filters adjust ) {
super( context );
mFilter = FilterLoaderFactory.get( adjust );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
ConfigService config = getContext().getService( ConfigService.class );
if ( null != config ) {
animDuration = config.getInteger( R.integer.feather_adjust_tool_anim_time );
resetAnimDuration = config.getInteger( R.integer.feather_adjust_tool_reset_anim_time );
enable3DAnimation = config.getBoolean( R.integer.feather_adjust_tool_enable_3d_flip );
enableFreeRotate = config.getBoolean( R.integer.feather_rotate_enable_free_rotate );
} else {
enable3DAnimation = false;
enableFreeRotate = false;
}
mView = (AdjustImageView) getContentView().findViewById( R.id.image );
mView.setResetAnimDuration( resetAnimDuration );
mView.setCameraEnabled( enable3DAnimation );
mView.setEnableFreeRotate( enableFreeRotate );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
mView.setImageBitmap( mBitmap );
mView.setOnResetListener( this );
View v = getOptionView();
v.findViewById( R.id.button1 ).setOnClickListener( this );
v.findViewById( R.id.button2 ).setOnClickListener( this );
v.findViewById( R.id.button3 ).setOnClickListener( this );
v.findViewById( R.id.button4 ).setOnClickListener( this );
//
// straighten stuff
//
contentReady();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
mView.setOnResetListener( null );
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
mView.setImageBitmap( null );
super.onDestroy();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_adjust_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_adjust_content, null );
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
if ( !isActive() || !isEnabled() ) return;
final int id = v.getId();
if ( id == R.id.button1 ) {
mView.rotate90( false, animDuration );
} else if ( id == R.id.button2 ) {
mView.rotate90( true, animDuration );
} else if ( id == R.id.button3 ) {
mView.flip( true, animDuration );
} else if ( id == R.id.button4 ) {
mView.flip( false, animDuration );
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#getIsChanged()
*/
@SuppressLint("NewApi")
@Override
public boolean getIsChanged() {
mLogger.info( "getIsChanged" );
boolean straightenStarted = mView.getStraightenStarted();
final int rotation = (int) mView.getRotation();
final int flip_type = mView.getFlipType();
return rotation != 0 || ( flip_type != FlipType.FLIP_NONE.nativeInt ) || straightenStarted;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#getContentDisplayMatrix()
*/
@Override
public Matrix getContentDisplayMatrix() {
return null;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
final int rotation = (int) mView.getRotation();
final double rotationFromStraighten = mView.getStraightenAngle();
final boolean horizontal = mView.getHorizontalFlip();
final boolean vertical = mView.getVerticalFlip();
final double growthFactor = ( 1 / mView.getGrowthFactor() );
AdjustFilter filter = (AdjustFilter) mFilter;
filter.setFixedRotation( rotation );
filter.setFlip( horizontal, vertical );
filter.setStraighten( rotationFromStraighten, growthFactor, growthFactor );
Bitmap output;
try {
output = filter.execute( mBitmap, null, 1, 1 );
} catch ( JSONException e ) {
e.printStackTrace();
onGenericError( e );
return;
}
mView.setImageBitmap( output );
onComplete( output, (MoaActionList) filter.getActions().clone() );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCancel()
*/
@SuppressLint("NewApi")
@Override
public boolean onCancel() {
if ( isClosing ) return true;
isClosing = true;
setEnabled( false );
final int rotation = (int) mView.getRotation();
final boolean hflip = mView.getHorizontalFlip();
final boolean vflip = mView.getVerticalFlip();
boolean straightenStarted = mView.getStraightenStarted();
final double rotationFromStraighten = mView.getStraightenAngle();
if ( rotation != 0 || hflip || vflip || ( straightenStarted && rotationFromStraighten != 0) ) {
mView.reset();
return true;
} else {
return false;
}
}
/**
* Reset animation is complete, now it is safe to call the parent {@link EffectContext#cancel()} method and close the panel.
*/
@Override
public void onResetComplete() {
getContext().cancel();
}
}
| Java |
package com.aviary.android.feather.effects;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.effects.AbstractEffectPanel.OptionPanel;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.services.PreferenceService;
import com.aviary.android.feather.widget.VibrationWidget;
abstract class AbstractOptionPanel extends AbstractEffectPanel implements OptionPanel {
/** The current option view. */
protected ViewGroup mOptionView;
/**
* Instantiates a new abstract option panel.
*
* @param context
* the context
*/
public AbstractOptionPanel( EffectContext context ) {
super( context );
}
@Override
public final ViewGroup getOptionView( LayoutInflater inflater, ViewGroup parent ) {
mOptionView = generateOptionView( inflater, parent );
return mOptionView;
}
/**
* Gets the panel option view.
*
* @return the option view
*/
public final ViewGroup getOptionView() {
return mOptionView;
}
@Override
protected void onDispose() {
mOptionView = null;
super.onDispose();
}
@Override
public void setEnabled( boolean value ) {
getOptionView().setEnabled( value );
super.setEnabled( value );
}
/**
* Generate option view.
*
* @param inflater
* the inflater
* @param parent
* the parent
* @return the view group
*/
protected abstract ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent );
/**
* Disable vibration feedback for each view in the passed array if necessary
*
* @param views
*/
protected void disableHapticIsNecessary( VibrationWidget... views ) {
boolean vibration = true;
if ( Constants.containsValue( Constants.EXTRA_TOOLS_DISABLE_VIBRATION ) ) {
vibration = false;
} else {
PreferenceService pref_service = getContext().getService( PreferenceService.class );
if ( null != pref_service ) {
if ( pref_service.isStandalone() ) {
vibration = pref_service.getStandaloneBoolean( "feather_app_vibration", true );
}
}
}
for ( VibrationWidget view : views ) {
view.setVibrationEnabled( vibration );
}
}
}
| Java |
package com.aviary.android.feather.effects;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.R;
import com.aviary.android.feather.async_tasks.AssetsAsyncDownloadManager;
import com.aviary.android.feather.async_tasks.AssetsAsyncDownloadManager.Thumb;
import com.aviary.android.feather.graphics.StickerBitmapDrawable;
import com.aviary.android.feather.library.content.FeatherIntent;
import com.aviary.android.feather.library.content.FeatherIntent.PluginType;
import com.aviary.android.feather.library.graphics.drawable.FeatherDrawable;
import com.aviary.android.feather.library.graphics.drawable.StickerDrawable;
import com.aviary.android.feather.library.moa.MoaAction;
import com.aviary.android.feather.library.moa.MoaActionFactory;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.moa.MoaPointParameter;
import com.aviary.android.feather.library.plugins.FeatherExternalPack;
import com.aviary.android.feather.library.plugins.FeatherInternalPack;
import com.aviary.android.feather.library.plugins.FeatherPack;
import com.aviary.android.feather.library.plugins.PluginManager;
import com.aviary.android.feather.library.plugins.PluginManager.IPlugin;
import com.aviary.android.feather.library.plugins.PluginManager.InternalPlugin;
import com.aviary.android.feather.library.plugins.UpdateType;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.DragControllerService;
import com.aviary.android.feather.library.services.DragControllerService.DragListener;
import com.aviary.android.feather.library.services.DragControllerService.DragSource;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.services.PluginService;
import com.aviary.android.feather.library.services.PluginService.OnUpdateListener;
import com.aviary.android.feather.library.services.PluginService.StickerType;
import com.aviary.android.feather.library.services.PreferenceService;
import com.aviary.android.feather.library.services.drag.DragView;
import com.aviary.android.feather.library.services.drag.DropTarget;
import com.aviary.android.feather.library.services.drag.DropTarget.DropTargetListener;
import com.aviary.android.feather.library.tracking.Tracker;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.IOUtils;
import com.aviary.android.feather.library.utils.ImageLoader;
import com.aviary.android.feather.library.utils.MatrixUtils;
import com.aviary.android.feather.library.utils.PackageManagerUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.utils.TypefaceUtils;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.DrawableHighlightView;
import com.aviary.android.feather.widget.DrawableHighlightView.OnDeleteClickListener;
import com.aviary.android.feather.widget.HorizontalFixedListView;
import com.aviary.android.feather.widget.HorizontalFixedListView.OnItemDragListener;
import com.aviary.android.feather.widget.ImageViewDrawableOverlay;
import com.aviary.android.feather.widget.wp.CellLayout;
import com.aviary.android.feather.widget.wp.CellLayout.CellInfo;
import com.aviary.android.feather.widget.wp.Workspace;
import com.aviary.android.feather.widget.wp.WorkspaceIndicator;
/**
*贴纸ֽ
* @author ting
*
*/
public class StickersPanel extends AbstractContentPanel implements OnUpdateListener, DragListener, DragSource, DropTargetListener {
private static enum Status {
Null, // home
Packs, // pack display
Stickers, // stickers
}
/** The default get more icon. */
// private Drawable mFolderIcon, mGetMoreIcon, mGetMoreFreeIcon;
private int mStickerHvEllipse, mStickerHvStrokeWidth, mStickerHvMinSize;
private int mStickerHvPadding;;
private ColorStateList mStickerHvStrokeColorStateList;
private ColorStateList mStickerHvFillColorStateList;
private Workspace mWorkspace;
private WorkspaceIndicator mWorkspaceIndicator;
private HorizontalFixedListView mHList;
private ViewFlipper mViewFlipper;
private int mStickerMinSize;
private Canvas mCanvas;
private AssetsAsyncDownloadManager mDownloadManager;
private PluginService mPluginService;
private int mWorkspaceCols;
private int mWorkspaceRows;
private int mWorkspaceItemsPerPage;
private List<String> mUsedStickers;
private List<String> mUsedStickersPacks;
private InternalPlugin mPlugin;
private ConfigService mConfig;
private Status mStatus = Status.Null;
private Status mPrevStatus = Status.Null;
private List<String> mInstalledPackages;
private View mLayoutLoader;
private final MoaActionList mActionList = MoaActionFactory.actionList();
private MoaAction mCurrentAction;
private PreferenceService mPrefService;
private DragControllerService mDragController;
private boolean mExternalPacksEnabled = true;
/**
* Instantiates a new stickers panel.
*
* @param context
* the context
*/
public StickersPanel( EffectContext context ) {
super( context );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
// Resolve layout resources
mWorkspaceIndicator = (WorkspaceIndicator) mOptionView.findViewById( R.id.workspace_indicator );
mWorkspace = (Workspace) mOptionView.findViewById( R.id.workspace );
mViewFlipper = (ViewFlipper) mOptionView.findViewById( R.id.flipper );
mHList = (HorizontalFixedListView) mOptionView.findViewById( R.id.gallery );
mImageView = (ImageViewDrawableOverlay) mDrawingPanel.findViewById( R.id.overlay );
mLayoutLoader = mOptionView.findViewById( R.id.layout_loader );
// retrive the used services
mConfig = getContext().getService( ConfigService.class );
mPluginService = getContext().getService( PluginService.class );
mPrefService = getContext().getService( PreferenceService.class );
// Load all the configurations
mStickerHvEllipse = mConfig.getInteger( R.integer.feather_sticker_highlight_ellipse );
mStickerHvStrokeWidth = mConfig.getInteger( R.integer.feather_sticker_highlight_stroke_width );
mStickerHvStrokeColorStateList = mConfig.getColorStateList( R.color.feather_sticker_color_stroke_selector );
mStickerHvFillColorStateList = mConfig.getColorStateList( R.color.feather_sticker_color_fill_selector );
mStickerHvMinSize = mConfig.getInteger( R.integer.feather_sticker_highlight_minsize );
mStickerHvPadding = mConfig.getInteger( R.integer.feather_sticker_highlight_padding );
// External packs enabled ?
mExternalPacksEnabled = Constants.getValueFromIntent( Constants.EXTRA_STICKERS_ENABLE_EXTERNAL_PACKS, true );
// Remember which stickers we used
mUsedStickers = new ArrayList<String>();
mUsedStickersPacks = new ArrayList<String>();
// Initialize the asset download manager
mDownloadManager = new AssetsAsyncDownloadManager( this.getContext().getBaseContext(), mHandler );
// setup the main imageview
( (ImageViewDrawableOverlay) mImageView ).setForceSingleSelection( false );
( (ImageViewDrawableOverlay) mImageView ).setDropTargetListener( this );
( (ImageViewDrawableOverlay) mImageView ).setScaleWithContent( true );
// setup the horizontal list
mHList.setOverScrollMode( View.OVER_SCROLL_ALWAYS );
mHList.setHideLastChild( true );
mHList.setInverted( true );
// setup the workspace
mWorkspace.setHapticFeedbackEnabled( false );
mWorkspace.setIndicator( mWorkspaceIndicator );
// resource manager used to load external stickers
mPlugin = null;
// Set the current view status
mPrevStatus = mStatus = Status.Null;
// initialize the content bitmap
createAndConfigurePreview();
if ( android.os.Build.VERSION.SDK_INT > 8 ) {
DragControllerService dragger = getContext().getService( DragControllerService.class );
dragger.addDropTarget( (DropTarget) mImageView );
dragger.setMoveTarget( mImageView );
dragger.setDragListener( this );
dragger.activate();
setDragController( dragger );
}
mExternalPacksEnabled = false;
// If external packs not enabled then skip to the stickers status
if ( !mExternalPacksEnabled ) {
mLayoutLoader.setVisibility( View.GONE );
mViewFlipper.setInAnimation( null );
mViewFlipper.setOutAnimation( null );
mWorkspace.setVisibility( View.GONE );
setCurrentPack( FeatherInternalPack.getDefault( getContext().getBaseContext() ) );
}
}
@Override
protected void onDispose() {
super.onDispose();
mWorkspace.setAdapter( null );
mHList.setAdapter( null );
}
/**
* Screen configuration has changed.
*
* @param newConfig
* the new config
*/
@Override
public void onConfigurationChanged( Configuration newConfig, Configuration oldConfig ) {
super.onConfigurationChanged( newConfig, oldConfig );
// we need to reload the current adapter...
if ( mExternalPacksEnabled ) {
initWorkspace();
}
mDownloadManager.clearCache();
if ( mStatus == Status.Null || mStatus == Status.Packs ) {
loadPacks( false );
} else {
loadStickers();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
super.onDeactivate();
if ( mExternalPacksEnabled ) {
mPluginService.removeOnUpdateListener( this );
}
( (ImageViewDrawableOverlay) mImageView ).setDropTargetListener( null );
if ( null != getDragController() ) {
getDragController().deactivate();
getDragController().removeDropTarget( (DropTarget) mImageView );
getDragController().setDragListener( null );
}
setDragController( null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
// getting the packs installed
mInstalledPackages = Collections.synchronizedList( new ArrayList<String>() );
// initialize the workspace
if ( mExternalPacksEnabled ) {
initWorkspace();
}
mImageView.setImageBitmap( mPreview, true, getContext().getCurrentImageViewMatrix(), UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
if ( mExternalPacksEnabled ) {
mPluginService.registerOnUpdateListener( this );
mWorkspace.setCacheEnabled( true );
mWorkspace.enableChildrenCache( 0, 1 );
setStatus( Status.Packs );
} else {
getContentView().setVisibility( View.VISIBLE );
contentReady();
}
}
private void startFirstAnimation() {
Animation animation = new TranslateAnimation( TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 1, TranslateAnimation.RELATIVE_TO_SELF, 0 );
animation.setDuration( 300 );
animation.setStartOffset( 100 );
animation.setInterpolator( AnimationUtils.loadInterpolator( getContext().getBaseContext(), android.R.anim.decelerate_interpolator ) );
animation.setFillEnabled( true );
animation.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
mWorkspace.setVisibility( View.VISIBLE );
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
getContentView().setVisibility( View.VISIBLE );
contentReady();
mWorkspace.clearChildrenCache();
mWorkspace.setCacheEnabled( false );
mWorkspace.requestLayout();
mWorkspace.postInvalidate();
}
} );
mWorkspace.startAnimation( animation );
}
/**
* Initialize the preview bitmap and canvas.
*/
private void createAndConfigurePreview() {
if ( mPreview != null && !mPreview.isRecycled() ) {
mPreview.recycle();
mPreview = null;
}
mPreview = BitmapUtils.copy( mBitmap, mBitmap.getConfig() );
mCanvas = new Canvas( mPreview );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
if ( mDownloadManager != null ) {
mDownloadManager.clearCache();
mDownloadManager.shutDownNow();
}
if( null != mPlugin ){
mPlugin.dispose();
}
mPlugin = null;
mCanvas = null;
super.onDestroy();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
onApplyCurrent( false );
super.onGenerateResult( mActionList );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onBackPressed()
*/
@Override
public boolean onBackPressed() {
if ( backHandled() ) return true;
return false;
}
/**
* Manager asked to cancel this panel Before leave ask user if he really want to leave and lose all stickers.
*
* @return true, if successful
*/
@Override
public boolean onCancel() {
if ( stickersOnScreen() ) {
askToLeaveWithoutApply();
return true;
}
return false;
}
/**
* Set the current pack as active and display its content.
*
* @param info
* the new current pack
*/
private void setCurrentPack( FeatherPack info ) {
if ( info == null ) {
getContext().downloadPlugin( FeatherIntent.PLUGIN_BASE_PACKAGE + "*", FeatherIntent.PluginType.TYPE_STICKER );
return;
}
if ( info instanceof FeatherExternalPack ) {
getContext().downloadPlugin( ( (FeatherExternalPack) info ).getPackageName(), FeatherIntent.PluginType.TYPE_STICKER );
return;
}
if( info.getStickerVersion() < mPluginService.getMinStickersVersion() || info.getStickerVersion() > mPluginService.getMaxStickersVersion() ) {
onGenericError( "The version of this plugin is not supported!" );
mLogger.error( "sticker version: " + info.getStickerVersion() );
return;
}
if( null != mPlugin ){
mPlugin.dispose();
}
mPlugin = (InternalPlugin) PluginManager.create( getContext().getBaseContext(), info );
/**
* send the event to localytics only once
*/
if ( !mPrefService.containsValue( "stickers." + info.getPackageName() ) ) {
if ( !getContext().getBaseContext().getPackageName().equals( info.getPackageName() ) ) {
mPrefService.putString( "stickers." + info.getPackageName(), info.getPackageName() );
HashMap<String, String> map = new HashMap<String, String>();
map.put( "assetType", "stickers" );
map.put( "assetID", info.getPackageName() );
Tracker.recordTag( "content: purchased", map );
}
}
setStatus( Status.Stickers );
}
/**
* Load all the available stickers packs.
*/
private void loadPacks( boolean animate ) {
updateInstalledPacks( animate );
if ( mViewFlipper.getDisplayedChild() != 0 ) {
mViewFlipper.setDisplayedChild( 0 );
}
}
/**
* Reload the installed packs and reload the workspace adapter.
*/
private void updateInstalledPacks( boolean animate ) {
if ( !isActive() ) return;
if ( getContext().getBaseContext() != null ) {
UpdateInstalledPacksTask task = new UpdateInstalledPacksTask( animate );
task.execute();
}
}
/**
* Load all the available stickers for the selected pack.
*/
private void loadStickers() {
String[] list = mPlugin.listStickers();
if ( list != null ) {
String[] listcopy = new String[list.length + 2];
System.arraycopy( list, 0, listcopy, 1, list.length );
mViewFlipper.setDisplayedChild( 1 );
getOptionView().post( new LoadStickersRunner( listcopy ) );
}
}
/**
* The Class LoadStickersRunner.
*/
private class LoadStickersRunner implements Runnable {
/** The mlist. */
String[] mlist;
/**
* Instantiates a new load stickers runner.
*
* @param list
* the list
*/
LoadStickersRunner( String[] list ) {
mlist = list;
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if ( mHList.getHeight() == 0 ) {
mOptionView.post( this );
return;
}
StickersAdapter adapter = new StickersAdapter( getContext().getBaseContext(), R.layout.feather_sticker_thumb, mlist );
mHList.setAdapter( adapter );
// setting the drag tolerance to the list view height
mHList.setDragTolerance( mHList.getHeight() );
// activate drag and drop only for android 2.3+
if ( android.os.Build.VERSION.SDK_INT > 8 ) {
mHList.setDragScrollEnabled( true );
mHList.setOnItemDragListener( new OnItemDragListener() {
@Override
public boolean onItemStartDrag( AdapterView<?> parent, View view, int position, long id ) {
return startDrag( parent, view, position, id, false );
}
} );
mHList.setLongClickable( true );
mHList.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick( AdapterView<?> parent, View view, int position, long id ) {
return startDrag( parent, view, position, id, true );
}
} );
} else {
mHList.setLongClickable( false );
}
mHList.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
final Object obj = parent.getAdapter().getItem( position );
final String sticker = (String) obj;
mLogger.log( view.getWidth() + ", " + view.getHeight() );
addSticker( sticker, null );
}
} );
mlist = null;
}
}
private boolean startDrag( AdapterView<?> parent, View view, int position, long id, boolean nativeClick ) {
if ( android.os.Build.VERSION.SDK_INT < 9 ) return false;
if ( parent == null || view == null || parent.getAdapter() == null ) {
return false;
}
if ( position == 0 || position >= parent.getAdapter().getCount() - 1 ) {
return false;
}
if ( null != view ) {
View image = view.findViewById( R.id.image );
if ( null != image ) {
final String dragInfo = (String) parent.getAdapter().getItem( position );
int size = mDownloadManager.getThumbSize();
Bitmap bitmap;
try {
bitmap = ImageLoader.loadStickerBitmap( mPlugin, dragInfo, StickerType.Small, size, size );
int offsetx = Math.abs( image.getWidth() - bitmap.getWidth() ) / 2;
int offsety = Math.abs( image.getHeight() - bitmap.getHeight() ) / 2;
return getDragController().startDrag( image, bitmap, offsetx, offsety, StickersPanel.this, dragInfo, DragControllerService.DRAG_ACTION_MOVE, nativeClick );
} catch ( Exception e ) {
e.printStackTrace();
}
return getDragController().startDrag( image, StickersPanel.this, dragInfo, DragControllerService.DRAG_ACTION_MOVE, nativeClick );
}
}
return false;
}
/**
* Inits the workspace.
*/
private void initWorkspace() {
ConfigService config = getContext().getService( ConfigService.class );
if ( config != null ) {
mWorkspaceRows = Math.max( config.getInteger( R.integer.feather_config_portraitRows ), 1 );
} else {
mWorkspaceRows = 1;
}
mWorkspaceCols = getContext().getBaseContext().getResources().getInteger( R.integer.featherStickerPacksCount );
mWorkspaceItemsPerPage = mWorkspaceRows * mWorkspaceCols;
}
/**
* Flatten the current sticker within the preview bitmap no more changes will be possible on this sticker.
*
* @param updateStatus
* the update status
*/
private void onApplyCurrent( boolean updateStatus ) {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getHighlightCount() < 1 ) return;
final DrawableHighlightView hv = ( (ImageViewDrawableOverlay) mImageView ).getHighlightViewAt( 0 );
if ( hv != null ) {
RectF cropRect = hv.getCropRectF();
Rect rect = new Rect( (int) cropRect.left, (int) cropRect.top, (int) cropRect.right, (int) cropRect.bottom );
Matrix rotateMatrix = hv.getCropRotationMatrix();
Matrix matrix = new Matrix( mImageView.getImageMatrix() );
if ( !matrix.invert( matrix ) ) {}
int saveCount = mCanvas.save( Canvas.MATRIX_SAVE_FLAG );
mCanvas.concat( rotateMatrix );
( (StickerDrawable) hv.getContent() ).setDropShadow( false );
hv.getContent().setBounds( rect );
hv.getContent().draw( mCanvas );
mCanvas.restoreToCount( saveCount );
mImageView.invalidate();
if ( mCurrentAction != null ) {
final int w = mBitmap.getWidth();
final int h = mBitmap.getHeight();
mCurrentAction.setValue( "topleft", new MoaPointParameter( cropRect.left / w, cropRect.top / h ) );
mCurrentAction.setValue( "bottomright", new MoaPointParameter( cropRect.right / w, cropRect.bottom / h ) );
mCurrentAction.setValue( "rotation", Math.toRadians( hv.getRotation() ) );
int dw = ( (StickerDrawable) hv.getContent() ).getBitmapWidth();
int dh = ( (StickerDrawable) hv.getContent() ).getBitmapHeight();
float scalew = cropRect.width() / dw;
float scaleh = cropRect.height() / dh;
// version 2
mCurrentAction.setValue( "center", new MoaPointParameter( cropRect.centerX() / w, cropRect.centerY() / h ) );
mCurrentAction.setValue( "scale", new MoaPointParameter( scalew, scaleh ) );
mActionList.add( mCurrentAction );
mCurrentAction = null;
}
}
onClearCurrent( true, updateStatus );
onPreviewChanged( mPreview, false );
}
/**
* Remove the current sticker.
*
* @param isApplying
* if true is passed it means we're currently in the "applying" status
* @param updateStatus
* if true will update the internal status
*/
private void onClearCurrent( boolean isApplying, boolean updateStatus ) {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
if ( image.getHighlightCount() > 0 ) {
final DrawableHighlightView hv = image.getHighlightViewAt( 0 );
onClearCurrent( hv, isApplying, updateStatus );
}
}
/**
* removes the current active sticker.
*
* @param hv
* the hv
* @param isApplying
* if panel is in the onGenerateResult state
* @param updateStatus
* update the panel status
*/
private void onClearCurrent( DrawableHighlightView hv, boolean isApplying, boolean updateStatus ) {
if ( mCurrentAction != null ) {
mCurrentAction = null;
}
if ( !isApplying ) {
FeatherDrawable content = hv.getContent();
String name;
String packagename;
if ( content instanceof StickerDrawable ) {
name = ( (StickerDrawable) content ).getName();
packagename = ( (StickerDrawable) content ).getPackageName();
if ( mUsedStickers.size() > 0 ) mUsedStickers.remove( name );
if ( mUsedStickersPacks.size() > 0 ) mUsedStickersPacks.remove( packagename );
} else {
if ( mUsedStickers.size() > 0 ) mUsedStickers.remove( mUsedStickers.size() - 1 );
if ( mUsedStickersPacks.size() > 0 ) mUsedStickersPacks.remove( mUsedStickersPacks.size() - 1 );
}
}
hv.setOnDeleteClickListener( null );
( (ImageViewDrawableOverlay) mImageView ).removeHightlightView( hv );
( (ImageViewDrawableOverlay) mImageView ).invalidate();
if ( updateStatus ) setStatus( Status.Stickers );
}
/**
* Add a new sticker to the canvas.
*
* @param drawable
* the drawable
*/
private void addSticker( String drawable, RectF position ) {
onApplyCurrent( false );
mLogger.info( "addSticker: " + drawable );
final boolean rotateAndResize = true;
InputStream stream = null;
try {
stream = mPlugin.getStickerStream( drawable, StickerType.Small );
} catch ( Exception e ) {
e.printStackTrace();
onGenericError( "Failed to load the selected sticker" );
return;
}
if ( stream != null ) {
StickerDrawable d = new StickerDrawable( mPlugin.getResources(), stream, mPlugin.getPackageName(), drawable );
d.setAntiAlias( true );
mUsedStickers.add( drawable );
mUsedStickersPacks.add( mPlugin.getPackageName() );
addSticker( d, rotateAndResize, position );
IOUtils.closeSilently( stream );
// adding the required action
ApplicationInfo info = PackageManagerUtils.getApplicationInfo( getContext().getBaseContext(), mPlugin.getPackageName() );
if ( info != null ) {
mCurrentAction = MoaActionFactory.action( "addsticker" );
String sourceDir = mPlugin.getSourceDir( PluginType.TYPE_STICKER );
if( null != sourceDir ) {
mCurrentAction.setValue( "source", sourceDir );
mLogger.log( "source-dir: " + sourceDir );
} else {
mLogger.error("Cannot find the source dir");
}
mCurrentAction.setValue( "url", drawable );
// version 2
mCurrentAction.setValue( "size", new MoaPointParameter( d.getBitmapWidth(), d.getBitmapHeight() ) );
mCurrentAction.setValue( "external", 0 );
}
}
}
/**
* Adds the sticker.
*
* @param drawable
* the drawable
* @param rotateAndResize
* the rotate and resize
*/
private void addSticker( FeatherDrawable drawable, boolean rotateAndResize, RectF positionRect ) {
setIsChanged( true );
DrawableHighlightView hv = new DrawableHighlightView( mImageView, drawable );
hv.setMinSize( mStickerMinSize );
hv.setOnDeleteClickListener( new OnDeleteClickListener() {
@Override
public void onDeleteClick() {
onClearCurrent( false, true );
}
} );
Matrix mImageMatrix = mImageView.getImageViewMatrix();
int cropWidth, cropHeight;
int x, y;
final int width = mImageView.getWidth();
final int height = mImageView.getHeight();
// width/height of the sticker
if ( positionRect != null ) {
cropWidth = (int) positionRect.width();
cropHeight = (int) positionRect.height();
} else {
cropWidth = drawable.getIntrinsicWidth();
cropHeight = drawable.getIntrinsicHeight();
}
final int cropSize = Math.max( cropWidth, cropHeight );
final int screenSize = Math.min( mImageView.getWidth(), mImageView.getHeight() );
if ( cropSize > screenSize ) {
float ratio;
float widthRatio = (float) mImageView.getWidth() / cropWidth;
float heightRatio = (float) mImageView.getHeight() / cropHeight;
if ( widthRatio < heightRatio ) {
ratio = widthRatio;
} else {
ratio = heightRatio;
}
cropWidth = (int) ( (float) cropWidth * ( ratio / 2 ) );
cropHeight = (int) ( (float) cropHeight * ( ratio / 2 ) );
if( positionRect == null ) {
int w = mImageView.getWidth();
int h = mImageView.getHeight();
positionRect = new RectF( w/2-cropWidth/2, h/2-cropHeight/2, w/2+cropWidth/2, h/2+cropHeight/2 );
}
positionRect.inset( ( positionRect.width() - cropWidth ) / 2, ( positionRect.height() - cropHeight ) / 2 );
}
if ( positionRect != null ) {
x = (int) positionRect.left;
y = (int) positionRect.top;
} else {
x = ( width - cropWidth ) / 2;
y = ( height - cropHeight ) / 2;
}
Matrix matrix = new Matrix( mImageMatrix );
matrix.invert( matrix );
float[] pts = new float[] { x, y, x + cropWidth, y + cropHeight };
MatrixUtils.mapPoints( matrix, pts );
RectF cropRect = new RectF( pts[0], pts[1], pts[2], pts[3] );
Rect imageRect = new Rect( 0, 0, width, height );
hv.setRotateAndScale( rotateAndResize );
hv.setup( mImageMatrix, imageRect, cropRect, false );
hv.drawOutlineFill( true );
hv.drawOutlineStroke( true );
hv.setPadding( mStickerHvPadding );
hv.setOutlineStrokeColor( mStickerHvStrokeColorStateList );
hv.setOutlineFillColor( mStickerHvFillColorStateList );
hv.setOutlineEllipse( mStickerHvEllipse );
hv.setMinSize( mStickerHvMinSize );
Paint stroke = hv.getOutlineStrokePaint();
stroke.setStrokeWidth( mStickerHvStrokeWidth );
hv.getOutlineFillPaint().setXfermode( new PorterDuffXfermode( android.graphics.PorterDuff.Mode.SRC_ATOP ) );
( (ImageViewDrawableOverlay) mImageView ).addHighlightView( hv );
( (ImageViewDrawableOverlay) mImageView ).setSelectedHighlightView( hv );
}
/**
* The Class StickersPacksAdapter.
*/
class StickersPacksAdapter extends ArrayAdapter<FeatherPack> {
int screenId, cellId;
LayoutInflater mLayoutInflater;
long mCurrentDate;
boolean mInFirstLayout = true;
String mGetMoreLabel;
Drawable mFolderIcon, mGetMoreIcon, mGetMoreFreeIcon;
Typeface mPackTypeface;
/**
* Instantiates a new stickers packs adapter.
*
* @param context
* the context
* @param resource
* the resource
* @param textViewResourceId
* the text view resource id
* @param objects
* the objects
*/
public StickersPacksAdapter( Context context, int resource, int textViewResourceId, FeatherPack objects[] ) {
super( context, resource, textViewResourceId, objects );
screenId = resource;
cellId = textViewResourceId;
mLayoutInflater = UIUtils.getLayoutInflater();
mCurrentDate = System.currentTimeMillis();
mGetMoreLabel = context.getString( R.string.get_more );
mFolderIcon = context.getResources().getDrawable( R.drawable.feather_sticker_pack_background );
mGetMoreIcon = context.getResources().getDrawable( R.drawable.feather_sticker_pack_background );
mGetMoreFreeIcon = context.getResources().getDrawable( R.drawable.feather_sticker_pack_background_free_more );
String packFont = context.getString( R.string.feather_sticker_pack_font );
if ( null != packFont && packFont.length() > 1 ) {
try {
mPackTypeface = TypefaceUtils.createFromAsset( context.getAssets(), packFont );
} catch ( Throwable t ) {
t.printStackTrace();
}
}
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getCount()
*/
@Override
public int getCount() {
return (int) Math.ceil( (double) ( super.getCount() ) / mWorkspaceItemsPerPage );
}
/**
* Gets the real count.
*
* @return the real count
*/
public int getRealCount() {
return super.getCount();
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
CellLayout view;
if ( convertView == null ) {
view = (CellLayout) mLayoutInflater.inflate( screenId, mWorkspace, false );
view.setNumCols( mWorkspaceCols );
} else {
view = (CellLayout) convertView;
}
int index = position * mWorkspaceItemsPerPage;
int count = getRealCount();
for ( int i = 0; i < mWorkspaceItemsPerPage; i++ ) {
View itemView = null;
CellInfo cellInfo = view.findVacantCell( 1, 1 );
if ( cellInfo == null ) {
itemView = view.getChildAt( i );
} else {
itemView = mLayoutInflater.inflate( cellId, parent, false );
CellLayout.LayoutParams lp = new CellLayout.LayoutParams( cellInfo.cellX, cellInfo.cellY, cellInfo.spanH, cellInfo.spanV );
view.addView( itemView, -1, lp );
}
if ( ( index + i ) < count ) {
final FeatherPack appInfo = getItem( index + i );
final IPlugin plugin = PluginManager.create( getContext(), appInfo );
CharSequence label;
Drawable icon;
if ( appInfo == null ) {
label = mGetMoreLabel;
icon = mGetMoreIcon;
} else {
label = plugin.getLabel( PluginType.TYPE_STICKER );
if ( plugin.isLocal() ) {
icon = plugin.getIcon( PluginType.TYPE_STICKER );
icon = UIUtils.drawFolderIcon( mFolderIcon, icon, null );
} else {
if ( plugin.isFree() ) {
icon = mGetMoreFreeIcon;
} else {
icon = mGetMoreIcon;
}
}
}
ImageView image = (ImageView) itemView.findViewById( R.id.image );
TextView text = (TextView) itemView.findViewById( R.id.text );
if ( null != mPackTypeface ) {
text.setTypeface( mPackTypeface );
}
image.setImageDrawable( icon );
text.setText( label );
itemView.setTag( appInfo );
itemView.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
setCurrentPack( appInfo );
}
} );
itemView.setVisibility( View.VISIBLE );
} else {
itemView.setVisibility( View.INVISIBLE );
}
}
mInFirstLayout = false;
view.setSelected( false );
return view;
}
}
class StickersAdapter extends ArrayAdapter<String> {
private LayoutInflater mLayoutInflater;
private int mStickerResourceId;
private int mFinalSize;
private int mContainerHeight;
/**
* Instantiates a new stickers adapter.
*
* @param context
* the context
* @param textViewResourceId
* the text view resource id
* @param objects
* the objects
*/
public StickersAdapter( Context context, int textViewResourceId, String[] objects ) {
super( context, textViewResourceId, objects );
mLogger.info( "StickersAdapter. size: " + objects.length );
mStickerResourceId = textViewResourceId;
mLayoutInflater = UIUtils.getLayoutInflater();
mContainerHeight = mHList.getHeight() - ( mHList.getPaddingBottom() + mHList.getPaddingTop() );
mFinalSize = (int) ( (float) mContainerHeight * ( 4.0 / 5.0 ) );
mLogger.log( "gallery height: " + mContainerHeight );
mLogger.log( "final size: " + mFinalSize );
mDownloadManager.setThumbSize( mFinalSize - 10 );
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getCount()
*/
@Override
public int getCount() {
return super.getCount();
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
View retval = mLayoutInflater.inflate( mStickerResourceId, null );
ImageView image = (ImageView) retval.findViewById( R.id.image );
ImageView background = (ImageView) retval.findViewById( R.id.background );
retval.setLayoutParams( new LinearLayout.LayoutParams( mContainerHeight, LayoutParams.MATCH_PARENT ) );
if ( position == 0 ) {
image.setVisibility( View.INVISIBLE );
background.setImageResource( R.drawable.feather_sticker_paper_left_edge );
} else if ( position >= getCount() - 1 ) {
background.setImageResource( R.drawable.feather_sticker_paper_center_1 );
} else {
if ( position % 2 == 0 ) {
background.setImageResource( R.drawable.feather_sticker_paper_center_1 );
} else {
background.setImageResource( R.drawable.feather_sticker_paper_center_2 );
}
loadStickerForImage( position, image );
}
return retval;
}
/**
* Load sticker for image.
*
* @param position
* the position
* @param view
* the view
*/
private void loadStickerForImage( int position, ImageView view ) {
final String sticker = getItem( position );
mDownloadManager.loadStickerAsset( mPlugin, sticker, null, view );
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_stickers_content, null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
ViewGroup view = (ViewGroup) inflater.inflate( R.layout.feather_stickers_panel, parent, false );
return view;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onComplete(android.graphics.Bitmap)
*/
@Override
protected void onComplete( Bitmap bitmap, MoaActionList actionlist ) {
mTrackingAttributes.put( "stickerCount", Integer.toString( mUsedStickers.size() ) );
mTrackingAttributes.put( "stickerNames", getUsedStickersNames().toString() );
mTrackingAttributes.put( "packNames", getUsedPacksNames().toString() );
super.onComplete( bitmap, actionlist );
}
/**
* Gets the used stickers names.
*
* @return the used stickers names
*/
StringBuilder getUsedStickersNames() {
StringBuilder sb = new StringBuilder();
for ( String s : mUsedStickers ) {
sb.append( s );
sb.append( "," );
}
mLogger.log( "used stickers: " + sb.toString() );
return sb;
}
/**
* Gets the used packs names.
*
* @return the used packs names
*/
StringBuilder getUsedPacksNames() {
SortedSet<String> map = new TreeSet<String>();
StringBuilder sb = new StringBuilder();
for ( String s : mUsedStickersPacks ) {
map.add( s );
}
for ( String s : map ) {
sb.append( s );
sb.append( "," );
}
mLogger.log( "packs: " + sb.toString() );
return sb;
}
/** The m update dialog. */
private AlertDialog mUpdateDialog;
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.PluginService.OnUpdateListener#onUpdate(android.os.Bundle)
*/
@Override
public void onUpdate( Bundle delta ) {
mLogger.info( "onUpdate: " + delta );
if ( isActive() ) {
if ( !validDelta( delta ) ) {
mLogger.log( "Suppress the alert, no stickers in the delta bundle" );
return;
}
if ( mUpdateDialog != null && mUpdateDialog.isShowing() ) {
mLogger.log( "dialog is already there, skip new alerts" );
return;
}
// update the available packs...
AlertDialog dialog = null;
switch ( mStatus ) {
case Null:
case Packs:
dialog = new AlertDialog.Builder( getContext().getBaseContext() ).setMessage( R.string.sticker_pack_updated_1 ).setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
loadPacks( false );
}
} ).create();
break;
case Stickers:
if ( stickersOnScreen() ) {
dialog = new AlertDialog.Builder( getContext().getBaseContext() ).setMessage( R.string.sticker_pack_updated_3 ).setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
onApplyCurrent( false );
setStatus( Status.Packs );
updateInstalledPacks( false );
}
} ).setNegativeButton( android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
onClearCurrent( false, false );
setStatus( Status.Packs );
updateInstalledPacks( false );
}
} ).create();
} else {
dialog = new AlertDialog.Builder( getContext().getBaseContext() ).setMessage( R.string.sticker_pack_updated_2 ).setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
setStatus( Status.Packs );
updateInstalledPacks( false );
}
} ).create();
}
break;
}
if ( dialog != null ) {
mUpdateDialog = dialog;
mUpdateDialog.setCancelable( false );
mUpdateDialog.show();
}
}
}
/**
* bundle contains a list of all updates applications. if one meets the criteria ( is a filter apk ) then return true
*
* @param bundle
* the bundle
* @return true if bundle contains a valid filter package
*/
private boolean validDelta( Bundle bundle ) {
if ( null != bundle ) {
if ( bundle.containsKey( "delta" ) ) {
try {
@SuppressWarnings("unchecked")
ArrayList<UpdateType> updates = (ArrayList<UpdateType>) bundle.getSerializable( "delta" );
if ( null != updates ) {
for ( UpdateType update : updates ) {
if ( FeatherIntent.PluginType.isSticker( update.getPluginType() ) ) {
return true;
}
if ( FeatherIntent.ACTION_PLUGIN_REMOVED.equals( update.getAction() ) ) {
// if it's removed check against current listed packs
if ( mInstalledPackages.contains( update.getPackageName() ) ) {
return true;
}
}
}
return false;
}
} catch ( ClassCastException e ) {
return true;
}
}
}
return true;
}
/** The m handler. */
private static final Handler mHandler = new Handler() {
@Override
public void handleMessage( Message msg ) {
switch ( msg.what ) {
case AssetsAsyncDownloadManager.THUMBNAIL_LOADED:
Thumb thumb = (Thumb) msg.obj;
if ( thumb.image != null && thumb.bitmap != null ) {
thumb.image.setImageDrawable( new StickerBitmapDrawable( thumb.bitmap, 10 ) );
}
break;
}
}
};
//
// STATUS
//
/** The is animating. */
boolean isAnimating = false;
/**
* Back Button is pressed. Handle the event if we're not in the top folder list, otherwise always handle it
*
* @return true if the event has been handled
*/
boolean backHandled() {
mLogger.error( "onBackPressed: " + mStatus + " ( is_animating? " + isAnimating + " )" );
if ( isAnimating ) return true;
switch ( mStatus ) {
case Null:
case Packs:
// we're in the root folder, so we dont need
// to handle the back button anymore ( exit the current panel )
if ( stickersOnScreen() ) {
askToLeaveWithoutApply();
return true;
}
return false;
case Stickers:
if ( mExternalPacksEnabled ) {
// if we wont allow more stickers or if there is only
// one pack installed then we wanna exit the current panel
setStatus( Status.Packs );
return true;
} else {
if ( stickersOnScreen() ) {
askToLeaveWithoutApply();
return true;
}
}
return false;
}
return false;
}
/**
* Ask to leave without apply.
*/
void askToLeaveWithoutApply() {
new AlertDialog.Builder( getContext().getBaseContext() ).setTitle( R.string.attention ).setMessage( R.string.tool_leave_question ).setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
getContext().cancel();
}
} ).setNegativeButton( android.R.string.no, null ).show();
}
/**
* Sets the status.
*
* @param status
* the new status
*/
void setStatus( Status status ) {
mLogger.error( "setStatus: " + mStatus + " >> " + status + " ( is animating? " + isAnimating + " )" );
if ( status != mStatus ) {
mPrevStatus = mStatus;
mStatus = status;
switch ( mStatus ) {
case Null:
// we never want to go to this status!
break;
case Packs: {
// move to the packs list view
if ( mPrevStatus == Status.Null ) {
loadPacks( true );
} else if ( mPrevStatus == Status.Stickers ) {
mViewFlipper.setDisplayedChild( 0 );
}
}
break;
case Stickers: {
if ( mPrevStatus == Status.Null || mPrevStatus == Status.Packs ) {
loadStickers();
}
}
break;
}
}
}
/**
* Stickers on screen.
*
* @return true, if successful
*/
private boolean stickersOnScreen() {
final ImageViewDrawableOverlay image = (ImageViewDrawableOverlay) mImageView;
mLogger.info( "stickers on screen?", mStatus, image.getHighlightCount() );
return image.getHighlightCount() > 0;
}
@Override
public void onDragStart( DragSource source, Object info, int dragAction ) {
mLogger.info( "onDragStart" );
mHList.setIsDragging( true );
}
@Override
public void onDragEnd() {
mLogger.info( "onDragEnd" );
mHList.setIsDragging( false );
}
@Override
public void onDropCompleted( View target, boolean success ) {
mLogger.info( "onDropCompleted: " + target + ", success: " + success );
mHList.setIsDragging( false );
}
@Override
public void setDragController( DragControllerService controller ) {
mDragController = controller;
}
@Override
public DragControllerService getDragController() {
return mDragController;
}
@Override
public boolean acceptDrop( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
return source == this;
}
@Override
public void onDrop( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
if ( dragInfo != null && dragInfo instanceof String ) {
String sticker = (String) dragInfo;
onApplyCurrent( true );
float scaleFactor = dragView.getScaleFactor();
float w = dragView.getWidth();
float h = dragView.getHeight();
int width = (int) ( w / scaleFactor );
int height = (int) ( h / scaleFactor );
mLogger.log( "sticker.size: " + width + "x" + height );
int targetX = (int) ( x - xOffset );
int targetY = (int) ( y - yOffset );
RectF rect = new RectF( targetX, targetY, targetX + width, targetY + height );
addSticker( sticker, rect );
}
}
// updated installed package names
private class UpdateInstalledPacksTask extends AsyncTask<Void, Void, FeatherPack[]> {
private boolean mPostAnimate;
UpdateInstalledPacksTask( boolean postAnimate ) {
mPostAnimate = postAnimate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mLayoutLoader.setVisibility( View.VISIBLE );
mWorkspace.setVisibility( View.INVISIBLE );
}
@Override
protected FeatherPack[] doInBackground( Void... params ) {
if ( getContext().getBaseContext() != null ) {
PluginService service = getContext().getService( PluginService.class );
if ( null != service ) {
while ( !service.isUpdated() ) {
try {
Thread.sleep( 50 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
FeatherPack[] packs = service.getInstalled( getContext().getBaseContext(), FeatherIntent.PluginType.TYPE_STICKER );
FeatherPack[] packs2 = service.getAvailable( FeatherIntent.PluginType.TYPE_STICKER );
int newlen = 0;
if ( null != packs && null != packs2 ) {
newlen = packs.length + packs2.length;
}
FeatherPack[] packs3 = new FeatherPack[newlen];
if ( null != packs ) System.arraycopy( packs, 0, packs3, 0, packs.length );
if ( null != packs2 ) System.arraycopy( packs2, 0, packs3, packs.length, packs2.length );
mInstalledPackages.clear();
if ( null != packs ) {
for ( FeatherPack pack : packs ) {
if ( !mInstalledPackages.contains( pack ) ) mInstalledPackages.add( pack.getPackageName() );
}
}
return packs3;
}
return new FeatherPack[0];
}
@Override
protected void onPostExecute( FeatherPack[] result ) {
super.onPostExecute( result );
StickersPacksAdapter adapter = new StickersPacksAdapter( getContext().getBaseContext(), R.layout.feather_workspace_screen, R.layout.feather_sticker_pack, result );
mWorkspace.setAdapter( adapter );
mWorkspaceIndicator.setVisibility( mWorkspace.getTotalPages() > 1 ? View.VISIBLE : View.INVISIBLE );
mDownloadManager.clearCache();
mLayoutLoader.setVisibility( View.GONE );
if ( mPostAnimate ) {
startFirstAnimation();
} else {
mWorkspace.setVisibility( View.VISIBLE );
}
}
}
}
| Java |
package com.aviary.android.feather.effects;
import java.util.HashSet;
import org.json.JSONException;
import android.R.attr;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.CropCheckboxDrawable;
import com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable;
import com.aviary.android.feather.library.filters.CropFilter;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.moa.MoaPointParameter;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.AdapterView;
import com.aviary.android.feather.widget.CropImageView;
import com.aviary.android.feather.widget.Gallery;
import com.aviary.android.feather.widget.Gallery.OnItemsScrollListener;
import com.aviary.android.feather.widget.HighlightView;
// TODO: Auto-generated Javadoc
/**
* The Class CropPanel.
*/
public class CropPanel extends AbstractContentPanel {
Gallery mGallery;
String[] mCropNames, mCropValues;
View mSelected;
int mSelectedPosition = 0;
boolean mIsPortrait = true;
final static int noImage = 0;
HashSet<Integer> nonInvertOptions = new HashSet<Integer>();
/* whether to use inversion and photo size detection */
boolean strict = false;
/** Whether or not the proportions are inverted */
boolean isChecked = false;
/**
* Instantiates a new crop panel.
*
* @param context
* the context
*/
public CropPanel( EffectContext context ) {
super( context );
}
private void invertRatios( String[] names, String[] values ) {
for ( int i = 0; i < names.length; i++ ) {
if ( names[i].contains( ":" ) ) {
String temp = names[i];
String[] splitted = temp.split( "[:]" );
String mNewOptionName = splitted[1] + ":" + splitted[0];
names[i] = mNewOptionName;
}
if ( values[i].contains( ":" ) ) {
String temp = values[i];
String[] splitted = temp.split( "[:]" );
String mNewOptionValue = splitted[1] + ":" + splitted[0];
values[i] = mNewOptionValue;
}
}
}
private void populateInvertOptions( HashSet<Integer> options, String[] cropValues ) {
for ( int i = 0; i < cropValues.length; i++ ) {
String value = cropValues[i];
String[] values = value.split( ":" );
int x = Integer.parseInt( values[0] );
int y = Integer.parseInt( values[1] );
if ( x == y ) {
options.add( i );
}
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
ConfigService config = getContext().getService( ConfigService.class );
mFilter = FilterLoaderFactory.get( Filters.CROP );
mCropNames = config.getStringArray( R.array.feather_crop_names );
mCropValues = config.getStringArray( R.array.feather_crop_values );
strict = config.getBoolean( R.integer.feather_crop_invert_policy );
if ( !strict ) {
if ( bitmap.getHeight() > bitmap.getWidth() ) {
mIsPortrait = true;
} else {
mIsPortrait = false;
}
// configure options that will not invert
populateInvertOptions( nonInvertOptions, mCropValues );
if ( mIsPortrait ) {
invertRatios( mCropNames, mCropValues );
}
}
mSelectedPosition = config.getInteger( R.integer.feather_crop_selected_value );
mImageView = (CropImageView) getContentView().findViewById( R.id.crop_image_view );
mImageView.setDoubleTapEnabled( false );
int minAreaSize = config.getInteger( R.integer.feather_crop_min_size );
( (CropImageView) mImageView ).setMinCropSize( minAreaSize );
mGallery = (Gallery) getOptionView().findViewById( R.id.gallery );
mGallery.setCallbackDuringFling( false );
mGallery.setSpacing( 0 );
mGallery.setAdapter( new GalleryAdapter( getContext().getBaseContext(), mCropNames ) );
mGallery.setSelection( mSelectedPosition, false, true );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
int position = mGallery.getSelectedItemPosition();
final double ratio = calculateAspectRatio( position, false );
disableHapticIsNecessary( mGallery );
setIsChanged( true );
contentReady();
mGallery.setOnItemsScrollListener( new OnItemsScrollListener() {
@Override
public void onScrollFinished( AdapterView<?> parent, View view, int position, long id ) {
if ( !isActive() ) return;
if ( position == mSelectedPosition ) {
if ( !strict && !nonInvertOptions.contains( position ) ) {
isChecked = !isChecked;
CropImageView cview = (CropImageView) mImageView;
double currentAspectRatio = cview.getAspectRatio();
HighlightView hv = cview.getHighlightView();
if ( !cview.getAspectRatioIsFixed() && hv != null ) {
currentAspectRatio = (double) hv.getDrawRect().width() / (double) hv.getDrawRect().height();
}
double invertedAspectRatio = 1 / currentAspectRatio;
cview.setAspectRatio( invertedAspectRatio, cview.getAspectRatioIsFixed() );
invertRatios( mCropNames, mCropValues );
mGallery.invalidateViews();
}
} else {
double ratio = calculateAspectRatio( position, false );
setCustomRatio( ratio, ratio != 0 );
}
updateSelection( view, position );
}
@Override
public void onScrollStarted( AdapterView<?> parent, View view, int position, long id ) {}
@Override
public void onScroll( AdapterView<?> parent, View view, int position, long id ) {}
} );
getOptionView().getHandler().post( new Runnable() {
@Override
public void run() {
createCropView( ratio, ratio != 0 );
updateSelection( (View) mGallery.getSelectedView(), mGallery.getSelectedItemPosition() );
}
} );
}
/**
* Calculate aspect ratio.
*
* @param position
* the position
* @param inverted
* the inverted
* @return the double
*/
private double calculateAspectRatio( int position, boolean inverted ) {
String value = mCropValues[position];
String[] values = value.split( ":" );
if ( values.length == 2 ) {
int aspectx = Integer.parseInt( inverted ? values[1] : values[0] );
int aspecty = Integer.parseInt( inverted ? values[0] : values[1] );
if ( aspectx == -1 ) {
aspectx = inverted ? mBitmap.getHeight() : mBitmap.getWidth();
}
if ( aspecty == -1 ) {
aspecty = inverted ? mBitmap.getWidth() : mBitmap.getHeight();
}
double ratio = 0;
if ( aspectx != 0 && aspecty != 0 ) {
ratio = (double) aspectx / (double) aspecty;
}
return ratio;
}
return 0;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
mImageView.clear();
( (CropImageView) mImageView ).setOnHighlightSingleTapUpConfirmedListener( null );
super.onDestroy();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
super.onDeactivate();
}
/**
* Creates the crop view.
*
* @param aspectRatio
* the aspect ratio
*/
private void createCropView( double aspectRatio, boolean isFixed ) {
( (CropImageView) mImageView ).setImageBitmap( mBitmap, aspectRatio, isFixed );
}
/**
* Sets the custom ratio.
*
* @param aspectRatio
* the aspect ratio
* @param isFixed
* the is fixed
*/
private void setCustomRatio( double aspectRatio, boolean isFixed ) {
( (CropImageView) mImageView ).setAspectRatio( aspectRatio, isFixed );
}
/**
* Update selection.
*
* @param newSelection
* the new selection
* @param position
* the position
*/
protected void updateSelection( View newSelection, int position ) {
if ( mSelected != null ) {
String label = (String) mSelected.getTag();
if ( label != null ) {
View textview = mSelected.findViewById( R.id.text );
if ( null != textview ) {
( (TextView) textview ).setText( getString( label ) );
}
View arrow = mSelected.findViewById( R.id.invertCropArrow );
if ( null != arrow ) {
arrow.setVisibility( View.INVISIBLE );
}
}
mSelected.setSelected( false );
}
mSelected = newSelection;
mSelectedPosition = position;
if ( mSelected != null ) {
mSelected = newSelection;
mSelected.setSelected( true );
View arrow = mSelected.findViewById( R.id.invertCropArrow );
if ( null != arrow && !nonInvertOptions.contains( position ) && !strict ) {
arrow.setVisibility( View.VISIBLE );
arrow.setSelected( isChecked );
} else {
arrow.setVisibility( View.INVISIBLE );
}
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
Rect crop_rect = ( (CropImageView) mImageView ).getHighlightView().getCropRect();
GenerateResultTask task = new GenerateResultTask( crop_rect );
task.execute( mBitmap );
}
/**
* Generate bitmap.
*
* @param bitmap
* the bitmap
* @param cropRect
* the crop rect
* @return the bitmap
*/
@SuppressWarnings("unused")
private Bitmap generateBitmap( Bitmap bitmap, Rect cropRect ) {
Bitmap croppedImage;
int width = cropRect.width();
int height = cropRect.height();
croppedImage = Bitmap.createBitmap( width, height, Bitmap.Config.RGB_565 );
Canvas canvas = new Canvas( croppedImage );
Rect dstRect = new Rect( 0, 0, width, height );
canvas.drawBitmap( mBitmap, cropRect, dstRect, null );
return croppedImage;
}
/**
* The Class GenerateResultTask.
*/
class GenerateResultTask extends AsyncTask<Bitmap, Void, Bitmap> {
/** The m crop rect. */
Rect mCropRect;
MoaActionList mActionList;
/**
* Instantiates a new generate result task.
*
* @param rect
* the rect
*/
public GenerateResultTask( Rect rect ) {
mCropRect = rect;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
onProgressModalStart();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Bitmap doInBackground( Bitmap... arg0 ) {
final Bitmap bitmap = arg0[0];
MoaPointParameter topLeft = new MoaPointParameter();
topLeft.setValue( (double) mCropRect.left / bitmap.getWidth(), (double) mCropRect.top / bitmap.getHeight() );
MoaPointParameter size = new MoaPointParameter();
size.setValue( (double) mCropRect.width() / bitmap.getWidth(), (double) mCropRect.height() / bitmap.getHeight() );
( (CropFilter) mFilter ).setTopLeft( topLeft );
( (CropFilter) mFilter ).setSize( size );
mActionList = (MoaActionList) ( (CropFilter) mFilter ).getActions().clone();
try {
return ( (CropFilter) mFilter ).execute( arg0[0], null, 1, 1 );
} catch ( JSONException e ) {
e.printStackTrace();
}
return arg0[0];
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
onProgressModalEnd();
( (CropImageView) mImageView ).setImageBitmap( result, ( (CropImageView) mImageView ).getAspectRatio(),
( (CropImageView) mImageView ).getAspectRatioIsFixed() );
( (CropImageView) mImageView ).setHighlightView( null );
onComplete( result, mActionList );
}
}
@Override
protected View generateContentView( LayoutInflater inflater ) {
View view = inflater.inflate( R.layout.feather_crop_content, null );
if ( SystemUtils.isHoneyComb() ) {
// Honeycomb bug with canvas clip
try {
ReflectionUtils.invokeMethod( view, "setLayerType", new Class[] { int.class, Paint.class }, 1, null );
} catch ( ReflectionException e ) {}
}
return view;
}
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_crop_panel, parent, false );
}
@Override
public Matrix getContentDisplayMatrix() {
return mImageView.getDisplayMatrix();
}
@Override
public void onConfigurationChanged( Configuration newConfig, Configuration oldConfig ) {
super.onConfigurationChanged( newConfig, oldConfig );
}
private String getString( String input ) {
int id = getContext().getBaseContext().getResources()
.getIdentifier( input, "string", getContext().getBaseContext().getPackageName() );
if ( id > 0 ) {
return getContext().getBaseContext().getResources().getString( id );
}
return input;
}
class GalleryAdapter extends BaseAdapter {
private String[] mStrings;
LayoutInflater mLayoutInflater;
Resources mRes;
private static final int VALID_POSITION = 0;
private static final int INVALID_POSITION = 1;
/**
* Instantiates a new gallery adapter.
*
* @param context
* the context
* @param values
* the values
*/
public GalleryAdapter( Context context, String[] values ) {
mLayoutInflater = UIUtils.getLayoutInflater();
mStrings = values;
mRes = getContext().getBaseContext().getResources();
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return mStrings.length;
}
public void updateStrings() {
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem( int position ) {
return mStrings[position];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return 0;
}
/*
* (non-Javadoc)
*
* @see android.widget.BaseAdapter#getViewTypeCount()
*/
@Override
public int getViewTypeCount() {
return 2;
}
/*
* (non-Javadoc)
*
* @see android.widget.BaseAdapter#getItemViewType(int)
*/
@Override
public int getItemViewType( int position ) {
final boolean valid = position >= 0 && position < getCount();
return valid ? VALID_POSITION : INVALID_POSITION;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@SuppressWarnings("deprecation")
@Override
public View getView( final int position, View convertView, ViewGroup parent ) {
int type = getItemViewType( position );
final View view;
if ( convertView == null ) {
if ( type == VALID_POSITION ) {
// use the default crop checkbox view
view = mLayoutInflater.inflate( R.layout.feather_crop_button, mGallery, false );
StateListDrawable st = new StateListDrawable();
Drawable unselectedBackground = new CropCheckboxDrawable( mRes, false, null, 1.0f, 0, 0 );
Drawable selectedBackground = new CropCheckboxDrawable( mRes, true, null, 1.0f, 0, 0 );
st.addState( new int[] { -attr.state_selected }, unselectedBackground );
st.addState( new int[] { attr.state_selected }, selectedBackground );
view.setBackgroundDrawable( st );
} else {
// use the blank view
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGallery, false );
Drawable unselectedBackground = new DefaultGalleryCheckboxDrawable( mRes, false );
view.setBackgroundDrawable( unselectedBackground );
}
} else {
view = convertView;
}
view.setSelected( mSelectedPosition == position );
if ( type == VALID_POSITION ) {
Object item = getItem( position );
view.setTag( item );
if ( null != item ) {
TextView text = (TextView) view.findViewById( R.id.text );
String textValue = "";
if ( position >= 0 && position < mStrings.length ) textValue = mStrings[position];
if ( null != text ) text.setText( getString( textValue ) );
View arrow = view.findViewById( R.id.invertCropArrow );
int targetVisibility;
if ( mSelectedPosition == position && !strict ) {
mSelected = view;
if ( null != arrow && !nonInvertOptions.contains( position ) ) {
targetVisibility = View.VISIBLE;
} else {
targetVisibility = View.INVISIBLE;
}
} else {
targetVisibility = View.INVISIBLE;
}
if( null != arrow ){
arrow.setVisibility( targetVisibility );
arrow.setSelected( isChecked );
}
}
}
return view;
}
}
}
| Java |
package com.aviary.android.feather.effects;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import android.R.attr;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.CropCheckboxDrawable;
import com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable;
import com.aviary.android.feather.graphics.GalleryCircleDrawable;
import com.aviary.android.feather.graphics.PreviewCircleDrawable;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.filters.IFilter;
import com.aviary.android.feather.library.filters.SpotBrushFilter;
import com.aviary.android.feather.library.graphics.FlattenPath;
import com.aviary.android.feather.library.moa.Moa;
import com.aviary.android.feather.library.moa.MoaAction;
import com.aviary.android.feather.library.moa.MoaActionFactory;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.services.ConfigService;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.AdapterView;
import com.aviary.android.feather.widget.Gallery;
import com.aviary.android.feather.widget.Gallery.OnItemsScrollListener;
import com.aviary.android.feather.widget.IToast;
import com.aviary.android.feather.widget.ImageViewSpotDraw;
import com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener;
import com.aviary.android.feather.widget.ImageViewSpotDraw.TouchMode;
/**
* The Class SpotDrawPanel.
*/
public class DelayedSpotDrawPanel extends AbstractContentPanel implements OnDrawListener {
/** The default option. */
protected int defaultOption = 0;
/** The brush size. */
protected int mBrushSize;
/** The filter type. */
protected Filters mFilterType;
protected Gallery mGallery;
/** The brush sizes. */
protected int[] mBrushSizes;
/** The current selected view. */
protected View mSelected;
/** The current selected position. */
protected int mSelectedPosition = -1;
protected ImageButton mLensButton;
/** The background draw thread. */
private MyHandlerThread mBackgroundDrawThread;
IToast mToast;
PreviewCircleDrawable mCircleDrawablePreview;
MoaActionList mActions = MoaActionFactory.actionList();
/** if true the drawing area will be limited */
private boolean mLimitDrawArea;
/**
* Show Brush size preview.
*
* @param size
* the brush preview size
*/
private void showSizePreview( int size ) {
if ( !isActive() ) return;
mToast.show();
updateSizePreview( size );
}
/**
* Hide the Brush size preview.
*/
private void hideSizePreview() {
if ( !isActive() ) return;
mToast.hide();
}
/**
* Update the Brush size preview
*
* @param size
* the brush preview size
*/
private void updateSizePreview( int size ) {
if ( !isActive() ) return;
mCircleDrawablePreview.setRadius( size / 2 );
View v = mToast.getView();
v.findViewById( R.id.size_preview_image );
v.invalidate();
}
/**
* Instantiates a new spot draw panel.
*
* @param context
* the context
* @param filter_type
* the filter_type
*/
public DelayedSpotDrawPanel( EffectContext context, Filters filter_type, boolean limit_area ) {
super( context );
mFilterType = filter_type;
mLimitDrawArea = limit_area;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
ConfigService config = getContext().getService( ConfigService.class );
mBrushSizes = config.getSizeArray( R.array.feather_spot_brush_sizes );
mBrushSize = mBrushSizes[0];
defaultOption = Math.min( mBrushSizes.length - 1,
Math.max( 0, config.getInteger( R.integer.feather_spot_brush_selected_size_index ) ) );
mLensButton = (ImageButton) getContentView().findViewById( R.id.lens_button );
mImageView = (ImageViewSpotDraw) getContentView().findViewById( R.id.image );
( (ImageViewSpotDraw) mImageView ).setBrushSize( (float) mBrushSize );
( (ImageViewSpotDraw) mImageView ).setDrawLimit( mLimitDrawArea ? 1000.0 : 0.0 );
mPreview = BitmapUtils.copy( mBitmap, Config.ARGB_8888 );
mImageView.setImageBitmap( mPreview, true, getContext().getCurrentImageViewMatrix(), UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
mGallery = (Gallery) getOptionView().findViewById( R.id.gallery );
mGallery.setCallbackDuringFling( false );
mGallery.setSpacing( 0 );
mGallery.setOnItemsScrollListener( new OnItemsScrollListener() {
@Override
public void onScrollFinished( AdapterView<?> parent, View view, int position, long id ) {
mBrushSize = mBrushSizes[position];
( (ImageViewSpotDraw) mImageView ).setBrushSize( (float) mBrushSize );
setSelectedTool( TouchMode.DRAW );
updateSelection( view, position );
hideSizePreview();
}
@Override
public void onScrollStarted( AdapterView<?> parent, View view, int position, long id ) {
showSizePreview( mBrushSizes[position] );
setSelectedTool( TouchMode.DRAW );
}
@Override
public void onScroll( AdapterView<?> parent, View view, int position, long id ) {
updateSizePreview( mBrushSizes[position] );
}
} );
mBackgroundDrawThread = new MyHandlerThread( "filter-thread", Thread.MIN_PRIORITY );
initAdapter();
}
/**
* Inits the adapter.
*/
private void initAdapter() {
int height = mGallery.getHeight();
if ( height < 1 ) {
mGallery.getHandler().post( new Runnable() {
@Override
public void run() {
initAdapter();
}
} );
return;
}
mGallery.setAdapter( new GalleryAdapter( getContext().getBaseContext(), mBrushSizes ) );
mGallery.setSelection( defaultOption, false, true );
mSelectedPosition = defaultOption;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
disableHapticIsNecessary( mGallery );
( (ImageViewSpotDraw) mImageView ).setOnDrawStartListener( this );
mBackgroundDrawThread.start();
mBackgroundDrawThread.setRadius( (float) Math.max( 1, mBrushSizes[0] ), mPreview.getWidth() );
mToast = IToast.make( getContext().getBaseContext(), -1 );
mCircleDrawablePreview = new PreviewCircleDrawable( 0 );
ImageView image = (ImageView) mToast.getView().findViewById( R.id.size_preview_image );
image.setImageDrawable( mCircleDrawablePreview );
mLensButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View arg0 ) {
// boolean selected = arg0.isSelected();
setSelectedTool( ( (ImageViewSpotDraw) mImageView ).getDrawMode() == TouchMode.DRAW ? TouchMode.IMAGE : TouchMode.DRAW );
}
} );
mLensButton.setVisibility( View.VISIBLE );
// TODO: check if selection is correct when panel opens
// updateSelection( (View) mGallery.getSelectedView(), mGallery.getSelectedItemPosition() );
contentReady();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#onDispose()
*/
@Override
protected void onDispose() {
mContentReadyListener = null;
super.onDispose();
}
/**
* Update selection.
*
* @param newSelection
* the new selection
* @param position
* the position
*/
protected void updateSelection( View newSelection, int position ) {
if ( mSelected != null ) {
mSelected.setSelected( false );
}
mSelected = newSelection;
mSelectedPosition = position;
if ( mSelected != null ) {
mSelected = newSelection;
mSelected.setSelected( true );
}
mGallery.invalidateViews();
}
/**
* Sets the selected tool.
*
* @param which
* the new selected tool
*/
private void setSelectedTool( TouchMode which ) {
( (ImageViewSpotDraw) mImageView ).setDrawMode( which );
mLensButton.setSelected( which == TouchMode.IMAGE );
setPanelEnabled( which != TouchMode.IMAGE );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
( (ImageViewSpotDraw) mImageView ).setOnDrawStartListener( null );
if ( mBackgroundDrawThread != null ) {
mBackgroundDrawThread.mQueue.clear();
if ( mBackgroundDrawThread.started ) {
mBackgroundDrawThread.pause();
}
if ( mBackgroundDrawThread.isAlive() ) {
mBackgroundDrawThread.quit();
while ( mBackgroundDrawThread.isAlive() ) {
// wait...
}
}
}
onProgressEnd();
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
mBackgroundDrawThread = null;
mImageView.clear();
mToast.hide();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCancelled()
*/
@Override
public void onCancelled() {
super.onCancelled();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener#onDrawStart(float[], int)
*/
@Override
public void onDrawStart( float[] points, int radius ) {
radius = Math.max( 1, radius );
mBackgroundDrawThread.pathStart( (float) radius, mPreview.getWidth() );
mBackgroundDrawThread.moveTo( points );
mBackgroundDrawThread.lineTo( points );
setIsChanged( true );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener#onDrawing(float[], int)
*/
@Override
public void onDrawing( float[] points, int radius ) {
mBackgroundDrawThread.quadTo( points );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.ImageViewSpotDraw.OnDrawListener#onDrawEnd()
*/
@Override
public void onDrawEnd() {
// TODO: empty
mBackgroundDrawThread.pathEnd();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
mLogger.info( "onGenerateResult: " + mBackgroundDrawThread.isCompleted() + ", " + mBackgroundDrawThread.isAlive() );
if ( !mBackgroundDrawThread.isCompleted() && mBackgroundDrawThread.isAlive() ) {
GenerateResultTask task = new GenerateResultTask();
task.execute();
} else {
onComplete( mPreview, mActions );
}
}
/**
* Sets the panel enabled.
*
* @param value
* the new panel enabled
*/
public void setPanelEnabled( boolean value ) {
if ( mOptionView != null ) {
if ( value != mOptionView.isEnabled() ) {
mOptionView.setEnabled( value );
if ( value ) {
getContext().restoreToolbarTitle();
} else {
getContext().setToolbarTitle( R.string.zoom_mode );
}
mOptionView.findViewById( R.id.disable_status ).setVisibility( value ? View.INVISIBLE : View.VISIBLE );
}
}
}
/**
* Prints the rect.
*
* @param rect
* the rect
* @return the string
*/
@SuppressWarnings("unused")
private String printRect( Rect rect ) {
return "( left=" + rect.left + ", top=" + rect.top + ", width=" + rect.width() + ", height=" + rect.height() + ")";
}
/**
* Creates the filter.
*
* @return the i filter
*/
protected IFilter createFilter() {
return FilterLoaderFactory.get( mFilterType );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#generateContentView(android.view.LayoutInflater)
*/
@Override
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_spotdraw_content, null );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_pixelbrush_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractContentPanel#getContentDisplayMatrix()
*/
@Override
public Matrix getContentDisplayMatrix() {
return mImageView.getDisplayMatrix();
}
/**
* background draw thread
*/
class MyHandlerThread extends Thread {
/** The started. */
boolean started;
/** The running. */
volatile boolean running;
/** The paused. */
boolean paused;
/** the filters queue */
Queue<SpotBrushFilter> mQueue = new LinkedBlockingQueue<SpotBrushFilter>();
SpotBrushFilter mCurrentFilter = null;
/**
* Instantiates a new my handler thread.
*
* @param name
* the name
* @param priority
* the priority
*/
public MyHandlerThread( String name, int priority ) {
super( name );
setPriority( priority );
init();
}
/**
* Inits the.
*/
void init() {}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#start()
*/
@Override
synchronized public void start() {
started = true;
running = true;
super.start();
}
/**
* Quit.
*/
synchronized public void quit() {
running = false;
pause();
interrupt();
};
/**
* Initialize a new path draw operation
*/
synchronized public void pathStart( float radius, int bitmapWidth ) {
SpotBrushFilter filter = (SpotBrushFilter) createFilter();
filter.setRadius( radius, bitmapWidth );
RectF rect = ( (ImageViewSpotDraw) mImageView ).getImageRect();
if ( null != rect ) {
( (ImageViewSpotDraw) mImageView ).getImageViewMatrix().mapRect( rect );
double ratio = rect.width() / mImageView.getWidth();
filter.getActions().get( 0 ).setValue( "image2displayratio", ratio );
}
setRadius( radius, bitmapWidth );
mCurrentFilter = filter;
}
/**
* Completes the path drawing operation and apply the filter
*/
synchronized public void pathEnd() {
if ( mCurrentFilter != null ) {
mQueue.add( mCurrentFilter );
}
mCurrentFilter = null;
}
/**
* Pause.
*/
public void pause() {
if ( !started ) throw new IllegalAccessError( "thread not started" );
paused = true;
}
/**
* Unpause.
*/
public void unpause() {
if ( !started ) throw new IllegalAccessError( "thread not started" );
paused = false;
}
/** the current brush radius size */
float mRadius = 10;
public void setRadius( float radius, int bitmapWidth ) {
mRadius = radius;
}
public void moveTo( float values[] ) {
mCurrentFilter.moveTo( values );
}
public void lineTo( float values[] ) {
mCurrentFilter.lineTo( values );
}
public void quadTo( float values[] ) {
mCurrentFilter.quadTo( values );
}
public boolean isCompleted() {
return mQueue.size() == 0;
}
public int queueSize() {
return mQueue.size();
}
public PointF getLerp( PointF pt1, PointF pt2, float t ) {
return new PointF( pt1.x + ( pt2.x - pt1.x ) * t, pt1.y + ( pt2.y - pt1.y ) * t );
}
@Override
public void run() {
while ( !started ) {}
boolean s = false;
mLogger.log( "thread.start!" );
while ( running ) {
if ( paused ) {
continue;
}
int currentSize;
currentSize = queueSize();
if ( currentSize > 0 && !isInterrupted() ) {
if ( !s ) {
s = true;
onProgressStart();
}
PointF firstPoint, lastPoint;
SpotBrushFilter filter = mQueue.peek();
FlattenPath path = filter.getFlattenPath();
firstPoint = path.remove();
while ( firstPoint == null && path.size() > 0 ) {
firstPoint = path.remove();
}
final int w = mPreview.getWidth();
final int h = mPreview.getHeight();
while ( path.size() > 0 ) {
lastPoint = path.remove();
float x = Math.abs( firstPoint.x - lastPoint.x );
float y = Math.abs( firstPoint.y - lastPoint.y );
float length = FloatMath.sqrt( x * x + y * y );
float currentPosition = 0;
float lerp;
if ( length == 0 ) {
filter.addPoint( firstPoint.x / w, firstPoint.y / h );
} else {
while ( currentPosition < length ) {
lerp = currentPosition / length;
PointF point = getLerp( lastPoint, firstPoint, lerp );
currentPosition += filter.getRealRadius();
filter.addPoint( point.x / w, point.y / h );
}
}
firstPoint = lastPoint;
}
filter.draw( mPreview );
if ( paused ) continue;
if ( SystemUtils.isHoneyComb() ) {
// There's a bug in Honeycomb which prevent the bitmap to be updated on a glcanvas
// so we need to force it
Moa.notifyPixelsChanged( mPreview );
}
try {
mActions.add( (MoaAction) filter.getActions().get( 0 ).clone() );
} catch ( CloneNotSupportedException e ) {}
mQueue.remove();
mImageView.postInvalidate();
} else {
if ( s ) {
onProgressEnd();
s = false;
}
}
}
onProgressEnd();
mLogger.log( "thread.end" );
};
};
/**
* Bottom Gallery adapter.
*
* @author alessandro
*/
class GalleryAdapter extends BaseAdapter {
private final int VALID_POSITION = 0;
private final int INVALID_POSITION = 1;
private int[] sizes;
LayoutInflater mLayoutInflater;
Drawable checkbox_unselected, checkbox_selected;
Resources mRes;
/**
* Instantiates a new gallery adapter.
*
* @param context
* the context
* @param values
* the values
*/
public GalleryAdapter( Context context, int[] values ) {
mLayoutInflater = UIUtils.getLayoutInflater();
sizes = values;
mRes = getContext().getBaseContext().getResources();
checkbox_selected = mRes.getDrawable( R.drawable.feather_crop_checkbox_selected );
checkbox_unselected = mRes.getDrawable( R.drawable.feather_crop_checkbox_unselected );
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return sizes.length;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem( int position ) {
return sizes[position];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId( int position ) {
return 0;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType( int position ) {
final boolean valid = position >= 0 && position < getCount();
return valid ? VALID_POSITION : INVALID_POSITION;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@SuppressWarnings("deprecation")
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
final int type = getItemViewType( position );
GalleryCircleDrawable mCircleDrawable = null;
int biggest = sizes[sizes.length - 1];
int size = 1;
View view;
if ( convertView == null ) {
if ( type == VALID_POSITION ) {
mCircleDrawable = new GalleryCircleDrawable( 1, 0 );
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGallery, false );
StateListDrawable st = new StateListDrawable();
Drawable d1 = new CropCheckboxDrawable( mRes, false, mCircleDrawable, 0.67088f, 0.4f, 0.0f );
Drawable d2 = new CropCheckboxDrawable( mRes, true, mCircleDrawable, 0.67088f, 0.4f, 0.0f );
st.addState( new int[] { -attr.state_selected }, d1 );
st.addState( new int[] { attr.state_selected }, d2 );
view.setBackgroundDrawable( st );
view.setTag( mCircleDrawable );
} else {
// use the blank view
view = mLayoutInflater.inflate( R.layout.feather_checkbox_button, mGallery, false );
Drawable unselectedBackground = new DefaultGalleryCheckboxDrawable( mRes, false );
view.setBackgroundDrawable( unselectedBackground );
}
} else {
view = convertView;
if ( type == VALID_POSITION ) {
mCircleDrawable = (GalleryCircleDrawable) view.getTag();
}
}
if ( mCircleDrawable != null && type == VALID_POSITION ) {
size = sizes[position];
float value = (float) size / biggest;
mCircleDrawable.update( value, 0 );
}
view.setSelected( mSelectedPosition == position );
return view;
}
}
/**
* GenerateResultTask is used when the background draw operation is still running. Just wait until the draw operation completed.
*/
class GenerateResultTask extends AsyncTask<Void, Void, Void> {
/** The m progress. */
ProgressDialog mProgress = new ProgressDialog( getContext().getBaseContext() );
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setTitle( getContext().getBaseContext().getString( R.string.feather_loading_title ) );
mProgress.setMessage( getContext().getBaseContext().getString( R.string.effect_loading_message ) );
mProgress.setIndeterminate( true );
mProgress.setCancelable( false );
mProgress.show();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Void doInBackground( Void... params ) {
if ( mBackgroundDrawThread != null ) {
while ( mBackgroundDrawThread != null && !mBackgroundDrawThread.isCompleted() ) {
mLogger.log( "waiting.... " + mBackgroundDrawThread.queueSize() );
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Void result ) {
super.onPostExecute( result );
if ( getContext().getBaseActivity().isFinishing() ) return;
if ( mProgress.isShowing() ) {
try {
mProgress.dismiss();
} catch ( IllegalArgumentException e ) {}
}
onComplete( mPreview, mActions );
}
}
}
| Java |
package com.aviary.android.feather.effects;
import java.util.HashMap;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.aviary.android.feather.library.filters.IFilter;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.services.EffectContext;
// TODO: Auto-generated Javadoc
/**
* Base class for all the feather tools.
*
* @author alessandro
*/
public abstract class AbstractEffectPanel {
/** The main listener handler. */
Handler mListenerHandler;
static final int PREVIEW_BITMAP_CHANGED = 1;
static final int PREVIEW_FILTER_CHANGED = 2;
static final int FILTER_SAVE_COMPLETED = 3;
static final int PROGRESS_START = 4;
static final int PROGRESS_END = 5;
static final int PROGRESS_MODAL_START = 6;
static final int PROGRESS_MODAL_END = 7;
/**
* If the current panel implements {@link #AbstractEffectPanel.ContentPanel} this listener is used by the FilterManager to hide the main
* application image when the content panel send the onReady event.
*
* @author alessandro
*
*/
public static interface OnContentReadyListener {
/**
* On ready. Panel is ready to display its contents
*
* @param panel
* the panel
*/
void onReady( AbstractEffectPanel panel );
};
/**
* The listener interface for receiving onProgress events. The class that is interested in processing a onProgress event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnProgressListener<code> method. When
* the onProgress event occurs, that object's appropriate
* method is invoked.
*
* @see OnProgressEvent
*/
public static interface OnProgressListener {
/**
* On progress start.
*/
void onProgressStart();
/**
* On progress end.
*/
void onProgressEnd();
/** a progress modal has been requested */
void onProgressModalStart();
/** hide the progress modal */
void onProgressModalEnd();
}
/**
* The listener interface for receiving onPreview events. The class that is interested in processing a onPreview event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnPreviewListener<code> method. When
* the onPreview event occurs, that object's appropriate
* method is invoked.
*
* @see OnPreviewEvent
*/
public static interface OnPreviewListener {
/**
* Some parameters have changed and the effect has generated a new bitmap with the new parameters applied on it.
*
* @param result
* the result
*/
void onPreviewChange( Bitmap result );
/**
* On preview change.
*
* @param colorFilter
* the color filter
*/
void onPreviewChange( ColorFilter colorFilter );
};
/**
* The listener interface for receiving onApplyResult events. The class that is interested in processing a onApplyResult event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnApplyResultListener<code> method. When
* the onApplyResult event occurs, that object's appropriate
* method is invoked.
*
* @see OnApplyResultEvent
*/
public static interface OnApplyResultListener {
/**
* On complete.
*
* @param result
* the result
* @param actions
* the actions executed
* @param trackingAttributes
* the tracking attributes
*/
void onComplete( Bitmap result, MoaActionList actions, HashMap<String, String> trackingAttributes );
}
/**
* The listener interface for receiving onError events. The class that is interested in processing a onError event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnErrorListener<code> method. When
* the onError event occurs, that object's appropriate
* method is invoked.
*
* @see OnErrorEvent
*/
public static interface OnErrorListener {
/**
* On error.
*
* @param error
* the error
*/
void onError( String error );
void onError( String error, int yesLabel, OnClickListener yesListener, int noLabel, OnClickListener noListener );
}
/**
* Base interface for all the tools.
*
* @author alessandro
*/
public static interface OptionPanel {
/**
* Returns a view used to populate the option panel.
*
* @param inflater
* the inflater
* @param viewGroup
* the view group
* @return the option view
*/
View getOptionView( LayoutInflater inflater, ViewGroup viewGroup );
}
/**
* Base interface for the tools which will provide a content panel.
*
* @author alessandro
*
*/
public static interface ContentPanel {
/**
* Sets the on ready listener.
*
* @param listener
* the new on ready listener
*/
void setOnReadyListener( OnContentReadyListener listener );
/**
* Creates and return a new view which will be placed over the original image and its used by the contentpanel to draw its own
* preview.
*
* @param inflater
* the inflater
* @return the content view
*/
View getContentView( LayoutInflater inflater );
/**
* Return the current content view.
*
* @return the content view
*/
View getContentView();
/**
* Returns the current Image display matrix used in the content panel. This is useful when the application leaves the current
* tool and the original image needs to be updated using the content panel image. We need to know the content's panel image
* matrix in order to present the same image size/position to the user.
*
* @return the content display matrix
*/
Matrix getContentDisplayMatrix();
}
/** If a tool need to store a copy of the input bitmap, use this member which will be automatically recycled. */
protected Bitmap mPreview;
/**
* This is the input Bitmap passed from the FilterManager class.
*/
protected Bitmap mBitmap;
private boolean mActive;
private boolean mCreated;
protected boolean mChanged;
protected boolean mSaving;
protected long mRenderTime;
protected boolean mEnabled;
protected IFilter mFilter;
protected HashMap<String, String> mTrackingAttributes;
protected OnProgressListener mProgressListener;
protected OnPreviewListener mListener;
protected OnApplyResultListener mApplyListener;
protected OnErrorListener mErrorListener;
private EffectContext mFilterContext;
protected Logger mLogger;
/**
* Instantiates a new abstract effect panel.
*
* @param context
* the context
*/
public AbstractEffectPanel( EffectContext context ) {
mFilterContext = context;
mActive = false;
mEnabled = true;
mTrackingAttributes = new HashMap<String, String>();
setIsChanged( false );
mLogger = LoggerFactory.getLogger( this.getClass().getSimpleName(), LoggerType.ConsoleLoggerType );
}
public Handler getHandler() {
return mListenerHandler;
}
/**
* On progress start.
*/
protected void onProgressStart() {
if ( isActive() ) {
mListenerHandler.sendEmptyMessage( PROGRESS_START );
}
}
/**
* On progress end.
*/
protected void onProgressEnd() {
if ( isActive() ) {
mListenerHandler.sendEmptyMessage( PROGRESS_END );
}
}
protected void onProgressModalStart() {
if ( isActive() ) {
mListenerHandler.sendEmptyMessage( PROGRESS_MODAL_START );
}
}
protected void onProgressModalEnd() {
if ( isActive() ) {
mListenerHandler.sendEmptyMessage( PROGRESS_MODAL_END );
}
}
/**
* Sets the panel enabled state.
*
* @param value
* the new enabled
*/
public void setEnabled( boolean value ) {
mEnabled = value;
}
/**
* Checks if is enabled.
*
* @return true, if is enabled
*/
public boolean isEnabled() {
return mEnabled;
}
/**
* Return true if current panel state is between the onActivate/onDeactivate states.
*
* @return true, if is active
*/
public boolean isActive() {
return mActive && isCreated();
}
/**
* Return true if current panel state is between onCreate/onDestroy states.
*
* @return true, if is created
*/
public boolean isCreated() {
return mCreated;
}
/**
* Sets the on preview listener.
*
* @param listener
* the new on preview listener
*/
public void setOnPreviewListener( OnPreviewListener listener ) {
mListener = listener;
}
/**
* Sets the on apply result listener.
*
* @param listener
* the new on apply result listener
*/
public void setOnApplyResultListener( OnApplyResultListener listener ) {
mApplyListener = listener;
}
/**
* Sets the on error listener.
*
* @param listener
* the new on error listener
*/
public void setOnErrorListener( OnErrorListener listener ) {
mErrorListener = listener;
}
/**
* Sets the on progress listener.
*
* @param listener
* the new on progress listener
*/
public void setOnProgressListener( OnProgressListener listener ) {
mProgressListener = listener;
}
/**
* Called first when the panel has been created and it is ready to be shown.
*
* @param bitmap
* the bitmap
*/
public void onCreate( Bitmap bitmap ) {
mLogger.info( "onCreate" );
mBitmap = bitmap;
mCreated = true;
}
/**
* panel is being shown.
*/
public void onOpening() {
mLogger.info( "onOpening" );
}
/**
* panel is being closed.
*/
public void onClosing() {
mLogger.info( "onClosing" );
}
/**
* Return true if you want the back event handled by the current panel otherwise return false and the back button will be handled
* by the system.
*
* @return true, if successful
*/
public boolean onBackPressed() {
return false;
}
/**
* Device configuration changed.
*
* @param newConfig
* the new config
*/
public void onConfigurationChanged( Configuration newConfig, Configuration oldConfig ) {
}
/**
* The main context requests to apply the current status of the filter.
*/
public void onSave() {
mLogger.info( "onSave" );
if ( mSaving == false ) {
mSaving = true;
mRenderTime = System.currentTimeMillis();
onGenerateResult();
}
}
/**
* Manager is asking to cancel the current tool. Return false if no further user interaction is necessary and you agree to close
* this panel. Return true otherwise and the next call to this panel will be onCancelled. If you want to manage this event you
* can then cancel the panel by calling {@link EffectContext#cancel()} on the current context
*
* onCancel -> onCancelled -> onDeactivate -> onDestroy
*
* @return true, if successful
*/
public boolean onCancel() {
mLogger.info( "onCancel" );
return false;
}
/*
* Panel is being closed without applying the result. Either because the user clicked on the cancel button or because a back
* event has been fired.
*/
/**
* On cancelled.
*/
public void onCancelled() {
mLogger.info( "onCancelled" );
setEnabled( false );
}
/**
* Check if the current panel has pending changes.
*
* @return the checks if is changed
*/
public boolean getIsChanged() {
return mChanged;
}
/**
* Sets the 'changed' status of the current panel.
*
* @param value
* the new checks if is changed
*/
protected void setIsChanged( boolean value ) {
mChanged = value;
}
/**
* Panel is now hidden and it need to be disposed.
*/
public void onDestroy() {
mLogger.info( "onDestroy" );
mCreated = false;
onDispose();
}
/**
* Called after onCreate as soon as the panel it's ready to receive user interactions
*
* panel lifecycle: 1. onCreate 2. onActivate 3. ( user interactions.. ) 3.1 onCancel/onBackPressed 4. onSave|onCancelled 5.
* onDeactivate 6. onDestroy
*/
public void onActivate() {
mLogger.info( "onActivate" );
mActive = true;
mListenerHandler = new Handler() {
@Override
public void handleMessage( Message msg ) {
super.handleMessage( msg );
switch ( msg.what ) {
case PREVIEW_FILTER_CHANGED:
if ( mListener != null && isActive() ) {
mListener.onPreviewChange( (ColorFilter) msg.obj );
}
break;
case PREVIEW_BITMAP_CHANGED:
if ( mListener != null && isActive() ) {
mListener.onPreviewChange( (Bitmap) msg.obj );
}
break;
case PROGRESS_START:
if ( mProgressListener != null && isCreated() ) {
mProgressListener.onProgressStart();
}
break;
case PROGRESS_END:
if ( mProgressListener != null && isCreated() ) {
mProgressListener.onProgressEnd();
}
break;
case PROGRESS_MODAL_START:
if ( mProgressListener != null && isCreated() ) {
mProgressListener.onProgressModalStart();
}
break;
case PROGRESS_MODAL_END:
if ( mProgressListener != null && isCreated() ) {
mProgressListener.onProgressModalEnd();
}
break;
default:
break;
}
}
};
}
/**
* Called just before start hiding the panel No user interactions should be accepted anymore after this point.
*/
public void onDeactivate() {
mLogger.info( "onDeactivate" );
setEnabled( false );
mActive = false;
mListenerHandler = null;
}
/**
* Return the current Effect Context.
*
* @return the context
*/
public EffectContext getContext() {
return mFilterContext;
}
/**
* On dispose.
*/
protected void onDispose() {
mLogger.info( "onDispose" );
internalDispose();
}
/**
* Internal dispose.
*/
private void internalDispose() {
recyclePreview();
mPreview = null;
mBitmap = null;
mListener = null;
mErrorListener = null;
mApplyListener = null;
mFilterContext = null;
mFilter = null;
}
/**
* Recycle and free the preview bitmap.
*/
protected void recyclePreview() {
if ( mPreview != null && !mPreview.isRecycled() && !mPreview.equals( mBitmap ) ) {
mLogger.warning( "[recycle] preview Bitmap: " + mPreview );
mPreview.recycle();
}
}
/**
* On preview changed.
*
* @param bitmap
* the bitmap
*/
protected void onPreviewChanged( Bitmap bitmap ) {
onPreviewChanged( bitmap, true );
}
/**
* On preview changed.
*
* @param colorFilter
* the color filter
* @param notify
* the notify
*/
protected void onPreviewChanged( ColorFilter colorFilter, boolean notify ) {
setIsChanged( colorFilter != null );
if ( notify && isActive() ) {
mListenerHandler.removeMessages( PREVIEW_FILTER_CHANGED );
Message msg = mListenerHandler.obtainMessage( PREVIEW_FILTER_CHANGED );
msg.obj = colorFilter;
mListenerHandler.sendMessage( msg );
}
// if ( mListener != null && notify && isActive() ) mListener.onPreviewChange( colorFilter );
}
/**
* On preview changed.
*
* @param bitmap
* the bitmap
* @param notify
* the notify
*/
protected void onPreviewChanged( Bitmap bitmap, boolean notify ) {
setIsChanged( bitmap != null );
if ( bitmap == null || !bitmap.equals( mPreview ) ) {
recyclePreview();
}
mPreview = bitmap;
if ( notify && isActive() ) {
Message msg = mListenerHandler.obtainMessage( PREVIEW_BITMAP_CHANGED );
msg.obj = bitmap;
mListenerHandler.sendMessage( msg );
}
// if ( mListener != null && notify && isActive() ) mListener.onPreviewChange( bitmap );
}
/**
* Called when the current effect panel has completed the generation of the final bitmap.
*
* @param bitmap
* the bitmap
* @param actions
* list of the current applied actions
*/
protected void onComplete( Bitmap bitmap, MoaActionList actions ) {
mLogger.info( "onComplete" );
long t = System.currentTimeMillis();
if ( mApplyListener != null && isActive() ) {
if ( !mTrackingAttributes.containsKey( "renderTime" ) )
mTrackingAttributes.put( "renderTime", Long.toString( t - mRenderTime ) );
mApplyListener.onComplete( bitmap, actions, mTrackingAttributes );
}
mPreview = null;
mSaving = false;
}
/**
* On generic error.
*
* @param error
* the error
*/
protected void onGenericError( String error ) {
if ( mErrorListener != null && isActive() ) mErrorListener.onError( error );
}
protected void onGenericError( int resId ) {
if ( mErrorListener != null && isActive() ) {
String label = getContext().getBaseContext().getString( resId );
mErrorListener.onError( label );
}
}
protected void onGenericError( int resId, int yesLabel, OnClickListener yesListener, int noLabel, OnClickListener noListener ) {
if ( mErrorListener != null && isActive() ) {
String message = getContext().getBaseContext().getString( resId );
onGenericError( message, yesLabel, yesListener, noLabel, noListener );
}
}
protected void onGenericError( String message, int yesLabel, OnClickListener yesListener, int noLabel, OnClickListener noListener ) {
if ( mErrorListener != null && isActive() ) {
mErrorListener.onError( message, yesLabel, yesListener, noLabel, noListener );
}
}
/**
* On generic error.
*
* @param e
* the e
*/
protected void onGenericError( Exception e ) {
onGenericError( e.getMessage() );
}
/**
* This methods is called by the {@link #onSave()} method. Here the implementation of the current option panel should generate
* the result bitmap, even asyncronously, and when completed it must call the {@link #onComplete(Bitmap)} event.
*/
protected void onGenerateResult() {
onGenerateResult( null );
}
protected void onGenerateResult( MoaActionList actions ) {
onComplete( mPreview, actions );
}
}
| Java |
package com.aviary.android.feather.effects;
import org.json.JSONException;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.filters.EnhanceFilter;
import com.aviary.android.feather.library.filters.EnhanceFilter.Types;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.moa.Moa;
import com.aviary.android.feather.library.moa.MoaActionList;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.widget.ImageButtonRadioGroup;
import com.aviary.android.feather.widget.ImageButtonRadioGroup.OnCheckedChangeListener;
// TODO: Auto-generated Javadoc
/**
* The Class EnhanceEffectPanel.
*/
public class EnhanceEffectPanel extends AbstractOptionPanel implements OnCheckedChangeListener {
/** current rendering task */
private RenderTask mCurrentTask;
private Filters mFilterType;
volatile boolean mIsRendering = false;
boolean enableFastPreview = false;
MoaActionList mActions = null;
/**
* Instantiates a new enhance effect panel.
*
* @param context
* the context
* @param type
* the type
*/
public EnhanceEffectPanel( EffectContext context, Filters type ) {
super( context );
mFilterType = type;
}
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
// well, it's better to have the big progress here
// enableFastPreview = Constants.getFastPreviewEnabled();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
mPreview = BitmapUtils.copy( mBitmap, Config.ARGB_8888 );
ImageButtonRadioGroup radio = (ImageButtonRadioGroup) getOptionView().findViewById( R.id.radio );
radio.setOnCheckedChangeListener( this );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#generateOptionView(android.view.LayoutInflater,
* android.view.ViewGroup)
*/
@Override
protected ViewGroup generateOptionView( LayoutInflater inflater, ViewGroup parent ) {
return (ViewGroup) inflater.inflate( R.layout.feather_enhance_panel, parent, false );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onBackPressed()
*/
@Override
public boolean onBackPressed() {
mLogger.info( "onBackPressed" );
killCurrentTask();
return super.onBackPressed();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCancelled()
*/
@Override
public void onCancelled() {
killCurrentTask();
mIsRendering = false;
super.onCancelled();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onCancel()
*/
@Override
public boolean onCancel() {
killCurrentTask();
return super.onCancel();
}
/**
* Kill current task.
*/
private void killCurrentTask() {
if ( mCurrentTask != null ) {
synchronized ( mCurrentTask ) {
mCurrentTask.cancel( true );
mCurrentTask.renderFilter.stop();
onProgressEnd();
}
mIsRendering = false;
mCurrentTask = null;
}
}
@Override
protected void onProgressEnd() {
if ( !enableFastPreview ) {
super.onProgressModalEnd();
} else {
super.onProgressEnd();
}
}
@Override
protected void onProgressStart() {
if ( !enableFastPreview ) {
super.onProgressModalStart();
} else {
super.onProgressStart();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#getIsChanged()
*/
@Override
public boolean getIsChanged() {
return super.getIsChanged() || mIsRendering == true;
}
/**
* The Class RenderTask.
*/
class RenderTask extends AsyncTask<Types, Void, Bitmap> {
/** The m error. */
String mError;
/** The render filter. */
volatile EnhanceFilter renderFilter;
/**
* Instantiates a new render task.
*/
public RenderTask() {
renderFilter = (EnhanceFilter) FilterLoaderFactory.get( mFilterType );
mError = null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
onProgressStart();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Bitmap doInBackground( Types... params ) {
if ( isCancelled() ) return null;
Bitmap result = null;
mIsRendering = true;
Types type = params[0];
renderFilter.setType( type );
try {
result = renderFilter.execute( mBitmap, mPreview, 1, 1 );
mActions = renderFilter.getActions();
} catch ( JSONException e ) {
e.printStackTrace();
mError = e.getMessage();
return null;
}
if ( isCancelled() ) return null;
return result;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
if ( !isActive() ) return;
onProgressEnd();
if ( isCancelled() ) return;
if ( result != null ) {
if ( SystemUtils.isHoneyComb() ) {
Moa.notifyPixelsChanged( mPreview );
}
onPreviewChanged( mPreview, true );
} else {
if ( mError != null ) {
onGenericError( mError );
}
}
mIsRendering = false;
mCurrentTask = null;
}
@Override
protected void onCancelled() {
renderFilter.stop();
super.onCancelled();
}
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.widget.ImageButtonRadioGroup.OnCheckedChangeListener#onCheckedChanged(com.aviary.android.feather
* .widget.ImageButtonRadioGroup, int, boolean)
*/
@Override
public void onCheckedChanged( ImageButtonRadioGroup group, int checkedId, boolean isChecked ) {
mLogger.info( "onCheckedChange: " + checkedId );
if ( !isActive() || !isEnabled() ) return;
Types type = null;
killCurrentTask();
if ( checkedId == R.id.button1 ) {
type = Types.AUTOENHANCE;
} else if ( checkedId == R.id.button2 ) {
type = Types.NIGHTENHANCE;
} else if ( checkedId == R.id.button3 ) {
type = Types.BACKLIGHT;
} else if ( checkedId == R.id.button4 ) {
type = Types.LABCORRECT;
}
if ( !isChecked ) {
// restore the original image
BitmapUtils.copy( mBitmap, mPreview );
onPreviewChanged( mPreview, true );
setIsChanged( false );
mActions = null;
} else {
if ( type != null ) {
mCurrentTask = new RenderTask();
mCurrentTask.execute( type );
}
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
if ( mIsRendering ) {
GenerateResultTask task = new GenerateResultTask();
task.execute();
} else {
onComplete( mPreview, mActions );
}
}
/**
* The Class GenerateResultTask.
*/
class GenerateResultTask extends AsyncTask<Void, Void, Void> {
/** The m progress. */
ProgressDialog mProgress = new ProgressDialog( getContext().getBaseContext() );
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setTitle( getContext().getBaseContext().getString( R.string.feather_loading_title ) );
mProgress.setMessage( getContext().getBaseContext().getString( R.string.effect_loading_message ) );
mProgress.setIndeterminate( true );
mProgress.setCancelable( false );
mProgress.show();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Void doInBackground( Void... params ) {
mLogger.info( "GenerateResultTask::doInBackground", mIsRendering );
while ( mIsRendering ) {
// mLogger.log( "waiting...." );
}
return null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Void result ) {
super.onPostExecute( result );
mLogger.info( "GenerateResultTask::onPostExecute" );
if ( getContext().getBaseActivity().isFinishing() ) return;
if ( mProgress.isShowing() ) mProgress.dismiss();
onComplete( mPreview, mActions );
}
}
}
| Java |
package com.aviary.android.feather.effects;
import java.io.IOException;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity.ImageToolEnum;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.content.EffectEntry;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.services.EffectContext;
import com.aviary.android.feather.library.services.EffectContextService;
/**
* The Class EffectLoaderService.
*/
public class EffectLoaderService extends EffectContextService {
public static final String NAME = "effect-loader";
/**
* Instantiates a new effect loader service.
*
* @param context
* the context
*/
public EffectLoaderService( EffectContext context ) {
super( context );
}
/**
* Passing a {@link EffectEntry} return an instance of {@link AbstractEffectPanel} used to create the requested tool.
*
* @param entry
* the entry
* @return the abstract effect panel
*/
public AbstractEffectPanel load( EffectEntry entry ) {
AbstractEffectPanel panel = null;
final EffectContext context = getContext();
switch ( entry.name ) {
case ADJUST:
panel = new AdjustEffectPanel( context, Filters.ADJUST );
break;
case BRIGHTNESS:
panel = new NativeEffectRangePanel( context, Filters.BRIGHTNESS, "brightness" );
break;
case SATURATION:
panel = new NativeEffectRangePanel( context, Filters.SATURATION, "saturation" );
break;
case CONTRAST:
panel = new NativeEffectRangePanel( context, Filters.CONTRAST, "contrast" );
break;
case SHARPNESS:
panel = new NativeEffectRangePanel( context, Filters.SHARPNESS, "sharpen" );
break;
case COLORTEMP:
panel = new NativeEffectRangePanel( context, Filters.COLORTEMP, "temperature" );
break;
case ENHANCE:
panel = new EnhanceEffectPanel( context, Filters.ENHANCE );
break;
case EFFECTS:
panel = new NativeEffectsPanel( context );
//panel = new EffectsPanel( context, FeatherIntent.PluginType.TYPE_FILTER );
break;
//case BORDERS:
// panel = new EffectsPanel( context, FeatherIntent.PluginType.TYPE_BORDER );
// break;
case CROP:
panel = new CropPanel( context );
break;
case RED_EYE:
panel = new DelayedSpotDrawPanel( context, Filters.RED_EYE, false );
break;
case WHITEN:
panel = new DelayedSpotDrawPanel( context, Filters.WHITEN, false );
break;
case BLEMISH:
panel = new DelayedSpotDrawPanel( context, Filters.BLEMISH, false );
break;
case DRAWING:
panel = new DrawingPanel( context );
break;
case STICKERS:
panel = new StickersPanel( context );
break;
case TEXT:
panel = new TextPanel( context );
break;
case MEME:
panel = new MemePanel( context );
break;
default:
Logger logger = LoggerFactory.getLogger( "EffectLoaderService", LoggerType.ConsoleLoggerType );
logger.error( "Effect with " + entry.name + " could not be found" );
break;
}
return panel;
}
/** The Constant mAllEntries. */
static final EffectEntry[] mAllEntries;
/** 涂鸦+贴图 mEntries. */
static final EffectEntry[] mDrawEntries;
/** 强化 效果 方向 裁切 清除污点 */
static final EffectEntry[] mEditEntries;
static {
mAllEntries = new EffectEntry[] {
new EffectEntry( FilterLoaderFactory.Filters.ENHANCE, R.drawable.feather_tool_icon_enhance, R.string.enhance ),
new EffectEntry( FilterLoaderFactory.Filters.EFFECTS, R.drawable.feather_tool_icon_effects, R.string.effects ),
/*new EffectEntry( FilterLoaderFactory.Filters.BORDERS, R.drawable.feather_tool_icon_borders, R.string.feather_borders ),*/
new EffectEntry( FilterLoaderFactory.Filters.STICKERS, R.drawable.feather_tool_icon_stickers, R.string.stickers ),
new EffectEntry( FilterLoaderFactory.Filters.ADJUST, R.drawable.feather_tool_icon_adjust, R.string.adjust ),
new EffectEntry( FilterLoaderFactory.Filters.CROP, R.drawable.feather_tool_icon_crop, R.string.crop ),
new EffectEntry( FilterLoaderFactory.Filters.BRIGHTNESS, R.drawable.feather_tool_icon_brightness, R.string.brightness ),
new EffectEntry( FilterLoaderFactory.Filters.COLORTEMP, R.drawable.feather_tool_icon_temperature,
R.string.feather_tool_temperature ),
new EffectEntry( FilterLoaderFactory.Filters.CONTRAST, R.drawable.feather_tool_icon_contrast, R.string.contrast ),
new EffectEntry( FilterLoaderFactory.Filters.SATURATION, R.drawable.feather_tool_icon_saturation, R.string.saturation ),
new EffectEntry( FilterLoaderFactory.Filters.SHARPNESS, R.drawable.feather_tool_icon_sharpen, R.string.sharpen ),
new EffectEntry( FilterLoaderFactory.Filters.DRAWING, R.drawable.feather_tool_icon_draw, R.string.draw ),
new EffectEntry( FilterLoaderFactory.Filters.TEXT, R.drawable.feather_tool_icon_text, R.string.text ),
new EffectEntry( FilterLoaderFactory.Filters.MEME, R.drawable.feather_tool_icon_meme, R.string.meme ),
new EffectEntry( FilterLoaderFactory.Filters.RED_EYE, R.drawable.feather_tool_icon_redeye, R.string.red_eye ),
new EffectEntry( FilterLoaderFactory.Filters.WHITEN, R.drawable.feather_tool_icon_whiten, R.string.whiten ),
new EffectEntry( FilterLoaderFactory.Filters.BLEMISH, R.drawable.feather_tool_icon_blemish, R.string.blemish ), };
}
static {
mEditEntries = new EffectEntry[] {
new EffectEntry( FilterLoaderFactory.Filters.ENHANCE, R.drawable.feather_tool_icon_enhance, R.string.enhance ),
new EffectEntry( FilterLoaderFactory.Filters.EFFECTS, R.drawable.feather_tool_icon_effects, R.string.effects ),
new EffectEntry( FilterLoaderFactory.Filters.ADJUST, R.drawable.feather_tool_icon_adjust, R.string.adjust ),
new EffectEntry( FilterLoaderFactory.Filters.CROP, R.drawable.feather_tool_icon_crop, R.string.crop ),
new EffectEntry( FilterLoaderFactory.Filters.BLEMISH, R.drawable.feather_tool_icon_blemish, R.string.blemish ), };
}
static {
mDrawEntries = new EffectEntry[] {
new EffectEntry( FilterLoaderFactory.Filters.STICKERS, R.drawable.feather_tool_icon_stickers, R.string.stickers ),
new EffectEntry( FilterLoaderFactory.Filters.DRAWING, R.drawable.feather_tool_icon_draw, R.string.draw ), };
}
/**
* Return a list of available effects.
*
* @return the effects
*/
public EffectEntry[] getEffects(int toolEnum) {
switch (toolEnum) {
case Constants.ACTIVITY_DRAW:
return mDrawEntries;
case Constants.ACTIVITY_EDIT:
return mEditEntries;
default:
break;
}
return mAllEntries;
}
public static final EffectEntry[] getAllEntries() {
return mAllEntries;
}
/**
* Check if the current application context has a valid folder "stickers" inside its assets folder.
*
* @return true, if successful
*/
public boolean hasStickers() {
try {
String[] list = null;
list = getContext().getBaseContext().getAssets().list( "stickers" );
return list.length > 0;
} catch ( IOException e ) {}
return false;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContextService#dispose()
*/
@Override
public void dispose() {}
}
| Java |
package com.aviary.android.feather.effects;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel;
import com.aviary.android.feather.library.services.EffectContext;
/**
* The Class AbstractContentPanel.
*/
abstract class AbstractContentPanel extends AbstractOptionPanel implements ContentPanel {
protected OnContentReadyListener mContentReadyListener;
protected View mDrawingPanel;
protected ImageViewTouch mImageView;
/**
* Instantiates a new abstract content panel.
*
* @param context
* the context
*/
public AbstractContentPanel( EffectContext context ) {
super( context );
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel#setOnReadyListener(com.aviary.android.feather.effects.
* AbstractEffectPanel.OnContentReadyListener)
*/
@Override
public final void setOnReadyListener( OnContentReadyListener listener ) {
mContentReadyListener = listener;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel#getContentView(android.view.LayoutInflater)
*/
@Override
public final View getContentView( LayoutInflater inflater ) {
mDrawingPanel = generateContentView( inflater );
return mDrawingPanel;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel#getContentView()
*/
@Override
public final View getContentView() {
return mDrawingPanel;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#onDispose()
*/
@Override
protected void onDispose() {
mContentReadyListener = null;
super.onDispose();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractOptionPanel#setEnabled(boolean)
*/
@Override
public void setEnabled( boolean value ) {
super.setEnabled( value );
getContentView().setEnabled( value );
}
/**
* Call this method when your tool is ready to display its overlay. After this call the main context will remove the main image
* and will replace it with the content of this panel
*/
protected void contentReady() {
if ( mContentReadyListener != null && isActive() ) mContentReadyListener.onReady( this );
}
/**
* Generate content view.
*
* @param inflater
* the inflater
* @return the view
*/
protected abstract View generateContentView( LayoutInflater inflater );
/**
* Return the current content image display matrix.
*
* @return the content display matrix
*/
@Override
public Matrix getContentDisplayMatrix() {
return mImageView.getDisplayMatrix();
}
}
| Java |
/*
* AVIARY API TERMS OF USE
* Full Legal Agreement
* The following terms and conditions and the terms and conditions at http://www.aviary.com/terms (collectively, the 鈥淭erms鈥� govern your use of any and all data, text, software, tools, documents and other materials associated with the application programming interface offered by Aviary, Inc. (the "API"). By clicking on the 鈥淎ccept鈥�button, OR BY USING OR ACCESSING ANY PORTION OF THE API, you or the entity or company that you represent are unconditionally agreeing to be bound by the terms, including those available by hyperlink from within this document, and are becoming a party to the Terms. Your continued use of the API shall also constitute assent to the Terms. If you do not unconditionally agree to all of the Terms, DO NOT USE OR ACCESS ANY PORTION OF THE API. If the terms set out herein are considered an offer, acceptance is expressly limited to these terms. IF YOU DO NOT AGREE TO THE TERMS, YOU MAY NOT USE THE API, IN WHOLE OR IN PART.
*
* Human-Friendly Summary
* If you use the API, you automatically agree to these Terms of Service. Don't use our API if you don't agree with this document!
* 1. GRANT OF LICENSE.
* Subject to your ("Licensee") full compliance with all of Terms of this agreement ("Agreement"), Aviary, Inc. ("Aviary") grants Licensee a non-exclusive, revocable, nonsublicensable, nontransferable license to download and use the API solely to embed a launchable Aviary application within Licensee鈥檚 mobile or website application (鈥淎pp鈥� and to access data from Aviary in connection with such application. Licensee may not install or use the API for any other purpose without Aviary's prior written consent.
*
* Licensee shall not use the API in connection with or to promote any products, services, or materials that constitute, promote or are used primarily for the purpose of dealing in: spyware, adware, or other malicious programs or code, counterfeit goods, items subject to U.S. embargo, unsolicited mass distribution of email ("spam"), multi-level marketing proposals, hate materials, hacking/surveillance/interception/descrambling equipment, libelous, defamatory, obscene, pornographic, abusive or otherwise offensive content, prostitution, body parts and bodily fluids, stolen products and items used for theft, fireworks, explosives, and hazardous materials, government IDs, police items, gambling, professional services regulated by state licensing regimes, non-transferable items such as airline tickets or event tickets, weapons and accessories.
*
* Use Aviary the way it's intended (as a photo-enhancement service), or get our permission first.
* If your service does anything illegal or potentially offensive, we don't want Aviary to be in your app. Nothing personal - it just reflects badly on our brand.
* 2. BRANDING.
* Licensee agrees to the following: (a) on every App page that makes use of the Aviary API, Licensee shall display an Aviary logo crediting Aviary only in accordance with the branding instructions available at [www.aviary.com/branding]; (b) it shall maintain a clickable link to the following location [www.aviary.com/api-info], prominently in the licensee App whenever the API is displayed to the end user. (c) it may not otherwise use the Aviary logo without specific written permission from Aviary; and (d) any use of the Aviary logo on an App page shall be less prominent than the logo or mark that primarily describes the Licensee website, and Licensee鈥檚 use of the Aviary logo shall not imply any endorsement of the Licensee website by Aviary.
*
* (a) Don't remove or obscure the Aviary logo in the editor.
* (b) Don't remove or obscure the link to Aviary's mobile info. We link the Aviary logo to this info so you don't need to add anything extra to your app.
* (c) We're probably cool with you using our logo as part of a press release announcing our editor or otherwise promoting your use of Aviary. Just please ask us first. :)
* (d) Please make sure that your users aren't confused as to who made your app by always keeping your logo more prominent than ours. You did most of the hard work for your app and should get all of the credit. :)
* 3. PROPRIETARY RIGHTS.
* As between Aviary and Licensee, the API and all intellectual property rights in and to the API are and shall at all times remain the sole and exclusive property of Aviary and are protected by applicable intellectual property laws and treaties. Except for the limited license expressly granted herein, no other license is granted, no other use is permitted and Aviary (and its licensors) shall retain all right, title and interest in and to the API and the Aviary logos.
*
* Aviary owns all of the rights in the API it is allowing you to use. Our allowance of you to use it, does not mean we are transferring ownership to you.
* 4. OTHER RESTRICTIONS.
* Except as expressly and unambiguously authorized under this Agreement, Licensee may not (i) copy, rent, lease, sell, transfer, assign, sublicense, disassemble, reverse engineer or decompile (except to the limited extent expressly authorized by applicable statutory law), modify or alter any part of the API; (ii) otherwise use the API on behalf of any third party.
*
* (i) Please don't break our API down and redistribute it without our consent.
* (ii) Please don't agree to use our API if you are not the party using it. If you are a developer building the API into a third party app, please have your client review these terms, as they have to agree to them before they can use the API.
* 5. MODIFICATIONS TO THIS AGREEMENT.
* Aviary reserves the right, in its sole discretion to modify this Agreement at any time by posting a notice to Aviary.com. You shall be responsible for reviewing and becoming familiar with any such modification. Such modifications are effective upon first posting or notification and use of the Aviary API by Licensee following any such notification constitutes Licensee鈥檚 acceptance of the terms and conditions of this Agreement as modified.
*
* We may update this agreement from time to time, as needed. We don't anticipate any major changes, just tweaks to the legalese to reflect any new feature updates or material changes to how the API is offered. While we will make a good faith effort to notify everyone when these terms update with posts on our blog, etc... it's your responsibility to keep up-to-date with these terms on a regular basis. We'll post the last-update date at the bottom of the agreement to make it easier to know if the terms have changed.
* 6. WARRANTY DISCLAIMER.
* THE API IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, AVIARY AND ITS VENDORS EACH DISCLAIM ALL WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, REGARDING THE API, INCLUDING WITHOUT LIMITATION ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, ACCURACY, RESULTS OF USE, RELIABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, INTERFERENCE WITH QUIET ENJOYMENT, AND NON-INFRINGEMENT OF THIRD-PARTY RIGHTS. FURTHER, AVIARY DISCLAIMS ANY WARRANTY THAT LICENSEE'S USE OF THE API WILL BE UNINTERRUPTED OR ERROR FREE.
*
* Things might break. Hopefully not and if so, we'll do our best to fix it immediately. But if it happens, please note that we aren't responsible. You are using the API "as is" and understand the risk inherent in that.
* 7. SUPPORT AND UPGRADES.
* This Agreement does not entitle Licensee to any support and/or upgrades for the APIs, unless Licensee makes separate arrangements with Aviary and pays all fees associated with such support. Any such support and/or upgrades provided by Aviary shall be subject to the terms of this Agreement as modified by the associated support Agreement.
*
* We can't promise to offer any kind of support or future upgrades. We plan to help all of our partners to the best of our ability, but use of our API doesn't entitle you to this.
* 8. LIABILITY LIMITATION.
* REGARDLESS OF WHETHER ANY REMEDY SET FORTH HEREIN FAILS OF ITS ESSENTIAL PURPOSE OR OTHERWISE, AND EXCEPT FOR BODILY INJURY, IN NO EVENT WILL AVIARY OR ITS VENDORS, BE LIABLE TO LICENSEE OR TO ANY THIRD PARTY UNDER ANY TORT, CONTRACT, NEGLIGENCE, STRICT LIABILITY OR OTHER LEGAL OR EQUITABLE THEORY FOR ANY LOST PROFITS, LOST OR CORRUPTED DATA, COMPUTER FAILURE OR MALFUNCTION, INTERRUPTION OF BUSINESS, OR OTHER SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND ARISING OUT OF THE USE OR INABILITY TO USE THE API, EVEN IF AVIARY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGES AND WHETHER OR NOT SUCH LOSS OR DAMAGES ARE FORESEEABLE. ANY CLAIM ARISING OUT OF OR RELATING TO THIS AGREEMENT MUST BE BROUGHT WITHIN ONE (1) YEAR AFTER THE OCCURRENCE OF THE EVENT GIVING RISE TO SUCH CLAIM. IN ADDITION, AVIARY DISCLAIMS ALL LIABILITY OF ANY KIND OF AVIARY'S VENDORS.
*
* Want to sue us anyway? That's cool (really not), but you only have a year to do it. Better act quick, Perry Mason.
* 9. INDEMNITY.
* Licensee agrees that Aviary shall have no liability whatsoever for any use Licensee makes of the API. Licensee shall indemnify and hold harmless Aviary from any and all claims, damages, liabilities, costs and fees (including reasonable attorneys' fees) arising from Licensee's use of the API.
*
* You acknowledge that we aren't responsible at all, for anything that happens resulting from your use of our API.
* 10. TERM AND TERMINATION.
* This Agreement shall continue until terminated as set forth in this Section. Either party may terminate this Agreement at any time, for any reason, or for no reason including, but not limited to, if Licensee violates any provision of this Agreement. Any termination of this Agreement shall also terminate the license granted hereunder. Upon termination of this Agreement for any reason, Licensee shall destroy and remove from all computers, hard drives, networks, and other storage media all copies of the API, and shall so certify to Aviary that such actions have occurred. Aviary shall have the right to inspect and audit Licensee's facilities to confirm the foregoing. Sections 3 through 11 and all accrued rights to payment shall survive termination of this Agreement.
*
* We can revoke your license (and you can choose to end your license) at any time, for any reason. We won't take this lightly, but we do hold onto this right should it be needed.
* If either party terminates this license, you will need to remove the Aviary API from your code entirely. We'll have the right to double-check to make sure you have.
* Terminating the agreement ends your ability to use our App. It doesn't change some of the other sections (namely 3-11).
* 11. GOVERNMENT USE.
* If Licensee is part of an agency, department, or other entity of the United States Government ("Government"), the use, duplication, reproduction, release, modification, disclosure or transfer of the API are restricted in accordance with the Federal Acquisition Regulations as applied to civilian agencies and the Defense Federal Acquisition Regulation Supplement as applied to military agencies. The API are a "commercial item," "commercial computer software" and "commercial computer software documentation." In accordance with such provisions, any use of the API by the Government shall be governed solely by the terms of this Agreement.
*
* Work for the government? Here is some special legalese just for you.
* 12. EXPORT CONTROLS.
* Licensee shall comply with all export laws and restrictions and regulations of the Department of Commerce, the United States Department of Treasury Office of Foreign Assets Control ("OFAC"), or other United States or foreign agency or authority, and Licensee shall not export, or allow the export or re-export of the API in violation of any such restrictions, laws or regulations. By downloading or using the API, Licensee agrees to the foregoing and represents and warrants that Licensee is not located in, under the control of, or a national or resident of any restricted country.
*
* To any potential partner located in a country with whom it is illegal for the USA to do business: We're genuinely sorry our governments are being jerks to each other and look forward to the day when it isn't illegal for us to do business together.
* 13. MISCELLANEOUS.
* Unless the parties have entered into a written amendment to this agreement that is signed by both parties regarding the Aviary API, this Agreement constitutes the entire agreement between Licensee and Aviary pertaining to the subject matter hereof, and supersedes any and all written or oral agreements with respect to such subject matter. This Agreement, and any disputes arising from or relating to the interpretation thereof, shall be governed by and construed under New York law as such law applies to agreements between New York residents entered into and to be performed within New York by two residents thereof and without reference to its conflict of laws principles or the United Nations Conventions for the International Sale of Goods. Except to the extent otherwise determined by Aviary, any action or proceeding arising from or relating to this Agreement must be brought in a federal court in the Southern District of New York or in state court in New York County, New York, and each party irrevocably submits to the jurisdiction and venue of any such court in any such action or proceeding. The prevailing party in any action arising out of this Agreement shall be entitled to an award of its costs and attorneys' fees. This Agreement may be amended only by a writing executed by Aviary. If any provision of this Agreement is held to be unenforceable for any reason, such provision shall be reformed only to the extent necessary to make it enforceable. The failure of Aviary to act with respect to a breach of this Agreement by Licensee or others does not constitute a waiver and shall not limit Aviary's rights with respect to such breach or any subsequent breaches. This Agreement is personal to Licensee and may not be assigned or transferred for any reason whatsoever (including, without limitation, by operation of law, merger, reorganization, or as a result of an acquisition or change of control involving Licensee) without Aviary's prior written consent and any action or conduct in violation of the foregoing shall be void and without effect. Aviary expressly reserves the right to assign this Agreement and to delegate any of its obligations hereunder.
*
* This is the entire and only material agreement on this matter between our companies (unless we have another one, signed by both of us).
* Any disputes on this agreement will be governed by NY law and NY courts. While you are in town suing us, please do make sure to stop in a real NY deli and get some pastrami and rye. It's delicious!
* More discussion of where the court will be located. Like boyscouts, our motto is "Always Be Prepared" and courts and wedding halls book up early this time of year.
* You sue us and we win, you're buying our attorneys a new Mercedes.
* Even if you use white-out on your screen to erase some of this agreement, it doesn't matter. Only Aviary can put the white-out on the screen.
* If some of this agreement isn't legally valid, whatever remains if it will hold strong.
* If we don't respond quickly to your breaching this agreement, it doesn't mean we can't do so in the future.
* This agreement will always be between Aviary, Inc and you. You can't transfer this agreement. If someone buys your product or company and plans to continue using it, they will need to agree to these terms separately.
* In the event that Aviary, Inc is sold or the API changes ownership, Aviary will be able to transfer the API to a new owner without impacting our agreement.
* If some of this agreement isn't legally valid, whatever remains if it will hold strong.
* Last Updated September 15, 2011
*
* It's a sunny, brisk day in NYC. We hope you're having a good day whenever you read and agree to this! Please do drop us an email with any further questions about this agreement to api@aviary.com and either way please do let us know how you plan to use our API so we can promote you! Cheers, Avi
*/
package com.aviary.android.feather;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.ColorFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.ViewAnimator;
import android.widget.ViewFlipper;
import com.aviary.android.feather.FilterManager.FeatherContext;
import com.aviary.android.feather.FilterManager.OnBitmapChangeListener;
import com.aviary.android.feather.FilterManager.OnToolListener;
import com.aviary.android.feather.async_tasks.DownloadImageAsyncTask;
import com.aviary.android.feather.async_tasks.DownloadImageAsyncTask.OnImageDownloadListener;
import com.aviary.android.feather.async_tasks.ExifTask;
import com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel;
import com.aviary.android.feather.effects.EffectLoaderService;
import com.aviary.android.feather.graphics.AnimatedRotateDrawable;
import com.aviary.android.feather.graphics.RepeatableHorizontalDrawable;
import com.aviary.android.feather.graphics.ToolIconsDrawable;
import com.aviary.android.feather.library.content.EffectEntry;
import com.aviary.android.feather.library.content.FeatherIntent;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.NativeFilterProxy;
import com.aviary.android.feather.library.graphics.animation.Flip3dAnimation;
import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.media.ExifInterfaceWrapper;
import com.aviary.android.feather.library.services.FutureListener;
import com.aviary.android.feather.library.services.LocalDataService;
import com.aviary.android.feather.library.services.ThreadPoolService;
import com.aviary.android.feather.library.services.drag.DragLayer;
import com.aviary.android.feather.library.tracking.Tracker;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.IOUtils;
import com.aviary.android.feather.library.utils.ImageLoader.ImageSizes;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.library.utils.UIConfiguration;
import com.aviary.android.feather.receivers.FeatherSystemReceiver;
import com.aviary.android.feather.utils.ThreadUtils;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.BottombarViewFlipper;
import com.aviary.android.feather.widget.IToast;
import com.aviary.android.feather.widget.ToolbarView;
import com.aviary.android.feather.widget.ToolbarView.OnToolbarClickListener;
import com.aviary.android.feather.widget.wp.CellLayout;
import com.aviary.android.feather.widget.wp.CellLayout.CellInfo;
import com.aviary.android.feather.widget.wp.Workspace;
import com.aviary.android.feather.widget.wp.Workspace.OnPageChangeListener;
import com.aviary.android.feather.widget.wp.WorkspaceIndicator;
/**
* FeatherActivity is the main activity controller.
*
* @author alessandro
*/
public class FeatherActivity extends MonitoredActivity implements OnToolbarClickListener, OnImageDownloadListener, OnToolListener,
FeatherContext, OnPageChangeListener, OnBitmapChangeListener {
/** The Constant ALERT_CONFIRM_EXIT. */
private static final int ALERT_CONFIRM_EXIT = 0;
/** The Constant ALERT_DOWNLOAD_ERROR. */
private static final int ALERT_DOWNLOAD_ERROR = 1;
/** The Constant ALERT_REVERT_IMAGE. */
private static final int ALERT_REVERT_IMAGE = 2;
static {
logger = LoggerFactory.getLogger( FeatherActivity.class.getSimpleName(), LoggerType.ConsoleLoggerType );
}
/** Version string number. */
public static final String SDK_VERSION = "2.1.91";
/** Internal version number. */
public static final int SDK_INT = 70;
/** SHA-1 version id. */
public static final String ID = "$Id: 81707a8d48adb1a2ffcba4e7d684647b22b66c3f $";
/** delay between click and panel opening */
private static final int TOOLS_OPEN_DELAY_TIME = 50;
/** The default result code. */
private int pResultCode = RESULT_CANCELED;
/** The main top toolbar view. */
private ToolbarView mToolbar;
/** The maim tools workspace. */
private Workspace mWorkspace;
/** The main view flipper. */
private ViewAnimator mViewFlipper;
/** The maim image view. */
private ImageViewTouch mImageView;
/** The main drawing view container for tools implementing {@link ContentPanel}. */
private ViewGroup mDrawingViewContainer;
/** inline progress loader. */
private View mInlineProgressLoader;
/** The main filter controller. */
protected FilterManager mFilterManager;
/** api key. */
protected String mApiKey = "";
/** tool list to show. */
protected List<String> mToolList;
/** The items per page for the main workspace. */
private int mItemsPerPage;
/** The total screen cols. */
private int mScreenCols;
/** The total screen rows. */
private int mScreenRows;
/** The workspace indicator. */
private WorkspaceIndicator mWorkspaceIndicator;
/** saving variable. */
protected boolean mSaving;
/** The current screen orientation. */
private int mOrientation;
/** The bottom bar flipper. */
private BottombarViewFlipper mBottomBarFlipper;
/** default logger. */
protected static Logger logger;
/** default handler. */
protected final Handler mHandler = new Handler();
/** hide exit alert confirmation. */
protected boolean mHideExitAlertConfirmation = false;
/** The list of tools entries. */
private List<EffectEntry> mListEntries;
/** The toolbar content animator. */
private ViewFlipper mToolbarContentAnimator;
/** The toolbar main animator. */
private ViewFlipper mToolbarMainAnimator;
private DragLayer mDragLayer;
/** Main image downloader task **/
private DownloadImageAsyncTask mDownloadTask;
private static class MyUIHandler extends Handler {
private WeakReference<FeatherActivity> mParent;
MyUIHandler( FeatherActivity parent ) {
mParent = new WeakReference<FeatherActivity>( parent );
}
@Override
public void handleMessage( Message msg ) {
super.handleMessage( msg );
FeatherActivity parent = mParent.get();
if ( null != parent ) {
switch ( msg.what ) {
case FilterManager.STATE_OPENING:
parent.mToolbar.setClickable( false );
parent.resetToolIndicator();
break;
case FilterManager.STATE_OPENED:
parent.mToolbar.setClickable( true );
break;
case FilterManager.STATE_CLOSING:
parent.mToolbar.setClickable( false );
parent.mImageView.setVisibility( View.VISIBLE );
break;
case FilterManager.STATE_CLOSED:
parent.mWorkspace.setEnabled( true );
parent.mToolbar.setClickable( true );
parent.mToolbar.setState( ToolbarView.STATE.STATE_SAVE, true );
parent.mToolbar.setSaveEnabled( true );
parent.mWorkspace.requestFocus();
break;
case FilterManager.STATE_DISABLED:
parent.mWorkspace.setEnabled( false );
parent.mToolbar.setClickable( false );
parent.mToolbar.setSaveEnabled( false );
break;
case FilterManager.STATE_CONTENT_READY:
parent.mImageView.setVisibility( View.GONE );
break;
case FilterManager.STATE_READY:
parent.mToolbar.setTitle( parent.mFilterManager.getCurrentEffect().labelResourceId, false );
parent.mToolbar.setState( ToolbarView.STATE.STATE_APPLY, false );
break;
}
}
}
}
private MyUIHandler mUIHandler;
/** The default broadcast receiver. It receives messages from the {@link FeatherSystemReceiver} */
private BroadcastReceiver mDefaultReceiver = new BroadcastReceiver() {
@Override
public void onReceive( Context context, Intent intent ) {
if ( mFilterManager != null ) {
Bundle extras = intent.getExtras();
if ( null != extras ) {
if ( extras.containsKey( FeatherIntent.APPLICATION_CONTEXT ) ) {
String app_context = extras.getString( FeatherIntent.APPLICATION_CONTEXT );
if ( app_context.equals( context.getApplicationContext().getPackageName() ) ) {
mFilterManager.onPluginChanged( intent );
}
}
}
}
}
};
/**
* Override the internal setResult in order to register the internal close status.
*
* @param resultCode
* the result code
* @param data
* the data
*/
protected final void onSetResult( int resultCode, Intent data ) {
pResultCode = resultCode;
setResult( resultCode, data );
}
@Override
public void onCreate( Bundle savedInstanceState ) {
onPreCreate();
super.onCreate( savedInstanceState );
requestWindowFeature( Window.FEATURE_NO_TITLE );
setContentView( R.layout.feather_main );
onInitializeUtils();
initializeUI();
onRegisterReceiver();
// initiate the filter manager
mUIHandler = new MyUIHandler( this );
mFilterManager = new FilterManager( this, mUIHandler, mApiKey );
mFilterManager.setOnToolListener( this );
mFilterManager.setOnBitmapChangeListener( this );
mFilterManager.setDragLayer( mDragLayer );
// first check the validity of the incoming intent
Uri srcUri = handleIntent( getIntent() );
if ( srcUri == null ) {
onSetResult( RESULT_CANCELED, null );
finish();
return;
}
LocalDataService data = mFilterManager.getService( LocalDataService.class );
data.setSourceImageUri( srcUri );
// download the requested image
loadImage( srcUri );
// initialize filters
delayedInitializeTools();
logger.error( "MAX MEMORY", mFilterManager.getApplicationMaxMemory() );
Tracker.recordTag( "feather: opened" );
}
protected void onPreCreate() {}
/**
* Initialize the IntentFilter receiver in order to get updates about new installed plugins
*/
protected void onRegisterReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction( FeatherIntent.ACTION_PLUGIN_ADDED );
filter.addAction( FeatherIntent.ACTION_PLUGIN_REMOVED );
filter.addAction( FeatherIntent.ACTION_PLUGIN_REPLACED );
filter.addDataScheme( "package" );
registerReceiver( mDefaultReceiver, filter );
}
/**
* Initialize utility classes
*/
protected void onInitializeUtils() {
UIUtils.init( this );
Constants.init( this );
NativeFilterProxy.init( this, null );
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState( Bundle outState ) {
logger.info( "onSaveInstanceState" );
super.onSaveInstanceState( outState );
}
@Override
protected void onRestoreInstanceState( Bundle savedInstanceState ) {
logger.info( "onRestoreInstanceState: " + savedInstanceState );
super.onRestoreInstanceState( savedInstanceState );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.MonitoredActivity#onDestroy()
*/
@Override
protected void onDestroy() {
logger.info( "onDestroy" );
if ( pResultCode != RESULT_OK ) Tracker.recordTag( "feather: cancelled" );
super.onDestroy();
unregisterReceiver( mDefaultReceiver );
mToolbar.setOnToolbarClickListener( null );
mFilterManager.setOnBitmapChangeListener( null );
mFilterManager.setOnToolListener( null );
mWorkspace.setOnPageChangeListener( null );
if ( null != mDownloadTask ) {
mDownloadTask.setOnLoadListener( null );
mDownloadTask = null;
}
if ( mFilterManager != null ) {
mFilterManager.dispose();
}
mUIHandler = null;
mFilterManager = null;
}
@Override
protected void onPause() {
super.onPause();
// here we tweak the default android animation between activities
// just comment the next line if you don't want to have custom animations
overridePendingTransition( R.anim.feather_app_zoom_enter_large, R.anim.feather_app_zoom_exit_large );
}
/**
* Initialize ui.
*/
@SuppressWarnings("deprecation")
private void initializeUI() {
// forcing a horizontal repeatable background
findViewById( R.id.workspace_container ).setBackgroundDrawable(
new RepeatableHorizontalDrawable( getResources(), R.drawable.feather_toolbar_background ) );
findViewById( R.id.toolbar ).setBackgroundDrawable(
new RepeatableHorizontalDrawable( getResources(), R.drawable.feather_toolbar_background ) );
// register the toolbar listeners
mToolbar.setOnToolbarClickListener( this );
mImageView.setDoubleTapEnabled( false );
// initialize the workspace
initWorkspace();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog( int id ) {
Dialog dialog = null;
switch ( id ) {
case ALERT_CONFIRM_EXIT:
dialog = new AlertDialog.Builder( this ).setTitle( R.string.confirm ).setMessage( R.string.confirm_quit_message )
.setPositiveButton( R.string.yes_leave, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
dialog.dismiss();
onBackPressed( true );
}
} ).setNegativeButton( R.string.keep_editing, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
dialog.dismiss();
}
} ).create();
break;
case ALERT_DOWNLOAD_ERROR:
dialog = new AlertDialog.Builder( this ).setTitle( R.string.attention )
.setMessage( R.string.error_download_image_message ).create();
break;
case ALERT_REVERT_IMAGE:
dialog = new AlertDialog.Builder( this ).setTitle( R.string.revert_dialog_title )
.setMessage( R.string.revert_dialog_message )
.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
dialog.dismiss();
onRevert();
}
} ).setNegativeButton( android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick( DialogInterface dialog, int which ) {
dialog.dismiss();
}
} ).create();
break;
}
return dialog;
}
/**
* Revert the original image.
*/
private void onRevert() {
Tracker.recordTag( "feather: reset image" );
LocalDataService service = mFilterManager.getService( LocalDataService.class );
loadImage( service.getSourceImageUri() );
}
/**
* Manage the screen configuration change if the screen orientation has changed, notify the filter manager and reload the main
* workspace view.
*
* @param newConfig
* the new config
*/
@Override
public void onConfigurationChanged( final Configuration newConfig ) {
super.onConfigurationChanged( newConfig );
if ( mOrientation != newConfig.orientation ) {
mOrientation = newConfig.orientation;
Constants.update( this );
mHandler.post( new Runnable() {
@Override
public void run() {
boolean handled = false;
if ( mFilterManager != null ) handled = mFilterManager.onConfigurationChanged( newConfig );
if ( !handled ) {
initWorkspace();
delayedInitializeTools();
} else {
mHandler.post( new Runnable() {
@Override
public void run() {
initWorkspace();
delayedInitializeTools();
}
} );
}
}
} );
}
mOrientation = newConfig.orientation;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu( Menu menu ) {
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.feather_menu, menu );
return true;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu( Menu menu ) {
if ( mSaving ) return false;
if ( mFilterManager.getEnabled() && mFilterManager.isClosed() ) {
return true;
} else {
return false;
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@SuppressWarnings("deprecation")
@Override
public boolean onOptionsItemSelected( MenuItem item ) {
int id = item.getItemId();
if ( id == R.id.edit_reset ) {
showDialog( ALERT_REVERT_IMAGE );
return true;
} else if ( id == R.id.edit_cancel ) {
onMenuCancel();
return true;
} else if ( id == R.id.edit_save ) {
onSaveClick();
return true;
} else if ( id == R.id.edit_premium ) {
onMenuFindMorePlugins();
return true;
} else {
return super.onOptionsItemSelected( item );
}
}
/**
* User clicked on cancel from the main menu
*/
@SuppressWarnings("deprecation")
private void onMenuCancel() {
if ( mFilterManager.getBitmapIsChanged() ) {
if ( mHideExitAlertConfirmation ) {
onSetResult( RESULT_CANCELED, null );
finish();
} else {
showDialog( ALERT_CONFIRM_EXIT );
}
} else {
onSetResult( RESULT_CANCELED, null );
finish();
}
}
/**
* User clicked on the store main menu item
*/
private void onMenuFindMorePlugins() {
mFilterManager.searchPlugin( -1 );
Tracker.recordTag( "menu: get_more" );
}
/**
* Load an image using an async task.
*
* @param data
* the data
*/
protected void loadImage( Uri data ) {
if ( null != mDownloadTask ) {
mDownloadTask.setOnLoadListener( null );
mDownloadTask = null;
}
mDownloadTask = new DownloadImageAsyncTask( data );
mDownloadTask.setOnLoadListener( this );
mDownloadTask.execute( getBaseContext() );
}
/**
* Inits the workspace.
*/
private void initWorkspace() {
mScreenRows = getResources().getInteger( R.integer.feather_config_portraitRows );
mScreenCols = getResources().getInteger( R.integer.toolCount );
mItemsPerPage = mScreenRows * mScreenCols;
mWorkspace.setHapticFeedbackEnabled( false );
mWorkspace.setIndicator( mWorkspaceIndicator );
mWorkspace.setOnPageChangeListener( this );
mWorkspace.setAdapter( null );
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onContentChanged()
*/
@Override
public void onContentChanged() {
super.onContentChanged();
mDragLayer = (DragLayer) findViewById( R.id.dragLayer );
mToolbar = (ToolbarView) findViewById( R.id.toolbar );
mBottomBarFlipper = (BottombarViewFlipper) findViewById( R.id.bottombar_view_flipper );
mWorkspace = (Workspace) mBottomBarFlipper.findViewById( R.id.workspace );
mImageView = (ImageViewTouch) findViewById( R.id.image );
mDrawingViewContainer = (ViewGroup) findViewById( R.id.drawing_view_container );
mInlineProgressLoader = findViewById( R.id.image_loading_view );
mWorkspaceIndicator = (WorkspaceIndicator) findViewById( R.id.workspace_indicator );
mViewFlipper = ( (ViewAnimator) findViewById( R.id.main_flipper ) );
mToolbarMainAnimator = ( (ViewFlipper) mToolbar.findViewById( R.id.top_indicator_main ) );
mToolbarContentAnimator = ( (ViewFlipper) mToolbar.findViewById( R.id.top_indicator_panel ) );
// update the progressbar animation drawable
AnimatedRotateDrawable d = new AnimatedRotateDrawable( getResources(), R.drawable.feather_spinner_white_16 );
ProgressBar view = (ProgressBar) mToolbarContentAnimator.getChildAt( 1 );
view.setIndeterminateDrawable( d );
// adding the bottombar content view at runtime, otherwise fail to get the corrent child
// LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
// View contentView = inflater.inflate( R.layout.feather_option_panel_content, mBottomBarFlipper, false );
// FrameLayout.LayoutParams p = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT,
// FrameLayout.LayoutParams.WRAP_CONTENT );
// p.gravity = Gravity.BOTTOM;
// mBottomBarFlipper.addView( contentView, 0, p );
mBottomBarFlipper.setDisplayedChild( 1 );
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onBackPressed()
*/
@SuppressWarnings("deprecation")
@Override
public void onBackPressed() {
if ( !mFilterManager.onBackPressed() ) {
if ( mToastLoader != null ) mToastLoader.hide();
// hide info screen if opened
if ( isInfoScreenVisible() ) {
hideInfoScreen();
return;
}
if ( mFilterManager.getBitmapIsChanged() ) {
if ( mHideExitAlertConfirmation ) {
super.onBackPressed();
} else {
showDialog( ALERT_CONFIRM_EXIT );
}
} else {
super.onBackPressed();
}
}
}
/**
* On back pressed.
*
* @param force
* the super backpressed behavior
*/
protected void onBackPressed( boolean force ) {
if ( force )
super.onBackPressed();
else
onBackPressed();
}
/**
* Handle the original received intent.
*
* @param intent
* the intent
* @return the uri
*/
protected Uri handleIntent( Intent intent ) {
LocalDataService service = mFilterManager.getService( LocalDataService.class );
if ( intent != null && intent.getData() != null ) {
Uri data = intent.getData();
if ( SystemUtils.isIceCreamSandwich() ) {
if ( data.toString().startsWith( "content://com.android.gallery3d.provider" ) ) {
// use the com.google provider, not the com.android provider ( for ICS only )
data = Uri.parse( data.toString().replace( "com.android.gallery3d", "com.google.android.gallery3d" ) );
}
}
Bundle extras = intent.getExtras();
if ( extras != null ) {
Uri destUri = (Uri) extras.getParcelable( Constants.EXTRA_OUTPUT );
mApiKey = extras.getString( Constants.API_KEY );
if ( destUri != null ) {
service.setDestImageUri( destUri );
String outputFormatString = extras.getString( Constants.EXTRA_OUTPUT_FORMAT );
if ( outputFormatString != null ) {
CompressFormat format = Bitmap.CompressFormat.valueOf( outputFormatString );
service.setOutputFormat( format );
}
}
if ( extras.containsKey( Constants.EXTRA_TOOLS_LIST ) ) {
mToolList = Arrays.asList( extras.getStringArray( Constants.EXTRA_TOOLS_LIST ) );
}
if ( extras.containsKey( Constants.EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION ) ) {
mHideExitAlertConfirmation = extras.getBoolean( Constants.EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION );
}
}
return data;
}
return null;
}
/**
* Load the current tools list in a separate thread
*/
private void delayedInitializeTools() {
Thread t = new Thread( new Runnable() {
@Override
public void run() {
final List<EffectEntry> listEntries = loadTools(getIntent().getIntExtra("From_Type", 0));
mHandler.post( new Runnable() {
@Override
public void run() {
onToolsLoaded( listEntries );
}
} );
}
} );
t.start();
}
private List<String> loadStandaloneTools() {
// let's use a global try..catch
try {
// This is the preference class used in the standalone app
// if the tool list is empty, let's try to use
// the user defined toolset
Object instance = ReflectionUtils.invokeStaticMethod( "com.aviary.android.feather.utils.SettingsUtils", "getInstance",
new Class[] { Context.class }, this );
if ( null != instance ) {
Object toolList = ReflectionUtils.invokeMethod( instance, "getToolList" );
if ( null != toolList && toolList instanceof String[] ) {
return Arrays.asList( (String[]) toolList );
}
}
} catch ( Exception t ) {
}
return null;
}
public enum ImageToolEnum {
DRAWING, EDITING;
}
private List<EffectEntry> loadTools(int toolEnum) {
if ( null == mListEntries ) {
EffectLoaderService service = mFilterManager.getService( EffectLoaderService.class );
if ( service == null ) return null;
if ( mToolList == null ) {
mToolList = loadStandaloneTools();
if ( null == mToolList ) {
mToolList = Arrays.asList( FilterLoaderFactory.getDefaultFilters() );
}
}
List<EffectEntry> listEntries = new ArrayList<EffectEntry>();
Map<String, EffectEntry> entryMap = new HashMap<String, EffectEntry>();
EffectEntry[] all_entries = service.getEffects(toolEnum);
for ( int i = 0; i < all_entries.length; i++ ) {
FilterLoaderFactory.Filters entry_name = all_entries[i].name;
if ( !mToolList.contains( entry_name.name() ) ) continue;
entryMap.put( entry_name.name(), all_entries[i] );
}
for ( String toolName : mToolList ) {
if ( !entryMap.containsKey( toolName ) ) continue;
listEntries.add( entryMap.get( toolName ) );
}
return listEntries;
}
return mListEntries;
}
protected void onToolsLoaded( List<EffectEntry> listEntries ) {
mListEntries = listEntries;
WorkspaceAdapter adapter = new WorkspaceAdapter( getBaseContext(), R.layout.feather_workspace_screen, -1, mListEntries );
mWorkspace.setAdapter( adapter );
if ( mListEntries.size() <= mItemsPerPage ) {
mWorkspaceIndicator.setVisibility( View.INVISIBLE );
} else {
mWorkspaceIndicator.setVisibility( View.VISIBLE );
}
}
/**
* Returns the application main toolbar which contains the save/undo/redo buttons.
*
* @return the toolbar
* @see ToolbarView
*/
@Override
public ToolbarView getToolbar() {
return mToolbar;
}
/**
* Return the current panel used to populate the active tool options.
*
* @return the options panel container
*/
@Override
public ViewGroup getOptionsPanelContainer() {
return mBottomBarFlipper.getContent();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.FilterManager.FeatherContext#getBottomBar()
*/
@Override
public BottombarViewFlipper getBottomBar() {
return mBottomBarFlipper;
}
/**
* Returns the application workspace view which contains the scrolling tools icons.
*
* @return the workspace
* @see WorkspaceView
*/
public Workspace getWorkspace() {
return mWorkspace;
}
/**
* Return the main image view.
*
* @return the main image
*/
@Override
public ImageViewTouch getMainImage() {
return mImageView;
}
/**
* Return the actual view used to populate a {@link ContentPanel}.
*
* @see {@link ContentPanel#getContentView(LayoutInflater)}
* @return the drawing image container
*/
@Override
public ViewGroup getDrawingImageContainer() {
return mDrawingViewContainer;
}
// ---------------------
// Toolbar events
// ---------------------
/**
* User clicked on the save button.<br />
* Start the save process
*/
@Override
public void onSaveClick() {
if ( mFilterManager.getEnabled() ) {
mFilterManager.onSave();
if ( mFilterManager != null ) {
Bitmap bitmap = mFilterManager.getBitmap();
if ( bitmap != null ) {
performSave( bitmap );
}
}
}
}
/**
* User clicked on the apply button.<br />
* Apply the current tool modifications and update the main image
*/
@Override
public void onApplyClick() {
mFilterManager.onApply();
}
/**
* User cancelled the active tool. Discard all the tool changes.
*/
@Override
public void onCancelClick() {
mFilterManager.onCancel();
}
/**
* load the original file EXIF data and store the result into the local data instance
*/
protected void loadExif() {
logger.log( "loadExif" );
final LocalDataService data = mFilterManager.getService( LocalDataService.class );
ThreadPoolService thread = mFilterManager.getService( ThreadPoolService.class );
if ( null != data && thread != null ) {
final String path = data.getSourceImagePath();
FutureListener<Bundle> listener = new FutureListener<Bundle>() {
@Override
public void onFutureDone( Future<Bundle> future ) {
try {
Bundle result = future.get();
if ( null != result ) {
data.setOriginalExifBundle( result );
}
} catch ( Throwable e ) {
e.printStackTrace();
}
}
};
if ( null != path ) {
thread.submit( new ExifTask(), listener, path );
} else {
logger.warning( "orinal file path not available" );
}
}
}
/**
* Try to compute the original file absolute path
*/
protected void computeOriginalFilePath() {
final LocalDataService data = mFilterManager.getService( LocalDataService.class );
if ( null != data ) {
data.setSourceImagePath( null );
Uri uri = data.getSourceImageUri();
if ( null != uri ) {
String path = IOUtils.getRealFilePath( this, uri );
if ( null != path ) {
data.setSourceImagePath( path );
}
}
}
}
// --------------------------------
// DownloadImageAsyncTask listener
// --------------------------------
/**
* Local or remote image has been completely loaded. Now it's time to enable all the tools and fade in the image
*
* @param result
* the result
* @param originalSize
* int array containing the width and height of the loaded bitmap
*/
@Override
public void onDownloadComplete( Bitmap result, ImageSizes sizes ) {
logger.log( "onDownloadComplete" );
mDownloadTask = null;
mImageView.setImageBitmap( result, true, null, UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
Animation animation = AnimationUtils.loadAnimation( this, android.R.anim.fade_in );
animation.setFillEnabled( true );
mImageView.setVisibility( View.VISIBLE );
mImageView.startAnimation( animation );
hideProgressLoader();
int[] originalSize = { -1, -1 };
if ( null != sizes ) {
originalSize = sizes.getRealSize();
onImageSize( sizes.getOriginalSize(), sizes.getNewSize(), sizes.getBucketSize() );
}
if ( mFilterManager != null ) {
if ( mFilterManager.getEnabled() ) {
mFilterManager.onReplaceImage( result, originalSize );
} else {
mFilterManager.onActivate( result, originalSize );
}
}
if ( null != result && null != originalSize && originalSize.length > 1 ) {
logger.error( "original.size: " + originalSize[0] + "x" + originalSize[1] );
logger.error( "final.size: " + result.getWidth() + "x" + result.getHeight() );
}
computeOriginalFilePath();
loadExif();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.async_tasks.DownloadImageAsyncTask.OnImageDownloadListener#onDownloadError(java.lang.String)
*/
@SuppressWarnings("deprecation")
@Override
public void onDownloadError( String error ) {
logger.error( "onDownloadError", error );
mDownloadTask = null;
hideProgressLoader();
showDialog( ALERT_DOWNLOAD_ERROR );
}
/**
* Hide progress loader.
*/
private void hideProgressLoader() {
Animation fadeout = new AlphaAnimation( 1, 0 );
fadeout.setDuration( getResources().getInteger( R.integer.feather_config_mediumAnimTime ) );
fadeout.setAnimationListener( new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
mInlineProgressLoader.setVisibility( View.GONE );
}
} );
mInlineProgressLoader.startAnimation( fadeout );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.async_tasks.DownloadImageAsyncTask.OnImageDownloadListener#onDownloadStart()
*/
@Override
public void onDownloadStart() {
mImageView.setVisibility( View.INVISIBLE );
mInlineProgressLoader.setVisibility( View.VISIBLE );
}
// -------------------------------
// Bitmap change listener
// -------------------------------
@Override
public void onPreviewChange( Bitmap bitmap ) {
final boolean changed = BitmapUtils.compareBySize( ( (IBitmapDrawable) mImageView.getDrawable() ).getBitmap(), bitmap );
mImageView.setImageBitmap( bitmap, changed, null, UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
}
@Override
public void onPreviewChange( ColorFilter filter ) {
mImageView.setColorFilter( filter );
}
@Override
public void onBitmapChange( Bitmap bitmap, boolean update, android.graphics.Matrix matrix ) {
mImageView.setImageBitmap( bitmap, update, matrix, UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
};
@Override
public void onClearColorFilter() {
mImageView.clearColorFilter();
}
/**
* Perform save.
*
* @param bitmap
* the bitmap
*/
protected void performSave( final Bitmap bitmap ) {
if ( mSaving ) return;
mSaving = true;
Tracker.recordTag( "feather: saved" );
// disable the filter manager...
mFilterManager.setEnabled( false );
LocalDataService service = mFilterManager.getService( LocalDataService.class );
// Release bitmap memory
Bundle myExtras = getIntent().getExtras();
// if request intent has "return-data" then the result bitmap
// will be encoded into the result itent
if ( myExtras != null && myExtras.getBoolean( Constants.EXTRA_RETURN_DATA ) ) {
Bundle extras = new Bundle();
extras.putParcelable( "data", bitmap );
onSetResult( RESULT_OK, new Intent().setData( service.getDestImageUri() ).setAction( "inline-data" ).putExtras( extras ) );
finish();
} else {
ThreadUtils.startBackgroundJob( this, null, "Saving...", new Runnable() {
@Override
public void run() {
doSave( bitmap );
}
}, mHandler );
}
}
/**
* Do save.
*
* @param bitmap
* the bitmap
*/
protected void doSave( Bitmap bitmap ) {
// result extras
Bundle extras = new Bundle();
LocalDataService service = mFilterManager.getService( LocalDataService.class );
Uri saveUri = service.getDestImageUri();
// if the request intent has EXTRA_OUTPUT declared
// then save the image into the output uri and return it
if ( saveUri != null ) {
OutputStream outputStream = null;
String scheme = saveUri.getScheme();
try {
if ( scheme == null ) {
outputStream = new FileOutputStream( saveUri.getPath() );
} else {
outputStream = getContentResolver().openOutputStream( saveUri );
}
if ( outputStream != null ) {
int quality = Constants.getValueFromIntent( Constants.EXTRA_OUTPUT_QUALITY, 80 );
bitmap.compress( service.getOutputFormat(), quality, outputStream );
}
} catch ( IOException ex ) {
logger.error( "Cannot open file", saveUri, ex );
} finally {
IOUtils.closeSilently( outputStream );
}
onSetResult( RESULT_OK, new Intent().setData( saveUri ).putExtras( extras ) );
} else {
// no output uri declared, save the image in a new path
// and return it
String url = Media.insertImage( getContentResolver(), bitmap, "title", "modified with Aviary Feather" );
if ( url != null ) {
saveUri = Uri.parse( url );
getContentResolver().notifyChange( saveUri, null );
}
onSetResult( RESULT_OK, new Intent().setData( saveUri ).putExtras( extras ) );
}
final Bitmap b = bitmap;
mHandler.post( new Runnable() {
@Override
public void run() {
mImageView.clear();
b.recycle();
}
} );
if ( null != saveUri ) {
saveExif( saveUri );
}
mSaving = false;
finish();
}
protected void saveExif( Uri uri ) {
logger.log( "saveExif: " + uri );
if ( null != uri ) {
saveExif( uri.getPath() );
}
}
protected void saveExif( String path ) {
logger.log( "saveExif: " + path );
if ( null == path ) {
return;
}
LocalDataService data = mFilterManager.getService( LocalDataService.class );
ExifInterfaceWrapper newexif = null;
if ( null != data ) {
try {
newexif = new ExifInterfaceWrapper( path );
} catch ( IOException e ) {
logger.error( e.getMessage() );
e.printStackTrace();
return;
};
Bundle bundle = data.getOriginalExifBundle();
if ( null != bundle ) {
try {
newexif.copyFrom( bundle );
newexif.setAttribute( ExifInterfaceWrapper.TAG_ORIENTATION, "0" );
newexif.setAttribute( ExifInterfaceWrapper.TAG_SOFTWARE, "Aviary for Android " + SDK_VERSION );
// implements this to include your own tags
onSaveCustomTags( newexif );
newexif.saveAttributes();
} catch ( Throwable t ) {
t.printStackTrace();
logger.error( t.getMessage() );
}
}
}
}
protected void onSaveCustomTags( ExifInterfaceWrapper exif ) {
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.FilterManager.OnToolListener#onToolCompleted()
*/
@Override
public void onToolCompleted() {
final long anim_time = mToolbar.getInAnimationTime();
mToolbarMainAnimator.postDelayed( new Runnable() {
@Override
public void run() {
mToolbarMainAnimator.setDisplayedChild( 2 );
}
}, anim_time + 100 );
mToolbarMainAnimator.postDelayed( new Runnable() {
@Override
public void run() {
mToolbarMainAnimator.setDisplayedChild( 0 );
}
}, anim_time + 900 );
}
private IToast mToastLoader;
/**
* show the progress indicator in the toolbar content.
*/
@Override
public void showToolProgress() {
mToolbarContentAnimator.setDisplayedChild( 1 );
}
/**
* hide the progress indicator in the toolbar content reset to the first null state.
*/
@Override
public void hideToolProgress() {
mToolbarContentAnimator.setDisplayedChild( 0 );
}
@Override
public void showModalProgress() {
if ( mToastLoader == null ) {
mToastLoader = UIUtils.createModalLoaderToast();
}
mToastLoader.show();
}
@Override
public void hideModalProgress() {
if ( mToastLoader != null ) {
mToastLoader.hide();
}
}
/**
* Creates the info screen animations.
*
* @param isOpening
* the is opening
*/
private void createInfoScreenAnimations( final boolean isOpening ) {
final float centerX = mViewFlipper.getWidth() / 2.0f;
final float centerY = mViewFlipper.getHeight() / 2.0f;
Animation mMainViewAnimationIn, mMainViewAnimationOut;
final int duration = getResources().getInteger( R.integer.feather_config_infoscreen_animTime );
// we allow the flip3d animation only if the OS is > android 2.2
if ( android.os.Build.VERSION.SDK_INT > 8 ) {
mMainViewAnimationIn = new Flip3dAnimation( isOpening ? -180 : 180, 0, centerX, centerY );
mMainViewAnimationOut = new Flip3dAnimation( 0, isOpening ? 180 : -180, centerX, centerY );
mMainViewAnimationIn.setDuration( duration );
mMainViewAnimationOut.setDuration( duration );
} else {
// otherwise let's just use a regular alpha animation
mMainViewAnimationIn = new AlphaAnimation( 0.0f, 1.0f );
mMainViewAnimationOut = new AlphaAnimation( 1.0f, 0.0f );
mMainViewAnimationIn.setDuration( duration / 2 );
mMainViewAnimationOut.setDuration( duration / 2 );
}
mViewFlipper.setInAnimation( mMainViewAnimationIn );
mViewFlipper.setOutAnimation( mMainViewAnimationOut );
}
/**
* Display the big info screen Flip the main image with the infoscreen view.
*/
private void showInfoScreen() {
createInfoScreenAnimations( true );
mViewFlipper.setDisplayedChild( 1 );
TextView text = (TextView) mViewFlipper.findViewById( R.id.version_text );
text.setText( "v " + FeatherActivity.SDK_VERSION );
mViewFlipper.findViewById( R.id.aviary_infoscreen_submit ).setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
String url = "http://www.aviary.com";
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData( Uri.parse( url ) );
try {
startActivity( i );
} catch ( ActivityNotFoundException e ) {
e.printStackTrace();
}
}
} );
}
/**
* Hide info screen.
*/
private void hideInfoScreen() {
createInfoScreenAnimations( false );
mViewFlipper.setDisplayedChild( 0 );
View convertView = mWorkspace.getChildAt( mWorkspace.getChildCount() - 1 );
if ( null != convertView ) {
View button = convertView.findViewById( R.id.tool_image );
if ( button != null && button instanceof ToggleButton ) {
( (ToggleButton) button ).setChecked( false );
}
}
}
/**
* Checks if is info screen visible.
*
* @return true, if is info screen visible
*/
private boolean isInfoScreenVisible() {
return mViewFlipper.getDisplayedChild() == 1;
}
/**
* reset the toolbar indicator to the first null state.
*/
public void resetToolIndicator() {
mToolbarContentAnimator.setDisplayedChild( 0 );
}
/**
* Gets the api key.
*
* @return the api key
*/
String getApiKey() {
return mApiKey;
}
/**
* Gets the uI handler.
*
* @return the uI handler
*/
Handler getUIHandler() {
return mUIHandler;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.MonitoredActivity#onStart()
*/
@Override
public void onStart() {
super.onStart();
mOrientation = getResources().getConfiguration().orientation; // getWindowManager().getDefaultDisplay().getRotation();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.MonitoredActivity#onStop()
*/
@Override
public void onStop() {
super.onStop();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.MonitoredActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
}
protected void onImageSize( String originalSize, String scaledSize, String bucket ) {
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put( "originalSize", originalSize );
attributes.put( "newSize", scaledSize );
attributes.put( "bucketSize", bucket );
Tracker.recordTag( "image: scaled", attributes );
}
/**
* The Class WorkspaceAdapter.
*/
class WorkspaceAdapter extends ArrayAdapter<EffectEntry> {
/** The m layout inflater. */
private LayoutInflater mLayoutInflater;
/** The m resource id. */
private int mResourceId;
/**
* Instantiates a new workspace adapter.
*
* @param context
* the context
* @param resource
* the resource
* @param textViewResourceId
* the text view resource id
* @param objects
* the objects
*/
public WorkspaceAdapter( Context context, int resource, int textViewResourceId, List<EffectEntry> objects ) {
super( context, resource, textViewResourceId, objects );
mResourceId = resource;
mLayoutInflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
}
/**
* We need to return 1 page more than the real count because of the info screen. Last page will be the info screen
*
* @return the count
*/
@Override
public int getCount() {
int realCount = (int) Math.ceil( (double) super.getCount() / mItemsPerPage );
return realCount;
}
/**
* Gets the real count.
*
* @return the real count
*/
public int getRealCount() {
return super.getCount();
}
/*
* (non-Javadoc)
*
* @see android.widget.BaseAdapter#getItemViewType(int)
*/
@Override
public int getItemViewType( int position ) {
if ( position == getCount() - 1 ) {
return 1;
} else {
return 0;
}
}
/*
* (non-Javadoc)
*
* @see android.widget.BaseAdapter#getViewTypeCount()
*/
@Override
public int getViewTypeCount() {
return 2;
}
/**
* The Class WorkspaceToolViewHolder.
*/
class WorkspaceToolViewHolder {
/** The image. */
public ImageView image;
/** The text. */
public TextView text;
};
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
if ( convertView == null ) {
convertView = mLayoutInflater.inflate( mResourceId, mWorkspace, false );
( (CellLayout) convertView ).setNumCols( mScreenCols );
}
CellLayout cell = (CellLayout) convertView;
int index = position * mItemsPerPage;
int realCount = getRealCount();
WorkspaceToolViewHolder holder;
// if ( getItemViewType( position ) == 1 ) {
//
// // last page, info screen
//
// cell.removeAllViews();
// CellInfo cellInfo = cell.findVacantCell( mScreenCols, 1 );
// ViewGroup toolView = (ViewGroup) mLayoutInflater.inflate( R.layout.feather_egg_info_view, parent, false );
// CellLayout.LayoutParams lp = new CellLayout.LayoutParams( cellInfo.cellX, cellInfo.cellY, cellInfo.spanH,
// cellInfo.spanV );
// cell.addView( toolView, -1, lp );
//
// ToggleButton button = (ToggleButton) toolView.findViewById( R.id.tool_image );
// button.setChecked( false );
//
// button.setOnCheckedChangeListener( new OnCheckedChangeListener() {
//
// @Override
// public void onCheckedChanged( CompoundButton buttonView, boolean isChecked ) {
// if ( isChecked ) {
// showInfoScreen();
// mWorkspace.setFocusable( false );
// } else {
// hideInfoScreen();
// mWorkspace.setFocusable( true );
// }
// }
// } );
//
// return cell;
// }
if ( cell.findViewById( R.id.egg_info_view ) != null ) {
cell.removeAllViews();
}
for ( int i = 0; i < mItemsPerPage; i++ ) {
ViewGroup toolView;
CellInfo cellInfo = cell.findVacantCell( 1, 1 );
if ( cellInfo == null ) {
toolView = (ViewGroup) cell.getChildAt( i );
holder = (WorkspaceToolViewHolder) toolView.getTag();
} else {
toolView = (ViewGroup) mLayoutInflater.inflate( R.layout.feather_egg_view, parent, false );
CellLayout.LayoutParams lp = new CellLayout.LayoutParams( cellInfo.cellX, cellInfo.cellY, cellInfo.spanH,
cellInfo.spanV );
cell.addView( toolView, -1, lp );
holder = new WorkspaceToolViewHolder();
holder.image = (ImageView) toolView.findViewById( R.id.tool_image );
holder.text = (TextView) toolView.findViewById( R.id.tool_text );
// if( null != UIUtils.getAppTypeFace() ){
// holder.text.setTypeface( UIUtils.getAppTypeFace() );
// }
toolView.setTag( holder );
}
if ( ( index + i ) < realCount ) {
loadEgg( index + i, toolView );
toolView.setVisibility( View.VISIBLE );
} else {
toolView.setVisibility( View.INVISIBLE );
}
}
convertView.requestLayout();
return convertView;
}
/**
* Load egg.
*
* @param position
* the position
* @param view
* the view
*/
private void loadEgg( int position, final ViewGroup view ) {
EffectEntry entry = getItem( position );
final WorkspaceToolViewHolder holder = (WorkspaceToolViewHolder) view.getTag();
holder.image.setImageDrawable( new ToolIconsDrawable( getResources(), entry.iconResourceId ) );
holder.text.setText( entry.labelResourceId );
holder.image.setTag( entry );
holder.image.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
mUIHandler.postDelayed( new Runnable() {
@Override
public void run() {
if ( mWorkspace.isEnabled() ) mFilterManager.activateEffect( (EffectEntry) holder.image.getTag() );
}
}, TOOLS_OPEN_DELAY_TIME );
}
} );
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.wp.Workspace.OnPageChangeListener#onPageChanged(int)
*/
@Override
public void onPageChanged( int which, int old ) {
if ( mWorkspace != null && mWorkspace.getAdapter() != null ) {
if ( which == mWorkspace.getAdapter().getCount() - 2 && old == mWorkspace.getAdapter().getCount() - 1 ) {
if ( isInfoScreenVisible() ) {
hideInfoScreen();
}
}
}
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ViewFlipper;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.graphics.animation.VoidAnimation;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
// TODO: Auto-generated Javadoc
/**
* The Class BottombarViewFlipper.
*/
public class BottombarViewFlipper extends ViewFlipper {
/** The logger. */
Logger logger = LoggerFactory.getLogger( "bottombar", LoggerType.ConsoleLoggerType );
/**
* The listener interface for receiving onPanelOpen events. The class that is interested in processing a onPanelOpen event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnPanelOpenListener<code> method. When
* the onPanelOpen event occurs, that object's appropriate
* method is invoked.
*
* @see OnPanelOpenEvent
*/
public static interface OnPanelOpenListener {
/**
* On opening.
*/
void onOpening();
/**
* On opened.
*/
void onOpened();
};
/**
* The listener interface for receiving onPanelClose events. The class that is interested in processing a onPanelClose event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnPanelCloseListener<code> method. When
* the onPanelClose event occurs, that object's appropriate
* method is invoked.
*
* @see OnPanelCloseEvent
*/
public static interface OnPanelCloseListener {
/**
* On closing.
*/
void onClosing();
/**
* On closed.
*/
void onClosed();
};
/** The m open animation listener. */
private AnimationListener mOpenAnimationListener = new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
if ( mOpenListener != null ) mOpenListener.onOpening();
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
if ( mOpenListener != null ) mOpenListener.onOpened();
animation.setAnimationListener( null );
}
};
/** The m close animation listener. */
private AnimationListener mCloseAnimationListener = new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
if ( mCloseListener != null ) mCloseListener.onClosing();
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
if ( mCloseListener != null ) mCloseListener.onClosed();
animation.setAnimationListener( null );
}
};
/** The m open listener. */
private OnPanelOpenListener mOpenListener;
/** The m close listener. */
private OnPanelCloseListener mCloseListener;
/** The m animation duration. */
private int mAnimationDuration = 500;
/** The m animation in. */
private Animation mAnimationIn;
/** The m animation out. */
private Animation mAnimationOut;
private int mAnimationOpenStartOffset = 100;
private int mAnimationCloseStartOffset = 100;
/**
* Instantiates a new bottombar view flipper.
*
* @param context
* the context
*/
public BottombarViewFlipper( Context context ) {
this( context, null );
init( context );
}
/**
* Instantiates a new bottombar view flipper.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public BottombarViewFlipper( Context context, AttributeSet attrs ) {
super( context, attrs );
init( context );
}
/**
* Inits the.
*
* @param context
* the context
*/
private void init( Context context ) {
setAnimationCacheEnabled( true );
// setDrawingCacheEnabled( true );
// setAlwaysDrawnWithCacheEnabled( false );
// setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
mAnimationDuration = context.getResources().getInteger( R.integer.feather_config_bottom_animTime );
mAnimationCloseStartOffset = context.getResources().getInteger( R.integer.feather_bottombar_close_offset );
mAnimationOpenStartOffset = context.getResources().getInteger( R.integer.feather_bottombar_open_offset );
}
/**
* Return the view which will contain all the options panel.
*
* @return the content
*/
public ViewGroup getContent() {
return (ViewGroup) getChildAt( mContentPanelIndex );
}
/**
* Gets the tool panel.
*
* @return the tool panel
*/
public ViewGroup getToolPanel() {
return (ViewGroup) getChildAt( mToolPanelIndex );
}
/** The m tool panel index. */
final int mToolPanelIndex = 1;
/** The m content panel index. */
final int mContentPanelIndex = 0;
/**
* Close the option panel and return to the tools list view.
*/
public void close() {
int height = getContent().getHeight();
Animation animationOut = createVoidAnimation( mAnimationDuration, mAnimationCloseStartOffset );
animationOut.setAnimationListener( mCloseAnimationListener );
height = getToolPanel().getHeight();
Animation animationIn = createInAnimation( TranslateAnimation.ABSOLUTE, height, mAnimationDuration,
mAnimationCloseStartOffset );
setInAnimation( animationIn );
setOutAnimation( animationOut );
setDisplayedChild( mToolPanelIndex );
}
/**
* Display the option panel while hiding the bottom tools.
*/
public void open() {
// first we must check the height of the content
// panel to use within the in animation
int height;
// getContent().setVisibility( View.INVISIBLE );
height = getContent().getMeasuredHeight();
if ( height == 0 ) {
getHandler().post( new Runnable() {
@Override
public void run() {
try {
Thread.sleep( 10 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
open();
}
} );
return;
}
Animation animationIn = createVoidAnimation( mAnimationDuration, mAnimationOpenStartOffset );
height = getToolPanel().getHeight();
Animation animationOut = createOutAnimation( TranslateAnimation.ABSOLUTE, height, mAnimationDuration,
mAnimationOpenStartOffset );
animationIn.setAnimationListener( mOpenAnimationListener );
setInAnimation( animationIn );
setOutAnimation( animationOut );
setDisplayedChild( mContentPanelIndex );
}
/**
* Creates the void animation.
*
* @param durationMillis
* the duration millis
* @param startOffset
* the start offset
* @return the animation
*/
private Animation createVoidAnimation( int durationMillis, int startOffset ) {
Animation animation = new VoidAnimation();
animation.setDuration( durationMillis );
animation.setStartOffset( startOffset );
return animation;
}
/**
* Creates the out animation.
*
* @param deltaType
* the delta type
* @param height
* the height
* @param durationMillis
* the duration millis
* @param startOffset
* the start offset
* @return the animation
*/
private Animation createOutAnimation( int deltaType, int height, int durationMillis, int startOffset ) {
if ( mAnimationOut == null ) {
mAnimationOut = new TranslateAnimation( deltaType, 0, deltaType, 0, deltaType, 0, deltaType, height );
mAnimationOut.setInterpolator( new DecelerateInterpolator( 0.4f ) );
mAnimationOut.setDuration( durationMillis );
mAnimationOut.setStartOffset( startOffset );
}
return mAnimationOut;
}
/**
* Creates the in animation.
*
* @param deltaType
* the delta type
* @param height
* the height
* @param durationMillis
* the duration millis
* @param startOffset
* the start offset
* @return the animation
*/
private Animation createInAnimation( int deltaType, int height, int durationMillis, int startOffset ) {
if ( mAnimationIn == null ) {
mAnimationIn = new TranslateAnimation( deltaType, 0, deltaType, 0, deltaType, height, deltaType, 0 );
mAnimationIn.setDuration( durationMillis );
mAnimationIn.setStartOffset( startOffset );
mAnimationIn.setInterpolator( new AccelerateInterpolator( 0.5f ) );
}
return mAnimationIn;
// return animation;
}
/**
* Sets the on panel open listener.
*
* @param listener
* the new on panel open listener
*/
public void setOnPanelOpenListener( OnPanelOpenListener listener ) {
mOpenListener = listener;
}
/**
* Sets the on panel close listener.
*
* @param listener
* the new on panel close listener
*/
public void setOnPanelCloseListener( OnPanelCloseListener listener ) {
mCloseListener = listener;
}
}
| Java |
package com.aviary.android.feather.widget;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
class Fling8Runnable extends IFlingRunnable {
private Scroller mScroller;
public Fling8Runnable( FlingRunnableView parent, int animationDuration ) {
super( parent, animationDuration );
mScroller = new Scroller( ( (View) parent ).getContext(), new DecelerateInterpolator() );
}
@Override
public float getCurrVelocity() {
return mScroller.getCurrVelocity();
}
@Override
public boolean isFinished() {
return mScroller.isFinished();
}
@Override
protected void _startUsingVelocity( int initialX, int velocity ) {
mScroller.fling( initialX, 0, velocity, 0, mParent.getMinX(), mParent.getMaxX(), 0, Integer.MAX_VALUE );
}
@Override
protected void _startUsingDistance( int initialX, int distance ) {
mScroller.startScroll( initialX, 0, distance, 0, mAnimationDuration );
}
@Override
protected void forceFinished( boolean finished ) {
mScroller.forceFinished( finished );
}
@Override
protected boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
protected int getCurrX() {
return mScroller.getCurrX();
}
@Override
public boolean springBack( int startX, int startY, int minX, int maxX, int minY, int maxY ) {
return false;
}
} | Java |
package com.aviary.android.feather.widget;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class ArrayAdapterExtended<T> extends BaseAdapterExtended implements Filterable {
/**
* Contains the list of objects that represent the data of this ArrayAdapter. The content of this list is referred to as
* "the array" in the documentation.
*/
private List<T> mObjects;
/**
* Lock used to modify the content of {@link #mObjects}. Any write operation performed on the array should be synchronized on
* this lock. This lock is also used by the filter (see {@link #getFilter()} to make a synchronized copy of the original array of
* data.
*/
private final Object mLock = new Object();
/**
* The resource indicating what views to inflate to display the content of this array adapter.
*/
private int mResource;
/**
* The resource indicating what views to inflate to display the content of this array adapter in a drop down widget.
*/
private int mDropDownResource;
/**
* If the inflated resource is not a TextView, {@link #mFieldId} is used to find a TextView inside the inflated views hierarchy.
* This field must contain the identifier that matches the one defined in the resource file.
*/
private int mFieldId = 0;
/**
* Indicates whether or not {@link #notifyDataSetChanged()} must be called whenever {@link #mObjects} is modified.
*/
private boolean mNotifyOnChange = true;
private Context mContext;
// A copy of the original mObjects array, initialized from and then used instead as soon as
// the mFilter ArrayFilter is used. mObjects will then only contain the filtered values.
private ArrayList<T> mOriginalValues;
private ArrayFilter mFilter;
private LayoutInflater mInflater;
/**
* Constructor
*
* @param context
* The current context.
* @param textViewResourceId
* The resource ID for a layout file containing a TextView to use when instantiating views.
*/
public ArrayAdapterExtended( Context context, int textViewResourceId ) {
init( context, textViewResourceId, 0, new ArrayList<T>() );
}
/**
* Constructor
*
* @param context
* The current context.
* @param resource
* The resource ID for a layout file containing a layout to use when instantiating views.
* @param textViewResourceId
* The id of the TextView within the layout resource to be populated
*/
public ArrayAdapterExtended( Context context, int resource, int textViewResourceId ) {
init( context, resource, textViewResourceId, new ArrayList<T>() );
}
/**
* Constructor
*
* @param context
* The current context.
* @param textViewResourceId
* The resource ID for a layout file containing a TextView to use when instantiating views.
* @param objects
* The objects to represent in the ListView.
*/
public ArrayAdapterExtended( Context context, int textViewResourceId, T[] objects ) {
init( context, textViewResourceId, 0, Arrays.asList( objects ) );
}
/**
* Constructor
*
* @param context
* The current context.
* @param resource
* The resource ID for a layout file containing a layout to use when instantiating views.
* @param textViewResourceId
* The id of the TextView within the layout resource to be populated
* @param objects
* The objects to represent in the ListView.
*/
public ArrayAdapterExtended( Context context, int resource, int textViewResourceId, T[] objects ) {
init( context, resource, textViewResourceId, Arrays.asList( objects ) );
}
/**
* Constructor
*
* @param context
* The current context.
* @param textViewResourceId
* The resource ID for a layout file containing a TextView to use when instantiating views.
* @param objects
* The objects to represent in the ListView.
*/
public ArrayAdapterExtended( Context context, int textViewResourceId, List<T> objects ) {
init( context, textViewResourceId, 0, objects );
}
/**
* Constructor
*
* @param context
* The current context.
* @param resource
* The resource ID for a layout file containing a layout to use when instantiating views.
* @param textViewResourceId
* The id of the TextView within the layout resource to be populated
* @param objects
* The objects to represent in the ListView.
*/
public ArrayAdapterExtended( Context context, int resource, int textViewResourceId, List<T> objects ) {
init( context, resource, textViewResourceId, objects );
}
/**
* Adds the specified object at the end of the array.
*
* @param object
* The object to add at the end of the array.
*/
public void add( T object ) {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
mOriginalValues.add( object );
} else {
mObjects.add( object );
}
}
if ( mNotifyOnChange ) notifyDataSetAdded();
}
/**
* Adds the specified Collection at the end of the array.
*
* @param collection
* The Collection to add at the end of the array.
*/
public void addAll( Collection<? extends T> collection ) {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
mOriginalValues.addAll( collection );
} else {
mObjects.addAll( collection );
}
}
if ( mNotifyOnChange ) notifyDataSetAdded();
}
/**
* Adds the specified items at the end of the array.
*
* @param items
* The items to add at the end of the array.
*/
public void addAll( T... items ) {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
Collections.addAll( mOriginalValues, items );
} else {
Collections.addAll( mObjects, items );
}
}
if ( mNotifyOnChange ) notifyDataSetAdded();
}
/**
* Inserts the specified object at the specified index in the array.
*
* @param object
* The object to insert into the array.
* @param index
* The index at which the object must be inserted.
*/
public void insert( T object, int index ) {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
mOriginalValues.add( index, object );
} else {
mObjects.add( index, object );
}
}
if ( mNotifyOnChange ) notifyDataSetChanged();
}
/**
* Removes the specified object from the array.
*
* @param object
* The object to remove.
*/
public void remove( T object ) {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
mOriginalValues.remove( object );
} else {
mObjects.remove( object );
}
}
if ( mNotifyOnChange ) notifyDataSetRemoved();
}
/**
* Remove all elements from the list.
*/
public void clear() {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
mOriginalValues.clear();
} else {
mObjects.clear();
}
}
if ( mNotifyOnChange ) notifyDataSetChanged();
}
/**
* Sorts the content of this adapter using the specified comparator.
*
* @param comparator
* The comparator used to sort the objects contained in this adapter.
*/
public void sort( Comparator<? super T> comparator ) {
synchronized ( mLock ) {
if ( mOriginalValues != null ) {
Collections.sort( mOriginalValues, comparator );
} else {
Collections.sort( mObjects, comparator );
}
}
if ( mNotifyOnChange ) notifyDataSetChanged();
}
/**
* {@inheritDoc}
*/
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mNotifyOnChange = true;
}
/**
* Control whether methods that change the list ({@link #add}, {@link #insert}, {@link #remove}, {@link #clear}) automatically
* call {@link #notifyDataSetChanged}. If set to false, caller must manually call notifyDataSetChanged() to have the changes
* reflected in the attached view.
*
* The default is true, and calling notifyDataSetChanged() resets the flag to true.
*
* @param notifyOnChange
* if true, modifications to the list will automatically call {@link #notifyDataSetChanged}
*/
public void setNotifyOnChange( boolean notifyOnChange ) {
mNotifyOnChange = notifyOnChange;
}
private void init( Context context, int resource, int textViewResourceId, List<T> objects ) {
mContext = context;
mInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
mResource = mDropDownResource = resource;
mObjects = objects;
mFieldId = textViewResourceId;
}
/**
* Returns the context associated with this array adapter. The context is used to create views from the resource passed to the
* constructor.
*
* @return The Context associated with this adapter.
*/
public Context getContext() {
return mContext;
}
/**
* {@inheritDoc}
*/
public int getCount() {
return mObjects.size();
}
/**
* {@inheritDoc}
*/
public T getItem( int position ) {
return mObjects.get( position );
}
/**
* Returns the position of the specified item in the array.
*
* @param item
* The item to retrieve the position of.
*
* @return The position of the specified item.
*/
public int getPosition( T item ) {
return mObjects.indexOf( item );
}
/**
* {@inheritDoc}
*/
public long getItemId( int position ) {
return position;
}
/**
* {@inheritDoc}
*/
public View getView( int position, View convertView, ViewGroup parent ) {
return createViewFromResource( position, convertView, parent, mResource );
}
private View createViewFromResource( int position, View convertView, ViewGroup parent, int resource ) {
View view;
TextView text;
if ( convertView == null ) {
view = mInflater.inflate( resource, parent, false );
} else {
view = convertView;
}
try {
if ( mFieldId == 0 ) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById( mFieldId );
}
} catch ( ClassCastException e ) {
Log.e( "ArrayAdapter", "You must supply a resource ID for a TextView" );
throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e );
}
T item = getItem( position );
if ( item instanceof CharSequence ) {
text.setText( (CharSequence) item );
} else {
text.setText( item.toString() );
}
return view;
}
/**
* <p>
* Sets the layout resource to create the drop down views.
* </p>
*
* @param resource
* the layout resource defining the drop down views
* @see #getDropDownView(int, android.view.View, android.view.ViewGroup)
*/
public void setDropDownViewResource( int resource ) {
this.mDropDownResource = resource;
}
/**
* {@inheritDoc}
*/
@Override
public View getDropDownView( int position, View convertView, ViewGroup parent ) {
return createViewFromResource( position, convertView, parent, mDropDownResource );
}
/**
* Creates a new ArrayAdapter from external resources. The content of the array is obtained through
* {@link android.content.res.Resources#getTextArray(int)}.
*
* @param context
* The application's environment.
* @param textArrayResId
* The identifier of the array to use as the data source.
* @param textViewResId
* The identifier of the layout used to create views.
*
* @return An ArrayAdapter<CharSequence>.
*/
public static ArrayAdapterExtended<CharSequence> createFromResource( Context context, int textArrayResId, int textViewResId ) {
CharSequence[] strings = context.getResources().getTextArray( textArrayResId );
return new ArrayAdapterExtended<CharSequence>( context, textViewResId, strings );
}
/**
* {@inheritDoc}
*/
public Filter getFilter() {
if ( mFilter == null ) {
mFilter = new ArrayFilter();
}
return mFilter;
}
/**
* <p>
* An array filter constrains the content of the array adapter with a prefix. Each item that does not start with the supplied
* prefix is removed from the list.
* </p>
*/
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering( CharSequence prefix ) {
FilterResults results = new FilterResults();
if ( mOriginalValues == null ) {
synchronized ( mLock ) {
mOriginalValues = new ArrayList<T>( mObjects );
}
}
if ( prefix == null || prefix.length() == 0 ) {
ArrayList<T> list;
synchronized ( mLock ) {
list = new ArrayList<T>( mOriginalValues );
}
results.values = list;
results.count = list.size();
} else {
String prefixString = prefix.toString().toLowerCase();
ArrayList<T> values;
synchronized ( mLock ) {
values = new ArrayList<T>( mOriginalValues );
}
final int count = values.size();
final ArrayList<T> newValues = new ArrayList<T>();
for ( int i = 0; i < count; i++ ) {
final T value = values.get( i );
final String valueText = value.toString().toLowerCase();
// First match against the whole, non-splitted value
if ( valueText.startsWith( prefixString ) ) {
newValues.add( value );
} else {
final String[] words = valueText.split( " " );
final int wordCount = words.length;
// Start at index 0, in case valueText starts with space(s)
for ( int k = 0; k < wordCount; k++ ) {
if ( words[k].startsWith( prefixString ) ) {
newValues.add( value );
break;
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@Override
protected void publishResults( CharSequence constraint, FilterResults results ) {
// noinspection unchecked
mObjects = (List<T>) results.values;
if ( results.count > 0 ) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
| Java |
package com.aviary.android.feather.widget;
import android.widget.BaseAdapter;
import com.aviary.android.feather.database.DataSetObservableExtended;
import com.aviary.android.feather.database.DataSetObserverExtended;
public abstract class BaseAdapterExtended extends BaseAdapter {
private final DataSetObservableExtended mDataSetObservableExtended = new DataSetObservableExtended();
public void registerDataSetObserverExtended( DataSetObserverExtended observer ) {
mDataSetObservableExtended.registerObserver( observer );
}
public void unregisterDataSetObserverExtended( DataSetObserverExtended observer ) {
mDataSetObservableExtended.unregisterObserver( observer );
}
/**
* Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh
* itself.
*/
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mDataSetObservableExtended.notifyChanged();
}
/**
* Notifies the attached observers that the underlying data is no longer valid or available. Once invoked this adapter is no
* longer valid and should not report further data set changes.
*/
public void notifyDataSetInvalidated() {
super.notifyDataSetInvalidated();
mDataSetObservableExtended.notifyInvalidated();
}
public void notifyDataSetAdded() {
mDataSetObservableExtended.notifyAdded();
}
public void notifyDataSetRemoved() {
mDataSetObservableExtended.notifyRemoved();
}
}
| Java |
/*
* 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.aviary.android.feather.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.ContextMenu.ContextMenuInfo;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Adapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Spinner;
// TODO: Auto-generated Javadoc
/**
* An AdapterView is a view whose children are determined by an {@link Adapter}.
*
* <p>
* See {@link ListView}, {@link GridView}, {@link Spinner} and {@link Gallery} for commonly used subclasses of AdapterView.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>
* For more information about using AdapterView, read the <a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with
* AdapterView</a> developer guide.
* </p>
* </div>
*
* @param <T>
* the generic type
*/
public abstract class AdapterView<T extends Adapter> 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;
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.
*/
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.
*/
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.
*/
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;
/** The m desired focusable in touch mode state. */
private boolean mDesiredFocusableInTouchModeState;
/** The m selection notifier. */
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;
/**
* Instantiates a new adapter view.
*
* @param context
* the context
*/
public AdapterView( Context context ) {
super( context );
}
/**
* Instantiates a new adapter view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public AdapterView( Context context, AttributeSet attrs ) {
super( context, attrs );
}
/**
* Instantiates a new adapter view.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public AdapterView( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
}
/**
* Interface definition for a callback to be invoked when an item in this AdapterView has been clicked.
*
* @see OnItemClickEvent
*/
public interface OnItemClickListener {
/**
* Callback method to be invoked when an item in this AdapterView has been clicked.
* <p>
* Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item.
*
* @param parent
* The AdapterView where the click happened.
* @param view
* The view within the AdapterView that was clicked (this will be a view provided by the adapter)
* @param position
* The position of the view in the adapter.
* @param id
* The row id of the item that was clicked.
*/
void onItemClick( AdapterView<?> parent, View view, int position, long id );
}
/**
* 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;
}
/**
* Gets the on item click 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, 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.
*
* @see OnItemLongClickEvent
*/
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( AdapterView<?> 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;
}
/**
* Gets the on item long click 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.
*
* @see OnItemSelectedEvent
*/
public interface OnItemSelectedListener {
/**
* <p>
* 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.
* </p>
*
* 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( AdapterView<?> 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( AdapterView<?> 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;
}
/**
* Gets the on item selected listener.
*
* @return the on item selected 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 {
/**
* Instantiates a new adapter context menu info.
*
* @param targetView
* the target view
* @param position
* the position
* @param id
* the id
*/
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.
*/
@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.
*/
@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.
*/
@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.
*/
@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.
*/
@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.
*/
@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.
*
*/
@Override
public void removeAllViews() {
throw new UnsupportedOperationException( "removeAllViews() is not supported in AdapterView" );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#onLayout(boolean, int, int, int, int)
*/
@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;
}
/**
* Gets the selected item id.
*
* @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;
}
/**
* Gets the selected view.
*
* @return The view corresponding to the currently selected item, or null if nothing is selected
*/
public abstract View getSelectedView();
/**
* Gets the selected item.
*
* @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;
}
}
/**
* Gets the count.
*
* @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.
*
* @param emptyView
* the new empty view
*/
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;
}
/*
* (non-Javadoc)
*
* @see android.view.View#setFocusable(boolean)
*/
@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() ) );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setFocusableInTouchMode(boolean)
*/
@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() ) );
}
/**
* Check focus.
*/
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).
*
* @param empty
* the empty
*/
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 );
}
/**
* Gets the item id at position.
*
* @param position
* the position
* @return the item id at position
*/
public long getItemIdAtPosition( int position ) {
T adapter = getAdapter();
return ( adapter == null || position < 0 ) ? INVALID_ROW_ID : adapter.getItemId( position );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setOnClickListener(android.view.View.OnClickListener)
*/
@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.
*
* @param container
* the container
*/
@Override
protected void dispatchSaveInstanceState( SparseArray<Parcelable> container ) {
dispatchFreezeSelfOnly( container );
}
/**
* Override to prevent thawing of any views created by the adapter.
*
* @param container
* the container
*/
@Override
protected void dispatchRestoreInstanceState( SparseArray<Parcelable> container ) {
dispatchThawSelfOnly( container );
}
/**
* An asynchronous update interface for receiving notifications about AdapterDataSet information as the AdapterDataSet is
* constructed.
*/
class AdapterDataSetObserver extends DataSetObserver {
/** The m instance state. */
private Parcelable mInstanceState = null;
/*
* (non-Javadoc)
*
* @see android.database.DataSetObserver#onChanged()
*/
@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 ( AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null && mOldItemCount == 0 && mItemCount > 0 ) {
AdapterView.this.onRestoreInstanceState( mInstanceState );
mInstanceState = null;
} else {
rememberSyncState();
}
checkFocus();
requestLayout();
}
/*
* (non-Javadoc)
*
* @see android.database.DataSetObserver#onInvalidated()
*/
@Override
public void onInvalidated() {
mDataChanged = true;
if ( AdapterView.this.getAdapter().hasStableIds() ) {
// Remember the current state for the case where our hosting activity is being
// stopped and later restarted
mInstanceState = AdapterView.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();
}
/**
* This method is called when information about an AdapterDataSet which was previously requested using an asynchronous
* interface becomes available.
*/
public void clearSavedState() {
mInstanceState = null;
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onDetachedFromWindow()
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeCallbacks( mSelectionNotifier );
}
/**
* The Class SelectionNotifier.
*/
private class SelectionNotifier implements Runnable {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
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();
}
}
}
/**
* Selection changed.
*/
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 );
}
}
/**
* Fire on 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 );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
*/
@Override
public boolean dispatchPopulateAccessibilityEvent( AccessibilityEvent event ) {
View selectedView = getSelectedView();
if ( selectedView != null && selectedView.getVisibility() == VISIBLE
&& selectedView.dispatchPopulateAccessibilityEvent( event ) ) {
return true;
}
return false;
}
/**
* Checks if is scrollable for accessibility.
*
* @return true, if is scrollable for accessibility
*/
private boolean isScrollableForAccessibility() {
T adapter = getAdapter();
if ( adapter != null ) {
final int itemCount = adapter.getCount();
return itemCount > 0 && ( getFirstVisiblePosition() > 0 || getLastVisiblePosition() < itemCount - 1 );
}
return false;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#canAnimate()
*/
@Override
protected boolean canAnimate() {
return super.canAnimate() && mItemCount > 0;
}
/**
* Handle data changed.
*/
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();
}
}
/**
* Check selection changed.
*/
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;
}
}
}
}
| Java |
package com.aviary.android.feather.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.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import com.aviary.android.feather.R;
// TODO: Auto-generated Javadoc
/**
* The Class WheelRadio.
*/
public class WheelRadio extends View {
static final String LOG_TAG = "wheel-radio";
Bitmap mIndicatorBig, mIndicatorSmall;
Shader mShader;
Shader mShader1;
Bitmap mIndicator;
Paint mPaint;
DrawFilter mFast;
int mPaddingLeft = 10;
int mPaddingRight = 10;
int mLineTickSize = 1;
int mLineBigSize = 3;
int mSmallTicksCount = 10;
int mBigTicksCount = 1;
float mCorrectionX = 0;
Rect mRealRect;
boolean mForceLayout;
float mValue = 0;
int mValueIndicatorColor, mSmallIndicatorColor, mBigIndicatorColor;
/**
* Instantiates a new wheel radio.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public WheelRadio( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
init( context, attrs, defStyle );
}
/**
* Instantiates a new wheel radio.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public WheelRadio( Context context, AttributeSet attrs ) {
this( context, attrs, -1 );
}
/**
* Instantiates a new wheel radio.
*
* @param context
* the context
*/
public WheelRadio( Context context ) {
this( context, null );
}
/**
* Inits the.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
private void init( Context context, AttributeSet attrs, int defStyle ) {
mFast = new PaintFlagsDrawFilter( Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG, 0 );
mPaint = new Paint( Paint.FILTER_BITMAP_FLAG );
TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.WheelRadio, defStyle, 0 );
mSmallTicksCount = a.getInteger( R.styleable.WheelRadio_smallTicks, 25 ) - 1;
mBigTicksCount = a.getInteger( R.styleable.WheelRadio_bigTicks, 5 ) - 1;
mValueIndicatorColor = a.getColor( R.styleable.WheelRadio_valueIndicatorColor, 0xFF00BBFF );
mSmallIndicatorColor = a.getColor( R.styleable.WheelRadio_smallIndicatorColor, 0x33FFFFFF );
mBigIndicatorColor = a.getColor( R.styleable.WheelRadio_bigIndicatorColor, 0x66FFFFFF );
a.recycle();
}
/**
* Sets the total ticks count.
*
* @param value
* the value
* @param value2
* the value2
*/
public void setTicksNumber( int value, int value2 ) {
mSmallTicksCount = value;
mBigTicksCount = value2;
mForceLayout = true;
requestLayout();
postInvalidate();
}
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
int w = right - left;
if ( w > 0 && changed || mForceLayout ) {
mRealRect = new Rect( mPaddingLeft, top, w - mPaddingRight, bottom );
mIndicatorSmall = makeBitmap2( w / mSmallTicksCount, bottom - top, mLineTickSize );
mShader = new BitmapShader( mIndicatorSmall, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP );
mIndicatorBig = makeBitmap3( mRealRect.width() / mBigTicksCount, bottom - top, mLineBigSize );
mShader1 = new BitmapShader( mIndicatorBig, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP );
mIndicator = makeIndicator( bottom - top, mLineBigSize );
mCorrectionX = ( ( (float) mRealRect.width() / mBigTicksCount ) % 1 ) * mBigTicksCount;
mForceLayout = false;
}
}
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
if ( mShader != null ) {
canvas.setDrawFilter( mFast );
int saveCount = canvas.save();
mPaint.setShader( mShader );
canvas.drawRect( mRealRect, mPaint );
canvas.translate( mPaddingLeft - mLineBigSize / 2, 0 );
mPaint.setShader( mShader1 );
canvas.drawPaint( mPaint );
mPaint.setShader( null );
float rw = ( (float) mRealRect.width() - ( mCorrectionX ) ) / 2;
canvas.drawBitmap( mIndicator, ( rw + ( rw * mValue ) ), 0, mPaint );
canvas.restoreToCount( saveCount );
}
}
/**
* Sets the current value.
*
* @param value
* the new value
*/
public void setValue( float value ) {
mValue = Math.min( Math.max( value, -1 ), 1 );
postInvalidate();
}
/**
* Gets the current value.
*
* @return the value
*/
public float getValue() {
return mValue;
}
/**
* Make small indicator bitmap.
*
* @param width
* the width
* @param height
* the height
* @param line_size
* the line_size
* @return the bitmap
*/
private Bitmap makeBitmap2( int width, int height, int line_size ) {
Bitmap bm = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
Canvas c = new Canvas( bm );
int center_h = height * 2 / 3;
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
p.setDither( true );
p.setColor( mSmallIndicatorColor );
RectF rect = new RectF( 0, height - center_h, line_size, height - ( height - center_h ) );
c.drawRect( rect, p );
return bm;
}
/**
* Make the big indicator bitmap.
*
* @param width
* the width
* @param height
* the height
* @param line_size
* the line_size
* @return the bitmap
*/
private Bitmap makeBitmap3( int width, int height, int line_size ) {
Bitmap bm = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
Canvas c = new Canvas( bm );
int center_h = height * 4 / 5;
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
p.setDither( true );
p.setColor( mBigIndicatorColor );
RectF rect = new RectF( 0, height - center_h, line_size, height - ( height - center_h ) );
c.drawRect( rect, p );
return bm;
}
/**
* Make current value indicator bitmap.
*
* @param height
* the height
* @param line_size
* the line_size
* @return the bitmap
*/
private Bitmap makeIndicator( int height, int line_size ) {
Bitmap bm = Bitmap.createBitmap( line_size, height, Bitmap.Config.ARGB_8888 );
Canvas c = new Canvas( bm );
int center_h = height;
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
p.setDither( true );
p.setColor( mValueIndicatorColor );
RectF rect = new RectF( 0, height - center_h, line_size, height - ( height - center_h ) );
c.drawRect( rect, p );
return bm;
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.easing.Sine;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.DrawFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import com.aviary.android.feather.R;
import com.aviary.android.feather.graphics.LinearGradientDrawable;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
import com.aviary.android.feather.widget.IFlingRunnable.FlingRunnableView;
// TODO: Auto-generated Javadoc
/**
* The Class Wheel.
*/
public class Wheel extends View implements OnGestureListener, FlingRunnableView, VibrationWidget {
/** The Constant LOG_TAG. */
static final String LOG_TAG = "wheel";
/**
* The listener interface for receiving onScroll events. The class that is interested in processing a onScroll event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnScrollListener<code> method. When
* the onScroll event occurs, that object's appropriate
* method is invoked.
*
* @see OnScrollEvent
*/
public interface OnScrollListener {
/**
* On scroll started.
*
* @param view
* the view
* @param value
* the value
* @param roundValue
* the round value
*/
void onScrollStarted( Wheel view, float value, int roundValue );
/**
* On scroll.
*
* @param view
* the view
* @param value
* the value
* @param roundValue
* the round value
*/
void onScroll( Wheel view, float value, int roundValue );
/**
* On scroll finished.
*
* @param view
* the view
* @param value
* the value
* @param roundValue
* the round value
*/
void onScrollFinished( Wheel view, float value, int roundValue );
}
/** The Constant MSG_VIBRATE. */
static final int MSG_VIBRATE = 1;
/** The m padding left. */
int mPaddingLeft = 0;
/** The m padding right. */
int mPaddingRight = 0;
/** The m padding top. */
int mPaddingTop = 0;
/** The m padding bottom. */
int mPaddingBottom = 0;
/** The m height. */
int mWidth, mHeight;
/** The m in layout. */
boolean mInLayout = false;
/** The m min x. */
int mMaxX, mMinX;
/** The m scroll listener. */
OnScrollListener mScrollListener;
/** The m paint. */
Paint mPaint;
/** The m shader3. */
Shader mShader3;
/** The m tick bitmap. */
Bitmap mTickBitmap;
/** The m indicator. */
Bitmap mIndicator;
/** The m df. */
DrawFilter mFast, mDF;
/** The m gesture detector. */
GestureDetector mGestureDetector;
/** The m is first scroll. */
boolean mIsFirstScroll;
/** The m fling runnable. */
IFlingRunnable mFlingRunnable;
/** The m animation duration. */
int mAnimationDuration = 200;
/** The m to left. */
boolean mToLeft;
/** The m touch slop. */
int mTouchSlop;
/** The m indicator x. */
float mIndicatorX = 0;
/** The m original x. */
int mOriginalX = 0;
/** The m original delta x. */
int mOriginalDeltaX = 0;
/** The m tick space. */
float mTickSpace = 30;
/** The m wheel size factor. */
int mWheelSizeFactor = 2;
/** The m ticks count. */
int mTicksCount = 18;
/** The m ticks size. */
float mTicksSize = 7.0f;
/** The m vibrator. */
Vibrator mVibrator;
/** The m vibration handler. */
static Handler mVibrationHandler;
/**
* Instantiates a new wheel.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public Wheel( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
init( context, attrs, defStyle );
}
/**
* Instantiates a new wheel.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public Wheel( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
/**
* Instantiates a new wheel.
*
* @param context
* the context
*/
public Wheel( Context context ) {
this( context, null );
}
/**
* Sets the on scroll listener.
*
* @param listener
* the new on scroll listener
*/
public void setOnScrollListener( OnScrollListener listener ) {
mScrollListener = listener;
}
/*
* (non-Javadoc)
*
* @see android.view.View#setPadding(int, int, int, int)
*/
@Override
public void setPadding( int left, int top, int right, int bottom ) {
super.setPadding( left, top, right, bottom );
// mPaddingLeft = left;
// mPaddingBottom = bottom;
// mPaddingTop = top;
// mPaddingRight = right;
}
/**
* Inits the.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
private void init( Context context, AttributeSet attrs, int defStyle ) {
if ( android.os.Build.VERSION.SDK_INT > 8 ) {
try {
mFlingRunnable = (IFlingRunnable) ReflectionUtils.newInstance( "com.aviary.android.feather.widget.Fling9Runnable",
new Class<?>[] { FlingRunnableView.class, int.class }, this, mAnimationDuration );
} catch ( ReflectionException e ) {
mFlingRunnable = new Fling8Runnable( this, mAnimationDuration );
}
} else {
mFlingRunnable = new Fling8Runnable( this, mAnimationDuration );
}
TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.Wheel, defStyle, 0 );
mTicksCount = a.getInteger( R.styleable.Wheel_ticks, 18 );
mWheelSizeFactor = a.getInteger( R.styleable.Wheel_numRotations, 2 );
a.recycle();
mFast = new PaintFlagsDrawFilter( Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG, 0 );
mPaint = new Paint( Paint.FILTER_BITMAP_FLAG );
mGestureDetector = new GestureDetector( context, this );
mGestureDetector.setIsLongpressEnabled( false );
setFocusable( true );
setFocusableInTouchMode( true );
mTouchSlop = ViewConfiguration.get( context ).getScaledTouchSlop();
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
TypedValue.complexToDimensionPixelSize( 25, metrics );
try {
mVibrator = (Vibrator) context.getSystemService( Context.VIBRATOR_SERVICE );
} catch ( Exception e ) {
Log.e( LOG_TAG, e.toString() );
}
if ( mVibrator != null ) {
setVibrationEnabled( true );
}
int[] colors = { 0xffa1a1a1, 0xffa1a1a1, 0xffffffff, 0xffa1a1a1, 0xffa1a1a1 };
float[] positions = { 0, 0.2f, 0.5f, 0.8f, 1f };
setBackgroundDrawable( new LinearGradientDrawable( Orientation.LEFT_RIGHT, colors, positions ) );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setBackgroundColor(int)
*/
@Override
public void setBackgroundColor( int color ) {
super.setBackgroundColor( color );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setBackgroundDrawable(android.graphics.drawable.Drawable)
*/
@Override
public void setBackgroundDrawable( Drawable d ) {
super.setBackgroundDrawable( d );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setBackgroundResource(int)
*/
@Override
public void setBackgroundResource( int resid ) {
super.setBackgroundResource( resid );
}
/**
* Make bitmap3.
*
* @param width
* the width
* @param height
* the height
* @return the bitmap
*/
private static Bitmap makeBitmap3( int width, int height ) {
Bitmap bm = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
Canvas c = new Canvas( bm );
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
int colors[] = { 0xdd000000, 0x00000000, 0x00000000, 0xdd000000 };
float positions[] = { 0f, 0.2f, 0.8f, 1f };
LinearGradient gradient = new LinearGradient( 0, 0, width, 0, colors, positions, TileMode.REPEAT );
p.setShader( gradient );
p.setDither( true );
c.drawRect( 0, 0, width, height, p );
return bm;
}
/**
* Make ticker bitmap.
*
* @param width
* the width
* @param height
* the height
* @return the bitmap
*/
private static Bitmap makeTickerBitmap( int width, int height ) {
float ellipse = width / 2;
Bitmap bm = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
Canvas c = new Canvas( bm );
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
p.setDither( true );
p.setColor( 0xFF888888 );
float h = (float)height;
float y = (h+10.0f)/10.0f;
float y2 = y*2.5f;
RectF rect = new RectF( 0, y, width, height - y2 );
c.drawRoundRect( rect, ellipse, ellipse, p );
p.setColor( 0xFFFFFFFF );
rect = new RectF( 0, y2, width, height - y );
c.drawRoundRect( rect, ellipse, ellipse, p );
p.setColor( 0xFFCCCCCC );
rect = new RectF( 0, y+2, width, height - (y+2) );
c.drawRoundRect( rect, ellipse, ellipse, p );
return bm;
}
/**
* Make bitmap indicator.
*
* @param width
* the width
* @param height
* the height
* @return the bitmap
*/
private static Bitmap makeBitmapIndicator( int width, int height ) {
float ellipse = width / 2;
float h = (float)height;
float y = (h+10.0f)/10.0f;
float y2 = y*2.5f;
Bitmap bm = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
Canvas c = new Canvas( bm );
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
p.setDither( true );
p.setColor( 0xFF666666 );
RectF rect = new RectF( 0, y, width, height - y2 );
c.drawRoundRect( rect, ellipse, ellipse, p );
p.setColor( 0xFFFFFFFF );
rect = new RectF( 0, y2, width, height - y );
c.drawRoundRect( rect, ellipse, ellipse, p );
rect = new RectF( 0, y+2, width, height - (y+2) );
int colors[] = { 0xFF0076E7, 0xFF00BBFF, 0xFF0076E7 };
float positions[] = { 0f, 0.5f, 1f };
LinearGradient gradient = new LinearGradient( 0, 0, width, 0, colors, positions, TileMode.REPEAT );
p.setShader( gradient );
c.drawRoundRect( rect, ellipse, ellipse, p );
return bm;
}
/** The m ticks easing. */
Easing mTicksEasing = new Sine();
/** The m draw matrix. */
Matrix mDrawMatrix = new Matrix();
/*
* (non-Javadoc)
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
if ( mShader3 != null ) {
canvas.setDrawFilter( mDF );
final int w = mWidth;
int total = mTicksCount;
float x2;
float scale, scale2;
mPaint.setShader( null );
for ( int i = 0; i < total; i++ ) {
float x = ( mOriginalDeltaX + ( ( (float) i / total ) * w ) );
if ( x < 0 ) {
x = w - ( -x % w );
} else {
x = x % w;
}
scale = (float) mTicksEasing.easeInOut( x, 0, 1.0, mWidth );
scale2 = (float) ( Math.sin( Math.PI * ( x / mWidth ) ) );
mDrawMatrix.reset();
mDrawMatrix.setScale( scale2, 1 );
mDrawMatrix.postTranslate( (int) ( scale * mWidth ) - ( mTicksSize / 2 ), 0 );
canvas.drawBitmap( mTickBitmap, mDrawMatrix, mPaint );
}
float indicatorx = ( mIndicatorX + mOriginalDeltaX );
if ( indicatorx < 0 ) {
indicatorx = ( mWidth * 2 ) - ( -indicatorx % ( mWidth * 2 ) );
} else {
indicatorx = indicatorx % ( mWidth * 2 );
}
if ( indicatorx > 0 && indicatorx < mWidth ) {
x2 = (float) mTicksEasing.easeInOut( indicatorx, 0, mWidth, w );
scale2 = (float) ( Math.sin( Math.PI * ( indicatorx / mWidth ) ) );
mDrawMatrix.reset();
mDrawMatrix.setScale( scale2, 1 );
mDrawMatrix.postTranslate( x2 - ( mTicksSize / 2 ), 0 );
canvas.drawBitmap( mIndicator, mDrawMatrix, mPaint );
}
mPaint.setShader( mShader3 );
canvas.drawPaint( mPaint );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onDetachedFromWindow()
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// if ( mVibrationHandlerThread != null ) {
// mVibrationHandlerThread.quit();
// }
}
/** The m force layout. */
boolean mForceLayout;
/**
* Sets the wheel scale factor.
*
* @param value
* the new wheel scale factor
*/
public void setWheelScaleFactor( int value ) {
mWheelSizeFactor = value;
mForceLayout = true;
requestLayout();
postInvalidate();
}
@Override
public synchronized void setVibrationEnabled( boolean value ) {
if ( !value ) {
mVibrationHandler = null;
} else {
if ( null == mVibrationHandler ) {
mVibrationHandler = new Handler() {
@Override
public void handleMessage( Message msg ) {
super.handleMessage( msg );
switch ( msg.what ) {
case MSG_VIBRATE:
try {
mVibrator.vibrate( 10 );
} catch ( SecurityException e ) {
// missing VIBRATE permission
}
}
}
};
}
}
}
@Override
public synchronized boolean getVibrationEnabled() {
return mVibrationHandler != null;
}
/**
* Gets the wheel scale factor.
*
* @return the wheel scale factor
*/
public int getWheelScaleFactor() {
return mWheelSizeFactor;
}
/**
* Gets the tick space.
*
* @return the tick space
*/
public float getTickSpace() {
return mTickSpace;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
mInLayout = true;
if ( changed || mForceLayout ) {
mWidth = right - left;
mHeight = bottom - top;
mTickSpace = (float) mWidth / mTicksCount;
mTicksSize = mWidth / mTicksCount / 4.0f;
mTicksSize = Math.min( Math.max( mTicksSize, 3.5f ), 6.0f );
mIndicatorX = (float) mWidth / 2.0f;
mOriginalX = (int) mIndicatorX;
mMaxX = mWidth * mWheelSizeFactor;
mIndicator = makeBitmapIndicator( (int) Math.ceil( mTicksSize ), bottom - top );
mTickBitmap = makeTickerBitmap( (int) Math.ceil( mTicksSize ), bottom - top );
mShader3 = new BitmapShader( makeBitmap3( right - left, bottom - top ), Shader.TileMode.CLAMP, Shader.TileMode.REPEAT );
mMinX = -mMaxX;
}
mInLayout = false;
mForceLayout = false;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown( MotionEvent event ) {
mDF = mFast;
mFlingRunnable.stop( false );
mIsFirstScroll = true;
return true;
}
/**
* On up.
*/
void onUp() {
if ( mFlingRunnable.isFinished() ) {
scrollIntoSlots();
}
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling( MotionEvent event0, MotionEvent event1, float velocityX, float velocityY ) {
boolean toleft = velocityX < 0;
if ( !toleft ) {
if ( mOriginalDeltaX > mMaxX ) {
mFlingRunnable.startUsingDistance( mOriginalDeltaX, mMaxX - mOriginalDeltaX );
return true;
}
} else {
if ( mOriginalDeltaX < mMinX ) {
mFlingRunnable.startUsingDistance( mOriginalDeltaX, mMinX - mOriginalDeltaX );
return true;
}
}
mFlingRunnable.startUsingVelocity( mOriginalDeltaX, (int) velocityX / 2 );
return true;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress( MotionEvent arg0 ) {}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll( MotionEvent event0, MotionEvent event1, float distanceX, float distanceY ) {
getParent().requestDisallowInterceptTouchEvent( true );
if ( mIsFirstScroll ) {
if ( distanceX > 0 )
distanceX -= mTouchSlop;
else
distanceX += mTouchSlop;
scrollStarted();
}
mIsFirstScroll = false;
float delta = -1 * distanceX;
mToLeft = delta < 0;
if ( !mToLeft ) {
if ( mOriginalDeltaX + delta > mMaxX ) {
delta /= ( ( (float) mOriginalDeltaX + delta ) - mMaxX ) / 10;
}
} else {
if ( mOriginalDeltaX + delta < mMinX ) {
delta /= -( ( (float) mOriginalDeltaX + delta ) - mMinX ) / 10;
}
}
trackMotionScroll( (int) ( mOriginalDeltaX + delta ) );
return true;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress( MotionEvent arg0 ) {}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp( MotionEvent arg0 ) {
return false;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
boolean retValue = mGestureDetector.onTouchEvent( event );
int action = event.getAction();
if ( action == MotionEvent.ACTION_UP ) {
mDF = null;
onUp();
} else if ( action == MotionEvent.ACTION_CANCEL ) {}
return retValue;
}
/** The m last motion value. */
float mLastMotionValue;
@Override
public void trackMotionScroll( int newX ) {
mOriginalDeltaX = newX;
scrollRunning();
invalidate();
}
/**
* Gets the limited motion scroll amount.
*
* @param motionToLeft
* the motion to left
* @param deltaX
* the delta x
* @return the limited motion scroll amount
*/
int getLimitedMotionScrollAmount( boolean motionToLeft, int deltaX ) {
if ( motionToLeft ) {} else {
if ( mMaxX >= mOriginalDeltaX ) {
// The extreme child is past his boundary point!
return deltaX;
}
}
int centerDifference = mOriginalDeltaX - mMaxX;
return motionToLeft ? Math.max( centerDifference, deltaX ) : Math.min( centerDifference, deltaX );
}
@Override
public void scrollIntoSlots() {
if ( !mFlingRunnable.isFinished() ) {
return;
}
if ( mOriginalDeltaX > mMaxX ) {
mFlingRunnable.startUsingDistance( mOriginalDeltaX, mMaxX - mOriginalDeltaX );
return;
} else if ( mOriginalDeltaX < mMinX ) {
mFlingRunnable.startUsingDistance( mOriginalDeltaX, mMinX - mOriginalDeltaX );
return;
}
int diff = Math.round( mOriginalDeltaX % mTickSpace );
int diff2 = (int) ( mTickSpace - diff );
int diff3 = (int) ( mTickSpace + diff );
if ( diff != 0 && diff2 != 0 && diff3 != 0 ) {
if ( Math.abs( diff ) < ( mTickSpace / 2 ) ) {
mFlingRunnable.startUsingDistance( mOriginalDeltaX, -diff );
} else {
mFlingRunnable.startUsingDistance( mOriginalDeltaX, (int) ( mToLeft ? -diff3 : diff2 ) );
}
} else {
onFinishedMovement();
}
}
/**
* On finished movement.
*/
private void onFinishedMovement() {
scrollCompleted();
}
/**
* Gets the real width.
*
* @return the real width
*/
private int getRealWidth() {
return ( getWidth() - mPaddingLeft - mPaddingRight );
}
/** The m scroll selection notifier. */
ScrollSelectionNotifier mScrollSelectionNotifier;
/**
* The Class ScrollSelectionNotifier.
*/
private class ScrollSelectionNotifier implements Runnable {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if ( mShader3 == null ) {
post( this );
} else {
fireOnScrollCompleted();
}
}
}
/**
* Scroll completed.
*/
void scrollCompleted() {
if ( mScrollListener != null ) {
if ( mInLayout ) {
if ( mScrollSelectionNotifier == null ) {
mScrollSelectionNotifier = new ScrollSelectionNotifier();
}
post( mScrollSelectionNotifier );
} else {
fireOnScrollCompleted();
}
}
}
/**
* Scroll started.
*/
void scrollStarted() {
if ( mScrollListener != null ) {
if ( mInLayout ) {
if ( mScrollSelectionNotifier == null ) {
mScrollSelectionNotifier = new ScrollSelectionNotifier();
}
post( mScrollSelectionNotifier );
} else {
fireOnScrollStarted();
}
}
}
/**
* Scroll running.
*/
void scrollRunning() {
if ( mScrollListener != null ) {
if ( mInLayout ) {
if ( mScrollSelectionNotifier == null ) {
mScrollSelectionNotifier = new ScrollSelectionNotifier();
}
post( mScrollSelectionNotifier );
} else {
fireOnScrollRunning();
}
}
}
/**
* Gets the value.
*
* @return the value
*/
public float getValue() {
int w = getRealWidth();
int position = mOriginalDeltaX;
float value = (float) position / ( w * mWheelSizeFactor );
return value;
}
/**
* Gets the tick value.
*
* @return the tick value
*/
int getTickValue() {
return (int) ( ( getCurrentPage() * mTicksCount ) + ( mOriginalDeltaX % mWidth ) / mTickSpace );
}
/**
* Return the total number of ticks available for scrolling.
*
* @return the ticks count
*/
public int getTicksCount() {
try {
return (int) ( ( ( mMaxX / mWidth ) * mTicksCount ) + ( mOriginalDeltaX % mWidth ) / mTickSpace ) * 2;
} catch ( ArithmeticException e ) {
return 0;
}
}
/**
* Gets the ticks.
*
* @return the ticks
*/
public int getTicks() {
return mTicksCount;
}
/**
* Gets the current page.
*
* @return the current page
*/
int getCurrentPage() {
return ( mOriginalDeltaX / mWidth );
}
/**
* Fire on scroll completed.
*/
private void fireOnScrollCompleted() {
mScrollListener.onScrollFinished( this, getValue(), getTickValue() );
}
/**
* Fire on scroll started.
*/
private void fireOnScrollStarted() {
mScrollListener.onScrollStarted( this, getValue(), getTickValue() );
}
/**
* Fire on scroll running.
*/
private void fireOnScrollRunning() {
int value = getTickValue();
if ( value != mLastMotionValue ) {
if ( mVibrationHandler != null ) {
mVibrationHandler.sendEmptyMessage( MSG_VIBRATE );
}
}
mScrollListener.onScroll( this, getValue(), value );
mLastMotionValue = value;
}
@Override
public int getMinX() {
return mMinX;
}
@Override
public int getMaxX() {
return mMaxX;
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.utils.TypefaceUtils;
public class TextViewCustomFont extends TextView {
@SuppressWarnings("unused")
private final String LOG_TAG = "TextViewCustomFont";
public TextViewCustomFont( Context context ) {
super( context );
}
public TextViewCustomFont( Context context, AttributeSet attrs ) {
super( context, attrs );
setCustomFont( context, attrs );
}
public TextViewCustomFont( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
setCustomFont( context, attrs );
}
private void setCustomFont( Context ctx, AttributeSet attrs ) {
TypedArray array = ctx.obtainStyledAttributes( attrs, R.styleable.TextViewCustomFont );
String font = array.getString( R.styleable.TextViewCustomFont_font );
setCustomFont( font );
array.recycle();
}
protected void setCustomFont( String fontname ) {
if ( null != fontname ) {
try {
Typeface font = TypefaceUtils.createFromAsset( getContext().getAssets(), fontname );
setTypeface( font );
} catch ( Throwable t ) {}
}
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.ViewSwitcher.ViewFactory;
import com.aviary.android.feather.R;
// TODO: Auto-generated Javadoc
/**
* The Class ToolbarView.
*/
public class ToolbarView extends ViewFlipper implements ViewFactory {
/**
* The listener interface for receiving onToolbarClick events. The class that is interested in processing a onToolbarClick event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnToolbarClickListener<code> method. When
* the onToolbarClick event occurs, that object's appropriate
* method is invoked.
*
* @see OnToolbarClickEvent
*/
public static interface OnToolbarClickListener {
/**
* On save click.
*/
void onSaveClick();
/**
* On apply click.
*/
void onApplyClick();
/**
* On cancel click.
*/
void onCancelClick();
};
/**
* The Enum STATE.
*/
public static enum STATE {
/** The STAT e_ save. */
STATE_SAVE,
/** The STAT e_ apply. */
STATE_APPLY,
};
/** The m apply button. */
private Button mApplyButton;
/** The m save button. */
private Button mSaveButton;
/** The m title text. */
private TextSwitcher mTitleText;
/** The m aviary logo. */
private TextView mAviaryLogo;
/** The is animating. */
@SuppressWarnings("unused")
private boolean isAnimating;
/** The m current state. */
private STATE mCurrentState;
/** The m out animation. */
private Animation mOutAnimation;
/** The m in animation. */
private Animation mInAnimation;
/** The m listener. */
private OnToolbarClickListener mListener;
/** The m clickable. */
private boolean mClickable;
/** The Constant MSG_SHOW_CHILD. */
private static final int MSG_SHOW_CHILD = 1;
/** The m handler. */
private Handler mHandler = new Handler() {
@Override
public void handleMessage( android.os.Message msg ) {
switch ( msg.what ) {
case MSG_SHOW_CHILD:
setDisplayedChild( msg.arg1 );
break;
}
};
};
/**
* Instantiates a new toolbar view.
*
* @param context
* the context
*/
public ToolbarView( Context context ) {
super( context );
init( context, null );
}
/**
* Instantiates a new toolbar view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public ToolbarView( Context context, AttributeSet attrs ) {
super( context, attrs );
init( context, attrs );
}
/**
* Inits the.
*
* @param context
* the context
* @param attrs
* the attrs
*/
private void init( Context context, AttributeSet attrs ) {
mCurrentState = STATE.STATE_SAVE;
setAnimationCacheEnabled( true );
setAlwaysDrawnWithCacheEnabled( true );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setClickable(boolean)
*/
@Override
public void setClickable( boolean clickable ) {
mClickable = clickable;
}
/*
* (non-Javadoc)
*
* @see android.view.View#isClickable()
*/
@Override
public boolean isClickable() {
return mClickable;
}
/**
* Gets the in animation time.
*
* @return the in animation time
*/
public long getInAnimationTime() {
return mInAnimation.getDuration() + mInAnimation.getStartOffset();
}
/**
* Gets the out animation time.
*
* @return the out animation time
*/
public long getOutAnimationTime() {
return mOutAnimation.getDuration() + mOutAnimation.getStartOffset();
}
/*
* (non-Javadoc)
*
* @see android.view.View#onFinishInflate()
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mApplyButton = (Button) findViewById( R.id.toolbar_content_panel ).findViewById( R.id.button_apply );
mSaveButton = (Button) findViewById( R.id.toolbar_main_panel ).findViewById( R.id.button_save );
mTitleText = (TextSwitcher) findViewById( R.id.toolbar_title );
mTitleText.setFactory( this );
mAviaryLogo = (TextView) findViewById( R.id.aviary_logo );
mInAnimation = AnimationUtils.loadAnimation( getContext(), R.anim.feather_push_up_in );
mInAnimation.setStartOffset( 100 );
mOutAnimation = AnimationUtils.loadAnimation( getContext(), R.anim.feather_push_up_out );
mOutAnimation.setStartOffset( 100 );
mOutAnimation.setAnimationListener( mInAnimationListener );
mInAnimation.setAnimationListener( mInAnimationListener );
setInAnimation( mInAnimation );
setOutAnimation( mOutAnimation );
mApplyButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
if ( mListener != null && mCurrentState == STATE.STATE_APPLY && isClickable() ) mListener.onApplyClick();
}
} );
mSaveButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
if ( mListener != null && mCurrentState == STATE.STATE_SAVE && isClickable() ) mListener.onSaveClick();
}
} );
}
/**
* Change the current toolbar state creating an animation between the current and the new view state.
*
* @param state
* the state
* @param showMiddle
* the show middle
*/
public void setState( STATE state, final boolean showMiddle ) {
if ( state != mCurrentState ) {
mCurrentState = state;
post( new Runnable() {
@Override
public void run() {
switch ( mCurrentState ) {
case STATE_APPLY:
showApplyState();
break;
case STATE_SAVE:
showSaveState( showMiddle );
break;
}
}
} );
}
}
/**
* Return the current toolbar state.
*
* @return the state
* @see #STATE
*/
public STATE getState() {
return mCurrentState;
}
/**
* Set the toolbar click listener.
*
* @param listener
* the new on toolbar click listener
* @see OnToolbarClickListener
*/
public void setOnToolbarClickListener( OnToolbarClickListener listener ) {
mListener = listener;
}
/**
* Sets the apply enabled.
*
* @param value
* the new apply enabled
*/
public void setApplyEnabled( boolean value ) {
mApplyButton.setEnabled( value );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setSaveEnabled(boolean)
*/
@Override
public void setSaveEnabled( boolean value ) {
mSaveButton.setEnabled( value );
}
/**
* Sets the title.
*
* @param value
* the new title
*/
public void setTitle( CharSequence value ) {
mTitleText.setText( value );
}
public void setTitle( CharSequence value, boolean animate ) {
if( !animate ){
Animation inAnimation = mTitleText.getInAnimation();
Animation outAnimation = mTitleText.getOutAnimation();
mTitleText.setInAnimation( null );
mTitleText.setOutAnimation( null );
mTitleText.setText( value );
mTitleText.setInAnimation( inAnimation );
mTitleText.setOutAnimation( outAnimation );
} else {
setTitle( value );
}
}
/**
* Sets the title.
*
* @param resourceId
* the new title
*/
public void setTitle( int resourceId ) {
setTitle( getContext().getString( resourceId ) );
}
public void setTitle( int resourceId, boolean animate ) {
setTitle( getContext().getString( resourceId ), animate );
}
/**
* Show apply state.
*/
private void showApplyState() {
setDisplayedChild( getChildCount() - 1 );
}
/**
* Show save state.
*
* @param showMiddle
* the show middle
*/
private void showSaveState( boolean showMiddle ) {
if ( showMiddle && getChildCount() == 3 )
setDisplayedChild( 1 );
else
setDisplayedChild( 0 );
}
/**
* Enable children cache.
*/
@SuppressWarnings("unused")
private void enableChildrenCache() {
setChildrenDrawnWithCacheEnabled( true );
setChildrenDrawingCacheEnabled( true );
for ( int i = 0; i < getChildCount(); i++ ) {
final View child = getChildAt( i );
child.setDrawingCacheEnabled( true );
child.buildDrawingCache( true );
}
}
/**
* Clear children cache.
*/
@SuppressWarnings("unused")
private void clearChildrenCache() {
setChildrenDrawnWithCacheEnabled( false );
}
/**
* Sets the apply enabled.
*
* @param applyEnabled
* the apply enabled
* @param cancelEnabled
* the cancel enabled
*/
public void setApplyEnabled( boolean applyEnabled, boolean cancelEnabled ) {
mApplyButton.setEnabled( applyEnabled );
}
/** The m in animation listener. */
AnimationListener mInAnimationListener = new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
isAnimating = true;
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
isAnimating = false;
if ( getDisplayedChild() == 1 && getChildCount() > 2 ) {
Thread t = new Thread( new Runnable() {
@Override
public void run() {
try {
Thread.sleep( 300 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
Message msg = mHandler.obtainMessage( MSG_SHOW_CHILD );
msg.arg1 = 0;
mHandler.sendMessage( msg );
}
} );
t.start();
}
}
};
/*
* (non-Javadoc)
*
* @see android.widget.ViewSwitcher.ViewFactory#makeView()
*/
@Override
public View makeView() {
View text = LayoutInflater.from( getContext() ).inflate( R.layout.feather_toolbar_title_text, null );
return text;
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.easing.Quad;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
// TODO: Auto-generated Javadoc
/**
* The Class HighlightView.
*/
public class HighlightView {
/** The Constant LOG_TAG. */
@SuppressWarnings("unused")
private static final String LOG_TAG = "hv";
/** The Constant GROW_NONE. */
static final int GROW_NONE = 1 << 0;
/** The Constant GROW_LEFT_EDGE. */
static final int GROW_LEFT_EDGE = 1 << 1;
/** The Constant GROW_RIGHT_EDGE. */
static final int GROW_RIGHT_EDGE = 1 << 2;
/** The Constant GROW_TOP_EDGE. */
static final int GROW_TOP_EDGE = 1 << 3;
/** The Constant GROW_BOTTOM_EDGE. */
static final int GROW_BOTTOM_EDGE = 1 << 4;
/** The Constant MOVE. */
static final int MOVE = 1 << 5;
/** The m hidden. */
private boolean mHidden;
/** The m context. */
private View mContext;
private static Handler mHandler = new Handler();
/**
* The Enum Mode.
*/
enum Mode {
/** The None. */
None,
/** The Move. */
Move,
/** The Grow. */
Grow
}
/** The m min size. */
private int mMinSize = 20;
/** The m mode. */
private Mode mMode;
/** The draw rect. */
private Rect mDrawRect = new Rect();
/** The image rect. */
private RectF mImageRect;
/** The crop rect. */
private RectF mCropRect;
private Matrix mMatrix;
/** The m maintain aspect ratio. */
private boolean mMaintainAspectRatio = false;
/** The m initial aspect ratio. */
private double mInitialAspectRatio;
/** The handle knob drawable. */
private Drawable mResizeDrawable;
private final Paint mOutlinePaint = new Paint();
private final Paint mOutlinePaint2 = new Paint();
private final Paint mOutlineFill = new Paint();
private Paint mLinesPaintShadow = new Paint();
/** The highlight_color. */
private int highlight_color;
/** The highlight_down_color. */
private int highlight_down_color;
/** The highlight_outside_color. */
private int highlight_outside_color;
/** The highlight_outside_color_down. */
private int highlight_outside_color_down;
/** The internal_stroke_width. */
private int stroke_width, internal_stroke_width;
/** internal grid colors */
private int highlight_internal_color, highlight_internal_color_down;
/** The d height. */
private int dWidth, dHeight;
final int grid_rows = 3;
final int grid_cols = 3;
/**
* Instantiates a new highlight view.
*
* @param ctx
* the ctx
*/
public HighlightView( View ctx ) {
mContext = ctx;
highlight_color = mContext.getResources().getColor( R.color.feather_crop_highlight );
highlight_down_color = mContext.getResources().getColor( R.color.feather_crop_highlight_down );
highlight_outside_color = mContext.getResources().getColor( R.color.feather_crop_highlight_outside );
highlight_outside_color_down = mContext.getResources().getColor( R.color.feather_crop_highlight_outside_down );
stroke_width = mContext.getResources().getInteger( R.integer.feather_crop_highlight_stroke_width );
internal_stroke_width = mContext.getResources().getInteger( R.integer.feather_crop_highlight_internal_stroke_width );
highlight_internal_color = mContext.getResources().getColor( R.color.feather_crop_highlight_internal );
highlight_internal_color_down = mContext.getResources().getColor( R.color.feather_crop_highlight_internal_down );
}
/**
* Inits the.
*/
private void init() {
android.content.res.Resources resources = mContext.getResources();
mResizeDrawable = resources.getDrawable( R.drawable.feather_highlight_crop_handle );
double w = mResizeDrawable.getIntrinsicWidth();
double h = mResizeDrawable.getIntrinsicHeight();
dWidth = (int) Math.ceil( w / 2.0 );
dHeight = (int) Math.ceil( h / 2.0 );
}
/**
* Dispose.
*/
public void dispose() {
mContext = null;
}
/**
* Sets the min size.
*
* @param value
* the new min size
*/
public void setMinSize( int value ) {
mMinSize = value;
}
/**
* Sets the hidden.
*
* @param hidden
* the new hidden
*/
public void setHidden( boolean hidden ) {
mHidden = hidden;
}
/** The m view drawing rect. */
private Rect mViewDrawingRect = new Rect();
/** The m path. */
private Path mPath = new Path();
/** The m lines path. */
private Path mLinesPath = new Path();
/** The m inverse path. */
private Path mInversePath = new Path();
private RectF tmpRect2 = new RectF();
private Rect tmpRect4 = new Rect();
private RectF tmpDrawRect2F = new RectF();
private RectF tmpDrawRectF = new RectF();
private RectF tmpDisplayRectF = new RectF();
private Rect tmpRectMotion = new Rect();
private RectF tmpRectMotionF = new RectF();
private RectF tempLayoutRectF = new RectF();
/**
* Draw.
*
* @param canvas
* the canvas
*/
protected void draw( Canvas canvas ) {
if ( mHidden ) return;
// canvas.save();
mPath.reset();
mInversePath.reset();
mLinesPath.reset();
mContext.getDrawingRect( mViewDrawingRect );
tmpDrawRectF.set( mDrawRect );
tmpDrawRect2F.set( mViewDrawingRect );
mInversePath.addRect( tmpDrawRect2F, Path.Direction.CW );
mInversePath.addRect( tmpDrawRectF, Path.Direction.CCW );
tmpDrawRectF.set( mDrawRect );
mPath.addRect( tmpDrawRectF, Path.Direction.CW );
tmpDrawRect2F.set( mDrawRect );
mLinesPath.addRect( tmpDrawRect2F, Path.Direction.CW );
float colStep = (float) mDrawRect.height() / grid_cols;
float rowStep = (float) mDrawRect.width() / grid_rows;
for ( int i = 1; i < grid_cols; i++ ) {
mLinesPath.moveTo( (int) mDrawRect.left, (int) ( mDrawRect.top + colStep * i ) );
mLinesPath.lineTo( (int) mDrawRect.right, (int) ( mDrawRect.top + colStep * i ) );
}
for ( int i = 1; i < grid_rows; i++ ) {
mLinesPath.moveTo( (int) ( mDrawRect.left + rowStep * i ), (int) mDrawRect.top );
mLinesPath.lineTo( (int) ( mDrawRect.left + rowStep * i ), (int) mDrawRect.bottom );
}
// canvas.restore();
canvas.drawPath( mInversePath, mOutlineFill );
// canvas.drawPath( mLinesPath, mLinesPaintShadow );
canvas.drawPath( mLinesPath, mOutlinePaint2 );
canvas.drawPath( mPath, mOutlinePaint );
if ( true /* || mMode == Mode.Grow */) {
int left = mDrawRect.left + 1;
int right = mDrawRect.right + 1;
int top = mDrawRect.top + 4;
int bottom = mDrawRect.bottom + 3;
if ( mResizeDrawable != null ) {
mResizeDrawable.setBounds( left - dWidth, top - dHeight, left + dWidth, top + dHeight );
mResizeDrawable.draw( canvas );
mResizeDrawable.setBounds( right - dWidth, top - dHeight, right + dWidth, top + dHeight );
mResizeDrawable.draw( canvas );
mResizeDrawable.setBounds( left - dWidth, bottom - dHeight, left + dWidth, bottom + dHeight );
mResizeDrawable.draw( canvas );
mResizeDrawable.setBounds( right - dWidth, bottom - dHeight, right + dWidth, bottom + dHeight );
mResizeDrawable.draw( canvas );
}
}
}
/**
* Sets the mode.
*
* @param mode
* the new mode
*/
public void setMode( Mode mode ) {
if ( mode != mMode ) {
mMode = mode;
mOutlinePaint.setColor( mMode == Mode.None ? highlight_color : highlight_down_color );
mOutlinePaint2.setColor( mMode == Mode.None ? highlight_internal_color : highlight_internal_color_down );
mLinesPaintShadow.setAlpha( mMode == Mode.None ? 102 : 0 );
mOutlineFill.setColor( mMode == Mode.None ? highlight_outside_color : highlight_outside_color_down );
mContext.invalidate();
}
}
/** The hysteresis. */
final float hysteresis = 30F;
/**
* Gets the hit.
*
* @param x
* the x
* @param y
* the y
* @return the hit
*/
public int getHit( float x, float y ) {
Rect r = new Rect();
computeLayout( false, r );
int retval = GROW_NONE;
boolean verticalCheck = ( y >= r.top - hysteresis ) && ( y < r.bottom + hysteresis );
boolean horizCheck = ( x >= r.left - hysteresis ) && ( x < r.right + hysteresis );
if ( ( Math.abs( r.left - x ) < hysteresis ) && verticalCheck ) retval |= GROW_LEFT_EDGE;
if ( ( Math.abs( r.right - x ) < hysteresis ) && verticalCheck ) retval |= GROW_RIGHT_EDGE;
if ( ( Math.abs( r.top - y ) < hysteresis ) && horizCheck ) retval |= GROW_TOP_EDGE;
if ( ( Math.abs( r.bottom - y ) < hysteresis ) && horizCheck ) retval |= GROW_BOTTOM_EDGE;
if ( retval == GROW_NONE && r.contains( (int) x, (int) y ) ) retval = MOVE;
return retval;
}
boolean isLeftEdge( int edge ) {
return ( GROW_LEFT_EDGE & edge ) == GROW_LEFT_EDGE;
}
boolean isRightEdge( int edge ) {
return ( GROW_RIGHT_EDGE & edge ) == GROW_RIGHT_EDGE;
}
boolean isTopEdge( int edge ) {
return ( GROW_TOP_EDGE & edge ) == GROW_TOP_EDGE;
}
boolean isBottomEdge( int edge ) {
return ( GROW_BOTTOM_EDGE & edge ) == GROW_BOTTOM_EDGE;
}
/**
* Handle motion.
*
* @param edge
* the edge
* @param dx
* the dx
* @param dy
* the dy
*/
void handleMotion( int edge, float dx, float dy ) {
if ( mRunning ) return;
computeLayout( false, tmpRect4 );
if ( edge == GROW_NONE ) {
return;
} else if ( edge == MOVE ) {
moveBy( dx * ( mCropRect.width() / tmpRect4.width() ), dy * ( mCropRect.height() / tmpRect4.height() ) );
} else {
if ( ( ( GROW_LEFT_EDGE | GROW_RIGHT_EDGE ) & edge ) == 0 ) dx = 0;
if ( ( ( GROW_TOP_EDGE | GROW_BOTTOM_EDGE ) & edge ) == 0 ) dy = 0;
// Convert to image space before sending to growBy().
double xDelta = Math.round( dx * ( mCropRect.width() / tmpRect4.width() ) );
double yDelta = Math.round( dy * ( mCropRect.height() / tmpRect4.height() ) );
if ( mMaintainAspectRatio ) {
growWithConstantAspectSize( edge, xDelta, yDelta );
} else {
growWithoutConstantAspectSize( edge, xDelta, yDelta );
}
}
}
double calculateDy( double dx, double dy ) {
double ndy = dy;
if ( dx != 0 ) {
ndy = ( dx / mInitialAspectRatio );
if ( dy != 0 ) {
if ( dy > 0 ) {
ndy = Math.abs( ndy );
} else {
ndy = Math.abs( ndy ) * -1;
}
}
dy = ndy;
}
return ndy;
}
double calculateDx( double dy, double dx ) {
double ndx = dx;
if ( dy != 0 ) {
ndx = ( dy * mInitialAspectRatio );
if ( dx != 0 ) {
if ( dx > 0 ) {
ndx = Math.abs( ndx );
} else {
ndx = Math.abs( ndx ) * -1;
}
}
dx = ndx;
}
return ndx;
}
/**
* Grow only one handle
*
* @param dx
* @param dy
*/
void growWithConstantAspectSize( int edge, double dx, double dy ) {
final boolean left = isLeftEdge( edge );
final boolean right = isRightEdge( edge );
final boolean top = isTopEdge( edge );
final boolean bottom = isBottomEdge( edge );
final boolean horizontal = left || right;
final boolean vertical = top || bottom;
final boolean singleSide = !( horizontal && vertical );
// check minimum size and outset the rectangle as needed
final double widthCap = (double) mMinSize / getScale();
double ndx, ndy;
tmpRectMotionF.set( mCropRect );
if ( singleSide ) {
if ( horizontal ) {
// horizontal only
ndx = dx;
ndy = calculateDy( ndx, 0 );
if ( left ) {
tmpRectMotionF.left += ndx;
tmpRectMotionF.inset( 0, (float) ( ndy / 2 ) );
} else {
tmpRectMotionF.right += ndx;
tmpRectMotionF.inset( 0, (float) ( -ndy / 2 ) );
}
} else {
// vertical only
ndy = dy;
ndx = calculateDx( ndy, 0 );
if ( top ) {
tmpRectMotionF.top += ndy;
tmpRectMotionF.inset( (float) ( ndx / 2 ), 0 );
} else if ( bottom ) {
tmpRectMotionF.bottom += ndy;
tmpRectMotionF.inset( (float) ( -ndx / 2 ), 0 );
}
}
} else {
// both horizontal & vertical
ndx = dx;
ndy = calculateDy( dx, 0 );
if ( left && top ) {
tmpRectMotionF.left += ndx;
tmpRectMotionF.top += ndy;
} else if ( left && bottom ) {
tmpRectMotionF.left += ndx;
tmpRectMotionF.bottom -= ndy;
} else if ( right && top ) {
tmpRectMotionF.right += ndx;
tmpRectMotionF.top -= ndy;
} else if ( right && bottom ) {
tmpRectMotionF.right += ndx;
tmpRectMotionF.bottom += ndy;
}
}
if ( tmpRectMotionF.width() >= widthCap && tmpRectMotionF.height() >= widthCap && mImageRect.contains( tmpRectMotionF ) ) {
mCropRect.set( tmpRectMotionF );
}
computeLayout( true, mDrawRect );
mContext.invalidate();
}
/**
* Grow only one handle
*
* @param dx
* @param dy
*/
void growWithoutConstantAspectSize( int edge, double dx, double dy ) {
final boolean left = isLeftEdge( edge );
final boolean right = isRightEdge( edge );
final boolean top = isTopEdge( edge );
final boolean bottom = isBottomEdge( edge );
final boolean horizontal = left || right;
final boolean vertical = top || bottom;
// check minimum size and outset the rectangle as needed
final double widthCap = (double) mMinSize / getScale();
tmpRectMotionF.set( mCropRect );
double ndy = dy;
double ndx = dx;
if ( horizontal ) {
if ( left ) {
tmpRectMotionF.left += ndx;
if ( !vertical ) tmpRectMotionF.inset( 0, (float) ( ndy / 2 ) );
} else if ( right ) {
tmpRectMotionF.right += ndx;
if ( !vertical ) tmpRectMotionF.inset( 0, (float) ( -ndy / 2 ) );
}
}
if ( vertical ) {
if ( top ) {
tmpRectMotionF.top += ndy;
if ( !horizontal ) tmpRectMotionF.inset( (float) ( ndx / 2 ), 0 );
} else if ( bottom ) {
tmpRectMotionF.bottom += ndy;
if ( !horizontal ) tmpRectMotionF.inset( (float) ( -ndx / 2 ), 0 );
}
}
if ( tmpRectMotionF.width() >= widthCap && tmpRectMotionF.height() >= widthCap && mImageRect.contains( tmpRectMotionF ) ) {
mCropRect.set( tmpRectMotionF );
}
computeLayout( true, mDrawRect );
mContext.invalidate();
}
/**
* Move by.
*
* @param dx
* the dx
* @param dy
* the dy
*/
void moveBy( float dx, float dy ) {
tmpRectMotion.set( mDrawRect );
mCropRect.offset( dx, dy );
mCropRect.offset( Math.max( 0, mImageRect.left - mCropRect.left ), Math.max( 0, mImageRect.top - mCropRect.top ) );
mCropRect.offset( Math.min( 0, mImageRect.right - mCropRect.right ), Math.min( 0, mImageRect.bottom - mCropRect.bottom ) );
computeLayout( false, mDrawRect );
tmpRectMotion.union( mDrawRect );
tmpRectMotion.inset( -dWidth * 2, -dHeight * 2 );
mContext.invalidate( tmpRectMotion );
}
/**
* Gets the scale.
*
* @return the scale
*/
protected float getScale() {
float values[] = new float[9];
mMatrix.getValues( values );
return values[Matrix.MSCALE_X];
}
/**
* @deprecated Old grow behavior
*/
void growBy( double dx, double dy ) {
if ( mMaintainAspectRatio ) {
if ( dx != 0 ) {
dy = dx / mInitialAspectRatio;
} else if ( dy != 0 ) {
dx = dy * mInitialAspectRatio;
}
}
tmpRectMotionF.set( mCropRect );
if ( dx > 0F && tmpRectMotionF.width() + 2 * dx > mImageRect.width() ) {
float adjustment = ( mImageRect.width() - tmpRectMotionF.width() ) / 2F;
dx = adjustment;
if ( mMaintainAspectRatio ) {
dy = dx / mInitialAspectRatio;
}
}
if ( dy > 0F && tmpRectMotionF.height() + 2 * dy > mImageRect.height() ) {
float adjustment = ( mImageRect.height() - tmpRectMotionF.height() ) / 2F;
dy = adjustment;
if ( mMaintainAspectRatio ) {
dx = dy * mInitialAspectRatio;
}
}
tmpRectMotionF.inset( (float) -dx, (float) -dy );
// check minimum size and outset the rectangle as needed
final double widthCap = (double) mMinSize / getScale();
if ( tmpRectMotionF.width() < widthCap ) {
tmpRectMotionF.inset( (float) ( -( widthCap - tmpRectMotionF.width() ) / 2F ), 0F );
}
double heightCap = mMaintainAspectRatio ? ( widthCap / mInitialAspectRatio ) : widthCap;
if ( tmpRectMotionF.height() < heightCap ) {
tmpRectMotionF.inset( 0F, (float) ( -( heightCap - tmpRectMotionF.height() ) / 2F ) );
}
mCropRect.set( tmpRectMotionF );
computeLayout( true, mDrawRect );
mContext.invalidate();
}
/**
* Adjust crop rect based on the current image.
*
* @param r
* - The {@link Rect} to be adjusted
*/
private void adjustCropRect( RectF r ) {
// Log.i( LOG_TAG, "adjustCropRect: " + r + ", mImageRect: " + mImageRect );
if ( r.left < mImageRect.left ) {
r.offset( mImageRect.left - r.left, 0F );
} else if ( r.right > mImageRect.right ) {
r.offset( -( r.right - mImageRect.right ), 0 );
}
if ( r.top < mImageRect.top ) {
r.offset( 0F, mImageRect.top - r.top );
} else if ( r.bottom > mImageRect.bottom ) {
r.offset( 0F, -( r.bottom - mImageRect.bottom ) );
}
double diffx = -1, diffy = -1;
if ( r.width() > mImageRect.width() ) {
if ( r.left < mImageRect.left ) {
diffx = mImageRect.left - r.left;
r.left += diffx;
} else if ( r.right > mImageRect.right ) {
diffx = ( r.right - mImageRect.right );
r.right += -diffx;
}
} else if ( r.height() > mImageRect.height() ) {
if ( r.top < mImageRect.top ) {
// top
diffy = mImageRect.top - r.top;
r.top += diffy;
} else if ( r.bottom > mImageRect.bottom ) {
// bottom
diffy = ( r.bottom - mImageRect.bottom );
r.bottom += -diffy;
}
}
if ( mMaintainAspectRatio ) {
// Log.d( LOG_TAG, "diffx: " + diffx + ", diffy: " + diffy );
if ( diffy != -1 ) {
diffx = diffy * mInitialAspectRatio;
r.inset( (float) ( diffx / 2.0 ), 0 );
} else if ( diffx != -1 ) {
diffy = diffx / mInitialAspectRatio;
r.inset( 0, (float) ( diffy / 2.0 ) );
}
}
r.sort();
}
/**
* Adjust real crop rect.
*
* @param matrix
* the matrix
* @param rect
* the rect
* @param outsideRect
* the outside rect
* @return the rect f
*/
private RectF adjustRealCropRect( Matrix matrix, RectF rect, RectF outsideRect ) {
// Log.i( LOG_TAG, "adjustRealCropRect" );
boolean adjusted = false;
tempLayoutRectF.set( rect );
matrix.mapRect( tempLayoutRectF );
float[] mvalues = new float[9];
matrix.getValues( mvalues );
final float scale = mvalues[Matrix.MSCALE_X];
if ( tempLayoutRectF.left < outsideRect.left ) {
adjusted = true;
rect.offset( ( outsideRect.left - tempLayoutRectF.left ) / scale, 0 );
} else if ( tempLayoutRectF.right > outsideRect.right ) {
adjusted = true;
rect.offset( -( tempLayoutRectF.right - outsideRect.right ) / scale, 0 );
}
if ( tempLayoutRectF.top < outsideRect.top ) {
adjusted = true;
rect.offset( 0, ( outsideRect.top - tempLayoutRectF.top ) / scale );
} else if ( tempLayoutRectF.bottom > outsideRect.bottom ) {
adjusted = true;
rect.offset( 0, -( tempLayoutRectF.bottom - outsideRect.bottom ) / scale );
}
tempLayoutRectF.set( rect );
matrix.mapRect( tempLayoutRectF );
if ( tempLayoutRectF.width() > outsideRect.width() ) {
adjusted = true;
if ( tempLayoutRectF.left < outsideRect.left ) rect.left += ( outsideRect.left - tempLayoutRectF.left ) / scale;
if ( tempLayoutRectF.right > outsideRect.right ) rect.right += -( tempLayoutRectF.right - outsideRect.right ) / scale;
}
if ( tempLayoutRectF.height() > outsideRect.height() ) {
adjusted = true;
if ( tempLayoutRectF.top < outsideRect.top ) rect.top += ( outsideRect.top - tempLayoutRectF.top ) / scale;
if ( tempLayoutRectF.bottom > outsideRect.bottom )
rect.bottom += -( tempLayoutRectF.bottom - outsideRect.bottom ) / scale;
}
if ( mMaintainAspectRatio && adjusted ) {
if ( mInitialAspectRatio >= 1 ) { // width > height
final double dy = rect.width() / mInitialAspectRatio;
rect.bottom = (float) ( rect.top + dy );
} else { // height >= width
final double dx = rect.height() * mInitialAspectRatio;
rect.right = (float) ( rect.left + dx );
}
}
rect.sort();
return rect;
}
/**
* Compute and adjust the current crop layout
*
* @param adjust
* - If true tries to adjust the crop rect
* @param outRect
* - The result will be stored in this {@link Rect}
*/
public void computeLayout( boolean adjust, Rect outRect ) {
if ( adjust ) {
adjustCropRect( mCropRect );
tmpRect2.set( 0, 0, mContext.getWidth(), mContext.getHeight() );
mCropRect = adjustRealCropRect( mMatrix, mCropRect, tmpRect2 );
}
getDisplayRect( mMatrix, mCropRect, outRect );
}
public void getDisplayRect( Matrix m, RectF supportRect, Rect outRect ) {
tmpDisplayRectF.set( supportRect.left, supportRect.top, supportRect.right, supportRect.bottom );
m.mapRect( tmpDisplayRectF );
outRect.set( Math.round( tmpDisplayRectF.left ), Math.round( tmpDisplayRectF.top ), Math.round( tmpDisplayRectF.right ),
Math.round( tmpDisplayRectF.bottom ) );
}
/**
* Invalidate.
*/
public void invalidate() {
if ( !mRunning ) {
computeLayout( true, mDrawRect );
}
}
/** true while the view is animating */
protected volatile boolean mRunning = false;
/** animation duration in ms */
protected int animationDurationMs = 300;
/** {@link Easing} used to animate the view */
protected Easing mEasing = new Quad();
/**
* Return true if the view is currently running
*
* @return
*/
public boolean isRunning() {
return mRunning;
}
public void animateTo( Matrix m, Rect imageRect, RectF cropRect, final boolean maintainAspectRatio ) {
if ( !mRunning ) {
mRunning = true;
setMode( Mode.None );
mMatrix = new Matrix( m );
mCropRect = cropRect;
mImageRect = new RectF( imageRect );
mMaintainAspectRatio = false;
double ratio = (double) mCropRect.width() / (double) mCropRect.height();
mInitialAspectRatio = Math.round( ratio * 1000.0 ) / 1000.0;
// Log.i( LOG_TAG, "aspect ratio: " + mInitialAspectRatio );
final Rect oldRect = mDrawRect;
final Rect newRect = new Rect();
computeLayout( false, newRect );
final float[] topLeft = { oldRect.left, oldRect.top };
final float[] bottomRight = { oldRect.right, oldRect.bottom };
final double pt1 = newRect.left - oldRect.left;
final double pt2 = newRect.right - oldRect.right;
final double pt3 = newRect.top - oldRect.top;
final double pt4 = newRect.bottom - oldRect.bottom;
final long startTime = System.currentTimeMillis();
mHandler.post( new Runnable() {
@Override
public void run() {
if ( mContext == null ) return;
long now = System.currentTimeMillis();
double currentMs = Math.min( animationDurationMs, now - startTime );
double value1 = mEasing.easeOut( currentMs, 0, pt1, animationDurationMs );
double value2 = mEasing.easeOut( currentMs, 0, pt2, animationDurationMs );
double value3 = mEasing.easeOut( currentMs, 0, pt3, animationDurationMs );
double value4 = mEasing.easeOut( currentMs, 0, pt4, animationDurationMs );
mDrawRect.left = (int) ( topLeft[0] + value1 );
mDrawRect.right = (int) ( bottomRight[0] + value2 );
mDrawRect.top = (int) ( topLeft[1] + value3 );
mDrawRect.bottom = (int) ( bottomRight[1] + value4 );
mContext.invalidate();
if ( currentMs < animationDurationMs ) {
mHandler.post( this );
} else {
mMaintainAspectRatio = maintainAspectRatio;
mRunning = false;
invalidate();
mContext.invalidate();
}
}
} );
}
}
/**
* Setup.
*
* @param m
* the m
* @param imageRect
* the image rect
* @param cropRect
* the crop rect
* @param maintainAspectRatio
* the maintain aspect ratio
*/
public void setup( Matrix m, Rect imageRect, RectF cropRect, boolean maintainAspectRatio ) {
mMatrix = new Matrix( m );
mCropRect = cropRect;
mImageRect = new RectF( imageRect );
mMaintainAspectRatio = maintainAspectRatio;
double ratio = (double) mCropRect.width() / (double) mCropRect.height();
mInitialAspectRatio = Math.round( ratio * 1000.0 ) / 1000.0;
// Log.i( LOG_TAG, "aspect ratio: " + mInitialAspectRatio );
computeLayout( true, mDrawRect );
mOutlinePaint.setStrokeWidth( stroke_width );
mOutlinePaint.setStyle( Paint.Style.STROKE );
mOutlinePaint.setAntiAlias( false );
try {
ReflectionUtils.invokeMethod( mOutlinePaint, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mOutlinePaint2.setStrokeWidth( internal_stroke_width );
mOutlinePaint2.setStyle( Paint.Style.STROKE );
mOutlinePaint2.setAntiAlias( false );
mOutlinePaint2.setColor( highlight_internal_color );
try {
ReflectionUtils.invokeMethod( mOutlinePaint2, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mOutlineFill.setColor( highlight_outside_color );
mOutlineFill.setStyle( Paint.Style.FILL );
mOutlineFill.setAntiAlias( false );
try {
ReflectionUtils.invokeMethod( mOutlineFill, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaintShadow.setStrokeWidth( internal_stroke_width );
mLinesPaintShadow.setAntiAlias( true );
mLinesPaintShadow.setColor( Color.BLACK );
mLinesPaintShadow.setStyle( Paint.Style.STROKE );
mLinesPaintShadow.setMaskFilter( new BlurMaskFilter( 2, Blur.NORMAL ) );
setMode( Mode.None );
init();
}
/**
* Sets the aspect ratio.
*
* @param value
* the new aspect ratio
*/
public void setAspectRatio( float value ) {
mInitialAspectRatio = value;
}
/**
* Sets the maintain aspect ratio.
*
* @param value
* the new maintain aspect ratio
*/
public void setMaintainAspectRatio( boolean value ) {
mMaintainAspectRatio = value;
}
/**
* Update.
*
* @param imageMatrix
* the image matrix
* @param imageRect
* the image rect
*/
public void update( Matrix imageMatrix, Rect imageRect ) {
mMatrix = new Matrix( imageMatrix );
mImageRect = new RectF( imageRect );
computeLayout( true, mDrawRect );
mContext.invalidate();
}
/**
* Gets the matrix.
*
* @return the matrix
*/
public Matrix getMatrix() {
return mMatrix;
}
/**
* Gets the draw rect.
*
* @return the draw rect
*/
public Rect getDrawRect() {
return mDrawRect;
}
/**
* Gets the crop rect f.
*
* @return the crop rect f
*/
public RectF getCropRectF() {
return mCropRect;
}
/**
* Returns the cropping rectangle in image space.
*
* @return the crop rect
*/
public Rect getCropRect() {
return new Rect( (int) mCropRect.left, (int) mCropRect.top, (int) mCropRect.right, (int) mCropRect.bottom );
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.easing.Expo;
import it.sephiroth.android.library.imagezoom.easing.Linear;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews.RemoteView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.graphics.Point2D;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
// TODO: Auto-generated Javadoc
/**
* Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or
* content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and
* provides various display options such as scaling and tinting.
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
* @attr ref android.R.styleable#ImageView_src
* @attr ref android.R.styleable#ImageView_maxWidth
* @attr ref android.R.styleable#ImageView_maxHeight
* @attr ref android.R.styleable#ImageView_tint
* @attr ref android.R.styleable#ImageView_scaleType
* @attr ref android.R.styleable#ImageView_cropToPadding
*/
@RemoteView
public class AdjustImageViewFreeRotation extends View {
/** The Constant LOG_TAG. */
static final String LOG_TAG = "rotate";
// settable by the client
/** The m uri. */
private Uri mUri;
/** The m resource. */
private int mResource = 0;
/** The m matrix. */
private Matrix mMatrix;
/** The m scale type. */
private ScaleType mScaleType;
/** The m adjust view bounds. */
private boolean mAdjustViewBounds = false;
/** The m max width. */
private int mMaxWidth = Integer.MAX_VALUE;
/** The m max height. */
private int mMaxHeight = Integer.MAX_VALUE;
// these are applied to the drawable
/** The m color filter. */
private ColorFilter mColorFilter;
/** The m alpha. */
private int mAlpha = 255;
/** The m view alpha scale. */
private int mViewAlphaScale = 256;
/** The m color mod. */
private boolean mColorMod = false;
/** The m drawable. */
private Drawable mDrawable = null;
/** The m state. */
private int[] mState = null;
/** The m merge state. */
private boolean mMergeState = false;
/** The m level. */
private int mLevel = 0;
/** The m drawable width. */
private int mDrawableWidth;
/** The m drawable height. */
private int mDrawableHeight;
/** The m draw matrix. */
private Matrix mDrawMatrix = null;
/** The m rotate matrix. */
private Matrix mRotateMatrix = new Matrix();
/** The m flip matrix. */
private Matrix mFlipMatrix = new Matrix();
// Avoid allocations...
/** The m temp src. */
private RectF mTempSrc = new RectF();
/** The m temp dst. */
private RectF mTempDst = new RectF();
/** The m crop to padding. */
private boolean mCropToPadding;
/** The m baseline. */
private int mBaseline = -1;
/** The m baseline align bottom. */
private boolean mBaselineAlignBottom = false;
/** The m have frame. */
private boolean mHaveFrame;
/** The m easing. */
private Easing mEasing = new Expo();
/** View is in the reset state. */
boolean isReset = false;
/** reset animation time. */
int resetAnimTime = 200;
Path mClipPath = new Path();
Path mInversePath = new Path();
Rect mViewDrawRect = new Rect();
Paint mOutlinePaint = new Paint();
Paint mOutlineFill = new Paint();
RectF mDrawRect;
PointF mCenter = new PointF();
Path mLinesPath = new Path();
Paint mLinesPaint = new Paint();
Paint mLinesPaintShadow = new Paint();
Drawable mResizeDrawable;
int handleWidth, handleHeight;
final int grid_rows = 3;
final int grid_cols = 3;
private boolean mEnableFreeRotate;
static Logger logger = LoggerFactory.getLogger( "rotate", LoggerType.ConsoleLoggerType );
/**
* Sets the reset anim duration.
*
* @param value
* the new reset anim duration
*/
public void setResetAnimDuration( int value ) {
resetAnimTime = value;
}
public void setEnableFreeRotate( boolean value ) {
mEnableFreeRotate = value;
}
public boolean isFreeRotateEnabled() {
return mEnableFreeRotate;
}
/**
* The listener interface for receiving onReset events. The class that is interested in processing a onReset event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnResetListener<code> method. When
* the onReset event occurs, that object's appropriate
* method is invoked.
*
* @see OnResetEvent
*/
public interface OnResetListener {
/**
* On reset complete.
*/
void onResetComplete();
}
/** The m reset listener. */
private OnResetListener mResetListener;
/**
* Sets the on reset listener.
*
* @param listener
* the new on reset listener
*/
public void setOnResetListener( OnResetListener listener ) {
mResetListener = listener;
}
/** The Constant sScaleTypeArray. */
@SuppressWarnings("unused")
private static final ScaleType[] sScaleTypeArray = {
ScaleType.MATRIX, ScaleType.FIT_XY, ScaleType.FIT_START, ScaleType.FIT_CENTER, ScaleType.FIT_END, ScaleType.CENTER,
ScaleType.CENTER_CROP, ScaleType.CENTER_INSIDE };
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
*/
public AdjustImageViewFreeRotation( Context context ) {
super( context );
initImageView();
}
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public AdjustImageViewFreeRotation( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public AdjustImageViewFreeRotation( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
initImageView();
}
/**
* Sets the easing.
*
* @param value
* the new easing
*/
public void setEasing( Easing value ) {
mEasing = value;
}
int mOutlinePaintAlpha, mOutlineFillAlpha, mLinesAlpha, mLinesShadowAlpha;
/**
* Inits the image view.
*/
private void initImageView() {
mMatrix = new Matrix();
mScaleType = ScaleType.FIT_CENTER;
Context context = getContext();
int highlight_color = context.getResources().getColor( R.color.feather_rotate_highlight_stroke_color );
int highlight_stroke_internal_color = context.getResources().getColor( R.color.feather_rotate_highlight_grid_stroke_color );
int highlight_stroke_internal_width = context.getResources()
.getInteger( R.integer.feather_rotate_highlight_grid_stroke_width );
int highlight_outside_color = context.getResources().getColor( R.color.feather_rotate_highlight_outside );
int highlight_stroke_width = context.getResources().getInteger( R.integer.feather_rotate_highlight_stroke_width );
mOutlinePaint.setStrokeWidth( highlight_stroke_width );
mOutlinePaint.setStyle( Paint.Style.STROKE );
mOutlinePaint.setAntiAlias( true );
mOutlinePaint.setColor( highlight_color );
mOutlineFill.setStyle( Paint.Style.FILL );
mOutlineFill.setAntiAlias( false );
mOutlineFill.setColor( highlight_outside_color );
mOutlineFill.setDither( false );
try {
ReflectionUtils.invokeMethod( mOutlineFill, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaint.setStrokeWidth( highlight_stroke_internal_width );
mLinesPaint.setAntiAlias( false );
mLinesPaint.setDither( false );
mLinesPaint.setStyle( Paint.Style.STROKE );
mLinesPaint.setColor( highlight_stroke_internal_color );
try {
ReflectionUtils.invokeMethod( mLinesPaint, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaintShadow.setStrokeWidth( highlight_stroke_internal_width );
mLinesPaintShadow.setAntiAlias( true );
mLinesPaintShadow.setColor( Color.BLACK );
mLinesPaintShadow.setStyle( Paint.Style.STROKE );
mLinesPaintShadow.setMaskFilter( new BlurMaskFilter( 2, Blur.NORMAL ) );
mOutlineFillAlpha = mOutlineFill.getAlpha();
mOutlinePaintAlpha = mOutlinePaint.getAlpha();
mLinesAlpha = mLinesPaint.getAlpha();
mLinesShadowAlpha = mLinesPaintShadow.getAlpha();
mOutlinePaint.setAlpha( 0 );
mOutlineFill.setAlpha( 0 );
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
android.content.res.Resources resources = getContext().getResources();
mResizeDrawable = resources.getDrawable( R.drawable.feather_highlight_crop_handle );
double w = mResizeDrawable.getIntrinsicWidth();
double h = mResizeDrawable.getIntrinsicHeight();
handleWidth = (int) Math.ceil( w / 2.0 );
handleHeight = (int) Math.ceil( h / 2.0 );
}
/*
* (non-Javadoc)
*
* @see android.view.View#verifyDrawable(android.graphics.drawable.Drawable)
*/
@Override
protected boolean verifyDrawable( Drawable dr ) {
return mDrawable == dr || super.verifyDrawable( dr );
}
/*
* (non-Javadoc)
*
* @see android.view.View#invalidateDrawable(android.graphics.drawable.Drawable)
*/
@Override
public void invalidateDrawable( Drawable dr ) {
if ( dr == mDrawable ) {
/*
* we invalidate the whole view in this case because it's very hard to know where the drawable actually is. This is made
* complicated because of the offsets and transformations that can be applied. In theory we could get the drawable's bounds
* and run them through the transformation and offsets, but this is probably not worth the effort.
*/
invalidate();
} else {
super.invalidateDrawable( dr );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSetAlpha(int)
*/
@Override
protected boolean onSetAlpha( int alpha ) {
if ( getBackground() == null ) {
int scale = alpha + ( alpha >> 7 );
if ( mViewAlphaScale != scale ) {
mViewAlphaScale = scale;
mColorMod = true;
applyColorMod();
}
return true;
}
return false;
}
private boolean isDown;
private double originalAngle;
private PointF getCenter() {
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
return new PointF( (float) vwidth / 2, (float) vheight / 2 );
}
private RectF getViewRect() {
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
return new RectF( 0, 0, vwidth, vheight );
}
private RectF getImageRect() {
return new RectF( 0, 0, mDrawableWidth, mDrawableHeight );
}
private void onTouchStart( float x, float y ) {
isDown = true;
PointF current = new PointF( x, y );
PointF center = getCenter();
double currentAngle = getRotationFromMatrix( mRotateMatrix );
originalAngle = Point2D.angle360( currentAngle + Point2D.angleBetweenPoints( center, current ) );
if ( mFadeHandlerStarted ) {
fadeinGrid( 300 );
} else {
fadeinOutlines( 600 );
}
}
private void onTouchMove( float x, float y ) {
if ( isDown ) {
PointF current = new PointF( x, y );
PointF center = getCenter();
float angle = (float) Point2D.angle360( originalAngle - Point2D.angleBetweenPoints( center, current ) );
logger.log( "ANGLE: " + angle + " .. " + getAngle90( angle ) );
setImageRotation( angle, false );
mRotation = angle;
invalidate();
}
}
private void setImageRotation( double angle, boolean invert ) {
PointF center = getCenter();
Matrix tempMatrix = new Matrix( mDrawMatrix );
RectF src = getImageRect();
RectF dst = getViewRect();
tempMatrix.setRotate( (float) angle, center.x, center.y );
tempMatrix.mapRect( src );
tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) );
float[] scale = getMatrixScale( tempMatrix );
float fScale = Math.min( scale[0], scale[1] );
if ( invert ) {
mRotateMatrix.setRotate( (float) angle, center.x, center.y );
mRotateMatrix.postScale( fScale, fScale, center.x, center.y );
} else {
mRotateMatrix.setScale( fScale, fScale, center.x, center.y );
mRotateMatrix.postRotate( (float) angle, center.x, center.y );
}
}
private void onTouchUp( float x, float y ) {
isDown = false;
setImageRotation( mRotation, true );
invalidate();
fadeoutGrid( 300 );
}
@Override
public boolean onTouchEvent( MotionEvent event ) {
if ( !mEnableFreeRotate ) return true;
if ( isRunning() ) return true;
int action = event.getAction() & MotionEvent.ACTION_MASK;
float x = event.getX();
float y = event.getY();
if ( action == MotionEvent.ACTION_DOWN ) {
onTouchStart( x, y );
} else if ( action == MotionEvent.ACTION_MOVE ) {
onTouchMove( x, y );
} else if ( action == MotionEvent.ACTION_UP ) {
onTouchUp( x, y );
} else
return true;
return true;
}
private double getRotationFromMatrix( Matrix matrix ) {
float[] pts = { 0, 0, 0, -100 };
matrix.mapPoints( pts );
double angle = Point2D.angleBetweenPoints( pts[0], pts[1], pts[2], pts[3], 0 );
return -angle;
}
/**
* Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
*
* @param adjustViewBounds
* Whether to adjust the bounds of this view to presrve the original aspect ratio of the drawable
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
*/
public void setAdjustViewBounds( boolean adjustViewBounds ) {
mAdjustViewBounds = adjustViewBounds;
if ( adjustViewBounds ) {
setScaleType( ScaleType.FIT_CENTER );
}
}
/**
* An optional argument to supply a maximum width for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been set
* to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.
*
* <p>
* Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image
* to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)}
* to determine how to fit the image within the bounds.
* </p>
*
* @param maxWidth
* maximum width for this view
*
* @attr ref android.R.styleable#ImageView_maxWidth
*/
public void setMaxWidth( int maxWidth ) {
mMaxWidth = maxWidth;
}
/**
* An optional argument to supply a maximum height for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been
* set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.
*
* <p>
* Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image
* to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)}
* to determine how to fit the image within the bounds.
* </p>
*
* @param maxHeight
* maximum height for this view
*
* @attr ref android.R.styleable#ImageView_maxHeight
*/
public void setMaxHeight( int maxHeight ) {
mMaxHeight = maxHeight;
}
/**
* Return the view's drawable, or null if no drawable has been assigned.
*
* @return the drawable
*/
public Drawable getDrawable() {
return mDrawable;
}
/**
* Sets a drawable as the content of this ImageView.
*
* <p class="note">
* This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using
*
* @param resId
* the resource identifier of the the drawable {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead.
* </p>
* @attr ref android.R.styleable#ImageView_src
*/
public void setImageResource( int resId ) {
if ( mUri != null || mResource != resId ) {
updateDrawable( null );
mResource = resId;
mUri = null;
resolveUri();
requestLayout();
invalidate();
}
}
/**
* Sets the content of this ImageView to the specified Uri.
*
* <p class="note">
* This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using
*
* @param uri
* The Uri of an image {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead.
* </p>
*/
public void setImageURI( Uri uri ) {
if ( mResource != 0 || ( mUri != uri && ( uri == null || mUri == null || !uri.equals( mUri ) ) ) ) {
updateDrawable( null );
mResource = 0;
mUri = uri;
resolveUri();
requestLayout();
invalidate();
}
}
/**
* Sets a drawable as the content of this ImageView.
*
* @param drawable
* The drawable to set
*/
public void setImageDrawable( Drawable drawable ) {
if ( mDrawable != drawable ) {
mResource = 0;
mUri = null;
int oldWidth = mDrawableWidth;
int oldHeight = mDrawableHeight;
updateDrawable( drawable );
if ( oldWidth != mDrawableWidth || oldHeight != mDrawableHeight ) {
requestLayout();
}
invalidate();
}
}
/**
* Sets a Bitmap as the content of this ImageView.
*
* @param bm
* The bitmap to set
*/
public void setImageBitmap( Bitmap bm ) {
// if this is used frequently, may handle bitmaps explicitly
// to reduce the intermediate drawable object
setImageDrawable( new BitmapDrawable( getContext().getResources(), bm ) );
}
/**
* Sets the image state.
*
* @param state
* the state
* @param merge
* the merge
*/
public void setImageState( int[] state, boolean merge ) {
mState = state;
mMergeState = merge;
if ( mDrawable != null ) {
refreshDrawableState();
resizeFromDrawable();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#setSelected(boolean)
*/
@Override
public void setSelected( boolean selected ) {
super.setSelected( selected );
resizeFromDrawable();
}
/**
* Sets the image level, when it is constructed from a {@link android.graphics.drawable.LevelListDrawable}.
*
* @param level
* The new level for the image.
*/
public void setImageLevel( int level ) {
mLevel = level;
if ( mDrawable != null ) {
mDrawable.setLevel( level );
resizeFromDrawable();
}
}
/**
* Options for scaling the bounds of an image to the bounds of this view.
*/
public enum ScaleType {
/**
* Scale using the image matrix when drawing. The image matrix can be set using {@link ImageView#setImageMatrix(Matrix)}. From
* XML, use this syntax: <code>android:scaleType="matrix"</code>.
*/
MATRIX( 0 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#FILL}. From XML, use this syntax: <code>android:scaleType="fitXY"</code>.
*/
FIT_XY( 1 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#START}. From XML, use this syntax: <code>android:scaleType="fitStart"</code>
* .
*/
FIT_START( 2 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#CENTER}. From XML, use this syntax:
* <code>android:scaleType="fitCenter"</code>.
*/
FIT_CENTER( 3 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#END}. From XML, use this syntax: <code>android:scaleType="fitEnd"</code>.
*/
FIT_END( 4 ),
/**
* Center the image in the view, but perform no scaling. From XML, use this syntax: <code>android:scaleType="center"</code>.
*/
CENTER( 5 ),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will
* be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view.
* From XML, use this syntax: <code>android:scaleType="centerCrop"</code>.
*/
CENTER_CROP( 6 ),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will
* be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view.
* From XML, use this syntax: <code>android:scaleType="centerInside"</code>.
*/
CENTER_INSIDE( 7 );
/**
* Instantiates a new scale type.
*
* @param ni
* the ni
*/
ScaleType( int ni ) {
nativeInt = ni;
}
/** The native int. */
final int nativeInt;
}
/**
* Controls how the image should be resized or moved to match the size of this ImageView.
*
* @param scaleType
* The desired scaling mode.
*
* @attr ref android.R.styleable#ImageView_scaleType
*/
public void setScaleType( ScaleType scaleType ) {
if ( scaleType == null ) {
throw new NullPointerException();
}
if ( mScaleType != scaleType ) {
mScaleType = scaleType;
setWillNotCacheDrawing( mScaleType == ScaleType.CENTER );
requestLayout();
invalidate();
}
}
/**
* Return the current scale type in use by this ImageView.
*
* @return the scale type
* @see ImageView.ScaleType
* @attr ref android.R.styleable#ImageView_scaleType
*/
public ScaleType getScaleType() {
return mScaleType;
}
/**
* Return the view's optional matrix. This is applied to the view's drawable when it is drawn. If there is not matrix, this
* method will return null. Do not change this matrix in place. If you want a different matrix applied to the drawable, be sure
* to call setImageMatrix().
*
* @return the image matrix
*/
public Matrix getImageMatrix() {
return mMatrix;
}
/**
* Sets the image matrix.
*
* @param matrix
* the new image matrix
*/
public void setImageMatrix( Matrix matrix ) {
// collaps null and identity to just null
if ( matrix != null && matrix.isIdentity() ) {
matrix = null;
}
// don't invalidate unless we're actually changing our matrix
if ( matrix == null && !mMatrix.isIdentity() || matrix != null && !mMatrix.equals( matrix ) ) {
mMatrix.set( matrix );
configureBounds();
invalidate();
}
}
/**
* Resolve uri.
*/
private void resolveUri() {
if ( mDrawable != null ) {
return;
}
Resources rsrc = getResources();
if ( rsrc == null ) {
return;
}
Drawable d = null;
if ( mResource != 0 ) {
try {
d = rsrc.getDrawable( mResource );
} catch ( Exception e ) {
Log.w( LOG_TAG, "Unable to find resource: " + mResource, e );
// Don't try again.
mUri = null;
}
} else if ( mUri != null ) {
String scheme = mUri.getScheme();
if ( ContentResolver.SCHEME_ANDROID_RESOURCE.equals( scheme ) ) {
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) || ContentResolver.SCHEME_FILE.equals( scheme ) ) {
try {
d = Drawable.createFromStream( getContext().getContentResolver().openInputStream( mUri ), null );
} catch ( Exception e ) {
Log.w( LOG_TAG, "Unable to open content: " + mUri, e );
}
} else {
d = Drawable.createFromPath( mUri.toString() );
}
if ( d == null ) {
System.out.println( "resolveUri failed on bad bitmap uri: " + mUri );
// Don't try again.
mUri = null;
}
} else {
return;
}
updateDrawable( d );
}
/*
* (non-Javadoc)
*
* @see android.view.View#onCreateDrawableState(int)
*/
@Override
public int[] onCreateDrawableState( int extraSpace ) {
if ( mState == null ) {
return super.onCreateDrawableState( extraSpace );
} else if ( !mMergeState ) {
return mState;
} else {
return mergeDrawableStates( super.onCreateDrawableState( extraSpace + mState.length ), mState );
}
}
/**
* Update drawable.
*
* @param d
* the d
*/
private void updateDrawable( Drawable d ) {
if ( mDrawable != null ) {
mDrawable.setCallback( null );
unscheduleDrawable( mDrawable );
}
mDrawable = d;
if ( d != null ) {
d.setCallback( this );
if ( d.isStateful() ) {
d.setState( getDrawableState() );
}
d.setLevel( mLevel );
mDrawableWidth = d.getIntrinsicWidth();
mDrawableHeight = d.getIntrinsicHeight();
applyColorMod();
configureBounds();
} else {
mDrawableWidth = mDrawableHeight = -1;
}
}
/**
* Resize from drawable.
*/
private void resizeFromDrawable() {
Drawable d = mDrawable;
if ( d != null ) {
int w = d.getIntrinsicWidth();
if ( w < 0 ) w = mDrawableWidth;
int h = d.getIntrinsicHeight();
if ( h < 0 ) h = mDrawableHeight;
if ( w != mDrawableWidth || h != mDrawableHeight ) {
mDrawableWidth = w;
mDrawableHeight = h;
requestLayout();
}
}
}
/** The Constant sS2FArray. */
private static final Matrix.ScaleToFit[] sS2FArray = {
Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END };
/**
* Scale type to scale to fit.
*
* @param st
* the st
* @return the matrix. scale to fit
*/
private static Matrix.ScaleToFit scaleTypeToScaleToFit( ScaleType st ) {
// ScaleToFit enum to their corresponding Matrix.ScaleToFit values
return sS2FArray[st.nativeInt - 1];
}
/*
* (non-Javadoc)
*
* @see android.view.View#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
if ( changed ) {
mHaveFrame = true;
double oldRotation = mRotation;
boolean flip_h = getHorizontalFlip();
boolean flip_v = getVerticalFlip();
configureBounds();
if ( flip_h || flip_v ) {
flip( flip_h, flip_v );
}
if ( oldRotation != 0 ) {
setImageRotation( oldRotation, false );
mRotation = oldRotation;
}
invalidate();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
resolveUri();
int w;
int h;
// Desired aspect ratio of the view's contents (not including padding)
float desiredAspect = 0.0f;
// We are allowed to change the view's width
boolean resizeWidth = false;
// We are allowed to change the view's height
boolean resizeHeight = false;
final int widthSpecMode = MeasureSpec.getMode( widthMeasureSpec );
final int heightSpecMode = MeasureSpec.getMode( heightMeasureSpec );
if ( mDrawable == null ) {
// If no drawable, its intrinsic size is 0.
mDrawableWidth = -1;
mDrawableHeight = -1;
w = h = 0;
} else {
w = mDrawableWidth;
h = mDrawableHeight;
if ( w <= 0 ) w = 1;
if ( h <= 0 ) h = 1;
// We are supposed to adjust view bounds to match the aspect
// ratio of our drawable. See if that is possible.
if ( mAdjustViewBounds ) {
resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
desiredAspect = (float) w / (float) h;
}
}
int pleft = getPaddingLeft();
int pright = getPaddingRight();
int ptop = getPaddingTop();
int pbottom = getPaddingBottom();
int widthSize;
int heightSize;
if ( resizeWidth || resizeHeight ) {
/*
* If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at
* least one dimension.
*/
// Get the max possible width given our constraints
widthSize = resolveAdjustedSize( w + pleft + pright, mMaxWidth, widthMeasureSpec );
// Get the max possible height given our constraints
heightSize = resolveAdjustedSize( h + ptop + pbottom, mMaxHeight, heightMeasureSpec );
if ( desiredAspect != 0.0f ) {
// See what our actual aspect ratio is
float actualAspect = (float) ( widthSize - pleft - pright ) / ( heightSize - ptop - pbottom );
if ( Math.abs( actualAspect - desiredAspect ) > 0.0000001 ) {
boolean done = false;
// Try adjusting width to be proportional to height
if ( resizeWidth ) {
int newWidth = (int) ( desiredAspect * ( heightSize - ptop - pbottom ) ) + pleft + pright;
if ( newWidth <= widthSize ) {
widthSize = newWidth;
done = true;
}
}
// Try adjusting height to be proportional to width
if ( !done && resizeHeight ) {
int newHeight = (int) ( ( widthSize - pleft - pright ) / desiredAspect ) + ptop + pbottom;
if ( newHeight <= heightSize ) {
heightSize = newHeight;
}
}
}
}
} else {
/*
* We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just
* measure in the normal way.
*/
w += pleft + pright;
h += ptop + pbottom;
w = Math.max( w, getSuggestedMinimumWidth() );
h = Math.max( h, getSuggestedMinimumHeight() );
widthSize = resolveSize( w, widthMeasureSpec );
heightSize = resolveSize( h, heightMeasureSpec );
}
setMeasuredDimension( widthSize, heightSize );
}
/**
* Resolve adjusted size.
*
* @param desiredSize
* the desired size
* @param maxSize
* the max size
* @param measureSpec
* the measure spec
* @return the int
*/
private int resolveAdjustedSize( int desiredSize, int maxSize, int measureSpec ) {
int result = desiredSize;
int specMode = MeasureSpec.getMode( measureSpec );
int specSize = MeasureSpec.getSize( measureSpec );
switch ( specMode ) {
case MeasureSpec.UNSPECIFIED:
/*
* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves.
*/
result = Math.min( desiredSize, maxSize );
break;
case MeasureSpec.AT_MOST:
// Parent says we can be as big as we want, up to specSize.
// Don't be larger than specSize, and don't be larger than
// the max size imposed on ourselves.
result = Math.min( Math.min( desiredSize, specSize ), maxSize );
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
/**
* Configure bounds.
*/
private void configureBounds() {
if ( mDrawable == null || !mHaveFrame ) {
return;
}
int dwidth = mDrawableWidth;
int dheight = mDrawableHeight;
int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
boolean fits = ( dwidth < 0 || vwidth == dwidth ) && ( dheight < 0 || vheight == dheight );
if ( dwidth <= 0 || dheight <= 0 || ScaleType.FIT_XY == mScaleType ) {
/*
* If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view.
*/
mDrawable.setBounds( 0, 0, vwidth, vheight );
mDrawMatrix = null;
} else {
// We need to do the scaling ourself, so have the drawable
// use its native size.
mDrawable.setBounds( 0, 0, dwidth, dheight );
if ( ScaleType.MATRIX == mScaleType ) {
// Use the specified matrix as-is.
if ( mMatrix.isIdentity() ) {
mDrawMatrix = null;
} else {
mDrawMatrix = mMatrix;
}
} else if ( fits ) {
// The bitmap fits exactly, no transform needed.
mDrawMatrix = null;
} else if ( ScaleType.CENTER == mScaleType ) {
// Center bitmap in view, no scaling.
mDrawMatrix = mMatrix;
mDrawMatrix.setTranslate( (int) ( ( vwidth - dwidth ) * 0.5f + 0.5f ), (int) ( ( vheight - dheight ) * 0.5f + 0.5f ) );
} else if ( ScaleType.CENTER_CROP == mScaleType ) {
mDrawMatrix = mMatrix;
float scale;
float dx = 0, dy = 0;
if ( dwidth * vheight > vwidth * dheight ) {
scale = (float) vheight / (float) dheight;
dx = ( vwidth - dwidth * scale ) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = ( vheight - dheight * scale ) * 0.5f;
}
mDrawMatrix.setScale( scale, scale );
mDrawMatrix.postTranslate( (int) ( dx + 0.5f ), (int) ( dy + 0.5f ) );
} else if ( ScaleType.CENTER_INSIDE == mScaleType ) {
mDrawMatrix = mMatrix;
float scale;
float dx;
float dy;
if ( dwidth <= vwidth && dheight <= vheight ) {
scale = 1.0f;
} else {
scale = Math.min( (float) vwidth / (float) dwidth, (float) vheight / (float) dheight );
}
dx = (int) ( ( vwidth - dwidth * scale ) * 0.5f + 0.5f );
dy = (int) ( ( vheight - dheight * scale ) * 0.5f + 0.5f );
mDrawMatrix.setScale( scale, scale );
mDrawMatrix.postTranslate( dx, dy );
} else {
// Generate the required transform.
mTempSrc.set( 0, 0, dwidth, dheight );
mTempDst.set( 0, 0, vwidth, vheight );
mDrawMatrix = mMatrix;
mDrawMatrix.setRectToRect( mTempSrc, mTempDst, scaleTypeToScaleToFit( mScaleType ) );
mCurrentScale = getMatrixScale( mDrawMatrix )[0];
Matrix tempMatrix = new Matrix( mMatrix );
RectF src = new RectF();
RectF dst = new RectF();
src.set( 0, 0, dheight, dwidth );
dst.set( 0, 0, vwidth, vheight );
tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) );
tempMatrix = new Matrix( mDrawMatrix );
tempMatrix.invert( tempMatrix );
float invertScale = getMatrixScale( tempMatrix )[0];
mDrawMatrix.postScale( invertScale, invertScale, vwidth / 2, vheight / 2 );
mRotateMatrix.reset();
mFlipMatrix.reset();
mFlipType = FlipType.FLIP_NONE.nativeInt;
mRotation = 0;
mRotateMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 );
mDrawRect = getImageRect();
mCenter = getCenter();
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#drawableStateChanged()
*/
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
Drawable d = mDrawable;
if ( d != null && d.isStateful() ) {
d.setState( getDrawableState() );
}
}
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
if ( mDrawable == null ) {
return; // couldn't resolve the URI
}
if ( mDrawableWidth == 0 || mDrawableHeight == 0 ) {
return; // nothing to draw (empty bounds)
}
final int mPaddingTop = getPaddingTop();
final int mPaddingLeft = getPaddingLeft();
final int mPaddingBottom = getPaddingBottom();
final int mPaddingRight = getPaddingRight();
if ( mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0 ) {
mDrawable.draw( canvas );
} else {
int saveCount = canvas.getSaveCount();
canvas.save();
if ( mCropToPadding ) {
final int scrollX = getScrollX();
final int scrollY = getScrollY();
canvas.clipRect( scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + getRight() - getLeft() - mPaddingRight,
scrollY + getBottom() - getTop() - mPaddingBottom );
}
canvas.translate( mPaddingLeft, mPaddingTop );
if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix );
if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix );
if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix );
mDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
if ( mEnableFreeRotate ) {
mDrawRect = getImageRect();
getDrawingRect( mViewDrawRect );
mClipPath.reset();
mInversePath.reset();
mLinesPath.reset();
float[] points = new float[] {
mDrawRect.left, mDrawRect.top, mDrawRect.right, mDrawRect.top, mDrawRect.right, mDrawRect.bottom, mDrawRect.left,
mDrawRect.bottom };
Matrix matrix = new Matrix( mDrawMatrix );
matrix.postConcat( mRotateMatrix );
matrix.mapPoints( points );
RectF invertRect = new RectF( mViewDrawRect );
invertRect.top -= mPaddingLeft;
invertRect.left -= mPaddingTop;
mInversePath.addRect( invertRect, Path.Direction.CW );
double sx = Point2D.distance( points[2], points[3], points[0], points[1] );
double sy = Point2D.distance( points[6], points[7], points[0], points[1] );
double angle = getAngle90( mRotation );
RectF rect;
if ( angle < 45 ) {
rect = crop( (float) sx, (float) sy, angle, mDrawableWidth, mDrawableHeight, mCenter, null );
} else {
rect = crop( (float) sx, (float) sy, angle, mDrawableHeight, mDrawableWidth, mCenter, null );
}
float colStep = (float) rect.height() / grid_cols;
float rowStep = (float) rect.width() / grid_rows;
for ( int i = 1; i < grid_cols; i++ ) {
// mLinesPath.addRect( (int)rect.left, (int)(rect.top + colStep * i), (int)rect.right, (int)(rect.top + colStep * i)
// + 3, Path.Direction.CW );
mLinesPath.moveTo( (int) rect.left, (int) ( rect.top + colStep * i ) );
mLinesPath.lineTo( (int) rect.right, (int) ( rect.top + colStep * i ) );
}
for ( int i = 1; i < grid_rows; i++ ) {
// mLinesPath.addRect( (int)(rect.left + rowStep * i), (int)rect.top, (int)(rect.left + rowStep * i) + 3,
// (int)rect.bottom, Path.Direction.CW );
mLinesPath.moveTo( (int) ( rect.left + rowStep * i ), (int) rect.top );
mLinesPath.lineTo( (int) ( rect.left + rowStep * i ), (int) rect.bottom );
}
mClipPath.addRect( rect, Path.Direction.CW );
mInversePath.addRect( rect, Path.Direction.CCW );
saveCount = canvas.save();
canvas.translate( mPaddingLeft, mPaddingTop );
canvas.drawPath( mInversePath, mOutlineFill );
// canvas.drawPath( mLinesPath, mLinesPaintShadow );
canvas.drawPath( mLinesPath, mLinesPaint );
canvas.drawPath( mClipPath, mOutlinePaint );
// if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix );
// if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix );
// if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix );
// mResizeDrawable.setBounds( (int) mDrawRect.right - handleWidth, (int) mDrawRect.bottom - handleHeight, (int)
// mDrawRect.right + handleWidth, (int) mDrawRect.bottom + handleHeight );
// mResizeDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
saveCount = canvas.save();
canvas.translate( mPaddingLeft, mPaddingTop );
mResizeDrawable.setBounds( (int) ( points[4] - handleWidth ), (int) ( points[5] - handleHeight ),
(int) ( points[4] + handleWidth ), (int) ( points[5] + handleHeight ) );
mResizeDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
}
}
}
Handler mFadeHandler = new Handler();
boolean mFadeHandlerStarted;
protected void fadeinGrid( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final float startAlpha = mLinesPaint.getAlpha();
final float startAlphaShadow = mLinesPaintShadow.getAlpha();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_lines = (float) easing.easeNone( currentMs, startAlpha, mLinesAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, startAlphaShadow, mLinesShadowAlpha, durationMs );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mLinesPaint.setAlpha( mLinesAlpha );
mLinesPaintShadow.setAlpha( mLinesShadowAlpha );
invalidate();
}
}
} );
}
protected void fadeoutGrid( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final float startAlpha = mLinesPaint.getAlpha();
final float startAlphaShadow = mLinesPaintShadow.getAlpha();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_lines = (float) easing.easeNone( currentMs, 0, startAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, startAlphaShadow, durationMs );
mLinesPaint.setAlpha( (int) startAlpha - (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) startAlphaShadow - (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
invalidate();
}
}
} );
}
protected void fadeinOutlines( final int durationMs ) {
if ( mFadeHandlerStarted ) return;
mFadeHandlerStarted = true;
final long startTime = System.currentTimeMillis();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_fill = (float) easing.easeNone( currentMs, 0, mOutlineFillAlpha, durationMs );
float new_alpha_paint = (float) easing.easeNone( currentMs, 0, mOutlinePaintAlpha, durationMs );
float new_alpha_lines = (float) easing.easeNone( currentMs, 0, mLinesAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, mLinesShadowAlpha, durationMs );
mOutlineFill.setAlpha( (int) new_alpha_fill );
mOutlinePaint.setAlpha( (int) new_alpha_paint );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mOutlineFill.setAlpha( mOutlineFillAlpha );
mOutlinePaint.setAlpha( mOutlinePaintAlpha );
mLinesPaint.setAlpha( mLinesAlpha );
mLinesPaintShadow.setAlpha( mLinesShadowAlpha );
invalidate();
}
}
} );
}
static double getAngle90( double value ) {
double rotation = Point2D.angle360( value );
double angle = rotation;
if ( rotation >= 270 ) {
angle = 360 - rotation;
} else if ( rotation >= 180 ) {
angle = rotation - 180;
} else if ( rotation > 90 ) {
angle = 180 - rotation;
}
return angle;
}
RectF crop( float originalWidth, float originalHeight, double angle, float targetWidth, float targetHeight, PointF center,
Canvas canvas ) {
double radians = Point2D.radians( angle );
PointF[] original = new PointF[] {
new PointF( 0, 0 ), new PointF( originalWidth, 0 ), new PointF( originalWidth, originalHeight ),
new PointF( 0, originalHeight ) };
Point2D.translate( original, -originalWidth / 2, -originalHeight / 2 );
PointF[] rotated = new PointF[original.length];
System.arraycopy( original, 0, rotated, 0, original.length );
Point2D.rotate( rotated, radians );
if ( angle >= 0 ) {
PointF[] ray = new PointF[] { new PointF( 0, 0 ), new PointF( -targetWidth / 2, -targetHeight / 2 ) };
PointF[] bound = new PointF[] { rotated[0], rotated[3] };
// Top Left intersection.
PointF intersectTL = Point2D.intersection( ray, bound );
PointF[] ray2 = new PointF[] { new PointF( 0, 0 ), new PointF( targetWidth / 2, -targetHeight / 2 ) };
PointF[] bound2 = new PointF[] { rotated[0], rotated[1] };
// Top Right intersection.
PointF intersectTR = Point2D.intersection( ray2, bound2 );
// Pick the intersection closest to the origin
PointF intersect = new PointF( Math.max( intersectTL.x, -intersectTR.x ), Math.max( intersectTL.y, intersectTR.y ) );
RectF newRect = new RectF( intersect.x, intersect.y, -intersect.x, -intersect.y );
newRect.offset( center.x, center.y );
if ( canvas != null ) { // debug
Point2D.translate( rotated, center.x, center.y );
Point2D.translate( ray, center.x, center.y );
Point2D.translate( ray2, center.x, center.y );
Paint paint = new Paint( Paint.ANTI_ALIAS_FLAG );
paint.setColor( 0x66FFFF00 );
paint.setStyle( Paint.Style.STROKE );
paint.setStrokeWidth( 2 );
// draw rotated
drawRect( rotated, canvas, paint );
paint.setColor( Color.GREEN );
drawLine( ray, canvas, paint );
paint.setColor( Color.BLUE );
drawLine( ray2, canvas, paint );
paint.setColor( Color.CYAN );
drawLine( bound, canvas, paint );
paint.setColor( Color.WHITE );
drawLine( bound2, canvas, paint );
paint.setColor( Color.GRAY );
canvas.drawRect( newRect, paint );
}
return newRect;
} else {
throw new IllegalArgumentException( "angle cannot be < 0" );
}
}
void drawLine( PointF[] line, Canvas canvas, Paint paint ) {
canvas.drawLine( line[0].x, line[0].y, line[1].x, line[1].y, paint );
}
void drawRect( PointF[] rect, Canvas canvas, Paint paint ) {
// draw rotated
Path path = new Path();
path.moveTo( rect[0].x, rect[0].y );
path.lineTo( rect[1].x, rect[1].y );
path.lineTo( rect[2].x, rect[2].y );
path.lineTo( rect[3].x, rect[3].y );
path.lineTo( rect[0].x, rect[0].y );
canvas.drawPath( path, paint );
}
/**
* <p>
* Return the offset of the widget's text baseline from the widget's top boundary.
* </p>
*
* @return the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported.
*/
@Override
public int getBaseline() {
if ( mBaselineAlignBottom ) {
return getMeasuredHeight();
} else {
return mBaseline;
}
}
/**
* <p>
* Set the offset of the widget's text baseline from the widget's top boundary. This value is overridden by the
*
* @param baseline
* The baseline to use, or -1 if none is to be provided. {@link #setBaselineAlignBottom(boolean)} property.
* </p>
* @see #setBaseline(int)
* @attr ref android.R.styleable#ImageView_baseline
*/
public void setBaseline( int baseline ) {
if ( mBaseline != baseline ) {
mBaseline = baseline;
requestLayout();
}
}
/**
* Set whether to set the baseline of this view to the bottom of the view. Setting this value overrides any calls to setBaseline.
*
* @param aligned
* If true, the image view will be baseline aligned with based on its bottom edge.
*
* @attr ref android.R.styleable#ImageView_baselineAlignBottom
*/
public void setBaselineAlignBottom( boolean aligned ) {
if ( mBaselineAlignBottom != aligned ) {
mBaselineAlignBottom = aligned;
requestLayout();
}
}
/**
* Return whether this view's baseline will be considered the bottom of the view.
*
* @return the baseline align bottom
* @see #setBaselineAlignBottom(boolean)
*/
public boolean getBaselineAlignBottom() {
return mBaselineAlignBottom;
}
/**
* Set a tinting option for the image.
*
* @param color
* Color tint to apply.
* @param mode
* How to apply the color. The standard mode is {@link PorterDuff.Mode#SRC_ATOP}
*
* @attr ref android.R.styleable#ImageView_tint
*/
public final void setColorFilter( int color, PorterDuff.Mode mode ) {
setColorFilter( new PorterDuffColorFilter( color, mode ) );
}
/**
* Set a tinting option for the image. Assumes {@link PorterDuff.Mode#SRC_ATOP} blending mode.
*
* @param color
* Color tint to apply.
* @attr ref android.R.styleable#ImageView_tint
*/
public final void setColorFilter( int color ) {
setColorFilter( color, PorterDuff.Mode.SRC_ATOP );
}
/**
* Clear color filter.
*/
public final void clearColorFilter() {
setColorFilter( null );
}
/**
* Apply an arbitrary colorfilter to the image.
*
* @param cf
* the colorfilter to apply (may be null)
*/
public void setColorFilter( ColorFilter cf ) {
if ( mColorFilter != cf ) {
mColorFilter = cf;
mColorMod = true;
applyColorMod();
invalidate();
}
}
/**
* Sets the alpha.
*
* @param alpha
* the new alpha
*/
public void setAlpha( int alpha ) {
alpha &= 0xFF; // keep it legal
if ( mAlpha != alpha ) {
mAlpha = alpha;
mColorMod = true;
applyColorMod();
invalidate();
}
}
/**
* Apply color mod.
*/
private void applyColorMod() {
// Only mutate and apply when modifications have occurred. This should
// not reset the mColorMod flag, since these filters need to be
// re-applied if the Drawable is changed.
if ( mDrawable != null && mColorMod ) {
mDrawable = mDrawable.mutate();
mDrawable.setColorFilter( mColorFilter );
mDrawable.setAlpha( mAlpha * mViewAlphaScale >> 8 );
}
}
/** The m handler. */
protected Handler mHandler = new Handler();
/** The m rotation. */
protected double mRotation = 0;
/** The m current scale. */
protected float mCurrentScale = 0;
/** The m running. */
protected boolean mRunning = false;
/**
* Rotate90.
*
* @param cw
* the cw
* @param durationMs
* the duration ms
*/
public void rotate90( boolean cw, int durationMs ) {
final double destRotation = ( cw ? 90 : -90 );
rotateBy( destRotation, durationMs );
}
/**
* Rotate to.
*
* @param cw
* the cw
* @param durationMs
* the duration ms
*/
protected void rotateBy( final double deltaRotation, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
final long startTime = System.currentTimeMillis();
final double destRotation = mRotation + deltaRotation;
final double srcRotation = mRotation;
setImageRotation( mRotation, false );
invalidate();
mHandler.post( new Runnable() {
@SuppressWarnings("unused")
float old_scale = 0;
@SuppressWarnings("unused")
float old_rotation = 0;
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_rotation = (float) mEasing.easeInOut( currentMs, 0, deltaRotation, durationMs );
mRotation = Point2D.angle360( srcRotation + new_rotation );
setImageRotation( mRotation, false );
old_rotation = new_rotation;
invalidate();
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
mRotation = Point2D.angle360( destRotation );
setImageRotation( mRotation, true );
invalidate();
printDetails();
mRunning = false;
if ( isReset ) {
onReset();
}
}
}
} );
}
/**
* Prints the details.
*/
public void printDetails() {
Log.i( LOG_TAG, "details:" );
Log.d( LOG_TAG, " flip horizontal: "
+ ( ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt ) );
Log.d( LOG_TAG, " flip vertical: " + ( ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt ) );
Log.d( LOG_TAG, " rotation: " + mRotation );
Log.d( LOG_TAG, "--------" );
}
/**
* Flip.
*
* @param horizontal
* the horizontal
* @param durationMs
* the duration ms
*/
public void flip( boolean horizontal, int durationMs ) {
flipTo( horizontal, durationMs );
}
/** The m camera enabled. */
private boolean mCameraEnabled;
/**
* Sets the camera enabled.
*
* @param value
* the new camera enabled
*/
public void setCameraEnabled( final boolean value ) {
if ( android.os.Build.VERSION.SDK_INT >= 14 && value )
mCameraEnabled = value;
else
mCameraEnabled = false;
}
/**
* Flip to.
*
* @param horizontal
* the horizontal
* @param durationMs
* the duration ms
*/
protected void flipTo( final boolean horizontal, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
final long startTime = System.currentTimeMillis();
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
final float centerx = vwidth / 2;
final float centery = vheight / 2;
final Camera camera = new Camera();
mHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
double currentMs = Math.min( durationMs, now - startTime );
if ( mCameraEnabled ) {
float degrees = (float) ( 0 + ( ( -180 - 0 ) * ( currentMs / durationMs ) ) );
camera.save();
if ( horizontal ) {
camera.rotateY( degrees );
} else {
camera.rotateX( degrees );
}
camera.getMatrix( mFlipMatrix );
camera.restore();
mFlipMatrix.preTranslate( -centerx, -centery );
mFlipMatrix.postTranslate( centerx, centery );
} else {
double new_scale = mEasing.easeInOut( currentMs, 1, -2, durationMs );
if ( horizontal )
mFlipMatrix.setScale( (float) new_scale, 1, centerx, centery );
else
mFlipMatrix.setScale( 1, (float) new_scale, centerx, centery );
}
invalidate();
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
if ( horizontal ) {
mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt;
mDrawMatrix.postScale( -1, 1, centerx, centery );
} else {
mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt;
mDrawMatrix.postScale( 1, -1, centerx, centery );
}
mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), centerx, centery );
mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) );
mFlipMatrix.reset();
invalidate();
printDetails();
mRunning = false;
if ( isReset ) {
onReset();
}
}
}
} );
}
private void flip( boolean horizontal, boolean vertical ) {
PointF center = getCenter();
if ( horizontal ) {
mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt;
mDrawMatrix.postScale( -1, 1, center.x, center.y );
}
if ( vertical ) {
mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt;
mDrawMatrix.postScale( 1, -1, center.x, center.y );
}
mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), center.x, center.y );
mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) );
mFlipMatrix.reset();
}
/** The m matrix values. */
protected final float[] mMatrixValues = new float[9];
/**
* Gets the value.
*
* @param matrix
* the matrix
* @param whichValue
* the which value
* @return the value
*/
protected float getValue( Matrix matrix, int whichValue ) {
matrix.getValues( mMatrixValues );
return mMatrixValues[whichValue];
}
/**
* Gets the matrix scale.
*
* @param matrix
* the matrix
* @return the matrix scale
*/
protected float[] getMatrixScale( Matrix matrix ) {
float[] result = new float[2];
result[0] = getValue( matrix, Matrix.MSCALE_X );
result[1] = getValue( matrix, Matrix.MSCALE_Y );
return result;
}
/** The m flip type. */
protected int mFlipType = FlipType.FLIP_NONE.nativeInt;
/**
* The Enum FlipType.
*/
public enum FlipType {
/** The FLI p_ none. */
FLIP_NONE( 1 << 0 ),
/** The FLI p_ horizontal. */
FLIP_HORIZONTAL( 1 << 1 ),
/** The FLI p_ vertical. */
FLIP_VERTICAL( 1 << 2 );
/**
* Instantiates a new flip type.
*
* @param ni
* the ni
*/
FlipType( int ni ) {
nativeInt = ni;
}
/** The native int. */
public final int nativeInt;
}
/*
* (non-Javadoc)
*
* @see android.view.View#getRotation()
*/
public float getRotation() {
return (float) mRotation;
}
/**
* Gets the horizontal flip.
*
* @return the horizontal flip
*/
public boolean getHorizontalFlip() {
if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) {
return ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt;
}
return false;
}
/**
* Gets the vertical flip.
*
* @return the vertical flip
*/
public boolean getVerticalFlip() {
if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) {
return ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt;
}
return false;
}
/**
* Gets the flip type.
*
* @return the flip type
*/
public int getFlipType() {
return mFlipType;
}
/**
* Checks if is running.
*
* @return true, if is running
*/
public boolean isRunning() {
return mRunning;
}
/**
* Reset the image to the original state.
*/
public void reset() {
isReset = true;
onReset();
}
/**
* On reset.
*/
private void onReset() {
if ( isReset ) {
final boolean hflip = getHorizontalFlip();
final boolean vflip = getVerticalFlip();
boolean handled = false;
if ( mRotation != 0 ) {
rotateBy( -mRotation, resetAnimTime );
handled = true;
}
if ( hflip ) {
flip( true, resetAnimTime );
handled = true;
}
if ( vflip ) {
flip( false, resetAnimTime );
handled = true;
}
if ( !handled ) {
fireOnResetComplete();
}
}
}
/**
* Fire on reset complete.
*/
private void fireOnResetComplete() {
if ( mResetListener != null ) {
mResetListener.onResetComplete();
}
}
}
| Java |
package com.aviary.android.feather.widget;
import android.annotation.TargetApi;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.OverScroller;
@TargetApi(9)
class Fling9Runnable extends IFlingRunnable {
private OverScroller mScroller;
public Fling9Runnable( FlingRunnableView parent, int animationDuration ) {
super( parent, animationDuration );
mScroller = new OverScroller( ( (View) parent ).getContext(), new DecelerateInterpolator() );
}
@Override
public float getCurrVelocity() {
return mScroller.getCurrVelocity();
}
@Override
public boolean isFinished() {
return mScroller.isFinished();
}
public boolean springBack( int startX, int startY, int minX, int maxX, int minY, int maxY ) {
return mScroller.springBack( startX, startY, minX, maxX, minY, maxY );
}
@Override
protected void _startUsingVelocity( int initialX, int velocity ) {
mScroller.fling( initialX, 0, velocity, 0, mParent.getMinX(), mParent.getMaxX(), 0, Integer.MAX_VALUE, 10, 0 );
}
@Override
protected void _startUsingDistance( int initialX, int distance ) {
mScroller.startScroll( initialX, 0, distance, 0, mAnimationDuration );
}
@Override
protected boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
protected int getCurrX() {
return mScroller.getCurrX();
}
@Override
protected void forceFinished( boolean finished ) {
mScroller.forceFinished( finished );
}
} | Java |
/*
* 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.aviary.android.feather.widget.wp;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Adapter;
import android.widget.LinearLayout;
import android.widget.Scroller;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
// TODO: Auto-generated Javadoc
/**
* The Class Workspace.
*/
public class Workspace extends ViewGroup {
/** The Constant INVALID_SCREEN. */
private static final int INVALID_SCREEN = -1;
/** The Constant OVER_SCROLL_NEVER. */
public static final int OVER_SCROLL_NEVER = 0;
/** The Constant OVER_SCROLL_ALWAYS. */
public static final int OVER_SCROLL_ALWAYS = 1;
/** The Constant OVER_SCROLL_IF_CONTENT_SCROLLS. */
public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 2;
/** The velocity at which a fling gesture will cause us to snap to the next screen. */
private static final int SNAP_VELOCITY = 600;
/** The m default screen. */
private int mDefaultScreen;
/** The m padding bottom. */
private int mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom;
/** The m first layout. */
private boolean mFirstLayout = true;
/** The m current screen. */
private int mCurrentScreen;
/** The m next screen. */
private int mNextScreen = INVALID_SCREEN;
/** The m old selected position. */
private int mOldSelectedPosition = INVALID_SCREEN;
/** The m scroller. */
private Scroller mScroller;
/** The m velocity tracker. */
private VelocityTracker mVelocityTracker;
/** The m last motion x. */
private float mLastMotionX;
/** The m last motion x2. */
private float mLastMotionX2;
/** The m last motion y. */
private float mLastMotionY;
/** The Constant TOUCH_STATE_REST. */
private final static int TOUCH_STATE_REST = 0;
/** The Constant TOUCH_STATE_SCROLLING. */
private final static int TOUCH_STATE_SCROLLING = 1;
/** The m touch state. */
private int mTouchState = TOUCH_STATE_REST;
/** The m allow long press. */
private boolean mAllowLongPress = true;
/** The m touch slop. */
private int mTouchSlop;
/** The m maximum velocity. */
private int mMaximumVelocity;
/** The Constant INVALID_POINTER. */
private static final int INVALID_POINTER = -1;
/** The m active pointer id. */
private int mActivePointerId = INVALID_POINTER;
/** The m indicator. */
private WorkspaceIndicator mIndicator;
/** The Constant NANOTIME_DIV. */
private static final float NANOTIME_DIV = 1000000000.0f;
/** The Constant SMOOTHING_SPEED. */
private static final float SMOOTHING_SPEED = 0.75f;
/** The Constant SMOOTHING_CONSTANT. */
private static final float SMOOTHING_CONSTANT = (float) ( 0.016 / Math.log( SMOOTHING_SPEED ) );
/** The Constant BASELINE_FLING_VELOCITY. */
private static final float BASELINE_FLING_VELOCITY = 2500.f;
/** The Constant FLING_VELOCITY_INFLUENCE. */
private static final float FLING_VELOCITY_INFLUENCE = 0.4f;
/** The m smoothing time. */
private float mSmoothingTime;
/** The m touch x. */
private float mTouchX;
/** The m scroll interpolator. */
private Interpolator mScrollInterpolator;
/** The m adapter. */
protected Adapter mAdapter;
/** The m observer. */
protected DataSetObserver mObserver;
/** The m data changed. */
protected boolean mDataChanged;
/** The m first position. */
protected int mFirstPosition;
/** The m item count. */
protected int mItemCount = 0;
/** The m item type count. */
protected int mItemTypeCount = 1;
/** The m recycler. */
protected RecycleBin mRecycler;
/** The m height measure spec. */
private int mHeightMeasureSpec;
/** The m width measure spec. */
private int mWidthMeasureSpec;
/** The m edge glow left. */
private EdgeGlow mEdgeGlowLeft;
/** The m edge glow right. */
private EdgeGlow mEdgeGlowRight;
/** The m over scroll mode. */
private int mOverScrollMode;
/** The m allow child selection. */
private boolean mAllowChildSelection = true;
private boolean mCacheEnabled = false;
/** The logger. */
private Logger logger;
/**
* The listener interface for receiving onPageChange events. The class that is interested in processing a onPageChange event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnPageChangeListener<code> method. When
* the onPageChange event occurs, that object's appropriate
* method is invoked.
*
* @see OnPageChangeEvent
*/
public interface OnPageChangeListener {
/**
* On page changed.
*
* @param which
* the which
*/
void onPageChanged( int which, int old );
}
/** The m on page change listener. */
private OnPageChangeListener mOnPageChangeListener;
/**
* Sets the on page change listener.
*
* @param listener
* the new on page change listener
*/
public void setOnPageChangeListener( OnPageChangeListener listener ) {
mOnPageChangeListener = listener;
}
/**
* The Class WorkspaceOvershootInterpolator.
*/
private static class WorkspaceOvershootInterpolator implements Interpolator {
/** The Constant DEFAULT_TENSION. */
private static final float DEFAULT_TENSION = 1.0f;
/** The m tension. */
private float mTension;
/**
* Instantiates a new workspace overshoot interpolator.
*/
public WorkspaceOvershootInterpolator() {
mTension = DEFAULT_TENSION;
}
/**
* Sets the distance.
*
* @param distance
* the new distance
*/
public void setDistance( int distance ) {
mTension = distance > 0 ? DEFAULT_TENSION / distance : DEFAULT_TENSION;
}
/**
* Disable settle.
*/
public void disableSettle() {
mTension = 0.f;
}
/*
* (non-Javadoc)
*
* @see android.animation.TimeInterpolator#getInterpolation(float)
*/
@Override
public float getInterpolation( float t ) {
t -= 1.0f;
return t * t * ( ( mTension + 1 ) * t + mTension ) + 1.0f;
}
}
/**
* Instantiates a new workspace.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public Workspace( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
initWorkspace( context, attrs, 0 );
}
/**
* Instantiates a new workspace.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public Workspace( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
initWorkspace( context, attrs, defStyle );
}
/**
* Inits the workspace.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
private void initWorkspace( Context context, AttributeSet attrs, int defStyle ) {
TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.Workspace, defStyle, 0 );
mDefaultScreen = a.getInt( R.styleable.Workspace_defaultScreen, 0 );
a.recycle();
logger = LoggerFactory.getLogger( "Workspace", LoggerType.ConsoleLoggerType );
setHapticFeedbackEnabled( false );
mScrollInterpolator = new DecelerateInterpolator( 1.0f );
mScroller = new Scroller( context, mScrollInterpolator );
mCurrentScreen = mDefaultScreen;
final ViewConfiguration configuration = ViewConfiguration.get( getContext() );
mTouchSlop = configuration.getScaledTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mPaddingTop = getPaddingTop();
mPaddingBottom = getPaddingBottom();
mPaddingLeft = getPaddingLeft();
mPaddingRight = getPaddingRight();
int overscrollMode = a.getInt( R.styleable.Workspace_overscroll, 0 );
setOverScroll( overscrollMode );
}
/**
* Sets the over scroll.
*
* @param mode
* the new over scroll
*/
public void setOverScroll( int mode ) {
if ( mode != OVER_SCROLL_NEVER ) {
if ( mEdgeGlowLeft == null ) {
final Resources res = getContext().getResources();
final Drawable edge = res.getDrawable( R.drawable.feather_overscroll_edge );
final Drawable glow = res.getDrawable( R.drawable.feather_overscroll_glow );
mEdgeGlowLeft = new EdgeGlow( edge, glow );
mEdgeGlowRight = new EdgeGlow( edge, glow );
mEdgeGlowLeft.setColorFilter( 0xFF454545, Mode.MULTIPLY );
}
} else {
mEdgeGlowLeft = null;
mEdgeGlowRight = null;
}
mOverScrollMode = mode;
}
/**
* Gets the over scroll.
*
* @return the over scroll
*/
public int getOverScroll() {
return mOverScrollMode;
}
/**
* Sets the allow child selection.
*
* @param value
* the new allow child selection
*/
public void setAllowChildSelection( boolean value ) {
mAllowChildSelection = value;
}
/**
* Gets the adapter.
*
* @return the adapter
*/
public Adapter getAdapter() {
return mAdapter;
}
/**
* Sets the adapter.
*
* @param adapter
* the new adapter
*/
public void setAdapter( Adapter adapter ) {
if ( mAdapter != null ) {
mAdapter.unregisterDataSetObserver( mObserver );
mAdapter = null;
}
mAdapter = adapter;
resetList();
if ( mAdapter != null ) {
mObserver = new WorkspaceDataSetObserver();
mAdapter.registerDataSetObserver( mObserver );
mItemTypeCount = adapter.getViewTypeCount();
mItemCount = adapter.getCount();
mRecycler = new RecycleBin( mItemTypeCount, 10 );
} else {
mItemCount = 0;
}
mDataChanged = true;
requestLayout();
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addView(android.view.View, int, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView( View child, int index, LayoutParams params ) {
if ( !( child instanceof CellLayout ) ) {
throw new IllegalArgumentException( "A Workspace can only have CellLayout children." );
}
super.addView( child, index, params );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addView(android.view.View)
*/
@Override
public void addView( View child ) {
if ( !( child instanceof CellLayout ) ) {
throw new IllegalArgumentException( "A Workspace can only have CellLayout children." );
}
super.addView( child );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addView(android.view.View, int)
*/
@Override
public void addView( View child, int index ) {
if ( !( child instanceof CellLayout ) ) {
throw new IllegalArgumentException( "A Workspace can only have CellLayout children." );
}
super.addView( child, index );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addView(android.view.View, int, int)
*/
@Override
public void addView( View child, int width, int height ) {
if ( !( child instanceof CellLayout ) ) {
throw new IllegalArgumentException( "A Workspace can only have CellLayout children." );
}
super.addView( child, width, height );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addView(android.view.View, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView( View child, LayoutParams params ) {
if ( !( child instanceof CellLayout ) ) {
throw new IllegalArgumentException( "A Workspace can only have CellLayout children." );
}
super.addView( child, params );
}
/**
* Checks if is default screen showing.
*
* @return true, if is default screen showing
*/
boolean isDefaultScreenShowing() {
return mCurrentScreen == mDefaultScreen;
}
/**
* Returns the index of the currently displayed screen.
*
* @return The index of the currently displayed screen.
*/
public int getCurrentScreen() {
return mCurrentScreen;
}
/**
* Gets the total pages.
*
* @return the total pages
*/
public int getTotalPages() {
return mItemCount;
}
/**
* Sets the current screen.
*
* @param currentScreen
* the new current screen
*/
void setCurrentScreen( int currentScreen ) {
if ( !mScroller.isFinished() ) mScroller.abortAnimation();
mCurrentScreen = Math.max( 0, Math.min( currentScreen, mItemCount - 1 ) );
if ( mIndicator != null ) mIndicator.setLevel( mCurrentScreen, mItemCount );
scrollTo( mCurrentScreen * getWidth(), 0 );
invalidate();
}
/*
* (non-Javadoc)
*
* @see android.view.View#scrollTo(int, int)
*/
@Override
public void scrollTo( int x, int y ) {
super.scrollTo( x, y );
mTouchX = x;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
}
/*
* (non-Javadoc)
*
* @see android.view.View#computeScroll()
*/
@Override
public void computeScroll() {
if ( mScroller.computeScrollOffset() ) {
mTouchX = mScroller.getCurrX();
float mScrollX = mTouchX;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
float mScrollY = mScroller.getCurrY();
scrollTo( (int) mScrollX, (int) mScrollY );
postInvalidate();
} else if ( mNextScreen != INVALID_SCREEN ) {
int which = Math.max( 0, Math.min( mNextScreen, mItemCount - 1 ) );
onFinishedAnimation( which );
} else if ( mTouchState == TOUCH_STATE_SCROLLING ) {
final float now = System.nanoTime() / NANOTIME_DIV;
final float e = (float) Math.exp( ( now - mSmoothingTime ) / SMOOTHING_CONSTANT );
final float dx = mTouchX - getScrollX();
float mScrollX = getScrollX() + ( dx * e );
scrollTo( (int) mScrollX, 0 );
mSmoothingTime = now;
// Keep generating points as long as we're more than 1px away from the target
if ( dx > 1.f || dx < -1.f ) {
postInvalidate();
}
}
}
/** The m old selected child. */
private View mOldSelectedChild;
/**
* On finished animation.
*
* @param newScreen
* the new screen
*/
private void onFinishedAnimation( int newScreen ) {
logger.log( "onFinishedAnimation: " + newScreen );
final int previousScreen = mCurrentScreen;
final boolean toLeft = newScreen > mCurrentScreen;
final boolean toRight = newScreen < mCurrentScreen;
final boolean changed = newScreen != mCurrentScreen;
mCurrentScreen = newScreen;
if ( mIndicator != null ) mIndicator.setLevel( mCurrentScreen, mItemCount );
mNextScreen = INVALID_SCREEN;
fillToGalleryRight();
fillToGalleryLeft();
if ( toLeft ) {
detachOffScreenChildren( true );
} else if ( toRight ) {
detachOffScreenChildren( false );
}
if ( changed || mItemCount == 1 || true ) {
View child = getChildAt( mCurrentScreen - mFirstPosition );
if ( null != child ) {
if ( mAllowChildSelection ) {
if ( null != mOldSelectedChild ) {
mOldSelectedChild.setSelected( false );
mOldSelectedChild = null;
}
child.setSelected( true );
mOldSelectedChild = child;
}
// int index = indexOfChild( child ) + mFirstPosition;
child.requestFocus();
}
}
clearChildrenCache();
if ( mOnPageChangeListener != null ) {
post( new Runnable() {
@Override
public void run() {
mOnPageChangeListener.onPageChanged( mCurrentScreen, previousScreen );
}
} );
}
postUpdateIndicator( mCurrentScreen, mItemCount );
}
/**
* Detach off screen children.
*
* @param toLeft
* the to left
*/
private void detachOffScreenChildren( boolean toLeft ) {
int numChildren = getChildCount();
int start = 0;
int count = 0;
if ( toLeft ) {
final int galleryLeft = mPaddingLeft + getScreenScrollPositionX( mCurrentScreen - 1 );;
for ( int i = 0; i < numChildren; i++ ) {
final View child = getChildAt( i );
if ( child.getRight() >= galleryLeft ) {
break;
} else {
count++;
mRecycler.add( mAdapter.getItemViewType( i + mFirstPosition ), child );
}
}
} else {
final int galleryRight = getTotalWidth() + getScreenScrollPositionX( mCurrentScreen + 1 );
for ( int i = numChildren - 1; i >= 0; i-- ) {
final View child = getChildAt( i );
if ( child.getLeft() <= galleryRight ) {
break;
} else {
start = i;
count++;
mRecycler.add( mAdapter.getItemViewType( i + mFirstPosition ), child );
}
}
}
detachViewsFromParent( start, count );
if ( toLeft && count > 0 ) {
mFirstPosition += count;
}
}
private Matrix mEdgeMatrix = new Matrix();
/**
* Draw edges.
*
* @param canvas
* the canvas
*/
private void drawEdges( Canvas canvas ) {
if ( mEdgeGlowLeft != null ) {
if ( !mEdgeGlowLeft.isFinished() ) {
final int restoreCount = canvas.save();
final int height = getHeight();
mEdgeMatrix.reset();
mEdgeMatrix.postRotate( -90 );
mEdgeMatrix.postTranslate( 0, height );
canvas.concat( mEdgeMatrix );
mEdgeGlowLeft.setSize( height, height / 5 );
if ( mEdgeGlowLeft.draw( canvas ) ) {
invalidate();
}
canvas.restoreToCount( restoreCount );
}
if ( !mEdgeGlowRight.isFinished() ) {
final int restoreCount = canvas.save();
final int width = getWidth();
final int height = getHeight();
mEdgeMatrix.reset();
mEdgeMatrix.postRotate( 90 );
mEdgeMatrix.postTranslate( getScrollX() + width, 0 );
canvas.concat( mEdgeMatrix );
mEdgeGlowRight.setSize( height, height / 5 );
if ( mEdgeGlowRight.draw( canvas ) ) {
invalidate();
}
canvas.restoreToCount( restoreCount );
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#dispatchDraw(android.graphics.Canvas)
*/
@Override
protected void dispatchDraw( Canvas canvas ) {
boolean restore = false;
int restoreCount = 0;
if ( mItemCount < 1 ) return;
if ( mCurrentScreen < 0 ) return;
boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN;
// If we are not scrolling or flinging, draw only the current screen
if ( fastDraw ) {
try {
drawChild( canvas, getChildAt( mCurrentScreen - mFirstPosition ), getDrawingTime() );
} catch ( RuntimeException e ) {
logger.error( e.getMessage() );
}
} else {
final long drawingTime = getDrawingTime();
final float scrollPos = (float) getScrollX() / getTotalWidth();
final int leftScreen = (int) scrollPos;
final int rightScreen = leftScreen + 1;
if ( leftScreen >= 0 ) {
try {
drawChild( canvas, getChildAt( leftScreen - mFirstPosition ), drawingTime );
} catch ( RuntimeException e ) {
logger.error( e.getMessage() );
}
}
if ( scrollPos != leftScreen && rightScreen < mItemCount ) {
try {
drawChild( canvas, getChildAt( rightScreen - mFirstPosition ), drawingTime );
} catch ( RuntimeException e ) {
logger.error( e.getMessage() );
}
}
}
// let's draw the edges only if we have more than 1 page
if ( mEdgeGlowLeft != null && mItemCount > 1 ) {
drawEdges( canvas );
}
if ( restore ) {
canvas.restoreToCount( restoreCount );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onAttachedToWindow()
*/
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
computeScroll();
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
super.onMeasure( widthMeasureSpec, heightMeasureSpec );
mWidthMeasureSpec = widthMeasureSpec;
mHeightMeasureSpec = heightMeasureSpec;
if ( mDataChanged ) {
mFirstLayout = true;
resetList();
handleDataChanged();
}
boolean needsMeasuring = true;
if ( mNextScreen > INVALID_SCREEN && mAdapter != null && mNextScreen < mItemCount ) {
}
final int width = MeasureSpec.getSize( widthMeasureSpec );
// final int height = MeasureSpec.getSize( heightMeasureSpec );
final int widthMode = MeasureSpec.getMode( widthMeasureSpec );
if ( widthMode != MeasureSpec.EXACTLY ) {
throw new IllegalStateException( "Workspace can only be used in EXACTLY mode." );
}
final int heightMode = MeasureSpec.getMode( heightMeasureSpec );
if ( heightMode != MeasureSpec.EXACTLY ) {
throw new IllegalStateException( "Workspace can only be used in EXACTLY mode." );
}
// The children are given the same width and height as the workspace
final int count = mItemCount;
if ( !needsMeasuring ) {
for ( int i = 0; i < count; i++ ) {
getChildAt( i ).measure( widthMeasureSpec, heightMeasureSpec );
}
}
if ( mItemCount < 1 ) {
mCurrentScreen = INVALID_SCREEN;
mFirstLayout = true;
}
if ( mFirstLayout ) {
setHorizontalScrollBarEnabled( false );
if ( mCurrentScreen > INVALID_SCREEN )
scrollTo( mCurrentScreen * width, 0 );
else
scrollTo( 0, 0 );
setHorizontalScrollBarEnabled( true );
mFirstLayout = false;
}
}
/**
* Handle data changed.
*/
private void handleDataChanged() {
if ( mItemCount > 0 )
setNextSelectedPositionInt( 0 );
else
setNextSelectedPositionInt( -1 );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
if ( changed ) {
if ( !mFirstLayout ) {
mDataChanged = true;
measure( mWidthMeasureSpec, mHeightMeasureSpec );
}
}
layout( 0, false );
}
/**
* Layout.
*
* @param delta
* the delta
* @param animate
* the animate
*/
void layout( int delta, boolean animate ) {
int childrenLeft = mPaddingLeft;
int childrenWidth = ( getRight() - getLeft() ) - ( mPaddingLeft + mPaddingRight );
if ( mItemCount == 0 ) {
return;
}
if ( mNextScreen > INVALID_SCREEN ) {
setSelectedPositionInt( mNextScreen );
}
if ( mDataChanged ) {
mFirstPosition = mCurrentScreen;
View sel = makeAndAddView( mCurrentScreen, 0, 0, true );
int selectedOffset = childrenLeft + ( childrenWidth / 2 ) - ( sel.getWidth() / 2 );
sel.offsetLeftAndRight( selectedOffset );
fillToGalleryRight();
fillToGalleryLeft();
checkSelectionChanged();
}
mDataChanged = false;
setNextSelectedPositionInt( mCurrentScreen );
}
/**
* Check selection changed.
*/
void checkSelectionChanged() {
if ( ( mCurrentScreen != mOldSelectedPosition ) ) {
// selectionChanged();
mOldSelectedPosition = mCurrentScreen;
}
}
/**
* Make and add view.
*
* @param position
* the position
* @param offset
* the offset
* @param x
* the x
* @param fromLeft
* the from left
* @return the view
*/
private View makeAndAddView( int position, int offset, int x, boolean fromLeft ) {
View child;
if ( !mDataChanged ) {
child = mRecycler.remove( mAdapter.getItemViewType( position ) );
if ( child != null ) {
child = mAdapter.getView( position, child, this );
setUpChild( child, offset, x, fromLeft );
return child;
}
}
// Nothing found in the recycler -- ask the adapter for a view
child = mAdapter.getView( position, null, this );
// Position the view
setUpChild( child, offset, x, fromLeft );
logger.info( "adding view: " + child );
return child;
}
/**
* Sets the up child.
*
* @param child
* the child
* @param offset
* the offset
* @param x
* the x
* @param fromLeft
* the from left
*/
private void setUpChild( View child, int offset, int x, boolean fromLeft ) {
// Respect layout params that are already in the view. Otherwise
// make some up...
LayoutParams lp = child.getLayoutParams();
if ( lp == null ) {
lp = (LayoutParams) generateDefaultLayoutParams();
}
addViewInLayout( child, fromLeft ? -1 : 0, lp );
if ( mAllowChildSelection ) {
// final boolean wantfocus = offset == 0;
// child.setSelected( wantfocus );
// if( wantfocus ){
// child.requestFocus();
// }
}
// Get measure specs
int childHeightSpec = ViewGroup.getChildMeasureSpec( mHeightMeasureSpec, mPaddingTop + mPaddingBottom, lp.height );
int childWidthSpec = ViewGroup.getChildMeasureSpec( mWidthMeasureSpec, mPaddingLeft + mPaddingRight, lp.width );
// Measure child
child.measure( childWidthSpec, childHeightSpec );
int childLeft;
int childRight;
// Position vertically based on gravity setting
int childTop = calculateTop( child, true );
int childBottom = childTop + child.getMeasuredHeight();
int width = child.getMeasuredWidth();
if ( fromLeft ) {
childLeft = x;
childRight = childLeft + width;
} else {
childLeft = x - width;
childRight = x;
}
child.layout( childLeft, childTop, childRight, childBottom );
}
/**
* Calculate top.
*
* @param child
* the child
* @param duringLayout
* the during layout
* @return the int
*/
private int calculateTop( View child, boolean duringLayout ) {
return mPaddingTop;
}
/**
* Gets the total width.
*
* @return the total width
*/
private int getTotalWidth() {
return getWidth();
}
/**
* Gets the screen scroll position x.
*
* @param screen
* the screen
* @return the screen scroll position x
*/
private int getScreenScrollPositionX( int screen ) {
return ( screen * getTotalWidth() );
}
/**
* Fill to gallery right.
*/
private void fillToGalleryRight() {
int itemSpacing = 0;
int galleryRight = getScreenScrollPositionX( mCurrentScreen + 3 );
int numChildren = getChildCount();
int numItems = mItemCount;
// Set state for initial iteration
View prevIterationView = getChildAt( numChildren - 1 );
int curPosition;
int curLeftEdge;
if ( prevIterationView != null ) {
curPosition = mFirstPosition + numChildren;
curLeftEdge = prevIterationView.getRight() + itemSpacing;
} else {
mFirstPosition = curPosition = mItemCount - 1;
curLeftEdge = mPaddingLeft;
}
while ( curLeftEdge < galleryRight && curPosition < numItems ) {
prevIterationView = makeAndAddView( curPosition, curPosition - mCurrentScreen, curLeftEdge, true );
// Set state for next iteration
curLeftEdge = prevIterationView.getRight() + itemSpacing;
curPosition++;
}
}
/**
* Fill to gallery left.
*/
private void fillToGalleryLeft() {
int itemSpacing = 0;
int galleryLeft = getScreenScrollPositionX( mCurrentScreen - 3 );
// Set state for initial iteration
View prevIterationView = getChildAt( 0 );
int curPosition;
int curRightEdge;
if ( prevIterationView != null ) {
curPosition = mFirstPosition - 1;
curRightEdge = prevIterationView.getLeft() - itemSpacing;
} else {
// No children available!
curPosition = 0;
curRightEdge = getRight() - getLeft() - mPaddingRight;
}
while ( curRightEdge > galleryLeft && curPosition >= 0 ) {
prevIterationView = makeAndAddView( curPosition, curPosition - mCurrentScreen, curRightEdge, false );
// Remember some state
mFirstPosition = curPosition;
// Set state for next iteration
curRightEdge = prevIterationView.getLeft() - itemSpacing;
curPosition--;
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#generateDefaultLayoutParams()
*/
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT );
}
/**
* Recycle all views.
*/
void recycleAllViews() {
/*
* final int childCount = getChildCount();
*
* for ( int i = 0; i < childCount; i++ ) { View v = getChildAt( i );
*
* if( mRecycler != null ) mRecycler.add( v ); }
*/
}
/**
* Reset list.
*/
void resetList() {
recycleAllViews();
while ( getChildCount() > 0 ) {
View view = getChildAt( 0 );
detachViewFromParent( view );
removeDetachedView( view, false );
}
// detachAllViewsFromParent();
if ( mRecycler != null ) mRecycler.clear();
mOldSelectedPosition = INVALID_SCREEN;
setSelectedPositionInt( INVALID_SCREEN );
setNextSelectedPositionInt( INVALID_SCREEN );
postInvalidate();
}
/**
* Sets the next selected position int.
*
* @param screen
* the new next selected position int
*/
private void setNextSelectedPositionInt( int screen ) {
mNextScreen = screen;
}
/**
* Sets the selected position int.
*
* @param screen
* the new selected position int
*/
private void setSelectedPositionInt( int screen ) {
mCurrentScreen = screen;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#requestChildRectangleOnScreen(android.view.View, android.graphics.Rect, boolean)
*/
@Override
public boolean requestChildRectangleOnScreen( View child, Rect rectangle, boolean immediate ) {
int screen = indexOfChild( child ) + mFirstPosition;
if ( screen != mCurrentScreen || !mScroller.isFinished() ) {
snapToScreen( screen );
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#onRequestFocusInDescendants(int, android.graphics.Rect)
*/
@Override
protected boolean onRequestFocusInDescendants( int direction, Rect previouslyFocusedRect ) {
if ( mItemCount < 1 ) return false;
if ( isEnabled() ) {
int focusableScreen;
if ( mNextScreen != INVALID_SCREEN ) {
focusableScreen = mNextScreen;
} else {
focusableScreen = mCurrentScreen;
}
if ( focusableScreen != INVALID_SCREEN ) {
View child = getChildAt( focusableScreen );
if ( null != child ) child.requestFocus( direction, previouslyFocusedRect );
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#dispatchUnhandledMove(android.view.View, int)
*/
@Override
public boolean dispatchUnhandledMove( View focused, int direction ) {
if ( direction == View.FOCUS_LEFT ) {
if ( getCurrentScreen() > 0 ) {
snapToScreen( getCurrentScreen() - 1 );
return true;
}
} else if ( direction == View.FOCUS_RIGHT ) {
if ( getCurrentScreen() < mItemCount - 1 ) {
snapToScreen( getCurrentScreen() + 1 );
return true;
}
}
return super.dispatchUnhandledMove( focused, direction );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setEnabled(boolean)
*/
@Override
public void setEnabled( boolean enabled ) {
super.setEnabled( enabled );
for ( int i = 0; i < getChildCount(); i++ ) {
getChildAt( i ).setEnabled( enabled );
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addFocusables(java.util.ArrayList, int, int)
*/
@Override
public void addFocusables( ArrayList<View> views, int direction, int focusableMode ) {
if ( isEnabled() ) {
View child = getChildAt( mCurrentScreen );
if ( null != child ) {
child.addFocusables( views, direction );
}
if ( direction == View.FOCUS_LEFT ) {
if ( mCurrentScreen > 0 ) {
child = getChildAt( mCurrentScreen - 1 );
if ( null != child ) {
child.addFocusables( views, direction );
}
}
} else if ( direction == View.FOCUS_RIGHT ) {
if ( mCurrentScreen < mItemCount - 1 ) {
child = getChildAt( mCurrentScreen + 1 );
if ( null != child ) {
child.addFocusables( views, direction );
}
}
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onInterceptTouchEvent( MotionEvent ev ) {
final int action = ev.getAction();
if ( !isEnabled() ) {
return false; // We don't want the events. Let them fall through to the all apps view.
}
if ( ( action == MotionEvent.ACTION_MOVE ) && ( mTouchState != TOUCH_STATE_REST ) ) {
return true;
}
acquireVelocityTrackerAndAddMovement( ev );
switch ( action & MotionEvent.ACTION_MASK ) {
case MotionEvent.ACTION_MOVE: {
/*
* Locally do absolute value. mLastMotionX is set to the y value of the down event.
*/
final int pointerIndex = ev.findPointerIndex( mActivePointerId );
if ( pointerIndex < 0 ) {
// invalid pointer
return true;
}
final float x = ev.getX( pointerIndex );
final float y = ev.getY( pointerIndex );
final int xDiff = (int) Math.abs( x - mLastMotionX );
final int yDiff = (int) Math.abs( y - mLastMotionY );
final int touchSlop = mTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
mLastMotionX2 = x;
if ( xMoved || yMoved ) {
if ( xMoved ) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
mLastMotionX = x;
mTouchX = getScrollX();
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
enableChildrenCache( mCurrentScreen - 1, mCurrentScreen + 1 );
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
// Remember location of down touch
mLastMotionX = x;
mLastMotionX2 = x;
mLastMotionY = y;
mActivePointerId = ev.getPointerId( 0 );
mAllowLongPress = true;
mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// Release the drag
clearChildrenCache();
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
mAllowLongPress = false;
releaseVelocityTracker();
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp( ev );
break;
}
/*
* The only time we want to intercept motion events is if we are in the drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
/**
* On secondary pointer up.
*
* @param ev
* the ev
*/
private void onSecondaryPointerUp( MotionEvent ev ) {
final int pointerIndex = ( ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK ) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId( pointerIndex );
if ( pointerId == mActivePointerId ) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = ev.getX( newPointerIndex );
mLastMotionX2 = ev.getX( newPointerIndex );
mLastMotionY = ev.getY( newPointerIndex );
mActivePointerId = ev.getPointerId( newPointerIndex );
if ( mVelocityTracker != null ) {
mVelocityTracker.clear();
}
}
}
/**
* If one of our descendant views decides that it could be focused now, only pass that along if it's on the current screen.
*
* This happens when live folders requery, and if they're off screen, they end up calling requestFocus, which pulls it on screen.
*
* @param focused
* the focused
*/
@Override
public void focusableViewAvailable( View focused ) {
View current = getChildAt( mCurrentScreen );
View v = focused;
while ( true ) {
if ( v == current ) {
super.focusableViewAvailable( focused );
return;
}
if ( v == this ) {
return;
}
ViewParent parent = v.getParent();
if ( parent instanceof View ) {
v = (View) v.getParent();
} else {
return;
}
}
}
/**
* Enable children cache.
*
* @param fromScreen
* the from screen
* @param toScreen
* the to screen
*/
public void enableChildrenCache( int fromScreen, int toScreen ) {
if ( !mCacheEnabled ) return;
if ( fromScreen > toScreen ) {
final int temp = fromScreen;
fromScreen = toScreen;
toScreen = temp;
}
final int count = getChildCount();
fromScreen = Math.max( fromScreen, 0 );
toScreen = Math.min( toScreen, count - 1 );
for ( int i = fromScreen; i <= toScreen; i++ ) {
final CellLayout layout = (CellLayout) getChildAt( i );
layout.setChildrenDrawnWithCacheEnabled( true );
layout.setChildrenDrawingCacheEnabled( true );
}
}
/**
* Clear children cache.
*/
public void clearChildrenCache() {
if ( !mCacheEnabled ) return;
final int count = getChildCount();
for ( int i = 0; i < count; i++ ) {
final CellLayout layout = (CellLayout) getChildAt( i );
layout.setChildrenDrawnWithCacheEnabled( false );
layout.setChildrenDrawingCacheEnabled( false );
}
}
public void setCacheEnabled( boolean value ) {
mCacheEnabled = value;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent ev ) {
final int action = ev.getAction();
if ( !isEnabled() ) {
if ( !mScroller.isFinished() ) {
mScroller.abortAnimation();
}
snapToScreen( mCurrentScreen );
return false; // We don't want the events. Let them fall through to the all apps view.
}
acquireVelocityTrackerAndAddMovement( ev );
switch ( action & MotionEvent.ACTION_MASK ) {
case MotionEvent.ACTION_DOWN:
/*
* If being flinged and user touches, stop the fling. isFinished will be false if being flinged.
*/
if ( !mScroller.isFinished() ) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mLastMotionX = ev.getX();
mLastMotionX2 = ev.getX();
mActivePointerId = ev.getPointerId( 0 );
if ( mTouchState == TOUCH_STATE_SCROLLING ) {
enableChildrenCache( mCurrentScreen - 1, mCurrentScreen + 1 );
}
break;
case MotionEvent.ACTION_MOVE:
if ( mTouchState == TOUCH_STATE_SCROLLING ) {
// Scroll to follow the motion event
final int pointerIndex = ev.findPointerIndex( mActivePointerId );
final float x = ev.getX( pointerIndex );
final float deltaX = mLastMotionX - x;
final float deltaX2 = mLastMotionX2 - x;
final int mode = mOverScrollMode;
mLastMotionX = x;
// Log.d( "hv", "delta: " + deltaX );
if ( deltaX < 0 ) {
mTouchX += deltaX;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
if ( mTouchX < 0 && mode != OVER_SCROLL_NEVER ) {
mTouchX = mLastMotionX = 0;
// mLastMotionX = x;
if ( mEdgeGlowLeft != null && deltaX2 < 0 ) {
float overscroll = ( (float) -deltaX2 * 1.5f ) / getWidth();
mEdgeGlowLeft.onPull( overscroll );
if ( !mEdgeGlowRight.isFinished() ) {
mEdgeGlowRight.onRelease();
}
}
}
invalidate();
} else if ( deltaX > 0 ) {
final int totalWidth = getScreenScrollPositionX( mItemCount - 1 );
final float availableToScroll = getScreenScrollPositionX( mItemCount ) - mTouchX;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
mTouchX += Math.min( availableToScroll, deltaX );
if ( availableToScroll <= getWidth() && mode != OVER_SCROLL_NEVER ) {
mTouchX = mLastMotionX = totalWidth;
// mLastMotionX = x;
if ( mEdgeGlowLeft != null && deltaX2 > 0 ) {
float overscroll = ( (float) deltaX2 * 1.5f ) / getWidth();
mEdgeGlowRight.onPull( overscroll );
if ( !mEdgeGlowLeft.isFinished() ) {
mEdgeGlowLeft.onRelease();
}
}
}
invalidate();
} else {
awakenScrollBars();
}
}
break;
case MotionEvent.ACTION_UP:
if ( mTouchState == TOUCH_STATE_SCROLLING ) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity( 1000, mMaximumVelocity );
final int velocityX = (int) velocityTracker.getXVelocity( mActivePointerId );
final int screenWidth = getWidth();
final int whichScreen = ( getScrollX() + ( screenWidth / 2 ) ) / screenWidth;
final float scrolledPos = (float) getScrollX() / screenWidth;
if ( velocityX > SNAP_VELOCITY && mCurrentScreen > 0 ) {
// Fling hard enough to move left.
// Don't fling across more than one screen at a time.
final int bound = scrolledPos < whichScreen ? mCurrentScreen - 1 : mCurrentScreen;
snapToScreen( Math.min( whichScreen, bound ), velocityX, true );
} else if ( velocityX < -SNAP_VELOCITY && mCurrentScreen < mItemCount - 1 ) {
// Fling hard enough to move right
// Don't fling across more than one screen at a time.
final int bound = scrolledPos > whichScreen ? mCurrentScreen + 1 : mCurrentScreen;
snapToScreen( Math.max( whichScreen, bound ), velocityX, true );
} else {
snapToScreen( whichScreen, 0, true );
}
if ( mEdgeGlowLeft != null ) {
mEdgeGlowLeft.onRelease();
mEdgeGlowRight.onRelease();
}
}
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
releaseVelocityTracker();
break;
case MotionEvent.ACTION_CANCEL:
if ( mTouchState == TOUCH_STATE_SCROLLING ) {
final int screenWidth = getWidth();
final int whichScreen = ( getScrollX() + ( screenWidth / 2 ) ) / screenWidth;
snapToScreen( whichScreen, 0, true );
}
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
releaseVelocityTracker();
if ( mEdgeGlowLeft != null ) {
mEdgeGlowLeft.onRelease();
mEdgeGlowRight.onRelease();
}
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp( ev );
break;
}
return true;
}
/**
* Acquire velocity tracker and add movement.
*
* @param ev
* the ev
*/
private void acquireVelocityTrackerAndAddMovement( MotionEvent ev ) {
if ( mVelocityTracker == null ) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement( ev );
}
/**
* Release velocity tracker.
*/
private void releaseVelocityTracker() {
if ( mVelocityTracker != null ) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
/**
* Snap to screen.
*
* @param whichScreen
* the which screen
*/
void snapToScreen( int whichScreen ) {
snapToScreen( whichScreen, 0, false );
}
/**
* Snap to screen.
*
* @param whichScreen
* the which screen
* @param velocity
* the velocity
* @param settle
* the settle
*/
private void snapToScreen( int whichScreen, int velocity, boolean settle ) {
whichScreen = Math.max( 0, Math.min( whichScreen, mItemCount - 1 ) );
enableChildrenCache( mCurrentScreen, whichScreen );
mNextScreen = whichScreen;
View focusedChild = getFocusedChild();
if ( focusedChild != null && whichScreen != mCurrentScreen && focusedChild == getChildAt( mCurrentScreen ) ) {
focusedChild.clearFocus();
}
final int screenDelta = Math.max( 1, Math.abs( whichScreen - mCurrentScreen ) );
final int newX = whichScreen * getWidth();
final int delta = newX - getScrollX();
int duration = ( screenDelta + 1 ) * 100;
if ( !mScroller.isFinished() ) {
mScroller.abortAnimation();
}
/*
if ( mScrollInterpolator instanceof WorkspaceOvershootInterpolator ) {
if ( settle ) {
( (WorkspaceOvershootInterpolator) mScrollInterpolator ).setDistance( screenDelta );
} else {
( (WorkspaceOvershootInterpolator) mScrollInterpolator ).disableSettle();
}
}
*/
velocity = Math.abs( velocity );
if ( velocity > 0 ) {
duration += (duration / (velocity / BASELINE_FLING_VELOCITY)) * FLING_VELOCITY_INFLUENCE;
} else {
duration += 100;
}
mScroller.startScroll( getScrollX(), 0, delta, 0, duration );
int mode = getOverScroll();
if ( delta != 0 && ( mode == OVER_SCROLL_IF_CONTENT_SCROLLS ) ) {
edgeReached( whichScreen, delta, velocity );
}
// postUpdateIndicator( mNextScreen, mItemCount );
invalidate();
}
private void postUpdateIndicator( final int screen, final int count ) {
getHandler().post( new Runnable() {
@Override
public void run() {
if ( mIndicator != null ) mIndicator.setLevel( screen, count );
}
} );
}
/**
* Edge reached.
*
* @param whichscreen
* the whichscreen
* @param delta
* the delta
* @param vel
* the vel
*/
void edgeReached( int whichscreen, int delta, int vel ) {
if ( whichscreen == 0 || whichscreen == ( mItemCount - 1 ) ) {
if ( delta < 0 ) {
mEdgeGlowLeft.onAbsorb( vel );
} else {
mEdgeGlowRight.onAbsorb( vel );
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSaveInstanceState()
*/
@Override
protected Parcelable onSaveInstanceState() {
final SavedState state = new SavedState( super.onSaveInstanceState() );
state.currentScreen = mCurrentScreen;
return state;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onRestoreInstanceState(android.os.Parcelable)
*/
@Override
protected void onRestoreInstanceState( Parcelable state ) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState( savedState.getSuperState() );
if ( savedState.currentScreen != -1 ) {
mCurrentScreen = savedState.currentScreen;
}
}
/**
* Scroll left.
*/
public void scrollLeft() {
if ( mScroller.isFinished() ) {
if ( mCurrentScreen > 0 ) snapToScreen( mCurrentScreen - 1 );
} else {
if ( mNextScreen > 0 ) snapToScreen( mNextScreen - 1 );
}
}
/**
* Scroll right.
*/
public void scrollRight() {
if ( mScroller.isFinished() ) {
if ( mCurrentScreen < mItemCount - 1 ) snapToScreen( mCurrentScreen + 1 );
} else {
if ( mNextScreen < mItemCount - 1 ) snapToScreen( mNextScreen + 1 );
}
}
/**
* Gets the screen for view.
*
* @param v
* the v
* @return the screen for view
*/
public int getScreenForView( View v ) {
int result = -1;
if ( v != null ) {
ViewParent vp = v.getParent();
int count = mItemCount;
for ( int i = 0; i < count; i++ ) {
if ( vp == getChildAt( i ) ) {
return i;
}
}
}
return result;
}
/**
* Gets the view for tag.
*
* @param tag
* the tag
* @return the view for tag
*/
public View getViewForTag( Object tag ) {
int screenCount = mItemCount;
for ( int screen = 0; screen < screenCount; screen++ ) {
CellLayout currentScreen = ( (CellLayout) getChildAt( screen ) );
int count = currentScreen.getChildCount();
for ( int i = 0; i < count; i++ ) {
View child = currentScreen.getChildAt( i );
if ( child.getTag() == tag ) {
return child;
}
}
}
return null;
}
/**
* Allow long press.
*
* @return True is long presses are still allowed for the current touch
*/
public boolean allowLongPress() {
return mAllowLongPress;
}
/**
* Set true to allow long-press events to be triggered, usually checked by {@link Launcher} to accept or block dpad-initiated
* long-presses.
*
* @param allowLongPress
* the new allow long press
*/
public void setAllowLongPress( boolean allowLongPress ) {
mAllowLongPress = allowLongPress;
}
/**
* Move to default screen.
*
* @param animate
* the animate
*/
void moveToDefaultScreen( boolean animate ) {
if ( animate ) {
snapToScreen( mDefaultScreen );
} else {
setCurrentScreen( mDefaultScreen );
}
getChildAt( mDefaultScreen ).requestFocus();
}
/**
* Sets the indicator.
*
* @param indicator
* the new indicator
*/
public void setIndicator( WorkspaceIndicator indicator ) {
mIndicator = indicator;
mIndicator.setLevel( mCurrentScreen, mItemCount );
}
/**
* The Class SavedState.
*/
public static class SavedState extends BaseSavedState {
/** The current screen. */
int currentScreen = -1;
/**
* Instantiates a new saved state.
*
* @param superState
* the super state
*/
SavedState( Parcelable superState ) {
super( superState );
}
/**
* Instantiates a new saved state.
*
* @param in
* the in
*/
private SavedState( Parcel in ) {
super( in );
currentScreen = in.readInt();
}
/*
* (non-Javadoc)
*
* @see android.view.AbsSavedState#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel( Parcel out, int flags ) {
super.writeToParcel( out, flags );
out.writeInt( currentScreen );
}
/** The Constant CREATOR. */
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel( Parcel in ) {
return new SavedState( in );
}
@Override
public SavedState[] newArray( int size ) {
return new SavedState[size];
}
};
}
/**
* An asynchronous update interface for receiving notifications about WorkspaceDataSet information as the WorkspaceDataSet is
* constructed.
*/
class WorkspaceDataSetObserver extends DataSetObserver {
/*
* (non-Javadoc)
*
* @see android.database.DataSetObserver#onChanged()
*/
@Override
public void onChanged() {
super.onChanged();
}
/*
* (non-Javadoc)
*
* @see android.database.DataSetObserver#onInvalidated()
*/
@Override
public void onInvalidated() {
super.onInvalidated();
}
}
/**
* The Class RecycleBin.
*/
class RecycleBin {
/** The array. */
protected View[][] array;
/** The start. */
protected int start[];
/** The end. */
protected int end[];
/** The max size. */
protected int maxSize;
/** The full. */
protected boolean full[];
/**
* Instantiates a new recycle bin.
*
* @param typeCount
* the type count
* @param size
* the size
*/
public RecycleBin( int typeCount, int size ) {
maxSize = size;
array = new View[typeCount][size];
start = new int[typeCount];
end = new int[typeCount];
full = new boolean[typeCount];
}
/**
* Checks if is empty.
*
* @param type
* the type
* @return true, if is empty
*/
public boolean isEmpty( int type ) {
return ( ( start[type] == end[type] ) && !full[type] );
}
/**
* Adds the.
*
* @param type
* the type
* @param o
* the o
*/
public void add( int type, View o ) {
if ( !full[type] ) array[type][start[type] = ( ++start[type] % array[type].length )] = o;
if ( start[type] == end[type] ) full[type] = true;
}
/**
* Removes the.
*
* @param type
* the type
* @return the view
*/
public View remove( int type ) {
if ( full[type] ) {
full[type] = false;
} else if ( isEmpty( type ) ) return null;
return array[type][end[type] = ( ++end[type] % array[type].length )];
}
/**
* Clear.
*/
void clear() {
int typeCount = array.length;
for ( int i = 0; i < typeCount; i++ ) {
while ( !isEmpty( i ) ) {
final View view = remove( i );
if ( view != null ) {
removeDetachedView( view, true );
}
}
}
array = new View[typeCount][maxSize];
start = new int[typeCount];
end = new int[typeCount];
full = new boolean[typeCount];
}
}
/**
* Gets the screen at.
*
* @param screen
* the screen
* @return the screen at
*/
public View getScreenAt( int screen ) {
return getChildAt( mCurrentScreen - mFirstPosition );
}
}
| Java |
/*
* 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.aviary.android.feather.widget.wp;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
// TODO: Auto-generated Javadoc
/**
* The Class CellLayout.
*/
public class CellLayout extends ViewGroup {
/** The m cell width. */
private int mCellWidth;
/** The m cell height. */
private int mCellHeight;
/** The m start padding. */
private int mStartPadding;
/** The m end padding. */
private int mEndPadding;
/** The m top padding. */
private int mTopPadding;
/** The m bottom padding. */
private int mBottomPadding;
/** The m axis rows. */
private int mAxisRows;
/** The m axis cells. */
private int mAxisCells;
/** The m width gap. */
private int mWidthGap;
/** The m height gap. */
private int mHeightGap;
/** The m cell padding h. */
private int mCellPaddingH;
/** The m cell padding v. */
private int mCellPaddingV;
/** The m cell info. */
public final CellInfo mCellInfo = new CellInfo();
/** The m cell xy. */
int[] mCellXY = new int[2];
/** The m occupied. */
boolean[][] mOccupied;
/** The m last down on occupied cell. */
private boolean mLastDownOnOccupiedCell = false;
/** The logger. */
@SuppressWarnings("unused")
private static Logger logger;
/**
* Instantiates a new cell layout.
*
* @param context
* the context
*/
public CellLayout( Context context ) {
this( context, null );
}
/**
* Instantiates a new cell layout.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public CellLayout( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
/**
* Instantiates a new cell layout.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public CellLayout( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
logger = LoggerFactory.getLogger( "CellLayout", LoggerType.ConsoleLoggerType );
TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.CellLayout, defStyle, 0 );
mCellPaddingH = a.getDimensionPixelSize( R.styleable.CellLayout_horizontalPadding, 0 );
mCellPaddingV = a.getDimensionPixelSize( R.styleable.CellLayout_horizontalPadding, 0 );
mStartPadding = a.getDimensionPixelSize( R.styleable.CellLayout_startPadding, 0 );
mEndPadding = a.getDimensionPixelSize( R.styleable.CellLayout_endPadding, 0 );
mTopPadding = a.getDimensionPixelSize( R.styleable.CellLayout_topPadding, 0 );
mBottomPadding = a.getDimensionPixelSize( R.styleable.CellLayout_bottomPadding, 0 );
// logger.log( "padding", mStartPadding, mEndPadding, mTopPadding, mBottomPadding );
mAxisCells = a.getInt( R.styleable.CellLayout_cells, 4 );
mAxisRows = a.getInt( R.styleable.CellLayout_rows, 1 );
a.recycle();
//setAlwaysDrawnWithCacheEnabled( false );
resetCells();
}
/**
* Reset cells.
*/
private void resetCells() {
mOccupied = new boolean[mAxisCells][mAxisRows];
}
/**
* Sets the num cols.
*
* @param value
* the new num cols
*/
public void setNumCols( int value ) {
if ( mAxisCells != value ) {
mAxisCells = value;
resetCells();
}
}
/**
* Sets the num rows.
*
* @param value
* the new num rows
*/
public void setNumRows( int value ) {
if ( value != mAxisRows ) {
mAxisRows = value;
resetCells();
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#removeAllViews()
*/
@Override
public void removeAllViews() {
super.removeAllViews();
mOccupied = new boolean[mAxisCells][mAxisRows];
}
/*
* (non-Javadoc)
*
* @see android.view.View#cancelLongPress()
*/
@Override
public void cancelLongPress() {
super.cancelLongPress();
// Cancel long press for all children
final int count = getChildCount();
for ( int i = 0; i < count; i++ ) {
final View child = getChildAt( i );
child.cancelLongPress();
}
}
/**
* Gets the count x.
*
* @return the count x
*/
int getCountX() {
return mAxisCells;
}
/**
* Gets the count y.
*
* @return the count y
*/
int getCountY() {
return mAxisRows;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#addView(android.view.View, int, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView( View child, int index, ViewGroup.LayoutParams params ) {
final LayoutParams cellParams = (LayoutParams) params;
// logger.info( "addView: (cellX=" + cellParams.cellX + ", cellY=" + cellParams.cellY + ", spanH=" + cellParams.cellHSpan +
// ", spanV=" + cellParams.cellVSpan + ")" );
cellParams.regenerateId = true;
mOccupied[cellParams.cellX][cellParams.cellY] = true;
super.addView( child, index, params );
}
/**
* Find vacant cell.
*
* @return the cell info
*/
public CellInfo findVacantCell() {
return findVacantCell( 1, 1 );
}
/**
* Find vacant cell.
*
* @param spanH
* the span h
* @param spanV
* the span v
* @return the cell info
*/
public CellInfo findVacantCell( int spanH, int spanV ) {
if ( spanH > mAxisCells ) {
return null;
}
if ( spanV > mAxisRows ) {
return null;
}
for ( int x = 0; x < mOccupied.length; x++ ) {
for ( int y = 0; y < mOccupied[x].length; y++ ) {
if ( findVacantCell( x, y, spanH, spanV ) ) {
CellInfo info = new CellInfo();
info.cellX = x;
info.cellY = y;
info.spanH = spanH;
info.spanV = spanV;
info.screen = mCellInfo.screen;
return info;
}
}
}
return null;
}
/**
* Find vacant cell.
*
* @param x
* the x
* @param y
* the y
* @param spanH
* the span h
* @param spanV
* the span v
* @return true, if successful
*/
private boolean findVacantCell( int x, int y, int spanH, int spanV ) {
if ( x < mOccupied.length ) {
if ( y < mOccupied[x].length ) {
if ( !mOccupied[x][y] ) {
boolean result = true;
if ( spanH > 1 ) {
result = findVacantCell( x + 1, y, spanH - 1, 1 );
} else {
result = true;
}
if ( spanV > 1 ) {
result &= findVacantCell( x, y + 1, 1, spanV - 1 );
} else {
result &= true;
}
if ( result ) return true;
}
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#requestChildFocus(android.view.View, android.view.View)
*/
@Override
public void requestChildFocus( View child, View focused ) {
super.requestChildFocus( child, focused );
if ( child != null ) {
Rect r = new Rect();
child.getDrawingRect( r );
requestRectangleOnScreen( r );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onAttachedToWindow()
*/
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mCellInfo.screen = ( (ViewGroup) getParent() ).indexOfChild( this );
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#requestFocus(int, android.graphics.Rect)
*/
@Override
public boolean requestFocus( int direction, Rect previouslyFocusedRect ) {
return super.requestFocus( direction, previouslyFocusedRect );
}
/*
* (non-Javadoc)
*
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
return true;
}
/**
* Given a point, return the cell that strictly encloses that point.
*
* @param x
* X coordinate of the point
* @param y
* Y coordinate of the point
* @param result
* Array of 2 ints to hold the x and y coordinate of the cell
*/
void pointToCellExact( int x, int y, int[] result ) {
final int hStartPadding = mStartPadding;
final int vStartPadding = mTopPadding;
result[0] = ( x - hStartPadding ) / ( mCellWidth + mWidthGap );
result[1] = ( y - vStartPadding ) / ( mCellHeight + mHeightGap );
final int xAxis = mAxisCells;
final int yAxis = mAxisRows;
if ( result[0] < 0 ) result[0] = 0;
if ( result[0] >= xAxis ) result[0] = xAxis - 1;
if ( result[1] < 0 ) result[1] = 0;
if ( result[1] >= yAxis ) result[1] = yAxis - 1;
}
/**
* Given a point, return the cell that most closely encloses that point.
*
* @param x
* X coordinate of the point
* @param y
* Y coordinate of the point
* @param result
* Array of 2 ints to hold the x and y coordinate of the cell
*/
void pointToCellRounded( int x, int y, int[] result ) {
pointToCellExact( x + ( mCellWidth / 2 ), y + ( mCellHeight / 2 ), result );
}
/**
* Given a cell coordinate, return the point that represents the upper left corner of that cell.
*
* @param cellX
* X coordinate of the cell
* @param cellY
* Y coordinate of the cell
* @param result
* Array of 2 ints to hold the x and y coordinate of the point
*/
void cellToPoint( int cellX, int cellY, int[] result ) {
final int hStartPadding = mStartPadding;
final int vStartPadding = mTopPadding;
result[0] = hStartPadding + cellX * ( mCellWidth + mWidthGap );
result[1] = vStartPadding + cellY * ( mCellHeight + mHeightGap );
}
/**
* Gets the cell width.
*
* @return the cell width
*/
public int getCellWidth() {
return mCellWidth;
}
/**
* Gets the cell height.
*
* @return the cell height
*/
public int getCellHeight() {
return mCellHeight;
}
/**
* Gets the left padding.
*
* @return the left padding
*/
public int getLeftPadding() {
return mStartPadding;
}
/**
* Gets the top padding.
*
* @return the top padding
*/
public int getTopPadding() {
return mTopPadding;
}
/**
* Gets the right padding.
*
* @return the right padding
*/
public int getRightPadding() {
return mEndPadding;
}
/**
* Gets the bottom padding.
*
* @return the bottom padding
*/
public int getBottomPadding() {
return mBottomPadding;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
int widthSpecMode = MeasureSpec.getMode( widthMeasureSpec );
int width = MeasureSpec.getSize( widthMeasureSpec );
int heightSpecMode = MeasureSpec.getMode( heightMeasureSpec );
int height = MeasureSpec.getSize( heightMeasureSpec );
if ( widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED ) {
throw new RuntimeException( "CellLayout cannot have UNSPECIFIED dimensions" );
}
int numHGaps = mAxisCells - 1;
int numVGaps = mAxisRows - 1;
int totalHGap = numHGaps * mCellPaddingH;
int totalVGap = numVGaps * mCellPaddingV;
int availableWidth = width - ( mStartPadding + mEndPadding );
int availableHeight = height - ( mTopPadding + mBottomPadding );
mCellWidth = ( ( availableWidth - totalHGap ) / mAxisCells );
mCellHeight = ( ( availableHeight - totalVGap ) / mAxisRows );
mHeightGap = 0;
mWidthGap = 0;
int vTotalSpace = availableHeight - ( mCellHeight * mAxisRows );
try {
mHeightGap = vTotalSpace / numVGaps;
} catch ( ArithmeticException e ) {}
int hTotalSpace = availableWidth - ( mCellWidth * mAxisCells );
if ( numHGaps > 0 ) {
mWidthGap = hTotalSpace / numHGaps;
}
int count = getChildCount();
// logger.log( "childCount: " + count );
for ( int i = 0; i < count; i++ ) {
View child = getChildAt( i );
LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.setup( mCellWidth, mCellHeight, mWidthGap, mHeightGap, mStartPadding, mTopPadding );
if ( lp.regenerateId ) {
child.setId( ( ( getId() & 0xFF ) << 16 ) | ( lp.cellX & 0xFF ) << 8 | ( lp.cellY & 0xFF ) );
lp.regenerateId = false;
}
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( lp.width, MeasureSpec.EXACTLY );
int childheightMeasureSpec = MeasureSpec.makeMeasureSpec( lp.height, MeasureSpec.EXACTLY );
child.measure( childWidthMeasureSpec, childheightMeasureSpec );
}
setMeasuredDimension( width, height );
// logger.log( "size: ", width, height );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int l, int t, int r, int b ) {
int count = getChildCount();
for ( int i = 0; i < count; i++ ) {
View child = getChildAt( i );
if ( child.getVisibility() != GONE ) {
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
int childLeft = lp.x;
int childTop = lp.y;
child.layout( childLeft, childTop, childLeft + lp.width, childTop + lp.height );
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#setChildrenDrawingCacheEnabled(boolean)
*/
@Override
public void setChildrenDrawingCacheEnabled( boolean enabled ) {
logger.info( "setChildrenDrawingCacheEnabled: " + enabled );
setDrawingCacheEnabled( enabled );
final int count = getChildCount();
for ( int i = 0; i < count; i++ ) {
final View view = getChildAt( i );
view.setDrawingCacheEnabled( enabled );
view.buildDrawingCache( true );
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#setChildrenDrawnWithCacheEnabled(boolean)
*/
@Override
public void setChildrenDrawnWithCacheEnabled( boolean enabled ) {
super.setChildrenDrawnWithCacheEnabled( enabled );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setEnabled(boolean)
*/
@Override
public void setEnabled( boolean enabled ) {
super.setEnabled( enabled );
for ( int i = 0; i < getChildCount(); i++ ) {
getChildAt( i ).setEnabled( enabled );
}
}
/**
* Computes a bounding rectangle for a range of cells.
*
* @param cellX
* X coordinate of upper left corner expressed as a cell position
* @param cellY
* Y coordinate of upper left corner expressed as a cell position
* @param cellHSpan
* Width in cells
* @param cellVSpan
* Height in cells
* @param dragRect
* Rectnagle into which to put the results
*/
public void cellToRect( int cellX, int cellY, int cellHSpan, int cellVSpan, RectF dragRect ) {
final int cellWidth = mCellWidth;
final int cellHeight = mCellHeight;
final int widthGap = mWidthGap;
final int heightGap = mHeightGap;
final int hStartPadding = mStartPadding;
final int vStartPadding = mTopPadding;
int width = cellHSpan * cellWidth + ( ( cellHSpan - 1 ) * widthGap );
int height = cellVSpan * cellHeight + ( ( cellVSpan - 1 ) * heightGap );
int x = hStartPadding + cellX * ( cellWidth + widthGap );
int y = vStartPadding + cellY * ( cellHeight + heightGap );
dragRect.set( x, y, x + width, y + height );
}
/**
* Find the first vacant cell, if there is one.
*
* @param vacant
* Holds the x and y coordinate of the vacant cell
* @param spanX
* Horizontal cell span.
* @param spanY
* Vertical cell span.
*
* @return True if a vacant cell was found
*/
public boolean getVacantCell( int[] vacant, int spanX, int spanY ) {
final int xCount = mAxisCells;
final int yCount = mAxisRows;
final boolean[][] occupied = mOccupied;
findOccupiedCells( xCount, yCount, occupied, null );
return findVacantCell( vacant, spanX, spanY, xCount, yCount, occupied );
}
/**
* Find vacant cell.
*
* @param vacant
* the vacant
* @param spanX
* the span x
* @param spanY
* the span y
* @param xCount
* the x count
* @param yCount
* the y count
* @param occupied
* the occupied
* @return true, if successful
*/
static boolean findVacantCell( int[] vacant, int spanX, int spanY, int xCount, int yCount, boolean[][] occupied ) {
for ( int x = 0; x < xCount; x++ ) {
for ( int y = 0; y < yCount; y++ ) {
boolean available = !occupied[x][y];
out:
for ( int i = x; i < x + spanX - 1 && x < xCount; i++ ) {
for ( int j = y; j < y + spanY - 1 && y < yCount; j++ ) {
available = available && !occupied[i][j];
if ( !available ) break out;
}
}
if ( available ) {
vacant[0] = x;
vacant[1] = y;
return true;
}
}
}
return false;
}
/**
* Gets the occupied cells.
*
* @return the occupied cells
*/
boolean[] getOccupiedCells() {
final int xCount = mAxisCells;
final int yCount = mAxisRows;
final boolean[][] occupied = mOccupied;
findOccupiedCells( xCount, yCount, occupied, null );
final boolean[] flat = new boolean[xCount * yCount];
for ( int y = 0; y < yCount; y++ ) {
for ( int x = 0; x < xCount; x++ ) {
flat[y * xCount + x] = occupied[x][y];
}
}
return flat;
}
/**
* Find occupied cells.
*
* @param xCount
* the x count
* @param yCount
* the y count
* @param occupied
* the occupied
* @param ignoreView
* the ignore view
*/
private void findOccupiedCells( int xCount, int yCount, boolean[][] occupied, View ignoreView ) {
for ( int x = 0; x < xCount; x++ ) {
for ( int y = 0; y < yCount; y++ ) {
occupied[x][y] = false;
}
}
int count = getChildCount();
for ( int i = 0; i < count; i++ ) {
View child = getChildAt( i );
if ( child.equals( ignoreView ) ) {
continue;
}
LayoutParams lp = (LayoutParams) child.getLayoutParams();
for ( int x = lp.cellX; x < lp.cellX + lp.cellHSpan && x < xCount; x++ ) {
for ( int y = lp.cellY; y < lp.cellY + lp.cellVSpan && y < yCount; y++ ) {
occupied[x][y] = true;
}
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#generateLayoutParams(android.util.AttributeSet)
*/
@Override
public ViewGroup.LayoutParams generateLayoutParams( AttributeSet attrs ) {
return new CellLayout.LayoutParams( getContext(), attrs );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#checkLayoutParams(android.view.ViewGroup.LayoutParams)
*/
@Override
protected boolean checkLayoutParams( ViewGroup.LayoutParams p ) {
return p instanceof CellLayout.LayoutParams;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#generateLayoutParams(android.view.ViewGroup.LayoutParams)
*/
@Override
protected ViewGroup.LayoutParams generateLayoutParams( ViewGroup.LayoutParams p ) {
return new CellLayout.LayoutParams( p );
}
/**
* The Class LayoutParams.
*/
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
/**
* Horizontal location of the item in the grid.
*/
public int cellX;
/**
* Vertical location of the item in the grid.
*/
public int cellY;
/**
* Number of cells spanned horizontally by the item.
*/
public int cellHSpan;
/**
* Number of cells spanned vertically by the item.
*/
public int cellVSpan;
// X coordinate of the view in the layout.
/** The x. */
int x;
// Y coordinate of the view in the layout.
/** The y. */
int y;
/** The regenerate id. */
boolean regenerateId;
/**
* Instantiates a new layout params.
*
* @param c
* the c
* @param attrs
* the attrs
*/
public LayoutParams( Context c, AttributeSet attrs ) {
super( c, attrs );
cellHSpan = 1;
cellVSpan = 1;
cellX = -1;
cellY = -1;
}
/**
* Instantiates a new layout params.
*
* @param source
* the source
*/
public LayoutParams( ViewGroup.LayoutParams source ) {
super( source );
cellHSpan = 1;
cellVSpan = 1;
cellX = -1;
cellY = -1;
}
/**
* Instantiates a new layout params.
*
* @param cellX
* the cell x
* @param cellY
* the cell y
* @param cellHSpan
* the cell h span
* @param cellVSpan
* the cell v span
*/
public LayoutParams( int cellX, int cellY, int cellHSpan, int cellVSpan ) {
super( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT );
this.cellX = cellX;
this.cellY = cellY;
this.cellHSpan = cellHSpan;
this.cellVSpan = cellVSpan;
}
/**
* Setup.
*
* @param cellWidth
* the cell width
* @param cellHeight
* the cell height
* @param widthGap
* the width gap
* @param heightGap
* the height gap
* @param hStartPadding
* the h start padding
* @param vStartPadding
* the v start padding
*/
public void setup( int cellWidth, int cellHeight, int widthGap, int heightGap, int hStartPadding, int vStartPadding ) {
final int myCellHSpan = cellHSpan;
final int myCellVSpan = cellVSpan;
final int myCellX = cellX;
final int myCellY = cellY;
width = myCellHSpan * cellWidth + ( ( myCellHSpan - 1 ) * widthGap ) - leftMargin - rightMargin;
height = myCellVSpan * cellHeight + ( ( myCellVSpan - 1 ) * heightGap ) - topMargin - bottomMargin;
x = hStartPadding + myCellX * ( cellWidth + widthGap ) + leftMargin;
y = vStartPadding + myCellY * ( cellHeight + heightGap ) + topMargin;
// logger.info( "setup. position: " + x + "x" + y + ", size: " + width + "x" + height + " gap: " + widthGap + "x" +
// heightGap );
}
}
/**
* The Class CellInfo.
*/
static public final class CellInfo implements ContextMenu.ContextMenuInfo {
/** The cell. */
View cell;
/** The cell x. */
public int cellX;
/** The cell y. */
public int cellY;
/** The span h. */
public int spanH;
/** The span v. */
public int spanV;
/** The screen. */
public int screen;
/** The valid. */
boolean valid;
/** The current. */
final Rect current = new Rect();
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Cell[view=" + ( cell == null ? "null" : cell.getClass() ) + ", x=" + cellX + "]";
}
/**
* Clear vacant cells.
*/
public void clearVacantCells() {
// TODO: implement this method
}
}
/**
* Last down on occupied cell.
*
* @return true, if successful
*/
public boolean lastDownOnOccupiedCell() {
return mLastDownOnOccupiedCell;
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.graphics.Point2D;
import com.aviary.android.feather.library.graphics.drawable.EditableDrawable;
import com.aviary.android.feather.library.graphics.drawable.FeatherDrawable;
// TODO: Auto-generated Javadoc
/**
* The Class DrawableHighlightView.
*/
public class DrawableHighlightView {
static final String LOG_TAG = "drawable-view";
/**
* The Enum Mode.
*/
enum Mode {
/** The None. */
None,
/** The Move. */
Move,
/** The Grow. */
Grow,
/** The Rotate. */
Rotate
};
/**
* The Enum AlignModeV.
*/
public enum AlignModeV {
/** The Top. */
Top,
/** The Bottom. */
Bottom,
/** The Center. */
Center
};
/**
* The listener interface for receiving onDeleteClick events. The class that is interested in processing a onDeleteClick event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnDeleteClickListener<code> method. When
* the onDeleteClick event occurs, that object's appropriate
* method is invoked.
*
* @see OnDeleteClickEvent
*/
public interface OnDeleteClickListener {
/**
* On delete click.
*/
void onDeleteClick();
}
private int STATE_NONE = 1 << 0;
private int STATE_SELECTED = 1 << 1;
private int STATE_FOCUSED = 1 << 2;
/** The m delete click listener. */
private OnDeleteClickListener mDeleteClickListener;
/** The Constant GROW_NONE. */
static final int GROW_NONE = 1 << 0; // 1
/** The Constant GROW_LEFT_EDGE. */
static final int GROW_LEFT_EDGE = 1 << 1; // 2
/** The Constant GROW_RIGHT_EDGE. */
static final int GROW_RIGHT_EDGE = 1 << 2; // 4
/** The Constant GROW_TOP_EDGE. */
static final int GROW_TOP_EDGE = 1 << 3; // 8
/** The Constant GROW_BOTTOM_EDGE. */
static final int GROW_BOTTOM_EDGE = 1 << 4; // 16
/** The Constant ROTATE. */
static final int ROTATE = 1 << 5; // 32
/** The Constant MOVE. */
static final int MOVE = 1 << 6; // 64
// tolerance for buttons hits
/** The Constant HIT_TOLERANCE. */
private static final float HIT_TOLERANCE = 40f;
/** The m hidden. */
private boolean mHidden;
/** The m context. */
private View mContext;
/** The m mode. */
private Mode mMode;
private int mState = STATE_NONE;
/** The m draw rect. */
private RectF mDrawRect;
/** The m crop rect. */
private RectF mCropRect;
/** The m matrix. */
private Matrix mMatrix;
/** The m content. */
private final FeatherDrawable mContent;
private final EditableDrawable mEditableContent;
// private Drawable mAnchorResize;
/** The m anchor rotate. */
private Drawable mAnchorRotate;
/** The m anchor delete. */
private Drawable mAnchorDelete;
/** The m anchor width. */
private int mAnchorWidth;
/** The m anchor height. */
private int mAnchorHeight;
/** The m outline stroke color. */
private int mOutlineStrokeColorNormal;
/** The m outline stroke color pressed. */
private int mOutlineStrokeColorPressed;
private int mOutlineStrokeColorUnselected;
/** The m rotate and scale. */
private boolean mRotateAndScale;
/** The m show delete button. */
private boolean mShowDeleteButton = true;
/** The m rotation. */
private float mRotation = 0;
/** The m ratio. */
private float mRatio = 1f;
/** The m rotate matrix. */
private Matrix mRotateMatrix = new Matrix();
/** The fpoints. */
private final float fpoints[] = new float[] { 0, 0 };
/** The m draw outline stroke. */
private boolean mDrawOutlineStroke = true;
/** The m draw outline fill. */
private boolean mDrawOutlineFill = true;
/** The m outline stroke paint. */
private Paint mOutlineStrokePaint;
/** The m outline fill paint. */
private Paint mOutlineFillPaint;
/** The m outline fill color normal. */
private int mOutlineFillColorNormal = 0x66000000;
/** The m outline fill color pressed. */
private int mOutlineFillColorPressed = 0x66a5a5a5;
private int mOutlineFillColorUnselected = 0;
private int mOutlineFillColorFocused = 0x88FFFFFF;
private int mOutlineStrokeColorFocused = 0x51000000;
/** The m outline ellipse. */
private int mOutlineEllipse = 0;
/** The m padding. */
private int mPadding = 0;
/** The m show anchors. */
private boolean mShowAnchors = true;
/** The m align vertical mode. */
private AlignModeV mAlignVerticalMode = AlignModeV.Center;
/**
* Instantiates a new drawable highlight view.
*
* @param ctx
* the ctx
* @param content
* the content
*/
public DrawableHighlightView( final View ctx, final FeatherDrawable content ) {
mContext = ctx;
mContent = content;
if( content instanceof EditableDrawable ){
mEditableContent = (EditableDrawable)content;
} else {
mEditableContent = null;
}
updateRatio();
setMinSize( 20f );
}
/**
* Sets the align mode v.
*
* @param mode
* the new align mode v
*/
public void setAlignModeV( AlignModeV mode ) {
mAlignVerticalMode = mode;
}
/**
* Request a layout update.
*
* @return the rect f
*/
protected RectF computeLayout() {
return getDisplayRect( mMatrix, mCropRect );
}
/**
* Dispose.
*/
public void dispose() {
mContext = null;
mDeleteClickListener = null;
}
/** The m outline path. */
private Path mOutlinePath = new Path();
// private FontMetrics metrics = new FontMetrics();
/**
* Draw.
*
* @param canvas
* the canvas
*/
protected void draw( final Canvas canvas ) {
if ( mHidden ) return;
RectF drawRectF = new RectF( mDrawRect );
drawRectF.inset( -mPadding, -mPadding );
final int saveCount = canvas.save();
canvas.concat( mRotateMatrix );
final Rect viewDrawingRect = new Rect();
mContext.getDrawingRect( viewDrawingRect );
mOutlinePath.reset();
mOutlinePath.addRoundRect( drawRectF, mOutlineEllipse, mOutlineEllipse, Path.Direction.CW );
if ( mDrawOutlineFill ) {
canvas.drawPath( mOutlinePath, mOutlineFillPaint );
}
if ( mDrawOutlineStroke ) {
canvas.drawPath( mOutlinePath, mOutlineStrokePaint );
}
boolean is_selected = getSelected();
boolean is_focused = getFocused();
if ( mEditableContent != null )
mEditableContent.setBounds( mDrawRect.left, mDrawRect.top, mDrawRect.right, mDrawRect.bottom );
else
mContent.setBounds( (int) mDrawRect.left, (int) mDrawRect.top, (int) mDrawRect.right, (int) mDrawRect.bottom );
mContent.draw( canvas );
if ( is_selected && !is_focused ) {
if ( mShowAnchors ) {
final int left = (int) ( drawRectF.left );
final int right = (int) ( drawRectF.right );
final int top = (int) ( drawRectF.top );
final int bottom = (int) ( drawRectF.bottom );
if ( mAnchorRotate != null ) {
mAnchorRotate.setBounds( right - mAnchorWidth, bottom - mAnchorHeight, right + mAnchorWidth, bottom + mAnchorHeight );
mAnchorRotate.draw( canvas );
}
if ( ( mAnchorDelete != null ) && mShowDeleteButton ) {
mAnchorDelete.setBounds( left - mAnchorWidth, top - mAnchorHeight, left + mAnchorWidth, top + mAnchorHeight );
mAnchorDelete.draw( canvas );
}
}
}
canvas.restoreToCount( saveCount );
if ( mEditableContent != null && is_selected ) {
if ( mEditableContent.isEditing() ) {
mContext.postInvalidateDelayed( 300 );
}
}
}
/**
* Show anchors.
*
* @param value
* the value
*/
public void showAnchors( boolean value ) {
mShowAnchors = value;
}
/**
* Draw.
*
* @param canvas
* the canvas
* @param source
* the source
*/
public void draw( final Canvas canvas, final Matrix source ) {
final Matrix matrix = new Matrix( source );
matrix.invert( matrix );
final int saveCount = canvas.save();
canvas.concat( matrix );
canvas.concat( mRotateMatrix );
mContent.setBounds( (int) mDrawRect.left, (int) mDrawRect.top, (int) mDrawRect.right, (int) mDrawRect.bottom );
mContent.draw( canvas );
canvas.restoreToCount( saveCount );
}
/**
* Returns the cropping rectangle in image space.
*
* @return the crop rect
*/
public Rect getCropRect() {
return new Rect( (int) mCropRect.left, (int) mCropRect.top, (int) mCropRect.right, (int) mCropRect.bottom );
}
/**
* Gets the crop rect f.
*
* @return the crop rect f
*/
public RectF getCropRectF() {
return mCropRect;
}
/**
* Gets the crop rotation matrix.
*
* @return the crop rotation matrix
*/
public Matrix getCropRotationMatrix() {
final Matrix m = new Matrix();
m.postTranslate( -mCropRect.centerX(), -mCropRect.centerY() );
m.postRotate( mRotation );
m.postTranslate( mCropRect.centerX(), mCropRect.centerY() );
return m;
}
/**
* Gets the display rect.
*
* @param m
* the m
* @param supportRect
* the support rect
* @return the display rect
*/
protected RectF getDisplayRect( final Matrix m, final RectF supportRect ) {
final RectF r = new RectF( supportRect );
m.mapRect( r );
return r;
}
/**
* Gets the display rect f.
*
* @return the display rect f
*/
public RectF getDisplayRectF() {
final RectF r = new RectF( mDrawRect );
mRotateMatrix.mapRect( r );
return r;
}
/**
* Gets the draw rect.
*
* @return the draw rect
*/
public RectF getDrawRect() {
return mDrawRect;
}
/**
* Gets the hit.
*
* @param x
* the x
* @param y
* the y
* @return the hit
*/
public int getHit( float x, float y ) {
final RectF rect = new RectF( mDrawRect );
rect.inset( -mPadding, -mPadding );
final float pts[] = new float[] { x, y };
final Matrix rotateMatrix = new Matrix();
rotateMatrix.postTranslate( -rect.centerX(), -rect.centerY() );
rotateMatrix.postRotate( -mRotation );
rotateMatrix.postTranslate( rect.centerX(), rect.centerY() );
rotateMatrix.mapPoints( pts );
x = pts[0];
y = pts[1];
mContext.invalidate();
int retval = DrawableHighlightView.GROW_NONE;
final boolean verticalCheck = ( y >= ( rect.top - DrawableHighlightView.HIT_TOLERANCE ) )
&& ( y < ( rect.bottom + DrawableHighlightView.HIT_TOLERANCE ) );
final boolean horizCheck = ( x >= ( rect.left - DrawableHighlightView.HIT_TOLERANCE ) )
&& ( x < ( rect.right + DrawableHighlightView.HIT_TOLERANCE ) );
// if horizontal and vertical checks are good then
// at least the move edge is selected
if( verticalCheck && horizCheck ){
retval = DrawableHighlightView.MOVE;
}
if ( !mRotateAndScale ) {
if ( ( Math.abs( rect.left - x ) < DrawableHighlightView.HIT_TOLERANCE ) && verticalCheck )
retval |= DrawableHighlightView.GROW_LEFT_EDGE;
if ( ( Math.abs( rect.right - x ) < DrawableHighlightView.HIT_TOLERANCE ) && verticalCheck )
retval |= DrawableHighlightView.GROW_RIGHT_EDGE;
if ( ( Math.abs( rect.top - y ) < DrawableHighlightView.HIT_TOLERANCE ) && horizCheck )
retval |= DrawableHighlightView.GROW_TOP_EDGE;
if ( ( Math.abs( rect.bottom - y ) < DrawableHighlightView.HIT_TOLERANCE ) && horizCheck )
retval |= DrawableHighlightView.GROW_BOTTOM_EDGE;
}
if ( ( Math.abs( rect.right - x ) < DrawableHighlightView.HIT_TOLERANCE )
&& ( Math.abs( rect.bottom - y ) < DrawableHighlightView.HIT_TOLERANCE ) && verticalCheck && horizCheck )
retval = DrawableHighlightView.ROTATE;
if ( ( retval == DrawableHighlightView.GROW_NONE ) && rect.contains( (int) x, (int) y ) )
retval = DrawableHighlightView.MOVE;
return retval;
}
/**
* On single tap confirmed.
*
* @param x
* the x
* @param y
* the y
*/
public void onSingleTapConfirmed( float x, float y ) {
final RectF rect = new RectF( mDrawRect );
rect.inset( -mPadding, -mPadding );
final float pts[] = new float[] { x, y };
final Matrix rotateMatrix = new Matrix();
rotateMatrix.postTranslate( -rect.centerX(), -rect.centerY() );
rotateMatrix.postRotate( -mRotation );
rotateMatrix.postTranslate( rect.centerX(), rect.centerY() );
rotateMatrix.mapPoints( pts );
x = pts[0];
y = pts[1];
mContext.invalidate();
final boolean verticalCheck = ( y >= ( rect.top - DrawableHighlightView.HIT_TOLERANCE ) )
&& ( y < ( rect.bottom + DrawableHighlightView.HIT_TOLERANCE ) );
final boolean horizCheck = ( x >= ( rect.left - DrawableHighlightView.HIT_TOLERANCE ) )
&& ( x < ( rect.right + DrawableHighlightView.HIT_TOLERANCE ) );
if ( mShowDeleteButton )
if ( ( Math.abs( rect.left - x ) < DrawableHighlightView.HIT_TOLERANCE )
&& ( Math.abs( rect.top - y ) < DrawableHighlightView.HIT_TOLERANCE ) && verticalCheck && horizCheck )
if ( mDeleteClickListener != null ) {
mDeleteClickListener.onDeleteClick();
}
}
/**
* Gets the invalidation rect.
*
* @return the invalidation rect
*/
protected Rect getInvalidationRect() {
final RectF r = new RectF( mDrawRect );
r.inset( -mPadding, -mPadding );
mRotateMatrix.mapRect( r );
final Rect rect = new Rect( (int) r.left, (int) r.top, (int) r.right, (int) r.bottom );
rect.inset( -mAnchorWidth * 2, -mAnchorHeight * 2 );
return rect;
}
/**
* Gets the matrix.
*
* @return the matrix
*/
public Matrix getMatrix() {
return mMatrix;
}
/**
* Gets the mode.
*
* @return the mode
*/
public Mode getMode() {
return mMode;
}
/**
* Gets the rotation.
*
* @return the rotation
*/
public float getRotation() {
return mRotation;
}
public Matrix getRotationMatrix() {
return mRotateMatrix;
}
/**
* Increase the size of the View.
*
* @param dx
* the dx
*/
protected void growBy( final float dx ) {
growBy( dx, dx / mRatio, true );
}
/**
* Increase the size of the View.
*
* @param dx
* the dx
* @param dy
* the dy
* @param checkMinSize
* the check min size
*/
protected void growBy( final float dx, final float dy, boolean checkMinSize ) {
final RectF r = new RectF( mCropRect );
if ( mAlignVerticalMode == AlignModeV.Center ) {
r.inset( -dx, -dy );
} else if ( mAlignVerticalMode == AlignModeV.Top ) {
r.inset( -dx, 0 );
r.bottom += dy * 2;
} else {
r.inset( -dx, 0 );
r.top -= dy * 2;
}
RectF testRect = getDisplayRect( mMatrix, r );
Log.d( LOG_TAG, "growBy: " + testRect.width() + "x" + testRect.height() );
if ( !mContent.validateSize( testRect ) && checkMinSize ) {
return;
}
mCropRect.set( r );
invalidate();
mContext.invalidate();
}
/**
* On mouse move.
*
* @param edge
* the edge
* @param event2
* the event2
* @param dx
* the dx
* @param dy
* the dy
*/
void onMouseMove( int edge, MotionEvent event2, float dx, float dy ) {
if ( edge == GROW_NONE ) {
return;
}
fpoints[0] = dx;
fpoints[1] = dy;
float xDelta;
@SuppressWarnings("unused")
float yDelta;
if ( edge == MOVE ) {
moveBy( dx * ( mCropRect.width() / mDrawRect.width() ), dy * ( mCropRect.height() / mDrawRect.height() ) );
} else if ( edge == ROTATE ) {
dx = fpoints[0];
dy = fpoints[1];
xDelta = dx * ( mCropRect.width() / mDrawRect.width() );
yDelta = dy * ( mCropRect.height() / mDrawRect.height() );
rotateBy( event2.getX(), event2.getY(), dx, dy );
invalidate();
mContext.invalidate( getInvalidationRect() );
} else {
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate( -mRotation );
rotateMatrix.mapPoints( fpoints );
dx = fpoints[0];
dy = fpoints[1];
if ( ( ( GROW_LEFT_EDGE | GROW_RIGHT_EDGE ) & edge ) == 0 ) dx = 0;
if ( ( ( GROW_TOP_EDGE | GROW_BOTTOM_EDGE ) & edge ) == 0 ) dy = 0;
xDelta = dx * ( mCropRect.width() / mDrawRect.width() );
yDelta = dy * ( mCropRect.height() / mDrawRect.height() );
growBy( ( ( ( edge & GROW_LEFT_EDGE ) != 0 ) ? -1 : 1 ) * xDelta );
invalidate();
mContext.invalidate( getInvalidationRect() );
}
}
void onMove( float dx, float dy ) {
moveBy( dx * ( mCropRect.width() / mDrawRect.width() ), dy * ( mCropRect.height() / mDrawRect.height() ) );
}
/**
* Inits the.
*/
private void init() {
final android.content.res.Resources resources = mContext.getResources();
// mAnchorResize = resources.getDrawable( R.drawable.camera_crop_width );
mAnchorRotate = resources.getDrawable( R.drawable.feather_resize_knob );
mAnchorDelete = resources.getDrawable( R.drawable.feather_highlight_delete_button );
mAnchorWidth = mAnchorRotate.getIntrinsicWidth() / 2;
mAnchorHeight = mAnchorRotate.getIntrinsicHeight() / 2;
mOutlineStrokeColorNormal = mContext.getResources().getColor( R.color.feather_drawable_highlight_focus );
mOutlineStrokeColorPressed = mContext.getResources().getColor( R.color.feather_drawable_highlight_down );
mOutlineStrokeColorUnselected = 0;
mOutlineStrokePaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mOutlineStrokePaint.setStrokeWidth( 2.0f );
mOutlineStrokePaint.setStyle( Paint.Style.STROKE );
mOutlineStrokePaint.setColor( mOutlineStrokeColorNormal );
mOutlineFillPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mOutlineFillPaint.setStyle( Paint.Style.FILL );
mOutlineFillPaint.setColor( mOutlineFillColorNormal );
setMode( Mode.None );
}
/**
* Invalidate.
*/
public void invalidate() {
mDrawRect = computeLayout(); // true
mRotateMatrix.reset();
mRotateMatrix.postTranslate( -mDrawRect.centerX(), -mDrawRect.centerY() );
mRotateMatrix.postRotate( mRotation );
mRotateMatrix.postTranslate( mDrawRect.centerX(), mDrawRect.centerY() );
}
/**
* Move by.
*
* @param dx
* the dx
* @param dy
* the dy
*/
void moveBy( final float dx, final float dy ) {
mCropRect.offset( dx, dy );
invalidate();
mContext.invalidate();
}
/**
* Rotate by.
*
* @param dx
* the dx
* @param dy
* the dy
* @param diffx
* the diffx
* @param diffy
* the diffy
*/
void rotateBy( final float dx, final float dy, float diffx, float diffy ) {
final float pt1[] = new float[] { mDrawRect.centerX(), mDrawRect.centerY() };
final float pt2[] = new float[] { mDrawRect.right, mDrawRect.bottom };
final float pt3[] = new float[] { dx, dy };
final double angle1 = Point2D.angleBetweenPoints( pt2, pt1 );
final double angle2 = Point2D.angleBetweenPoints( pt3, pt1 );
if ( !mRotateAndScale ) mRotation = -(float) ( angle2 - angle1 );
final Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate( -mRotation );
if ( mRotateAndScale ) {
final float points[] = new float[] { diffx, diffy };
rotateMatrix.mapPoints( points );
diffx = points[0];
diffy = points[1];
final float xDelta = diffx * ( mCropRect.width() / mDrawRect.width() );
final float yDelta = diffy * ( mCropRect.height() / mDrawRect.height() );
final float pt4[] = new float[] { mDrawRect.right + xDelta, mDrawRect.bottom + yDelta };
final double distance1 = Point2D.distance( pt1, pt2 );
final double distance2 = Point2D.distance( pt1, pt4 );
final float distance = (float) ( distance2 - distance1 );
// float ratio = mDrawRect.width() / mDrawRect.height();
mRotation = -(float) ( angle2 - angle1 );
growBy( distance );
}
}
void onRotateAndGrow( double angle, float scaleFactor ) {
if ( !mRotateAndScale ) mRotation -= (float) ( angle );
if ( mRotateAndScale ) {
mRotation -= (float) ( angle );
growBy( scaleFactor * ( mCropRect.width() / mDrawRect.width() ) );
}
invalidate();
mContext.invalidate( getInvalidationRect() );
}
/**
* Toggle visibility to the current View.
*
* @param hidden
* the new hidden
*/
public void setHidden( final boolean hidden ) {
mHidden = hidden;
}
/**
* Sets the min size.
*
* @param size
* the new min size
*/
public void setMinSize( final float size ) {
if ( mRatio >= 1 ) {
mContent.setMinSize( size, size / mRatio );
} else {
mContent.setMinSize( size * mRatio, size );
}
}
/**
* Sets the mode.
*
* @param mode
* the new mode
*/
public void setMode( final Mode mode ) {
if ( mode != mMode ) {
mMode = mode;
invalidateColors();
mContext.invalidate();
}
}
protected void invalidateColors() {
boolean is_selected = getSelected();
boolean is_focused = getFocused();
if( is_selected ){
if( mMode == Mode.None ){
if( is_focused ){
mOutlineFillPaint.setColor( mOutlineFillColorFocused );
mOutlineStrokePaint.setColor( mOutlineStrokeColorFocused );
} else {
mOutlineFillPaint.setColor( mOutlineFillColorNormal );
mOutlineStrokePaint.setColor( mOutlineStrokeColorNormal );
}
} else {
mOutlineFillPaint.setColor( mOutlineFillColorPressed );
mOutlineStrokePaint.setColor( mOutlineStrokeColorPressed );
}
} else {
mOutlineFillPaint.setColor( mOutlineFillColorUnselected );
mOutlineStrokePaint.setColor( mOutlineStrokeColorUnselected );
}
}
/**
* Sets the on delete click listener.
*
* @param listener
* the new on delete click listener
*/
public void setOnDeleteClickListener( final OnDeleteClickListener listener ) {
mDeleteClickListener = listener;
}
/**
* Sets the rotate and scale.
*
* @param value
* the new rotate and scale
*/
public void setRotateAndScale( final boolean value ) {
mRotateAndScale = value;
}
/**
* Show delete.
*
* @param value
* the value
*/
public void showDelete( boolean value ) {
mShowDeleteButton = value;
}
/**
* Sets the selected.
*
* @param selected
* the new selected
*/
public void setSelected( final boolean selected ) {
boolean is_selected = getSelected();
if ( is_selected != selected ) {
mState ^= STATE_SELECTED;
invalidateColors();
}
mContext.invalidate();
}
public boolean getSelected() {
return ( mState & STATE_SELECTED ) == STATE_SELECTED;
}
public void setFocused( final boolean value ) {
boolean is_focused = getFocused();
if ( is_focused != value ) {
mState ^= STATE_FOCUSED;
if( null != mEditableContent ){
if( value ){
mEditableContent.beginEdit();
} else {
mEditableContent.endEdit();
}
}
invalidateColors();
}
mContext.invalidate();
}
public boolean getFocused() {
return ( mState & STATE_FOCUSED ) == STATE_FOCUSED;
}
/**
* Setup.
*
* @param m
* the m
* @param imageRect
* the image rect
* @param cropRect
* the crop rect
* @param maintainAspectRatio
* the maintain aspect ratio
*/
public void setup( final Matrix m, final Rect imageRect, final RectF cropRect, final boolean maintainAspectRatio ) {
init();
mMatrix = new Matrix( m );
mRotation = 0;
mRotateMatrix = new Matrix();
mCropRect = cropRect;
invalidate();
}
/**
* Update.
*
* @param imageMatrix
* the image matrix
* @param imageRect
* the image rect
*/
public void update( final Matrix imageMatrix, final Rect imageRect ) {
setMode( Mode.None );
mMatrix = new Matrix( imageMatrix );
mRotation = 0;
mRotateMatrix = new Matrix();
invalidate();
}
/**
* Draw outline stroke.
*
* @param value
* the value
*/
public void drawOutlineStroke( boolean value ) {
mDrawOutlineStroke = value;
}
/**
* Draw outline fill.
*
* @param value
* the value
*/
public void drawOutlineFill( boolean value ) {
mDrawOutlineFill = value;
}
/**
* Gets the outline stroke paint.
*
* @return the outline stroke paint
*/
public Paint getOutlineStrokePaint() {
return mOutlineStrokePaint;
}
/**
* Gets the outline fill paint.
*
* @return the outline fill paint
*/
public Paint getOutlineFillPaint() {
return mOutlineFillPaint;
}
public void setOutlineFillColor( ColorStateList colors ){
mOutlineFillColorNormal = colors.getColorForState( new int[]{ android.R.attr.state_selected }, 0 );
mOutlineFillColorFocused = colors.getColorForState( new int[]{ android.R.attr.state_focused }, 0 );
mOutlineFillColorPressed = colors.getColorForState( new int[]{ android.R.attr.state_pressed }, 0 );
mOutlineFillColorUnselected = colors.getColorForState( new int[]{ android.R.attr.state_active }, 0 );
invalidateColors();
invalidate();
mContext.invalidate();
}
public void setOutlineStrokeColor( ColorStateList colors ){
mOutlineStrokeColorNormal = colors.getColorForState( new int[]{ android.R.attr.state_selected }, 0 );
mOutlineStrokeColorFocused = colors.getColorForState( new int[]{ android.R.attr.state_focused }, 0 );
mOutlineStrokeColorPressed = colors.getColorForState( new int[]{ android.R.attr.state_pressed }, 0 );
mOutlineStrokeColorUnselected = colors.getColorForState( new int[]{ android.R.attr.state_active }, 0 );
invalidateColors();
invalidate();
mContext.invalidate();
}
/**
* Sets the outline ellipse.
*
* @param value
* the new outline ellipse
*/
public void setOutlineEllipse( int value ) {
mOutlineEllipse = value;
invalidate();
mContext.invalidate();
}
/**
* Gets the content.
*
* @return the content
*/
public FeatherDrawable getContent() {
return mContent;
}
/**
* Update ratio.
*/
private void updateRatio() {
final int w = mContent.getIntrinsicWidth();
final int h = mContent.getIntrinsicHeight();
mRatio = (float) w / (float) h;
}
/**
* Force update.
*/
public void forceUpdate() {
Log.i( LOG_TAG, "forceUpdate" );
RectF cropRect = getCropRectF();
RectF drawRect = getDrawRect();
if ( mEditableContent != null ) {
final int textWidth = mContent.getIntrinsicWidth();
final int textHeight = mContent.getIntrinsicHeight();
Log.d( LOG_TAG, "text.size: " + textWidth + "x" + textHeight );
updateRatio();
RectF textRect = new RectF( cropRect );
getMatrix().mapRect( textRect );
float dx = textWidth - textRect.width();
float dy = textHeight - textRect.height();
float[] fpoints = new float[] { dx, dy };
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate( -mRotation );
// rotateMatrix.mapPoints( fpoints );
dx = fpoints[0];
dy = fpoints[1];
float xDelta = dx * ( cropRect.width() / drawRect.width() );
float yDelta = dy * ( cropRect.height() / drawRect.height() );
if ( xDelta != 0 || yDelta != 0 ) {
growBy( xDelta / 2, yDelta / 2, false );
}
invalidate();
mContext.invalidate( getInvalidationRect() );
}
}
/**
* Sets the padding.
*
* @param value
* the new padding
*/
public void setPadding( int value ) {
mPadding = value;
}
}
| Java |
package com.aviary.android.feather.widget;
public interface VibrationWidget {
/**
* Enable the vibration feedback
*
* @param value
*/
public void setVibrationEnabled( boolean value );
/**
* Get the vibration feedback enabled status
*
* @return
*/
public boolean getVibrationEnabled();
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.ToggleButton;
import com.aviary.android.feather.R;
import com.aviary.android.feather.utils.TypefaceUtils;
public class ToggleButtonCustomFont extends ToggleButton {
@SuppressWarnings("unused")
private final String LOG_TAG = "ToggleButtonCustomFont";
public ToggleButtonCustomFont( Context context ) {
super( context );
}
public ToggleButtonCustomFont( Context context, AttributeSet attrs ) {
super( context, attrs );
setCustomFont( context, attrs );
}
public ToggleButtonCustomFont( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
setCustomFont( context, attrs );
}
private void setCustomFont( Context ctx, AttributeSet attrs ) {
TypedArray array = ctx.obtainStyledAttributes( attrs, R.styleable.TextViewCustomFont );
String font = array.getString( R.styleable.TextViewCustomFont_font );
setCustomFont( font );
array.recycle();
}
protected void setCustomFont( String fontname ) {
if ( null != fontname ) {
try {
Typeface font = TypefaceUtils.createFromAsset( getContext().getAssets(), fontname );
setTypeface( font );
} catch ( Throwable t ) {}
}
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable;
// TODO: Auto-generated Javadoc
/**
* The Class ImageViewTouchAndDraw.
*/
public class ImageViewTouchAndDraw extends ImageViewTouch {
/**
* The Enum TouchMode.
*/
public static enum TouchMode {
/** The IMAGE. */
IMAGE,
/** The DRAW. */
DRAW
};
/**
* The listener interface for receiving onDrawStart events. The class that is interested in processing a onDrawStart event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnDrawStartListener<code> method. When
* the onDrawStart event occurs, that object's appropriate
* method is invoked.
*
* @see OnDrawStartEvent
*/
public static interface OnDrawStartListener {
/**
* On draw start.
*/
void onDrawStart();
};
public static interface OnDrawPathListener {
void onStart();
void onMoveTo( float x, float y );
void onLineTo( float x, float y );
void onQuadTo( float x, float y, float x1, float y1 );
void onEnd();
}
/** The m paint. */
protected Paint mPaint;
/** The tmp path. */
protected Path tmpPath = new Path();
/** The m canvas. */
protected Canvas mCanvas;
/** The m touch mode. */
protected TouchMode mTouchMode = TouchMode.DRAW;
/** The m y. */
protected float mX, mY;
/** The m identity matrix. */
protected Matrix mIdentityMatrix = new Matrix();
/** The m inverted matrix. */
protected Matrix mInvertedMatrix = new Matrix();
/** The m copy. */
protected Bitmap mCopy;
/** The Constant TOUCH_TOLERANCE. */
protected static final float TOUCH_TOLERANCE = 4;
/** The m draw listener. */
private OnDrawStartListener mDrawListener;
private OnDrawPathListener mDrawPathListener;
/**
* Instantiates a new image view touch and draw.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public ImageViewTouchAndDraw( Context context, AttributeSet attrs ) {
super( context, attrs );
}
/**
* Sets the on draw start listener.
*
* @param listener
* the new on draw start listener
*/
public void setOnDrawStartListener( OnDrawStartListener listener ) {
mDrawListener = listener;
}
public void setOnDrawPathListener( OnDrawPathListener listener ) {
mDrawPathListener = listener;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#init()
*/
@Override
protected void init() {
super.init();
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mPaint.setDither( true );
mPaint.setFilterBitmap( false );
mPaint.setColor( 0xFFFF0000 );
mPaint.setStyle( Paint.Style.STROKE );
mPaint.setStrokeJoin( Paint.Join.ROUND );
mPaint.setStrokeCap( Paint.Cap.ROUND );
mPaint.setStrokeWidth( 10.0f );
tmpPath = new Path();
}
/**
* Gets the draw mode.
*
* @return the draw mode
*/
public TouchMode getDrawMode() {
return mTouchMode;
}
/**
* Sets the draw mode.
*
* @param mode
* the new draw mode
*/
public void setDrawMode( TouchMode mode ) {
if ( mode != mTouchMode ) {
mTouchMode = mode;
onDrawModeChanged();
}
}
/**
* On draw mode changed.
*/
protected void onDrawModeChanged() {
if ( mTouchMode == TouchMode.DRAW ) {
Matrix m1 = new Matrix( getImageMatrix() );
mInvertedMatrix.reset();
float[] v1 = getMatrixValues( m1 );
m1.invert( m1 );
float[] v2 = getMatrixValues( m1 );
mInvertedMatrix.postTranslate( -v1[Matrix.MTRANS_X], -v1[Matrix.MTRANS_Y] );
mInvertedMatrix.postScale( v2[Matrix.MSCALE_X], v2[Matrix.MSCALE_Y] );
mCanvas.setMatrix( mInvertedMatrix );
}
}
/**
* Gets the paint.
*
* @return the paint
*/
public Paint getPaint() {
return mPaint;
}
/**
* Sets the paint.
*
* @param paint
* the new paint
*/
public void setPaint( Paint paint ) {
mPaint.set( paint );
}
/*
* (non-Javadoc)
*
* @see android.widget.ImageView#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
// canvas.drawPath( tmpPath, mPaint );
if ( mCopy != null ) {
final int saveCount = canvas.getSaveCount();
canvas.save();
canvas.drawBitmap( mCopy, getImageMatrix(), null );
canvas.restoreToCount( saveCount );
}
}
/**
* Commit.
*
* @param canvas
* the canvas
*/
public void commit( Canvas canvas ) {
canvas.drawBitmap( ( (IBitmapDrawable) getDrawable() ).getBitmap(), new Matrix(), null );
canvas.drawBitmap( mCopy, new Matrix(), null );
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onBitmapChanged(android.graphics.drawable.Drawable)
*/
@Override
protected void onBitmapChanged( Drawable drawable ) {
super.onBitmapChanged( drawable );
if ( mCopy != null ) {
mCopy.recycle();
mCopy = null;
}
if ( drawable != null && ( drawable instanceof IBitmapDrawable ) ) {
final Bitmap bitmap = ( (IBitmapDrawable) drawable ).getBitmap();
mCopy = Bitmap.createBitmap( bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888 );
mCanvas = new Canvas( mCopy );
mCanvas.drawColor( 0 );
onDrawModeChanged();
}
}
/**
* Touch_start.
*
* @param x
* the x
* @param y
* the y
*/
private void touch_start( float x, float y ) {
tmpPath.reset();
tmpPath.moveTo( x, y );
mX = x;
mY = y;
if ( mDrawListener != null ) mDrawListener.onDrawStart();
if ( mDrawPathListener != null ) {
mDrawPathListener.onStart();
float[] pts = new float[] { x, y };
mInvertedMatrix.mapPoints( pts );
mDrawPathListener.onMoveTo( pts[0], pts[1] );
}
}
/**
* Touch_move.
*
* @param x
* the x
* @param y
* the y
*/
private void touch_move( float x, float y ) {
float dx = Math.abs( x - mX );
float dy = Math.abs( y - mY );
if ( dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE ) {
float x1 = ( x + mX ) / 2;
float y1 = ( y + mY ) / 2;
tmpPath.quadTo( mX, mY, x1, y1 );
mCanvas.drawPath( tmpPath, mPaint );
tmpPath.reset();
tmpPath.moveTo( x1, y1 );
if ( mDrawPathListener != null ) {
float[] pts = new float[] { mX, mY, x1, y1 };
mInvertedMatrix.mapPoints( pts );
mDrawPathListener.onQuadTo( pts[0], pts[1], pts[2], pts[3] );
}
mX = x;
mY = y;
}
}
/**
* Touch_up.
*/
private void touch_up() {
// mCanvas.drawPath( tmpPath, mPaint );
tmpPath.reset();
if ( mDrawPathListener != null ) {
mDrawPathListener.onEnd();
}
}
/**
* Gets the matrix values.
*
* @param m
* the m
* @return the matrix values
*/
public static float[] getMatrixValues( Matrix m ) {
float[] values = new float[9];
m.getValues( values );
return values;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
if ( mTouchMode == TouchMode.DRAW && event.getPointerCount() == 1 ) {
float x = event.getX();
float y = event.getY();
switch ( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
touch_start( x, y );
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move( x, y );
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
} else {
if ( mTouchMode == TouchMode.IMAGE )
return super.onTouchEvent( event );
else
return false;
}
}
/**
* Gets the overlay bitmap.
*
* @return the overlay bitmap
*/
public Bitmap getOverlayBitmap() {
return mCopy;
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.aviary.android.feather.R;
public class ImageViewWithShadow extends ImageView {
private Drawable mShadowDrawable;
private boolean mShadowEnabled = false;
private int mShadowOffsetX = 10;
private int mShadowOffsetY = 10;
public ImageViewWithShadow( Context context, AttributeSet attrs ) {
super( context, attrs );
init( context, attrs, 0 );
}
private void init( Context context, AttributeSet attrs, int defStyle ) {
TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.ImageViewWithShadow, defStyle, 0 );
mShadowDrawable = a.getDrawable( R.styleable.ImageViewWithShadow_shadowDrawable );
if ( null == mShadowDrawable ) {
mShadowEnabled = false;
} else {
mShadowEnabled = true;
}
mShadowOffsetX = a.getInteger( R.styleable.ImageViewWithShadow_shadowOffsetX, 5 );
mShadowOffsetY = a.getInteger( R.styleable.ImageViewWithShadow_shadowOffsetY, 5 );
a.recycle();
}
public void setShadowEnabled( boolean value ) {
mShadowEnabled = value;
}
@Override
protected void onDraw( Canvas canvas ) {
Drawable drawable = getDrawable();
Matrix matrix = getImageMatrix();
if ( null != drawable && mShadowEnabled ) {
int saveCount = canvas.getSaveCount();
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int dwidth = drawable.getIntrinsicWidth();
int dheight = drawable.getIntrinsicHeight();
mShadowDrawable.setBounds( 0, 0, dwidth + mShadowOffsetX, dheight + mShadowOffsetY );
canvas.save();
canvas.translate( paddingLeft, paddingTop );
if ( null != matrix ) {
// canvas.concat( matrix );
}
mShadowDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
}
super.onDraw( canvas );
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import com.aviary.android.feather.library.services.DragControllerService.DragSource;
import com.aviary.android.feather.library.services.drag.DragView;
import com.aviary.android.feather.library.services.drag.DropTarget;
import com.aviary.android.feather.widget.DrawableHighlightView.Mode;
public class ImageViewDrawableOverlay extends ImageViewTouch implements DropTarget {
/**
* The listener interface for receiving onLayout events. The class that is interested in processing a onLayout event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnLayoutListener<code> method. When
* the onLayout event occurs, that object's appropriate
* method is invoked.
*
* @see OnLayoutEvent
*/
public interface OnLayoutListener {
/**
* On layout changed.
*
* @param changed
* the changed
* @param left
* the left
* @param top
* the top
* @param right
* the right
* @param bottom
* the bottom
*/
void onLayoutChanged( boolean changed, int left, int top, int right, int bottom );
}
/**
* The listener interface for receiving onDrawableEvent events. The class that is interested in processing a onDrawableEvent
* event implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnDrawableEventListener<code> method. When
* the onDrawableEvent event occurs, that object's appropriate
* method is invoked.
*
* @see OnDrawableEventEvent
*/
public static interface OnDrawableEventListener {
/**
* On focus change.
*
* @param newFocus
* the new focus
* @param oldFocus
* the old focus
*/
void onFocusChange( DrawableHighlightView newFocus, DrawableHighlightView oldFocus );
/**
* On down.
*
* @param view
* the view
*/
void onDown( DrawableHighlightView view );
/**
* On move.
*
* @param view
* the view
*/
void onMove( DrawableHighlightView view );
/**
* On click.
*
* @param view
* the view
*/
void onClick( DrawableHighlightView view );
};
/** The m motion edge. */
private int mMotionEdge = DrawableHighlightView.GROW_NONE;
/** The m overlay views. */
private List<DrawableHighlightView> mOverlayViews = new ArrayList<DrawableHighlightView>();
/** The m overlay view. */
private DrawableHighlightView mOverlayView;
/** The m layout listener. */
private OnLayoutListener mLayoutListener;
/** The m drawable listener. */
private OnDrawableEventListener mDrawableListener;
/** The m force single selection. */
private boolean mForceSingleSelection = true;
private DropTargetListener mDropTargetListener;
private Paint mDropPaint;
private Rect mTempRect = new Rect();
private boolean mScaleWithContent = false;
/**
* Instantiates a new image view drawable overlay.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public ImageViewDrawableOverlay( Context context, AttributeSet attrs ) {
super( context, attrs );
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#init()
*/
@Override
protected void init() {
super.init();
mTouchSlop = 20 * 20;
mGestureDetector.setIsLongpressEnabled( false );
}
/**
* How overlay content will be scaled/moved when zomming/panning the base image
*
* @param value
* - if true then the content will be scale according to the image
*/
public void setScaleWithContent( boolean value ) {
mScaleWithContent = value;
}
public boolean getScaleWithContent() {
return mScaleWithContent;
}
/**
* If true, when the user tap outside the drawable overlay and there is only one active overlay selection is not changed.
*
* @param value
* the new force single selection
*/
public void setForceSingleSelection( boolean value ) {
mForceSingleSelection = value;
}
public void setDropTargetListener( DropTargetListener listener ) {
mDropTargetListener = listener;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#getGestureListener()
*/
@Override
protected OnGestureListener getGestureListener() {
return new CropGestureListener();
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#getScaleListener()
*/
@Override
protected OnScaleGestureListener getScaleListener() {
return new CropScaleListener();
}
/**
* Sets the on layout listener.
*
* @param listener
* the new on layout listener
*/
public void setOnLayoutListener( OnLayoutListener listener ) {
mLayoutListener = listener;
}
/**
* Sets the on drawable event listener.
*
* @param listener
* the new on drawable event listener
*/
public void setOnDrawableEventListener( OnDrawableEventListener listener ) {
mDrawableListener = listener;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#setImageBitmap(android.graphics.Bitmap, boolean,
* android.graphics.Matrix)
*/
@Override
public void setImageBitmap( final Bitmap bitmap, final boolean reset, Matrix matrix ) {
clearOverlays();
super.setImageBitmap( bitmap, reset, matrix );
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
if ( mLayoutListener != null ) mLayoutListener.onLayoutChanged( changed, left, top, right, bottom );
if ( getDrawable() != null && changed ) {
Iterator<DrawableHighlightView> iterator = mOverlayViews.iterator();
while ( iterator.hasNext() ) {
DrawableHighlightView view = iterator.next();
view.getMatrix().set( getImageMatrix() );
view.invalidate();
}
}
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#postTranslate(float, float)
*/
@Override
protected void postTranslate( float deltaX, float deltaY ) {
super.postTranslate( deltaX, deltaY );
Iterator<DrawableHighlightView> iterator = mOverlayViews.iterator();
while ( iterator.hasNext() ) {
DrawableHighlightView view = iterator.next();
if ( getScale() != 1 ) {
float[] mvalues = new float[9];
getImageMatrix().getValues( mvalues );
final float scale = mvalues[Matrix.MSCALE_X];
if ( !mScaleWithContent ) view.getCropRectF().offset( -deltaX / scale, -deltaY / scale );
}
view.getMatrix().set( getImageMatrix() );
view.invalidate();
}
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#postScale(float, float, float)
*/
@Override
protected void postScale( float scale, float centerX, float centerY ) {
if ( mOverlayViews.size() > 0 ) {
Iterator<DrawableHighlightView> iterator = mOverlayViews.iterator();
Matrix oldMatrix = new Matrix( getImageViewMatrix() );
super.postScale( scale, centerX, centerY );
while ( iterator.hasNext() ) {
DrawableHighlightView view = iterator.next();
if ( !mScaleWithContent ) {
RectF cropRect = view.getCropRectF();
RectF rect1 = view.getDisplayRect( oldMatrix, view.getCropRectF() );
RectF rect2 = view.getDisplayRect( getImageViewMatrix(), view.getCropRectF() );
float[] mvalues = new float[9];
getImageViewMatrix().getValues( mvalues );
final float currentScale = mvalues[Matrix.MSCALE_X];
cropRect.offset( ( rect1.left - rect2.left ) / currentScale, ( rect1.top - rect2.top ) / currentScale );
cropRect.right += -( rect2.width() - rect1.width() ) / currentScale;
cropRect.bottom += -( rect2.height() - rect1.height() ) / currentScale;
view.getMatrix().set( getImageMatrix() );
view.getCropRectF().set( cropRect );
} else {
view.getMatrix().set( getImageMatrix() );
}
view.invalidate();
}
} else {
super.postScale( scale, centerX, centerY );
}
}
/**
* Ensure visible.
*
* @param hv
* the hv
*/
private void ensureVisible( DrawableHighlightView hv, float deltaX, float deltaY ) {
RectF r = hv.getDrawRect();
int panDeltaX1 = 0, panDeltaX2 = 0;
int panDeltaY1 = 0, panDeltaY2 = 0;
if ( deltaX > 0 ) panDeltaX1 = (int) Math.max( 0, getLeft() - r.left );
if ( deltaX < 0 ) panDeltaX2 = (int) Math.min( 0, getRight() - r.right );
if ( deltaY > 0 ) panDeltaY1 = (int) Math.max( 0, getTop() - r.top );
if ( deltaY < 0 ) panDeltaY2 = (int) Math.min( 0, getBottom() - r.bottom );
int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2;
int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2;
if ( panDeltaX != 0 || panDeltaY != 0 ) {
panBy( panDeltaX, panDeltaY );
}
}
/*
* (non-Javadoc)
*
* @see android.widget.ImageView#onDraw(android.graphics.Canvas)
*/
@Override
public void onDraw( Canvas canvas ) {
super.onDraw( canvas );
for ( int i = 0; i < mOverlayViews.size(); i++ ) {
canvas.save( Canvas.MATRIX_SAVE_FLAG );
mOverlayViews.get( i ).draw( canvas );
canvas.restore();
}
if ( null != mDropPaint ) {
getDrawingRect( mTempRect );
canvas.drawRect( mTempRect, mDropPaint );
}
}
/**
* Clear overlays.
*/
public void clearOverlays() {
setSelectedHighlightView( null );
while ( mOverlayViews.size() > 0 ) {
DrawableHighlightView hv = mOverlayViews.remove( 0 );
hv.dispose();
}
mOverlayView = null;
mMotionEdge = DrawableHighlightView.GROW_NONE;
}
/**
* Adds the highlight view.
*
* @param hv
* the hv
* @return true, if successful
*/
public boolean addHighlightView( DrawableHighlightView hv ) {
for ( int i = 0; i < mOverlayViews.size(); i++ ) {
if ( mOverlayViews.get( i ).equals( hv ) ) return false;
}
mOverlayViews.add( hv );
postInvalidate();
if ( mOverlayViews.size() == 1 ) {
setSelectedHighlightView( hv );
}
return true;
}
/**
* Gets the highlight count.
*
* @return the highlight count
*/
public int getHighlightCount() {
return mOverlayViews.size();
}
/**
* Gets the highlight view at.
*
* @param index
* the index
* @return the highlight view at
*/
public DrawableHighlightView getHighlightViewAt( int index ) {
return mOverlayViews.get( index );
}
/**
* Removes the hightlight view.
*
* @param view
* the view
* @return true, if successful
*/
public boolean removeHightlightView( DrawableHighlightView view ) {
for ( int i = 0; i < mOverlayViews.size(); i++ ) {
if ( mOverlayViews.get( i ).equals( view ) ) {
DrawableHighlightView hv = mOverlayViews.remove( i );
if ( hv.equals( mOverlayView ) ) {
setSelectedHighlightView( null );
}
hv.dispose();
return true;
}
}
return false;
}
@Override
protected void onZoomAnimationCompleted( float scale ) {
Log.i( LOG_TAG, "onZoomAnimationCompleted: " + scale );
super.onZoomAnimationCompleted( scale );
if ( mOverlayView != null ) {
mOverlayView.setMode( Mode.Move );
mMotionEdge = DrawableHighlightView.MOVE;
}
}
/**
* Return the current selected highlight view.
*
* @return the selected highlight view
*/
public DrawableHighlightView getSelectedHighlightView() {
return mOverlayView;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
int action = event.getAction() & MotionEvent.ACTION_MASK;
mScaleDetector.onTouchEvent( event );
if ( !mScaleDetector.isInProgress() ) mGestureDetector.onTouchEvent( event );
switch ( action ) {
case MotionEvent.ACTION_UP:
if ( mOverlayView != null ) {
mOverlayView.setMode( DrawableHighlightView.Mode.None );
}
mMotionEdge = DrawableHighlightView.GROW_NONE;
if ( getScale() < 1f ) {
zoomTo( 1f, 50 );
}
break;
}
return true;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onDoubleTapPost(float, float)
*/
@Override
protected float onDoubleTapPost( float scale, float maxZoom ) {
return super.onDoubleTapPost( scale, maxZoom );
}
private boolean onDoubleTap( MotionEvent e ) {
float scale = getScale();
float targetScale = scale;
targetScale = ImageViewDrawableOverlay.this.onDoubleTapPost( scale, getMaxZoom() );
targetScale = Math.min( getMaxZoom(), Math.max( targetScale, 1 ) );
mCurrentScaleFactor = targetScale;
zoomTo( targetScale, e.getX(), e.getY(), DEFAULT_ANIMATION_DURATION );
invalidate();
return true;
}
/**
* Check selection.
*
* @param e
* the e
* @return the drawable highlight view
*/
private DrawableHighlightView checkSelection( MotionEvent e ) {
Iterator<DrawableHighlightView> iterator = mOverlayViews.iterator();
DrawableHighlightView selection = null;
while ( iterator.hasNext() ) {
DrawableHighlightView view = iterator.next();
int edge = view.getHit( e.getX(), e.getY() );
if ( edge != DrawableHighlightView.GROW_NONE ) {
selection = view;
}
}
return selection;
}
/**
* Check up selection.
*
* @param e
* the e
* @return the drawable highlight view
*/
private DrawableHighlightView checkUpSelection( MotionEvent e ) {
Iterator<DrawableHighlightView> iterator = mOverlayViews.iterator();
DrawableHighlightView selection = null;
while ( iterator.hasNext() ) {
DrawableHighlightView view = iterator.next();
if ( view.getSelected() ) {
view.onSingleTapConfirmed( e.getX(), e.getY() );
}
}
return selection;
}
/**
* Sets the selected highlight view.
*
* @param newView
* the new selected highlight view
*/
public void setSelectedHighlightView( DrawableHighlightView newView ) {
final DrawableHighlightView oldView = mOverlayView;
if ( mOverlayView != null && !mOverlayView.equals( newView ) ) {
mOverlayView.setSelected( false );
}
if ( newView != null ) {
newView.setSelected( true );
}
mOverlayView = newView;
if ( mDrawableListener != null ) {
mDrawableListener.onFocusChange( newView, oldView );
}
}
/**
* The listener interface for receiving cropGesture events. The class that is interested in processing a cropGesture event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addCropGestureListener<code> method. When
* the cropGesture event occurs, that object's appropriate
* method is invoked.
*
* @see CropGestureEvent
*/
class CropGestureListener extends GestureDetector.SimpleOnGestureListener {
boolean mScrollStarted;
float mLastMotionX, mLastMotionY;
@Override
public boolean onDown( MotionEvent e ) {
mScrollStarted = false;
mLastMotionX = e.getX();
mLastMotionY = e.getY();
DrawableHighlightView newSelection = checkSelection( e );
DrawableHighlightView realNewSelection = newSelection;
if ( newSelection == null && mOverlayViews.size() == 1 && mForceSingleSelection ) {
newSelection = mOverlayViews.get( 0 );
}
setSelectedHighlightView( newSelection );
if ( realNewSelection != null && mScaleWithContent ) {
RectF displayRect = realNewSelection.getDisplayRect( realNewSelection.getMatrix(), realNewSelection.getCropRectF() );
boolean invalidSize = realNewSelection.getContent().validateSize( displayRect );
if ( !invalidSize ) {
float minW = realNewSelection.getContent().getMinWidth();
float minH = realNewSelection.getContent().getMinHeight();
float minSize = Math.min( minW, minH ) * 1.1f;
float minRectSize = Math.min( displayRect.width(), displayRect.height() );
float diff = minSize / minRectSize;
Log.d( LOG_TAG, "drawable too small!!!" );
Log.d( LOG_TAG, "min.size: " + minW + "x" + minH );
Log.d( LOG_TAG, "cur.size: " + displayRect.width() + "x" + displayRect.height() );
zoomTo( getScale() * diff, displayRect.centerX(), displayRect.centerY(), DEFAULT_ANIMATION_DURATION * 1.5f );
return true;
}
}
if ( mOverlayView != null ) {
int edge = mOverlayView.getHit( e.getX(), e.getY() );
if ( edge != DrawableHighlightView.GROW_NONE ) {
mMotionEdge = edge;
mOverlayView
.setMode( ( edge == DrawableHighlightView.MOVE ) ? DrawableHighlightView.Mode.Move
: ( edge == DrawableHighlightView.ROTATE ? DrawableHighlightView.Mode.Rotate
: DrawableHighlightView.Mode.Grow ) );
if ( mDrawableListener != null ) {
mDrawableListener.onDown( mOverlayView );
}
}
}
return super.onDown( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onSingleTapConfirmed(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapConfirmed( MotionEvent e ) {
checkUpSelection( e );
return super.onSingleTapConfirmed( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp( MotionEvent e ) {
if ( mOverlayView != null ) {
int edge = mOverlayView.getHit( e.getX(), e.getY() );
if ( ( edge & DrawableHighlightView.MOVE ) == DrawableHighlightView.MOVE ) {
if ( mDrawableListener != null ) mDrawableListener.onClick( mOverlayView );
return true;
}
mOverlayView.setMode( Mode.None );
if ( mOverlayViews.size() != 1 ) setSelectedHighlightView( null );
}
return super.onSingleTapUp( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onDoubleTap(android.view.MotionEvent)
*/
@Override
public boolean onDoubleTap( MotionEvent e ) {
if ( !mDoubleTapEnabled ) return false;
return ImageViewDrawableOverlay.this.onDoubleTap( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent,
* float, float)
*/
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
if ( !mScrollEnabled ) return false;
if ( e1 == null || e2 == null ) return false;
if ( e1.getPointerCount() > 1 || e2.getPointerCount() > 1 ) return false;
if ( mScaleDetector.isInProgress() ) return false;
// remove the touch slop lag ( see bug @1084 )
float x = e2.getX();
float y = e2.getY();
if( !mScrollStarted ){
distanceX = 0;
distanceY = 0;
mScrollStarted = true;
} else {
distanceX = mLastMotionX - x;
distanceY = mLastMotionY - y;
}
mLastMotionX = x;
mLastMotionY = y;
if ( mOverlayView != null && mMotionEdge != DrawableHighlightView.GROW_NONE ) {
mOverlayView.onMouseMove( mMotionEdge, e2, -distanceX, -distanceY );
if ( mDrawableListener != null ) {
mDrawableListener.onMove( mOverlayView );
}
if ( mMotionEdge == DrawableHighlightView.MOVE ) {
if ( !mScaleWithContent ) {
ensureVisible( mOverlayView, distanceX, distanceY );
}
}
return true;
} else {
scrollBy( -distanceX, -distanceY );
invalidate();
return true;
}
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent,
* float, float)
*/
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
if ( !mScrollEnabled ) return false;
if ( e1.getPointerCount() > 1 || e2.getPointerCount() > 1 ) return false;
if ( mScaleDetector.isInProgress() ) return false;
if ( mOverlayView != null && mOverlayView.getMode() != Mode.None ) return false;
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
if ( Math.abs( velocityX ) > 800 || Math.abs( velocityY ) > 800 ) {
scrollBy( diffX / 2, diffY / 2, 300 );
invalidate();
}
return super.onFling( e1, e2, velocityX, velocityY );
}
}
/**
* The listener interface for receiving cropScale events. The class that is interested in processing a cropScale event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addCropScaleListener<code> method. When
* the cropScale event occurs, that object's appropriate
* method is invoked.
*
* @see CropScaleEvent
*/
class CropScaleListener extends ScaleListener {
/*
* (non-Javadoc)
*
* @see
* it.sephiroth.android.library.imagezoom.ScaleGestureDetector.SimpleOnScaleGestureListener#onScaleBegin(it.sephiroth.android
* .library.imagezoom.ScaleGestureDetector)
*/
@Override
public boolean onScaleBegin( ScaleGestureDetector detector ) {
if ( !mScaleEnabled ) return false;
return super.onScaleBegin( detector );
}
/*
* (non-Javadoc)
*
* @see
* it.sephiroth.android.library.imagezoom.ScaleGestureDetector.SimpleOnScaleGestureListener#onScaleEnd(it.sephiroth.android
* .library.imagezoom.ScaleGestureDetector)
*/
@Override
public void onScaleEnd( ScaleGestureDetector detector ) {
if ( !mScaleEnabled ) return;
super.onScaleEnd( detector );
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch.ScaleListener#onScale(it.sephiroth.android.library.imagezoom.
* ScaleGestureDetector)
*/
@Override
public boolean onScale( ScaleGestureDetector detector ) {
if ( !mScaleEnabled ) return false;
return super.onScale( detector );
}
}
@Override
public void onDrop( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
if ( mDropTargetListener != null ) {
mDropTargetListener.onDrop( source, x, y, xOffset, yOffset, dragView, dragInfo );
}
}
@Override
public void onDragEnter( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
mDropPaint = new Paint();
mDropPaint.setColor( 0xff33b5e5 );
mDropPaint.setStrokeWidth( 2 );
mDropPaint.setMaskFilter( new BlurMaskFilter( 4.0f, Blur.NORMAL ) );
mDropPaint.setStyle( Paint.Style.STROKE );
invalidate();
}
@Override
public void onDragOver( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {}
@Override
public void onDragExit( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
mDropPaint = null;
invalidate();
}
@Override
public boolean acceptDrop( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo ) {
if ( mDropTargetListener != null ) {
return mDropTargetListener.acceptDrop( source, x, y, xOffset, yOffset, dragView, dragInfo );
}
return false;
}
@Override
public Rect estimateDropLocation( DragSource source, int x, int y, int xOffset, int yOffset, DragView dragView, Object dragInfo,
Rect recycle ) {
return null;
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.aviary.android.feather.R;
public class ImageViewWithSelection extends ImageView {
private Drawable mSelectionDrawable;
private Rect mSelectionDrawablePadding;
private RectF mRect;
private boolean mSelected;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
public ImageViewWithSelection( Context context, AttributeSet attrs ) {
super( context, attrs );
init( context, attrs, -1 );
}
public ImageViewWithSelection( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
init( context, attrs, defStyle );
}
private void init( Context context, AttributeSet attrs, int defStyle ) {
TypedArray array = context.obtainStyledAttributes( attrs, R.styleable.ImageViewWithSelection, defStyle, 0 );
mSelectionDrawable = array.getDrawable( R.styleable.ImageViewWithSelection_selectionSrc );
int pleft = array.getDimensionPixelSize( R.styleable.ImageViewWithSelection_selectionPaddingLeft, 0 );
int ptop = array.getDimensionPixelSize( R.styleable.ImageViewWithSelection_selectionPaddingTop, 0 );
int pright = array.getDimensionPixelSize( R.styleable.ImageViewWithSelection_selectionPaddingRight, 0 );
int pbottom = array.getDimensionPixelSize( R.styleable.ImageViewWithSelection_selectionPaddingBottom, 0 );
mSelectionDrawablePadding = new Rect( pleft, ptop, pright, pbottom );
array.recycle();
mRect = new RectF();
}
@Override
public void setSelected( boolean value ) {
super.setSelected( value );
mSelected = value;
invalidate();
}
public boolean getSelected() {
return mSelected;
}
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
mPaddingLeft = getPaddingLeft();
mPaddingTop = getPaddingTop();
}
@Override
public void setPadding( int left, int top, int right, int bottom ) {
mPaddingLeft = left;
mPaddingTop = top;
super.setPadding( left, top, right, bottom );
}
@Override
protected void onDraw( Canvas canvas ) {
Drawable drawable = getDrawable();
if ( null == drawable ) return;
Rect bounds = drawable.getBounds();
mRect.set( bounds );
if ( getImageMatrix() != null ) {
getImageMatrix().mapRect( mRect );
mRect.offset( mPaddingLeft, mPaddingTop );
mRect.inset( -( mSelectionDrawablePadding.left + mSelectionDrawablePadding.right ),
-( mSelectionDrawablePadding.top + mSelectionDrawablePadding.bottom ) );
}
if ( mSelectionDrawable != null && mSelected ) {
mSelectionDrawable.setBounds( (int) mRect.left, (int) mRect.top, (int) mRect.right, (int) mRect.bottom );
mSelectionDrawable.draw( canvas );
}
super.onDraw( canvas );
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable;
import com.aviary.android.feather.library.utils.UIConfiguration;
// TODO: Auto-generated Javadoc
/**
* The Class CropImageView.
*/
public class CropImageView extends ImageViewTouch {
/**
* The listener interface for receiving onLayout events. The class that is interested in processing a onLayout event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnLayoutListener<code> method. When
* the onLayout event occurs, that object's appropriate
* method is invoked.
*
* @see OnLayoutEvent
*/
public interface OnLayoutListener {
/**
* On layout changed.
*
* @param changed
* the changed
* @param left
* the left
* @param top
* the top
* @param right
* the right
* @param bottom
* the bottom
*/
void onLayoutChanged( boolean changed, int left, int top, int right, int bottom );
}
/**
* The listener interface for receiving onHighlightSingleTapUpConfirmed events. The class that is interested in processing a
* onHighlightSingleTapUpConfirmed event implements this interface, and the object created with that class is registered with a
* component using the component's <code>addOnHighlightSingleTapUpConfirmedListener<code> method. When
* the onHighlightSingleTapUpConfirmed event occurs, that object's appropriate
* method is invoked.
*
* @see OnHighlightSingleTapUpConfirmedEvent
*/
public interface OnHighlightSingleTapUpConfirmedListener {
/**
* On single tap up confirmed.
*/
void onSingleTapUpConfirmed();
}
/** The Constant GROW. */
public static final int GROW = 0;
/** The Constant SHRINK. */
public static final int SHRINK = 1;
/** The m motion edge. */
private int mMotionEdge = HighlightView.GROW_NONE;
/** The m highlight view. */
private HighlightView mHighlightView;
/** The m layout listener. */
private OnLayoutListener mLayoutListener;
/** The m highlight single tap up listener. */
private OnHighlightSingleTapUpConfirmedListener mHighlightSingleTapUpListener;
/** The m motion highlight view. */
private HighlightView mMotionHighlightView;
/** The m crop min size. */
private int mCropMinSize = 10;
protected Handler mHandler = new Handler();
/**
* Instantiates a new crop image view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public CropImageView( Context context, AttributeSet attrs ) {
super( context, attrs );
}
/**
* Sets the on highlight single tap up confirmed listener.
*
* @param listener
* the new on highlight single tap up confirmed listener
*/
public void setOnHighlightSingleTapUpConfirmedListener( OnHighlightSingleTapUpConfirmedListener listener ) {
mHighlightSingleTapUpListener = listener;
}
/**
* Sets the min crop size.
*
* @param value
* the new min crop size
*/
public void setMinCropSize( int value ) {
mCropMinSize = value;
if ( mHighlightView != null ) {
mHighlightView.setMinSize( value );
}
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#init()
*/
@Override
protected void init() {
super.init();
mGestureDetector = null;
mScaleDetector = null;
mGestureListener = null;
mScaleListener = null;
mScaleDetector = new ScaleGestureDetector( getContext(), new CropScaleListener() );
mGestureDetector = new GestureDetector( getContext(), new CropGestureListener(), null, true );
mGestureDetector.setIsLongpressEnabled( false );
// mTouchSlop = 20 * 20;
}
/**
* Sets the on layout listener.
*
* @param listener
* the new on layout listener
*/
public void setOnLayoutListener( OnLayoutListener listener ) {
mLayoutListener = listener;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#setImageBitmap(android.graphics.Bitmap, boolean)
*/
@Override
public void setImageBitmap( Bitmap bitmap, boolean reset ) {
mMotionHighlightView = null;
super.setImageBitmap( bitmap, reset );
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
if ( mLayoutListener != null ) mLayoutListener.onLayoutChanged( changed, left, top, right, bottom );
mHandler.post( onLayoutRunnable );
}
Runnable onLayoutRunnable = new Runnable() {
@Override
public void run() {
final Drawable drawable = getDrawable();
if ( drawable != null && ( (IBitmapDrawable) drawable ).getBitmap() != null ) {
if ( mHighlightView != null ) {
if ( mHighlightView.isRunning() ) {
mHandler.post( this );
} else {
// Log.d( LOG_TAG, "onLayoutRunnable.. running" );
mHighlightView.getMatrix().set( getImageMatrix() );
mHighlightView.invalidate();
}
}
}
}
};
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouchBase#postTranslate(float, float)
*/
@Override
protected void postTranslate( float deltaX, float deltaY ) {
super.postTranslate( deltaX, deltaY );
if ( mHighlightView != null ) {
if ( mHighlightView.isRunning() ) {
return;
}
if ( getScale() != 1 ) {
float[] mvalues = new float[9];
getImageMatrix().getValues( mvalues );
final float scale = mvalues[Matrix.MSCALE_X];
mHighlightView.getCropRectF().offset( -deltaX / scale, -deltaY / scale );
}
mHighlightView.getMatrix().set( getImageMatrix() );
mHighlightView.invalidate();
}
}
private Rect mRect1 = new Rect();
private Rect mRect2 = new Rect();
@Override
protected void postScale( float scale, float centerX, float centerY ) {
if ( mHighlightView != null ) {
if ( mHighlightView.isRunning() ) return;
RectF cropRect = mHighlightView.getCropRectF();
mHighlightView.getDisplayRect( getImageViewMatrix(), mHighlightView.getCropRectF(), mRect1 );
super.postScale( scale, centerX, centerY );
mHighlightView.getDisplayRect( getImageViewMatrix(), mHighlightView.getCropRectF(), mRect2 );
float[] mvalues = new float[9];
getImageViewMatrix().getValues( mvalues );
final float currentScale = mvalues[Matrix.MSCALE_X];
cropRect.offset( ( mRect1.left - mRect2.left ) / currentScale, ( mRect1.top - mRect2.top ) / currentScale );
cropRect.right += -( mRect2.width() - mRect1.width() ) / currentScale;
cropRect.bottom += -( mRect2.height() - mRect1.height() ) / currentScale;
mHighlightView.getMatrix().set( getImageMatrix() );
mHighlightView.getCropRectF().set( cropRect );
mHighlightView.invalidate();
} else {
super.postScale( scale, centerX, centerY );
}
}
/**
* Ensure visible.
*
* @param hv
* the hv
*/
private void ensureVisible( HighlightView hv ) {
Rect r = hv.getDrawRect();
int panDeltaX1 = Math.max( 0, getLeft() - r.left );
int panDeltaX2 = Math.min( 0, getRight() - r.right );
int panDeltaY1 = Math.max( 0, getTop() - r.top );
int panDeltaY2 = Math.min( 0, getBottom() - r.bottom );
int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2;
int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2;
if ( panDeltaX != 0 || panDeltaY != 0 ) {
panBy( panDeltaX, panDeltaY );
}
}
/*
* (non-Javadoc)
*
* @see android.widget.ImageView#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
if ( mHighlightView != null ) mHighlightView.draw( canvas );
}
/**
* Sets the highlight view.
*
* @param hv
* the new highlight view
*/
public void setHighlightView( HighlightView hv ) {
if ( mHighlightView != null ) {
mHighlightView.dispose();
}
mMotionHighlightView = null;
mHighlightView = hv;
invalidate();
}
/**
* Gets the highlight view.
*
* @return the highlight view
*/
public HighlightView getHighlightView() {
return mHighlightView;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
int action = event.getAction() & MotionEvent.ACTION_MASK;
mScaleDetector.onTouchEvent( event );
if ( !mScaleDetector.isInProgress() ) mGestureDetector.onTouchEvent( event );
switch ( action ) {
case MotionEvent.ACTION_UP:
if ( mHighlightView != null ) {
mHighlightView.setMode( HighlightView.Mode.None );
}
mMotionHighlightView = null;
mMotionEdge = HighlightView.GROW_NONE;
if ( getScale() < 1f ) {
zoomTo( 1f, 50 );
}
break;
}
return true;
}
/**
* Distance.
*
* @param x2
* the x2
* @param y2
* the y2
* @param x1
* the x1
* @param y1
* the y1
* @return the float
*/
@SuppressLint("FloatMath")
static float distance( float x2, float y2, float x1, float y1 ) {
return (float) Math.sqrt( Math.pow( x2 - x1, 2 ) + Math.pow( y2 - y1, 2 ) );
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onDoubleTapPost(float, float)
*/
@Override
protected float onDoubleTapPost( float scale, float maxZoom ) {
return super.onDoubleTapPost( scale, maxZoom );
}
/**
* The listener interface for receiving cropGesture events. The class that is interested in processing a cropGesture event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addCropGestureListener<code> method. When
* the cropGesture event occurs, that object's appropriate
* method is invoked.
*
* @see CropGestureEvent
*/
class CropGestureListener extends GestureDetector.SimpleOnGestureListener {
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown( MotionEvent e ) {
mMotionHighlightView = null;
HighlightView hv = mHighlightView;
if ( hv != null ) {
int edge = hv.getHit( e.getX(), e.getY() );
if ( edge != HighlightView.GROW_NONE ) {
mMotionEdge = edge;
mMotionHighlightView = hv;
mMotionHighlightView.setMode( ( edge == HighlightView.MOVE ) ? HighlightView.Mode.Move : HighlightView.Mode.Grow );
}
}
return super.onDown( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onSingleTapConfirmed(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapConfirmed( MotionEvent e ) {
mMotionHighlightView = null;
return super.onSingleTapConfirmed( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp( MotionEvent e ) {
mMotionHighlightView = null;
if ( mHighlightView != null && mMotionEdge == HighlightView.MOVE ) {
if ( mHighlightSingleTapUpListener != null ) {
mHighlightSingleTapUpListener.onSingleTapUpConfirmed();
}
}
return super.onSingleTapUp( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onDoubleTap(android.view.MotionEvent)
*/
@Override
public boolean onDoubleTap( MotionEvent e ) {
if ( mDoubleTapEnabled ) {
mMotionHighlightView = null;
float scale = getScale();
float targetScale = scale;
targetScale = CropImageView.this.onDoubleTapPost( scale, getMaxZoom() );
targetScale = Math.min( getMaxZoom(), Math.max( targetScale, 1 ) );
mCurrentScaleFactor = targetScale;
zoomTo( targetScale, e.getX(), e.getY(), 200 );
// zoomTo( targetScale, e.getX(), e.getY() );
invalidate();
}
return super.onDoubleTap( e );
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent,
* float, float)
*/
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
if ( e1 == null || e2 == null ) return false;
if ( e1.getPointerCount() > 1 || e2.getPointerCount() > 1 ) return false;
if ( mScaleDetector.isInProgress() ) return false;
if ( mMotionHighlightView != null && mMotionEdge != HighlightView.GROW_NONE ) {
mMotionHighlightView.handleMotion( mMotionEdge, -distanceX, -distanceY );
ensureVisible( mMotionHighlightView );
return true;
} else {
scrollBy( -distanceX, -distanceY );
invalidate();
return true;
}
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.SimpleOnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent,
* float, float)
*/
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
if ( e1.getPointerCount() > 1 || e2.getPointerCount() > 1 ) return false;
if ( mScaleDetector.isInProgress() ) return false;
if ( mMotionHighlightView != null ) return false;
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
if ( Math.abs( velocityX ) > 800 || Math.abs( velocityY ) > 800 ) {
scrollBy( diffX / 2, diffY / 2, 300 );
invalidate();
}
return super.onFling( e1, e2, velocityX, velocityY );
}
}
/**
* The listener interface for receiving cropScale events. The class that is interested in processing a cropScale event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addCropScaleListener<code> method. When
* the cropScale event occurs, that object's appropriate
* method is invoked.
*
* @see CropScaleEvent
*/
class CropScaleListener extends SimpleOnScaleGestureListener {
/*
* (non-Javadoc)
*
* @see
* it.sephiroth.android.library.imagezoom.ScaleGestureDetector.SimpleOnScaleGestureListener#onScaleBegin(it.sephiroth.android
* .library.imagezoom.ScaleGestureDetector)
*/
@Override
public boolean onScaleBegin( ScaleGestureDetector detector ) {
return super.onScaleBegin( detector );
}
/*
* (non-Javadoc)
*
* @see
* it.sephiroth.android.library.imagezoom.ScaleGestureDetector.SimpleOnScaleGestureListener#onScaleEnd(it.sephiroth.android
* .library.imagezoom.ScaleGestureDetector)
*/
@Override
public void onScaleEnd( ScaleGestureDetector detector ) {
super.onScaleEnd( detector );
}
/*
* (non-Javadoc)
*
* @see
* it.sephiroth.android.library.imagezoom.ScaleGestureDetector.SimpleOnScaleGestureListener#onScale(it.sephiroth.android.library
* .imagezoom.ScaleGestureDetector)
*/
@Override
public boolean onScale( ScaleGestureDetector detector ) {
float targetScale = mCurrentScaleFactor * detector.getScaleFactor();
if ( true ) {
targetScale = Math.min( getMaxZoom(), Math.max( targetScale, 1 ) );
zoomTo( targetScale, detector.getFocusX(), detector.getFocusY() );
mCurrentScaleFactor = Math.min( getMaxZoom(), Math.max( targetScale, 1 ) );
mDoubleTapDirection = 1;
invalidate();
}
return true;
}
}
/** The m aspect ratio. */
protected double mAspectRatio = 0;
/** The m aspect ratio fixed. */
private boolean mAspectRatioFixed;
/**
* Set the new image display and crop view. If both aspect
*
* @param bitmap
* Bitmap to display
* @param aspectRatio
* aspect ratio for the crop view. If 0 is passed, then the crop rectangle can be free transformed by the user,
* otherwise the width/height are fixed according to the aspect ratio passed.
*/
public void setImageBitmap( Bitmap bitmap, double aspectRatio, boolean isFixed ) {
mAspectRatio = aspectRatio;
mAspectRatioFixed = isFixed;
setImageBitmap( bitmap, true, null, UIConfiguration.IMAGE_VIEW_MAX_ZOOM );
}
/**
* Sets the aspect ratio.
*
* @param value
* the value
* @param isFixed
* the is fixed
*/
public void setAspectRatio( double value, boolean isFixed ) {
// Log.d( LOG_TAG, "setAspectRatio" );
if ( getDrawable() != null ) {
mAspectRatio = value;
mAspectRatioFixed = isFixed;
updateCropView( false );
}
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onBitmapChanged(android.graphics.drawable.Drawable)
*/
@Override
protected void onBitmapChanged( Drawable drawable ) {
super.onBitmapChanged( drawable );
if ( null != getHandler() ) {
getHandler().post( new Runnable() {
@Override
public void run() {
updateCropView( true );
}
} );
}
}
/**
* Update crop view.
*/
public void updateCropView( boolean bitmapChanged ) {
if ( bitmapChanged ) {
setHighlightView( null );
}
if ( getDrawable() == null ) {
setHighlightView( null );
invalidate();
return;
}
if ( getHighlightView() != null ) {
updateAspectRatio( mAspectRatio, getHighlightView(), true );
} else {
HighlightView hv = new HighlightView( this );
hv.setMinSize( mCropMinSize );
updateAspectRatio( mAspectRatio, hv, false );
setHighlightView( hv );
}
invalidate();
}
/**
* Update aspect ratio.
*
* @param aspectRatio
* the aspect ratio
* @param hv
* the hv
*/
private void updateAspectRatio( double aspectRatio, HighlightView hv, boolean animate ) {
// Log.d( LOG_TAG, "updateAspectRatio" );
float width = getDrawable().getIntrinsicWidth();
float height = getDrawable().getIntrinsicHeight();
Rect imageRect = new Rect( 0, 0, (int) width, (int) height );
Matrix mImageMatrix = getImageMatrix();
RectF cropRect = computeFinalCropRect( aspectRatio );
if ( animate ) {
hv.animateTo( mImageMatrix, imageRect, cropRect, mAspectRatioFixed );
} else {
hv.setup( mImageMatrix, imageRect, cropRect, mAspectRatioFixed );
}
}
public void onConfigurationChanged( Configuration config ) {
// Log.d( LOG_TAG, "onConfigurationChanged" );
if ( null != getHandler() ) {
getHandler().postDelayed( new Runnable() {
@Override
public void run() {
setAspectRatio( mAspectRatio, getAspectRatioIsFixed() );
}
}, 500 );
}
postInvalidate();
}
private RectF computeFinalCropRect( double aspectRatio ) {
float scale = getScale();
float width = getDrawable().getIntrinsicWidth();
float height = getDrawable().getIntrinsicHeight();
final int viewWidth = getWidth();
final int viewHeight = getHeight();
float cropWidth = Math.min( Math.min( width / scale, viewWidth ), Math.min( height / scale, viewHeight ) ) * 0.8f;
float cropHeight = cropWidth;
if ( aspectRatio != 0 ) {
if ( aspectRatio > 1 ) {
cropHeight = cropHeight / (float) aspectRatio;
} else {
cropWidth = cropWidth * (float) aspectRatio;
}
}
Matrix mImageMatrix = getImageMatrix();
Matrix tmpMatrix = new Matrix();
if( !mImageMatrix.invert( tmpMatrix ) ){
Log.e( LOG_TAG, "cannot invert matrix" );
}
RectF r = new RectF( 0, 0, viewWidth, viewHeight );
tmpMatrix.mapRect( r );
float x = r.centerX() - cropWidth / 2;
float y = r.centerY() - cropHeight / 2;
RectF cropRect = new RectF( x, y, x + cropWidth, y + cropHeight );
return cropRect;
}
/**
* Gets the aspect ratio.
*
* @return the aspect ratio
*/
public double getAspectRatio() {
return mAspectRatio;
}
public boolean getAspectRatioIsFixed() {
return mAspectRatioFixed;
}
} | Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.easing.Linear;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
public class EffectThumbLayout extends RelativeLayout {
private boolean opened;
int mThumbSelectionHeight = 20;
int mThumbAnimationDuration = 200;
View mHiddenView;
View mImageView;
Logger logger = LoggerFactory.getLogger( "effect-thumb", LoggerType.ConsoleLoggerType );
public EffectThumbLayout( Context context, AttributeSet attrs ) {
super( context, attrs );
init( context, attrs, 0 );
opened = false;
}
private void init( Context context, AttributeSet attrs, int defStyle ) {
TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.EffectThumbLayout, defStyle, 0 );
mThumbSelectionHeight = a.getDimensionPixelSize( R.styleable.EffectThumbLayout_selectedHeight, 20 );
mThumbAnimationDuration = a.getInteger( R.styleable.EffectThumbLayout_selectionAnimationDuration, 200 );
a.recycle();
}
@Override
public void setSelected( boolean selected ) {
boolean animate = isSelected() != selected;
super.setSelected( selected );
if ( null != mHiddenView && animate ) {
mHiddenView.setVisibility( View.VISIBLE );
if ( selected ) {
open();
} else {
close();
}
} else {
opened = selected;
}
}
void open() {
animateView( mThumbAnimationDuration, false );
}
void close() {
animateView( mThumbAnimationDuration, true );
}
void setIsOpened( boolean value ) {
if ( null != mHiddenView ) {
opened = value;
postSetIsOpened();
} else {
opened = value;
}
}
protected void postSetIsOpened() {
if( null != getHandler() ){
getHandler().postDelayed( new Runnable() {
@Override
public void run() {
if( mImageView != null && mHiddenView != null ){
if( mHiddenView.getHeight() == 0 ){
postSetIsOpened();
return;
}
mHiddenView.setVisibility( opened ? View.VISIBLE : View.INVISIBLE );
mImageView.setPadding( 0, 0, 0, opened ? mHiddenView.getHeight() : 0 );
}
}
}, 10 );
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHiddenView = null;
mImageView = null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mHiddenView = findViewById( R.id.hidden );
mImageView = findViewById( R.id.image );
setIsOpened( opened );
}
protected void postAnimateView( final int durationMs, final boolean isClosing ) {
if( null != getHandler() ){
getHandler().post( new Runnable() {
@Override
public void run() {
animateView( durationMs, isClosing );
}
} );
}
}
protected void animateView( final int durationMs, final boolean isClosing ) {
boolean is_valid = mHiddenView != null && mImageView != null;
if ( !is_valid ) return;
if( mHiddenView.getHeight() == 0 ){
postAnimateView( durationMs, isClosing );
}
final long startTime = System.currentTimeMillis();
final float startHeight = 0;
final float endHeight = isClosing ? mImageView.getPaddingBottom() : mHiddenView.getHeight();
final Easing easing = new Linear();
if ( null != mHiddenView && null != getParent() && null != getHandler() ) {
getHandler().post( new Runnable() {
@Override
public void run() {
if ( null != mHiddenView ) {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float newHeight = (float) easing.easeOut( currentMs, startHeight, endHeight, durationMs );
int height = isClosing ? (int) ( endHeight - newHeight ) : (int) newHeight;
mImageView.setPadding( 0, 0, 0, height );
if ( currentMs < durationMs ) {
if ( null != getHandler() ) {
getHandler().post( this );
}
} else {
opened = !isClosing;
if ( null != getParent() ) {
requestLayout();
}
}
}
}
} );
}
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;
import com.aviary.android.feather.R;
import com.aviary.android.feather.utils.TypefaceUtils;
public class ButtonCustomFont extends Button {
@SuppressWarnings("unused")
private final String LOG_TAG = "ButtonCustomFont";
public ButtonCustomFont( Context context ) {
super( context );
}
public ButtonCustomFont( Context context, AttributeSet attrs ) {
super( context, attrs );
setCustomFont( context, attrs );
}
public ButtonCustomFont( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
setCustomFont( context, attrs );
}
private void setCustomFont( Context ctx, AttributeSet attrs ) {
TypedArray array = ctx.obtainStyledAttributes( attrs, R.styleable.TextViewCustomFont );
String font = array.getString( R.styleable.TextViewCustomFont_font );
setCustomFont( font );
array.recycle();
}
protected void setCustomFont( String fontname ) {
if ( null != fontname ) {
try {
Typeface font = TypefaceUtils.createFromAsset( getContext().getAssets(), fontname );
setTypeface( font );
} catch ( Throwable t ) {}
}
}
}
| Java |
/*
* 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.aviary.android.feather.widget;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
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.Adapter;
// TODO: Auto-generated Javadoc
/**
* 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 AbsSpinner extends AdapterView<Adapter> {
/** The m adapter. */
Adapter mAdapter;
/** The m height measure spec. */
int mHeightMeasureSpec;
/** The m width measure spec. */
int mWidthMeasureSpec;
/** The m block layout requests. */
boolean mBlockLayoutRequests;
/** The m selection left padding. */
int mSelectionLeftPadding = 0;
/** The m selection top padding. */
int mSelectionTopPadding = 0;
/** The m selection right padding. */
int mSelectionRightPadding = 0;
/** The m selection bottom padding. */
int mSelectionBottomPadding = 0;
/** The m spinner padding. */
final Rect mSpinnerPadding = new Rect();
/** The m padding left. */
int mPaddingLeft;
/** The m padding right. */
int mPaddingRight;
/** The m padding top. */
int mPaddingTop;
/** The m padding bottom. */
int mPaddingBottom;
/** The m recycler. */
protected final List<Queue<View>> mRecycleBin;
/** The m data set observer. */
private DataSetObserver mDataSetObserver;
/** Temporary frame to hold a child View's frame rectangle. */
private Rect mTouchFrame;
/**
* Instantiates a new abs spinner.
*
* @param context
* the context
*/
public AbsSpinner( Context context ) {
super( context );
mRecycleBin = Collections.synchronizedList( new ArrayList<Queue<View>>() );
initAbsSpinner();
}
/**
* Instantiates a new abs spinner.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public AbsSpinner( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
/**
* Instantiates a new abs spinner.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public AbsSpinner( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
mRecycleBin = Collections.synchronizedList( new ArrayList<Queue<View>>() );
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<CharSequence>
* adapter = new ArrayAdapter<CharSequence>(context, R.layout.simple_spinner_item, entries);
* adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); setAdapter(adapter); } a.recycle();
*/
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#setPadding(int, int, int, int)
*/
@Override
public void setPadding( int left, int top, int right, int bottom ) {
super.setPadding( left, top, right, bottom );
mPaddingLeft = left;
mPaddingBottom = bottom;
mPaddingTop = top;
mPaddingRight = right;
}
/**
* 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( Adapter adapter ) {
if ( null != mAdapter ) {
mAdapter.unregisterDataSetObserver( mDataSetObserver );
emptyRecycler();
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;
int total = mAdapter.getViewTypeCount();
for ( int i = 0; i < total; i++ ) {
mRecycleBin.add( new LinkedList<View>() );
}
setSelectedPositionInt( position );
setNextSelectedPositionInt( position );
if ( mItemCount == 0 ) {
// Nothing selected
checkSelectionChanged();
}
} else {
checkFocus();
resetList();
// Nothing selected
checkSelectionChanged();
}
requestLayout();
}
private void emptyRecycler() {
emptySubRecycler();
if ( null != mRecycleBin ) {
mRecycleBin.clear();
}
}
protected void emptySubRecycler() {
if ( null != mRecycleBin ) {
for( int i = 0; i < mRecycleBin.size(); i++ ){
mRecycleBin.get( i ).clear();
}
}
}
/**
* 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();
}
/**
* On measure.
*
* @param widthMeasureSpec
* the width measure spec
* @param heightMeasureSpec
* the height measure spec
* @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;
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)
int viewType = mAdapter.getItemViewType( selectedPosition );
View view = mRecycleBin.get( viewType ).poll();
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
mRecycleBin.get( viewType ).offer( 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() );
heightSize = resolveSize( preferredHeight, heightMeasureSpec );
widthSize = resolveSize( preferredWidth, widthMeasureSpec );
setMeasuredDimension( widthSize, heightSize );
mHeightMeasureSpec = heightMeasureSpec;
mWidthMeasureSpec = widthMeasureSpec;
}
/**
* Gets the child height.
*
* @param child
* the child
* @return the child height
*/
int getChildHeight( View child ) {
return child.getMeasuredHeight();
}
/**
* Gets the child width.
*
* @param child
* the child
* @return the child width
*/
int getChildWidth( View child ) {
return child.getMeasuredWidth();
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#generateDefaultLayoutParams()
*/
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT );
}
/**
* Recycle all views.
*/
void recycleAllViews() {
final int childCount = getChildCount();
final int position = mFirstPosition;
// All views go in recycler
for ( int i = 0; i < childCount; i++ ) {
View v = getChildAt( i );
int index = position + i;
int viewType = mAdapter.getItemViewType( index );
mRecycleBin.get( viewType ).offer( v );
// if ( position + i < 0 ) {
// recycleBin2.put( index, v );
// } else {
// recycleBin.put( index, v );
// }
}
// recycleBin2.clear();
}
/**
* Jump directly to a specific item in the adapter data.
*
* @param position
* the position
* @param animate
* the animate
*/
public void setSelection( int position, boolean animate, boolean changed ) {
// Animate only if requested position is already on screen somewhere
boolean shouldAnimate = animate && mFirstPosition <= position && position <= mFirstPosition + getChildCount() - 1;
setSelectionInt( position, shouldAnimate, changed );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#setSelection(int)
*/
@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, boolean changed ) {
if ( position != mOldSelectedPosition ) {
mBlockLayoutRequests = true;
int delta = position - mSelectedPosition;
setNextSelectedPositionInt( position );
layout( delta, animate, changed );
mBlockLayoutRequests = false;
}
}
/**
* Layout.
*
* @param delta
* the delta
* @param animate
* the animate
*/
abstract void layout( int delta, boolean animate, boolean changed );
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#getSelectedView()
*/
@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();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#getAdapter()
*/
@Override
public Adapter getAdapter() {
return mAdapter;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#getCount()
*/
@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;
}
/**
* The Class SavedState.
*/
static class SavedState extends BaseSavedState {
/** The selected id. */
long selectedId;
/** The position. */
int position;
/**
* Constructor called from {@link AbsSpinner#onSaveInstanceState()}.
*
* @param superState
* the super state
*/
SavedState( Parcelable superState ) {
super( superState );
}
/**
* Constructor called from {@link #CREATOR}.
*
* @param in
* the in
*/
private SavedState( Parcel in ) {
super( in );
selectedId = in.readLong();
position = in.readInt();
}
/*
* (non-Javadoc)
*
* @see android.view.AbsSavedState#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel( Parcel out, int flags ) {
super.writeToParcel( out, flags );
out.writeLong( selectedId );
out.writeInt( position );
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "AbsSpinner.SavedState{" + Integer.toHexString( System.identityHashCode( this ) ) + " selectedId=" + selectedId
+ " position=" + position + "}";
}
/** The Constant CREATOR. */
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel( Parcel in ) {
return new SavedState( in );
}
public SavedState[] newArray( int size ) {
return new SavedState[size];
}
};
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSaveInstanceState()
*/
@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;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onRestoreInstanceState(android.os.Parcelable)
*/
@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();
}
}
/**
* The Class RecycleBin.
*/
class RecycleBin {
/** The m scrap heap. */
@SuppressWarnings("unused")
private final SparseArray<View> mScrapHeap = new SparseArray<View>();
/** The m heap. */
private final ArrayList<View> mHeap = new ArrayList<View>( 100 );
/**
* Put.
*
* @param position
* the position
* @param v
* the v
*/
public void put( int position, View v ) {
mHeap.add( v );
// mScrapHeap.put( position, v );
}
/**
* Gets the.
*
* @param position
* the position
* @return the view
*/
View get( int position ) {
if ( mHeap.size() < 1 ) return null;
View result = mHeap.remove( 0 );
return result;
/*
* View result = mScrapHeap.get( position ); if ( result != null ) { mScrapHeap.delete( position ); } else { } return
* result;
*/
}
/**
* Clear.
*/
void clear() {
/*
* final SparseArray<View> 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();
*/
final int count = mHeap.size();
for ( int i = 0; i < count; i++ ) {
final View view = mHeap.remove( 0 );
if ( view != null ) {
removeDetachedView( view, true );
}
}
mHeap.clear();
}
}
}
| Java |
/*
* HorizontalListView.java v1.5
*
*
* The MIT License
* Copyright (c) 2011 Paul Soucy (paul@dev-smart.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.aviary.android.feather.widget;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import com.aviary.android.feather.R;
import com.aviary.android.feather.database.DataSetObserverExtended;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
import com.aviary.android.feather.widget.IFlingRunnable.FlingRunnableView;
import com.aviary.android.feather.widget.wp.EdgeGlow;
// TODO: Auto-generated Javadoc
/**
* The Class HorizontialFixedListView.
*/
public class HorizontalFixedListView extends AdapterView<ListAdapter> implements OnGestureListener, FlingRunnableView {
/** The Constant LOG_TAG. */
protected static final String LOG_TAG = "hv";
/** The m adapter. */
protected ListAdapter mAdapter;
/** The m left view index. */
private int mLeftViewIndex = -1;
/** The m right view index. */
private int mRightViewIndex = 0;
/** The m gesture. */
private GestureDetector mGesture;
/** The m removed view queue. */
private List<Queue<View>> mRecycleBin;
/** The m on item selected. */
private OnItemSelectedListener mOnItemSelected;
/** The m on item clicked. */
private OnItemClickListener mOnItemClicked;
/** The m data changed. */
private boolean mDataChanged = false;
/** The m fling runnable. */
private IFlingRunnable mFlingRunnable;
/** The m force layout. */
private boolean mForceLayout;
private int mDragTolerance = 0;
private boolean mDragScrollEnabled;
protected int mItemCount = 0;
protected EdgeGlow mEdgeGlowLeft, mEdgeGlowRight;
private int mOverScrollMode = OVER_SCROLL_NEVER;
static Logger logger = LoggerFactory.getLogger( "HorizontalFixedList", LoggerType.ConsoleLoggerType );
/**
* Interface definition for a callback to be invoked when an item in this view has been clicked and held.
*/
public interface OnItemDragListener {
/**
* Callback method to be invoked when an item in this view has been dragged outside the vertical tolerance area.
*
* 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 onItemStartDrag( AdapterView<?> parent, View view, int position, long id );
}
private OnItemDragListener mItemDragListener;
public void setOnItemDragListener( OnItemDragListener listener ) {
mItemDragListener = listener;
}
public OnItemDragListener getOnItemDragListener() {
return mItemDragListener;
}
/**
* Instantiates a new horizontial fixed list view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public HorizontalFixedListView( Context context, AttributeSet attrs ) {
super( context, attrs );
initView();
}
public HorizontalFixedListView( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
initView();
}
/**
* Inits the view.
*/
private synchronized void initView() {
if ( Build.VERSION.SDK_INT > 8 ) {
try {
mFlingRunnable = (IFlingRunnable) ReflectionUtils.newInstance( "com.aviary.android.feather.widget.Fling9Runnable",
new Class<?>[] { FlingRunnableView.class, int.class }, this, mAnimationDuration );
} catch ( ReflectionException e ) {
mFlingRunnable = new Fling8Runnable( this, mAnimationDuration );
}
} else {
mFlingRunnable = new Fling8Runnable( this, mAnimationDuration );
}
mLeftViewIndex = -1;
mRightViewIndex = 0;
mMaxX = 0;
mMinX = 0;
mChildWidth = 0;
mChildHeight = 0;
mRightEdge = 0;
mLeftEdge = 0;
mGesture = new GestureDetector( getContext(), mGestureListener );
mGesture.setIsLongpressEnabled( true );
setFocusable( true );
setFocusableInTouchMode( true );
ViewConfiguration configuration = ViewConfiguration.get( getContext() );
mTouchSlop = configuration.getScaledTouchSlop();
mDragTolerance = mTouchSlop;
mOverscrollDistance = 10;
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
}
public void setOverScrollMode( int mode ) {
mOverScrollMode = mode;
if ( mode != OVER_SCROLL_NEVER ) {
if ( mEdgeGlowLeft == null ) {
Drawable glow = getContext().getResources().getDrawable( R.drawable.feather_overscroll_glow );
Drawable edge = getContext().getResources().getDrawable( R.drawable.feather_overscroll_edge );
mEdgeGlowLeft = new EdgeGlow( edge, glow );
mEdgeGlowRight = new EdgeGlow( edge, glow );
mEdgeGlowLeft.setColorFilter( 0xFF33b5e5, Mode.MULTIPLY );
}
} else {
mEdgeGlowLeft = mEdgeGlowRight = null;
}
}
public void setEdgeHeight( int value ) {
mEdgesHeight = value;
}
public void setEdgeGravityY( int value ) {
mEdgesGravityY = value;
}
@Override
public void trackMotionScroll( int newX ) {
scrollTo( newX, 0 );
mCurrentX = getScrollX();
removeNonVisibleItems( mCurrentX );
fillList( mCurrentX );
invalidate();
}
@Override
protected void dispatchDraw( Canvas canvas ) {
super.dispatchDraw( canvas );
if ( getChildCount() > 0 ) {
drawEdges( canvas );
}
}
private Matrix mEdgeMatrix = new Matrix();
/**
* Draw glow edges.
*
* @param canvas
* the canvas
*/
private void drawEdges( Canvas canvas ) {
if ( mEdgeGlowLeft != null ) {
if ( !mEdgeGlowLeft.isFinished() ) {
final int restoreCount = canvas.save();
final int height = mEdgesHeight;
mEdgeMatrix.reset();
mEdgeMatrix.postRotate( -90 );
mEdgeMatrix.postTranslate( 0, height );
if ( mEdgesGravityY == Gravity.BOTTOM ) {
mEdgeMatrix.postTranslate( 0, getHeight() - height );
}
canvas.concat( mEdgeMatrix );
mEdgeGlowLeft.setSize( height, height / 5 );
if ( mEdgeGlowLeft.draw( canvas ) ) {
postInvalidate();
}
canvas.restoreToCount( restoreCount );
}
if ( !mEdgeGlowRight.isFinished() ) {
final int restoreCount = canvas.save();
final int width = getWidth();
final int height = mEdgesHeight;
mEdgeMatrix.reset();
mEdgeMatrix.postRotate( 90 );
mEdgeMatrix.postTranslate( mCurrentX + width, 0 );
if ( mEdgesGravityY == Gravity.BOTTOM ) {
mEdgeMatrix.postTranslate( 0, getHeight() - height );
}
canvas.concat( mEdgeMatrix );
mEdgeGlowRight.setSize( height, height / 5 );
if ( mEdgeGlowRight.draw( canvas ) ) {
postInvalidate();
}
canvas.restoreToCount( restoreCount );
}
}
}
/**
* Set if a vertical scroll movement will trigger a long click event
*
* @param value
*/
public void setDragScrollEnabled( boolean value ) {
mDragScrollEnabled = value;
}
public boolean getDragScrollEnabled() {
return mDragScrollEnabled;
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener)
*/
@Override
public void setOnItemSelectedListener( AdapterView.OnItemSelectedListener listener ) {
mOnItemSelected = listener;
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
*/
@Override
public void setOnItemClickListener( AdapterView.OnItemClickListener listener ) {
mOnItemClicked = listener;
}
private DataSetObserverExtended mDataObserverExtended = new DataSetObserverExtended() {
public void onAdded() {
logger.log( "DataSet::onAdded" );
synchronized ( HorizontalFixedListView.this ) {
mItemCount = mAdapter.getCount();
}
mDataChanged = true;
requestLayout();
};
public void onRemoved() {
logger.log( "DataSet::onRemoved" );
this.onChanged();
};
public void onChanged() {
logger.log( "DataSet::onChanged" );
mItemCount = mAdapter.getCount();
reset();
};
public void onInvalidated() {
logger.log( "DataSet::onInvalidated" );
this.onChanged();
};
};
/** The m data observer. */
private DataSetObserver mDataObserver = new DataSetObserver() {
@Override
public void onChanged() {
logger.log( "DataSet::onChanged" );
synchronized ( HorizontalFixedListView.this ) {
mItemCount = mAdapter.getCount();
}
invalidate();
reset();
}
@Override
public void onInvalidated() {
logger.log( "DataSet::onInvalidated" );
mItemCount = mAdapter.getCount();
invalidate();
reset();
}
};
public void requestFullLayout() {
mForceLayout = true;
invalidate();
requestLayout();
}
/** The m height measure spec. */
private int mHeightMeasureSpec;
/** The m width measure spec. */
private int mWidthMeasureSpec;
/** The m left edge. */
private int mRightEdge, mLeftEdge;
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#getAdapter()
*/
@Override
public ListAdapter getAdapter() {
return mAdapter;
}
@Override
public View getSelectedView() {
return null;
}
@Override
public void setAdapter( ListAdapter adapter ) {
if ( mAdapter != null ) {
if ( mAdapter instanceof BaseAdapterExtended ) {
( (BaseAdapterExtended) mAdapter ).unregisterDataSetObserverExtended( mDataObserverExtended );
} else {
mAdapter.unregisterDataSetObserver( mDataObserver );
}
emptyRecycler();
mItemCount = 0;
}
mAdapter = adapter;
if ( mAdapter != null ) {
mItemCount = mAdapter.getCount();
if ( mAdapter instanceof BaseAdapterExtended ) {
( (BaseAdapterExtended) mAdapter ).registerDataSetObserverExtended( mDataObserverExtended );
} else {
mAdapter.registerDataSetObserver( mDataObserver );
}
int total = mAdapter.getViewTypeCount();
mRecycleBin = Collections.synchronizedList( new ArrayList<Queue<View>>() );
for ( int i = 0; i < total; i++ ) {
mRecycleBin.add( new LinkedList<View>() );
}
}
reset();
}
private void emptyRecycler() {
if ( null != mRecycleBin ) {
while ( mRecycleBin.size() > 0 ) {
Queue<View> recycler = mRecycleBin.remove( 0 );
recycler.clear();
}
mRecycleBin.clear();
}
}
/**
* Reset.
*/
private synchronized void reset() {
mCurrentX = 0;
initView();
removeAllViewsInLayout();
mForceLayout = true;
requestLayout();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
Log.d( LOG_TAG, "onDetachedFromWindow" );
emptyRecycler();
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setSelection(int)
*/
@Override
public void setSelection( int position ) {}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
super.onMeasure( widthMeasureSpec, heightMeasureSpec );
mHeightMeasureSpec = heightMeasureSpec;
mWidthMeasureSpec = widthMeasureSpec;
}
/**
* Adds the and measure child.
*
* @param child
* the child
* @param viewPos
* the view pos
*/
private void addAndMeasureChild( final View child, int viewPos ) {
LayoutParams params = child.getLayoutParams();
if ( params == null ) {
params = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT );
}
addViewInLayout( child, viewPos, params, false );
forceChildLayout( child, params );
}
public void forceChildLayout( View child, LayoutParams params ) {
int childHeightSpec = ViewGroup.getChildMeasureSpec( mHeightMeasureSpec, getPaddingTop() + getPaddingBottom(), params.height );
int childWidthSpec = ViewGroup.getChildMeasureSpec( mWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), params.width );
child.measure( childWidthSpec, childHeightSpec );
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
if ( mAdapter == null ) {
return;
}
if ( !changed && !mDataChanged ) {
layoutChildren();
}
if ( changed ) {
mCurrentX = mOldX = 0;
initView();
removeAllViewsInLayout();
trackMotionScroll( 0 );
}
if ( mDataChanged ) {
trackMotionScroll( mCurrentX );
mDataChanged = false;
}
if ( mForceLayout ) {
mOldX = mCurrentX;
initView();
removeAllViewsInLayout();
trackMotionScroll( mOldX );
mForceLayout = false;
}
}
public void layoutChildren() {
int paddingTop = getPaddingTop();
int left, right;
for ( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
forceChildLayout( child, child.getLayoutParams() );
left = child.getLeft();
right = child.getRight();
child.layout( left, paddingTop, right, paddingTop + child.getMeasuredHeight() );
}
}
/**
* Fill list.
*
* @param positionX
* the position x
*/
private void fillList( final int positionX ) {
int edge = 0;
View child = getChildAt( getChildCount() - 1 );
if ( child != null ) {
edge = child.getRight();
}
fillListRight( mCurrentX, edge );
edge = 0;
child = getChildAt( 0 );
if ( child != null ) {
edge = child.getLeft();
}
fillListLeft( mCurrentX, edge );
}
/**
* Fill list left.
*
* @param positionX
* the position x
* @param leftEdge
* the left edge
*/
private void fillListLeft( int positionX, int leftEdge ) {
if ( mAdapter == null ) return;
while ( ( leftEdge - positionX ) > mLeftEdge && mLeftViewIndex >= 0 ) {
int viewType = mAdapter.getItemViewType( mLeftViewIndex );
View child = mAdapter.getView( mLeftViewIndex, mRecycleBin.get( viewType ).poll(), this );
addAndMeasureChild( child, 0 );
int childTop = getPaddingTop();
child.layout( leftEdge - mChildWidth, childTop, leftEdge, childTop + mChildHeight );
leftEdge -= mChildWidth;
mLeftViewIndex--;
}
}
public View getItemAt( int position ) {
return getChildAt( position - ( mLeftViewIndex + 1 ) );
}
public int getScreenPositionForView( 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 i;
}
}
// Child not found!
return INVALID_POSITION;
}
@Override
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 mLeftViewIndex + i + 1;
}
}
// Child not found!
return INVALID_POSITION;
}
public void setHideLastChild( boolean value ) {
mHideLastChild = value;
}
/**
* Items will appear from right to left
*
* @param value
*/
public void setInverted( boolean value ) {
mInverted = value;
}
/**
* Fill list right.
*
* @param positionX
* the position x
* @param rightEdge
* the right edge
*/
private void fillListRight( int positionX, int rightEdge ) {
boolean firstChild = getChildCount() == 0 || mDataChanged || mForceLayout;
if ( mAdapter == null ) return;
while ( ( rightEdge - positionX ) < mRightEdge || firstChild ) {
if ( mRightViewIndex >= mItemCount ) {
break;
}
int viewType = mAdapter.getItemViewType( mRightViewIndex );
View child = mAdapter.getView( mRightViewIndex, mRecycleBin.get( viewType ).poll(), this );
addAndMeasureChild( child, -1 );
if ( firstChild ) {
mChildWidth = child.getMeasuredWidth();
mChildHeight = child.getMeasuredHeight();
if ( mEdgesHeight == -1 ) {
mEdgesHeight = mChildHeight;
}
mRightEdge = getWidth() + mChildWidth;
mLeftEdge = -mChildWidth;
mMaxX = Math.max( mItemCount * ( mChildWidth ) - ( getWidth() ) - ( mHideLastChild ? mChildWidth / 2 : 0 ), 0 );
mMinX = 0;
firstChild = false;
//Log.d( LOG_TAG, "min: " + mMinX + ", max: " + mMaxX );
//Log.d( LOG_TAG, "left: " + mLeftEdge + ", right: " + mRightEdge );
if ( mMaxX == 0 ) {
if ( mInverted ) rightEdge += getWidth() - ( mItemCount * mChildWidth );
mLeftEdge = 0;
mRightEdge = getWidth();
// Log.d( "hv", "new right: " + rightEdge );
}
}
int childTop = getPaddingTop();
child.layout( rightEdge, childTop, rightEdge + mChildWidth, childTop + child.getMeasuredHeight() );
rightEdge += mChildWidth;
mRightViewIndex++;
}
}
/**
* Removes the non visible items.
*
* @param positionX
* the position x
*/
private void removeNonVisibleItems( final int positionX ) {
View child = getChildAt( 0 );
// remove to left...
while ( child != null && child.getRight() - positionX <= mLeftEdge ) {
if ( null != mAdapter ) {
int position = getPositionForView( child );
int viewType = mAdapter.getItemViewType( position );
mRecycleBin.get( viewType ).offer( child );
}
removeViewInLayout( child );
mLeftViewIndex++;
child = getChildAt( 0 );
}
// remove to right...
child = getChildAt( getChildCount() - 1 );
while ( child != null && child.getLeft() - positionX >= mRightEdge ) {
if ( null != mAdapter ) {
int position = getPositionForView( child );
int viewType = mAdapter.getItemViewType( position );
mRecycleBin.get( viewType ).offer( child );
}
removeViewInLayout( child );
mRightViewIndex--;
child = getChildAt( getChildCount() - 1 );
}
}
private float mTestDragX, mTestDragY;
private boolean mCanCheckDrag;
private boolean mWasFlinging;
private WeakReference<View> mOriginalDragItem;
@Override
public boolean onDown( MotionEvent event ) {
return true;
}
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
return true;
}
@Override
public boolean onFling( MotionEvent event0, MotionEvent event1, float velocityX, float velocityY ) {
if ( mMaxX == 0 ) return false;
mCanCheckDrag = false;
mWasFlinging = true;
mFlingRunnable.startUsingVelocity( mCurrentX, (int) -velocityX );
return true;
}
@Override
public void onLongPress( MotionEvent e ) {
if ( mWasFlinging ) return;
OnItemLongClickListener listener = getOnItemLongClickListener();
if ( null != listener ) {
if ( !mFlingRunnable.isFinished() ) return;
int i = getChildAtPosition( e.getX(), e.getY() );
if ( i > -1 ) {
View child = getChildAt( i );
fireLongPress( child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ) );
}
}
}
private int getChildAtPosition( float x, float y ) {
Rect viewRect = new Rect();
for ( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
int left = child.getLeft();
int right = child.getRight();
int top = child.getTop();
int bottom = child.getBottom();
viewRect.set( left, top, right, bottom );
viewRect.offset( -mCurrentX, 0 );
if ( viewRect.contains( (int) x, (int) y ) ) {
return i;
}
}
return -1;
}
private boolean fireLongPress( View item, int position, long id ) {
if ( getOnItemLongClickListener().onItemLongClick( HorizontalFixedListView.this, item, position, id ) ) {
performHapticFeedback( HapticFeedbackConstants.LONG_PRESS );
return true;
}
return false;
}
private boolean fireItemDragStart( View item, int position, long id ) {
mCanCheckDrag = false;
mIsBeingDragged = false;
if ( mItemDragListener.onItemStartDrag( HorizontalFixedListView.this, item, position, id ) ) {
performHapticFeedback( HapticFeedbackConstants.LONG_PRESS );
mIsDragging = true;
return true;
}
return false;
}
public void setIsDragging( boolean value ) {
logger.info( "setIsDragging: " + value );
mIsDragging = value;
}
private int getItemIndex( View view ) {
final int total = getChildCount();
for ( int i = 0; i < total; i++ ) {
if ( view == getChildAt( i ) ) {
return i;
}
}
return -1;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress( MotionEvent arg0 ) {}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp( MotionEvent arg0 ) {
logger.error( "onSingleTapUp" );
return false;
}
private boolean mIsDragging = false;
private boolean mIsBeingDragged = false;
private int mActivePointerId = -1;
private int mLastMotionX;
private float mLastMotionX2;
private VelocityTracker mVelocityTracker;
private static final int INVALID_POINTER = -1;
private int mOverscrollDistance;
private int mMinimumVelocity;
private int mMaximumVelocity;
private void initOrResetVelocityTracker() {
if ( mVelocityTracker == null ) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
}
private void initVelocityTrackerIfNotExists() {
if ( mVelocityTracker == null ) {
mVelocityTracker = VelocityTracker.obtain();
}
}
private void recycleVelocityTracker() {
if ( mVelocityTracker != null ) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
@Override
public void requestDisallowInterceptTouchEvent( boolean disallowIntercept ) {
if ( disallowIntercept ) {
recycleVelocityTracker();
}
super.requestDisallowInterceptTouchEvent( disallowIntercept );
}
@Override
public boolean onInterceptTouchEvent( MotionEvent ev ) {
if( mIsDragging ) return false;
final int action = ev.getAction();
mGesture.onTouchEvent( ev );
/*
* Shortcut the most recurring case: the user is in the dragging state and he is moving his finger. We want to intercept this
* motion.
*/
if ( action == MotionEvent.ACTION_MOVE ) {
if( mIsBeingDragged )
return true;
}
switch ( action & MotionEvent.ACTION_MASK ) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check whether the user has moved far enough
* from his original down touch.
*/
final int activePointerId = mActivePointerId;
if ( activePointerId == INVALID_POINTER ) {
// If we don't have a valid id, the touch down wasn't on content.
break;
}
final int pointerIndex = ev.findPointerIndex( activePointerId );
final int x = (int) ev.getX( pointerIndex );
final int y = (int) ev.getY( pointerIndex );
final int xDiff = Math.abs( x - mLastMotionX );
mLastMotionX2 = x;
if( checkDrag( x, y ) ){
return false;
}
if ( xDiff > mTouchSlop ) {
mIsBeingDragged = true;
mLastMotionX = x;
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement( ev );
final ViewParent parent = getParent();
if ( parent != null ) {
parent.requestDisallowInterceptTouchEvent( true );
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
final int x = (int) ev.getX();
final int y = (int) ev.getY();
mTestDragX = x;
mTestDragY = y;
/*
* Remember location of down touch. ACTION_DOWN always refers to pointer index 0.
*/
mLastMotionX = x;
mLastMotionX2 = x;
mActivePointerId = ev.getPointerId( 0 );
initOrResetVelocityTracker();
mVelocityTracker.addMovement( ev );
/*
* If being flinged and user touches the screen, initiate drag; otherwise don't. mScroller.isFinished should be false
* when being flinged.
*/
mIsBeingDragged = !mFlingRunnable.isFinished();
mWasFlinging = !mFlingRunnable.isFinished();
mFlingRunnable.stop( false );
mCanCheckDrag = isLongClickable() && getDragScrollEnabled() && ( mItemDragListener != null );
if ( mCanCheckDrag ) {
int i = getChildAtPosition( x, y );
if ( i > -1 ) {
mOriginalDragItem = new WeakReference<View>( getChildAt( i ) );
}
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
/* Release the drag */
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
recycleVelocityTracker();
if ( mFlingRunnable.springBack( mCurrentX, 0, mMinX, mMaxX, 0, 0 ) ) {
postInvalidate();
}
mCanCheckDrag = false;
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp( ev );
break;
}
return mIsBeingDragged;
}
@Override
public boolean onTouchEvent( MotionEvent ev ) {
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement( ev );
final int action = ev.getAction();
switch ( action & MotionEvent.ACTION_MASK ) {
case MotionEvent.ACTION_DOWN: { // DOWN
if ( getChildCount() == 0 ) {
return false;
}
if ( ( mIsBeingDragged = !mFlingRunnable.isFinished() ) ) {
final ViewParent parent = getParent();
if ( parent != null ) {
parent.requestDisallowInterceptTouchEvent( true );
}
}
/*
* If being flinged and user touches, stop the fling. isFinished will be false if being flinged.
*/
if ( !mFlingRunnable.isFinished() ) {
// mScroller.abortAnimation();
mFlingRunnable.stop( false );
}
// Remember where the motion event started
mTestDragX = ev.getX();
mTestDragY = ev.getY();
mLastMotionX2 = mLastMotionX = (int) ev.getX();
mActivePointerId = ev.getPointerId( 0 );
break;
}
case MotionEvent.ACTION_MOVE: {
// MOVE
final int activePointerIndex = ev.findPointerIndex( mActivePointerId );
final int x = (int) ev.getX( activePointerIndex );
final int y = (int) ev.getY( activePointerIndex );
int deltaX = mLastMotionX - x;
if ( !mIsBeingDragged && Math.abs( deltaX ) > mTouchSlop ) {
final ViewParent parent = getParent();
if ( parent != null ) {
parent.requestDisallowInterceptTouchEvent( true );
}
mIsBeingDragged = true;
if ( deltaX > 0 ) {
deltaX -= mTouchSlop;
} else {
deltaX += mTouchSlop;
}
}
// first check if we can drag the item
if( checkDrag( x, y ) ){
return false;
}
if ( mIsBeingDragged ) {
// Scroll to follow the motion event
mLastMotionX = x;
final float deltaX2 = mLastMotionX2 - x;
final int oldX = getScrollX();
final int range = mMaxX - mMinX;
final int overscrollMode = mOverScrollMode;
final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS
|| ( overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0 );
if ( overScrollingBy( deltaX, 0, mCurrentX, 0, range, 0, 0, mOverscrollDistance, true ) ) {
mVelocityTracker.clear();
}
if ( canOverscroll && mEdgeGlowLeft != null ) {
final int pulledToX = oldX + deltaX;
if ( pulledToX < mMinX ) {
float overscroll = ( (float) -deltaX2 * 1.5f ) / getWidth();
mEdgeGlowLeft.onPull( overscroll );
if ( !mEdgeGlowRight.isFinished() ) {
mEdgeGlowRight.onRelease();
}
} else if ( pulledToX > mMaxX ) {
float overscroll = ( (float) deltaX2 * 1.5f ) / getWidth();
mEdgeGlowRight.onPull( overscroll );
if ( !mEdgeGlowLeft.isFinished() ) {
mEdgeGlowLeft.onRelease();
}
}
if ( mEdgeGlowLeft != null && ( !mEdgeGlowLeft.isFinished() || !mEdgeGlowRight.isFinished() ) ) {
postInvalidate();
}
}
}
break;
}
case MotionEvent.ACTION_UP: {
if ( mIsBeingDragged ) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity( 1000, mMaximumVelocity );
final float velocityY = velocityTracker.getYVelocity();
final float velocityX = velocityTracker.getXVelocity();
if ( getChildCount() > 0 ) {
if ( ( Math.abs( velocityX ) > mMinimumVelocity ) ) {
onFling( ev, null, velocityX, velocityY );
} else {
if ( mFlingRunnable.springBack( mCurrentX, 0, mMinX, mMaxX, 0, 0 ) ) {
postInvalidate();
}
}
}
mActivePointerId = INVALID_POINTER;
endDrag();
mCanCheckDrag = false;
if ( mFlingRunnable.isFinished() ) {
scrollIntoSlots();
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
if ( mIsBeingDragged && getChildCount() > 0 ) {
if ( mFlingRunnable.springBack( mCurrentX, 0, mMinX, mMaxX, 0, 0 ) ) {
postInvalidate();
}
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
}
case MotionEvent.ACTION_POINTER_UP: {
onSecondaryPointerUp( ev );
mTestDragX = mLastMotionX2 = mLastMotionX = (int) ev.getX( ev.findPointerIndex( mActivePointerId ) );
mTestDragY = ev.getY( ev.findPointerIndex( mActivePointerId ) );
break;
}
}
return true;
}
private void onSecondaryPointerUp( MotionEvent ev ) {
final int pointerIndex = ( ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK ) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId( pointerIndex );
if ( pointerId == mActivePointerId ) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mTestDragX = mLastMotionX2 = mLastMotionX = (int) ev.getX( newPointerIndex );
mTestDragY = ev.getY( newPointerIndex );
mActivePointerId = ev.getPointerId( newPointerIndex );
if ( mVelocityTracker != null ) {
mVelocityTracker.clear();
}
}
}
/**
* Check if the movement will fire a drag start event
* @param x
* @param y
* @return
*/
private boolean checkDrag( int x, int y ) {
if ( mCanCheckDrag && !mIsDragging ) {
float dx = Math.abs( x - mTestDragX );
if ( dx > mDragTolerance ) {
mCanCheckDrag = false;
} else {
float dy = Math.abs( y - mTestDragY );
if ( dy > ((double)mDragTolerance*1.5) ) {
if ( mOriginalDragItem != null && mAdapter != null ) {
View view = mOriginalDragItem.get();
int position = getItemIndex( view );
if ( null != view && position > -1 ) {
getParent().requestDisallowInterceptTouchEvent( false );
if ( mItemDragListener != null ) {
fireItemDragStart( view, mLeftViewIndex + 1 + position, mAdapter.getItemId( mLeftViewIndex + 1 + position ) );
return true;
}
}
}
mCanCheckDrag = false;
}
}
}
return false;
}
private void endDrag() {
mIsBeingDragged = false;
recycleVelocityTracker();
if ( mEdgeGlowLeft != null ) {
mEdgeGlowLeft.onRelease();
mEdgeGlowRight.onRelease();
}
}
/**
* Scroll the view with standard behavior for scrolling beyond the normal content boundaries. Views that call this method should
* override {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the results of an over-scroll operation.
*
* Views can use this method to handle any touch or fling-based scrolling.
*
* @param deltaX
* Change in X in pixels
* @param deltaY
* Change in Y in pixels
* @param scrollX
* Current X scroll value in pixels before applying deltaX
* @param scrollY
* Current Y scroll value in pixels before applying deltaY
* @param scrollRangeX
* Maximum content scroll range along the X axis
* @param scrollRangeY
* Maximum content scroll range along the Y axis
* @param maxOverScrollX
* Number of pixels to overscroll by in either direction along the X axis.
* @param maxOverScrollY
* Number of pixels to overscroll by in either direction along the Y axis.
* @param isTouchEvent
* true if this scroll operation is the result of a touch event.
* @return true if scrolling was clamped to an over-scroll boundary along either axis, false otherwise.
*/
protected boolean overScrollingBy( int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY,
int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent ) {
final int overScrollMode = mOverScrollMode;
final boolean toLeft = deltaX > 0;
final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS;
int newScrollX = scrollX + deltaX;
if ( !overScrollHorizontal ) {
maxOverScrollX = 0;
}
// Clamp values if at the limits and record
final int left = mMinX - maxOverScrollX;
final int right = mMaxX + maxOverScrollX;
boolean clampedX = false;
if ( newScrollX > right && toLeft ) {
newScrollX = right;
deltaX = mMaxX - scrollX;
clampedX = true;
} else if ( newScrollX < left && !toLeft ) {
newScrollX = left;
deltaX = mMinX - scrollX;
clampedX = true;
}
onScrolling( newScrollX, deltaX, clampedX );
return clampedX;
}
public boolean onScrolling( int scrollX, int deltaX, boolean clampedX ) {
if ( mAdapter == null ) return true;
if ( mMaxX == 0 ) return true;
if ( !mFlingRunnable.isFinished() ) {
mCurrentX = getScrollX();
if ( clampedX ) {
mFlingRunnable.springBack( scrollX, 0, mMinX, mMaxX, 0, 0 );
}
} else {
trackMotionScroll( scrollX );
}
return true;
}
@Override
public void computeScroll() {
if ( mFlingRunnable.computeScrollOffset() ) {
int oldX = mCurrentX;
int x = mFlingRunnable.getCurrX();
if ( oldX != x ) {
final int range = getScrollRange();
final int overscrollMode = mOverScrollMode;
final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS
|| ( overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0 );
overScrollingBy( x - oldX, 0, oldX, 0, range, 0, mOverscrollDistance, 0, false );
if ( canOverscroll && mEdgeGlowLeft != null ) {
if ( x < 0 && oldX >= 0 ) {
mEdgeGlowLeft.onAbsorb( (int) mFlingRunnable.getCurrVelocity() );
} else if ( x > range && oldX <= range ) {
mEdgeGlowRight.onAbsorb( (int) mFlingRunnable.getCurrVelocity() );
}
}
}
postInvalidate();
}
}
int getScrollRange() {
if ( getChildCount() > 0 ) {
return mMaxX - mMinX;
}
return 0;
}
/** The m animation duration. */
int mAnimationDuration = 400;
/** The m child height. */
int mMaxX, mMinX, mChildWidth, mChildHeight;
boolean mHideLastChild;
boolean mInverted;
/** The m should stop fling. */
boolean mShouldStopFling;
/** The m to left. */
boolean mToLeft;
/** The m current x. */
int mCurrentX = 0;
/** The m old x. */
int mOldX = 0;
/** The m touch slop. */
int mTouchSlop;
int mEdgesHeight = -1;
int mEdgesGravityY = Gravity.CENTER;
@Override
public void scrollIntoSlots() {
if ( !mFlingRunnable.isFinished() ) {
return;
}
// boolean greater_enough = mItemCount * ( mChildWidth ) > getWidth();
if ( mCurrentX > mMaxX || mCurrentX < mMinX ) {
if ( mCurrentX > mMaxX ) {
if ( mMaxX < 0 ) {
mFlingRunnable.startUsingDistance( mCurrentX, mMinX - mCurrentX );
} else {
mFlingRunnable.startUsingDistance( mCurrentX, mMaxX - mCurrentX );
}
return;
} else {
mFlingRunnable.startUsingDistance( mCurrentX, mMinX - mCurrentX );
return;
}
}
onFinishedMovement();
}
/**
* On finished movement.
*/
protected void onFinishedMovement() {
logger.info( "onFinishedMovement" );
}
/** The m gesture listener. */
private OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap( MotionEvent e ) {
return false;
};
public boolean onSingleTapUp(MotionEvent e) {
logger.error( "onSingleTapUp" );
return onItemClick( e );
};
@Override
public boolean onDown( MotionEvent e ) {
return false;
// return HorizontalFixedListView.this.onDown( e );
};
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
return false;
// return HorizontalFixedListView.this.onFling( e1, e2, velocityX, velocityY );
};
@Override
public void onLongPress( MotionEvent e ) {
HorizontalFixedListView.this.onLongPress( e );
};
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
return false;
// return HorizontalFixedListView.this.onScroll( e1, e2, distanceX, distanceY );
};
@Override
public void onShowPress( MotionEvent e ) {};
@Override
public boolean onSingleTapConfirmed( MotionEvent e ) {
logger.error( "onSingleTapConfirmed" );
return true;
}
private boolean onItemClick( MotionEvent ev ){
if ( !mFlingRunnable.isFinished() || mWasFlinging ) return false;
Rect viewRect = new Rect();
for ( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
int left = child.getLeft();
int right = child.getRight();
int top = child.getTop();
int bottom = child.getBottom();
viewRect.set( left, top, right, bottom );
viewRect.offset( -mCurrentX, 0 );
if ( viewRect.contains( (int) ev.getX(), (int) ev.getY() ) ) {
if ( mOnItemClicked != null ) {
playSoundEffect( SoundEffectConstants.CLICK );
mOnItemClicked.onItemClick( HorizontalFixedListView.this, child, mLeftViewIndex + 1 + i,
mAdapter.getItemId( mLeftViewIndex + 1 + i ) );
}
if ( mOnItemSelected != null ) {
mOnItemSelected.onItemSelected( HorizontalFixedListView.this, child, mLeftViewIndex + 1 + i,
mAdapter.getItemId( mLeftViewIndex + 1 + i ) );
}
break;
}
}
return true;
}
};
public View getChild( MotionEvent e ) {
Rect viewRect = new Rect();
for ( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
int left = child.getLeft();
int right = child.getRight();
int top = child.getTop();
int bottom = child.getBottom();
viewRect.set( left, top, right, bottom );
viewRect.offset( -mCurrentX, 0 );
if ( viewRect.contains( (int) e.getX(), (int) e.getY() ) ) {
return child;
}
}
return null;
}
@Override
public int getMinX() {
return mMinX;
}
@Override
public int getMaxX() {
return mMaxX;
}
public void setDragTolerance( int value ) {
mDragTolerance = value;
}
}
| Java |
/*
* HorizontalListView.java v1.5
*
*
* The MIT License
* Copyright (c) 2011 Paul Soucy (paul@dev-smart.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.aviary.android.feather.widget;
import java.util.LinkedList;
import java.util.Queue;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;
import com.aviary.android.feather.library.log.LoggerFactory;
// TODO: Auto-generated Javadoc
/**
* The Class HorizontialListView.
*/
public class HorizontalListView extends AdapterView<ListAdapter> {
/** The m always override touch. */
public boolean mAlwaysOverrideTouch = true;
/** The m adapter. */
protected ListAdapter mAdapter;
/** The m left view index. */
private int mLeftViewIndex = -1;
/** The m right view index. */
private int mRightViewIndex = 0;
/** The m current x. */
protected int mCurrentX;
/** The m next x. */
protected int mNextX;
/** The m max x. */
private int mMaxX = Integer.MAX_VALUE;
/** The m display offset. */
private int mDisplayOffset = 0;
/** The m scroller. */
protected Scroller mScroller;
/** The m gesture. */
private GestureDetector mGesture;
/** The m removed view queue. */
private Queue<View> mRemovedViewQueue = new LinkedList<View>();
/** The m on item selected. */
private OnItemSelectedListener mOnItemSelected;
/** The m on item clicked. */
private OnItemClickListener mOnItemClicked;
/** The m data changed. */
private boolean mDataChanged = false;
/**
* Instantiates a new horizontial list view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public HorizontalListView( Context context, AttributeSet attrs ) {
super( context, attrs );
initView();
}
/**
* Inits the view.
*/
private synchronized void initView() {
mLeftViewIndex = -1;
mRightViewIndex = 0;
mDisplayOffset = 0;
mCurrentX = 0;
mNextX = 0;
mMaxX = Integer.MAX_VALUE;
mScroller = new Scroller( getContext() );
mGesture = new GestureDetector( getContext(), mOnGesture );
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener)
*/
@Override
public void setOnItemSelectedListener( AdapterView.OnItemSelectedListener listener ) {
mOnItemSelected = listener;
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
*/
@Override
public void setOnItemClickListener( AdapterView.OnItemClickListener listener ) {
mOnItemClicked = listener;
}
/** The m data observer. */
private DataSetObserver mDataObserver = new DataSetObserver() {
@Override
public void onChanged() {
synchronized ( HorizontalListView.this ) {
mDataChanged = true;
}
invalidate();
requestLayout();
}
@Override
public void onInvalidated() {
reset();
invalidate();
requestLayout();
}
};
/** The m height measure spec. */
private int mHeightMeasureSpec;
/** The m width measure spec. */
private int mWidthMeasureSpec;
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#getAdapter()
*/
@Override
public ListAdapter getAdapter() {
return mAdapter;
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#getSelectedView()
*/
@Override
public View getSelectedView() {
// TODO: implement
return null;
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setAdapter(android.widget.Adapter)
*/
@Override
public void setAdapter( ListAdapter adapter ) {
if ( mAdapter != null ) {
mAdapter.unregisterDataSetObserver( mDataObserver );
}
mAdapter = adapter;
if ( null != mAdapter ) {
mAdapter.registerDataSetObserver( mDataObserver );
}
reset();
}
/**
* Reset.
*/
private synchronized void reset() {
initView();
removeAllViewsInLayout();
requestLayout();
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#setSelection(int)
*/
@Override
public void setSelection( int position ) {
// TODO: implement
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
Log.d( VIEW_LOG_TAG, "onMeasure" );
super.onMeasure( widthMeasureSpec, heightMeasureSpec );
mHeightMeasureSpec = heightMeasureSpec;
mWidthMeasureSpec = widthMeasureSpec;
}
/**
* Adds the and measure child.
*
* @param child
* the child
* @param viewPos
* the view pos
*/
private void addAndMeasureChild( final View child, int viewPos ) {
LayoutParams params = child.getLayoutParams();
if ( params == null ) {
params = new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT );
}
addViewInLayout( child, viewPos, params );
forceChildLayout( child, params );
}
public void forceChildLayout( final View child, final LayoutParams params ) {
int childHeightSpec = ViewGroup.getChildMeasureSpec( mHeightMeasureSpec, getPaddingTop() + getPaddingBottom(), params.height );
int childWidthSpec = ViewGroup.getChildMeasureSpec( mWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), params.width );
child.measure( childWidthSpec, childHeightSpec );
}
/**
* Gets the real height.
*
* @return the real height
*/
@SuppressWarnings("unused")
private int getRealHeight() {
return getHeight() - ( getPaddingTop() + getPaddingBottom() );
}
/**
* Gets the real width.
*
* @return the real width
*/
@SuppressWarnings("unused")
private int getRealWidth() {
return getWidth() - ( getPaddingLeft() + getPaddingRight() );
}
public void requestFullLayout() {
mDataChanged = true;
invalidate();
requestLayout();
}
/*
* (non-Javadoc)
*
* @see android.widget.AdapterView#onLayout(boolean, int, int, int, int)
*/
@Override
protected synchronized void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
Log.d( VIEW_LOG_TAG, "onLayout: " + changed );
if ( mAdapter == null ) {
return;
}
if ( mDataChanged ) {
int oldCurrentX = mCurrentX;
initView();
removeAllViewsInLayout();
mNextX = oldCurrentX;
mDataChanged = false;
}
if ( mScroller.computeScrollOffset() ) {
int scrollx = mScroller.getCurrX();
mNextX = scrollx;
}
if ( mNextX < 0 ) {
mNextX = 0;
mScroller.forceFinished( true );
}
if ( mNextX > mMaxX ) {
mNextX = mMaxX;
mScroller.forceFinished( true );
}
int dx = mCurrentX - mNextX;
removeNonVisibleItems( dx );
fillList( dx );
positionItems( dx );
mCurrentX = mNextX;
if ( !mScroller.isFinished() ) {
post( mRequestLayoutRunnable );
}
}
private Runnable mRequestLayoutRunnable = new Runnable() {
@Override
public void run() {
requestLayout();
}
};
/**
* Fill list.
*
* @param dx
* the dx
*/
private void fillList( final int dx ) {
int edge = 0;
View child = getChildAt( getChildCount() - 1 );
if ( child != null ) {
edge = child.getRight();
}
fillListRight( edge, dx );
edge = 0;
child = getChildAt( 0 );
if ( child != null ) {
edge = child.getLeft();
}
fillListLeft( edge, dx );
}
/**
* Fill list right.
*
* @param rightEdge
* the right edge
* @param dx
* the dx
*/
private void fillListRight( int rightEdge, final int dx ) {
while ( rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount() ) {
View child = mAdapter.getView( mRightViewIndex, mRemovedViewQueue.poll(), this );
addAndMeasureChild( child, -1 );
rightEdge += child.getMeasuredWidth();
if ( mRightViewIndex == mAdapter.getCount() - 1 ) {
mMaxX = mCurrentX + rightEdge - getWidth();
}
mRightViewIndex++;
}
}
/**
* Fill list left.
*
* @param leftEdge
* the left edge
* @param dx
* the dx
*/
private void fillListLeft( int leftEdge, final int dx ) {
while ( leftEdge + dx > 0 && mLeftViewIndex >= 0 ) {
View child = mAdapter.getView( mLeftViewIndex, mRemovedViewQueue.poll(), this );
addAndMeasureChild( child, 0 );
leftEdge -= child.getMeasuredWidth();
mLeftViewIndex--;
mDisplayOffset -= child.getMeasuredWidth();
}
}
/**
* Removes the non visible items.
*
* @param dx
* the dx
*/
private void removeNonVisibleItems( final int dx ) {
View child = getChildAt( 0 );
while ( child != null && child.getRight() + dx <= 0 ) {
mDisplayOffset += child.getMeasuredWidth();
mRemovedViewQueue.offer( child );
removeViewInLayout( child );
mLeftViewIndex++;
child = getChildAt( 0 );
}
child = getChildAt( getChildCount() - 1 );
while ( child != null && child.getLeft() + dx >= getWidth() ) {
mRemovedViewQueue.offer( child );
removeViewInLayout( child );
mRightViewIndex--;
child = getChildAt( getChildCount() - 1 );
}
}
/**
* Position items.
*
* @param dx
* the dx
*/
private void positionItems( final int dx ) {
if ( getChildCount() > 0 ) {
mDisplayOffset += dx;
int left = mDisplayOffset;
for ( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
int childWidth = child.getMeasuredWidth();
int childTop = getPaddingTop();
child.layout( left, childTop, left + childWidth, childTop + child.getMeasuredHeight() );
left += childWidth;
}
}
}
/**
* Scroll to.
*
* @param x
* the x
*/
public synchronized void scrollTo( int x ) {
mScroller.startScroll( mNextX, 0, x - mNextX, 0 );
requestLayout();
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean dispatchTouchEvent( MotionEvent ev ) {
boolean handled = mGesture.onTouchEvent( ev );
return handled;
}
/**
* On fling.
*
* @param e1
* the e1
* @param e2
* the e2
* @param velocityX
* the velocity x
* @param velocityY
* the velocity y
* @return true, if successful
*/
protected boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
synchronized ( HorizontalListView.this ) {
Log.i( LoggerFactory.LOG_TAG, "onFling: " + -velocityX + ", " + mMaxX );
mScroller.fling( mNextX, 0, (int) -( velocityX / 2 ), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0 );
}
requestLayout();
return true;
}
/** The m scroller running. */
boolean mScrollerRunning;
/**
* On down.
*
* @param e
* the e
* @return true, if successful
*/
protected boolean onDown( MotionEvent e ) {
if ( !mScroller.isFinished() ) {
mScrollerRunning = true;
} else {
mScrollerRunning = false;
}
mScroller.forceFinished( true );
return true;
}
/** The m on gesture. */
private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown( MotionEvent e ) {
return HorizontalListView.this.onDown( e );
}
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
return HorizontalListView.this.onFling( e1, e2, velocityX, velocityY );
}
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
synchronized ( HorizontalListView.this ) {
mNextX += (int) distanceX;
}
requestLayout();
return true;
}
@Override
public boolean onSingleTapConfirmed( MotionEvent e ) {
Log.i( LoggerFactory.LOG_TAG, "onSingleTapConfirmed" );
if ( mScrollerRunning ) return false;
Rect viewRect = new Rect();
for ( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
int left = child.getLeft();
int right = child.getRight();
int top = child.getTop();
int bottom = child.getBottom();
viewRect.set( left, top, right, bottom );
if ( viewRect.contains( (int) e.getX(), (int) e.getY() ) ) {
if ( mOnItemClicked != null ) {
mOnItemClicked.onItemClick( HorizontalListView.this, child, mLeftViewIndex + 1 + i,
mAdapter.getItemId( mLeftViewIndex + 1 + i ) );
}
if ( mOnItemSelected != null ) {
mOnItemSelected.onItemSelected( HorizontalListView.this, child, mLeftViewIndex + 1 + i,
mAdapter.getItemId( mLeftViewIndex + 1 + i ) );
}
break;
}
}
return true;
}
};
}
| Java |
/*
* 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.aviary.android.feather.widget;
import android.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Transformation;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
import com.aviary.android.feather.widget.IFlingRunnable.FlingRunnableView;
// TODO: Auto-generated Javadoc
/**
* A view that shows items in a center-locked, horizontally scrolling list.
* <p>
* The default values for the Gallery assume you will be using {@link android.R.styleable#Theme_galleryItemBackground} as the
* background for each View given to the Gallery from the Adapter. If you are not doing this, you may need to adjust some Gallery
* properties, such as the spacing.
* <p>
* Views given to the Gallery should use {@link Gallery.LayoutParams} as their layout parameters type.
*
* <p>
* See the <a href="{@docRoot}resources/tutorials/views/hello-gallery.html">Gallery tutorial</a>.
* </p>
*
* @attr ref android.R.styleable#Gallery_animationDuration
* @attr ref android.R.styleable#Gallery_spacing
* @attr ref android.R.styleable#Gallery_gravity
*/
public class Gallery extends AbsSpinner implements GestureDetector.OnGestureListener, FlingRunnableView, VibrationWidget {
/**
* The listener interface for receiving onItemsScroll events. The class that is interested in processing a onItemsScroll event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnItemsScrollListener<code> method. When
* the onItemsScroll event occurs, that object's appropriate
* method is invoked.
*
* @see OnItemsScrollEvent
*/
public interface OnItemsScrollListener {
/**
* On scroll started.
*
* @param parent
* the parent
* @param view
* the view
* @param position
* the position
* @param id
* the id
*/
void onScrollStarted( AdapterView<?> parent, View view, int position, long id );
/**
* On scroll.
*
* @param parent
* the parent
* @param view
* the view
* @param position
* the position
* @param id
* the id
*/
void onScroll( AdapterView<?> parent, View view, int position, long id );
/**
* On scroll finished.
*
* @param parent
* the parent
* @param view
* the view
* @param position
* the position
* @param id
* the id
*/
void onScrollFinished( AdapterView<?> parent, View view, int position, long id );
}
/** The Constant TAG. */
private static final String TAG = "gallery";
/** The Constant MSG_VIBRATE. */
private static final int MSG_VIBRATE = 1;
/** Vibration. */
Vibrator mVibrator;
/** The m vibration handler. */
static Handler mVibrationHandler;
/** set child selected automatically. */
private boolean mAutoSelectChild = false;
/** The m items scroll listener. */
private OnItemsScrollListener mItemsScrollListener = null;
/**
* Duration in milliseconds from the start of a scroll during which we're unsure whether the user is scrolling or flinging.
*/
private static final int SCROLL_TO_FLING_UNCERTAINTY_TIMEOUT = 250;
/**
* Horizontal spacing between items.
*/
private int mSpacing = 0;
/**
* How long the transition animation should run when a child view changes position, measured in milliseconds.
*/
private int mAnimationDuration = 400;
/**
* The alpha of items that are not selected.
*/
private float mUnselectedAlpha;
/**
* Left most edge of a child seen so far during layout.
*/
private int mLeftMost;
/**
* Right most edge of a child seen so far during layout.
*/
private int mRightMost;
/** The m gravity. */
private int mGravity;
/**
* Helper for detecting touch gestures.
*/
private GestureDetector mGestureDetector;
/**
* The position of the item that received the user's down touch.
*/
private int mDownTouchPosition;
/**
* The view of the item that received the user's down touch.
*/
private View mDownTouchView;
/**
* Executes the delta scrolls from a fling or scroll movement.
*/
private IFlingRunnable mFlingRunnable;
/** The m auto scroll to center. */
private boolean mAutoScrollToCenter = true;
/** The m touch slop. */
int mTouchSlop;
/**
* Sets mSuppressSelectionChanged = false. This is used to set it to false in the future. It will also trigger a selection
* changed.
*/
private Runnable mDisableSuppressSelectionChangedRunnable = new Runnable() {
@Override
public void run() {
mSuppressSelectionChanged = false;
selectionChanged();
}
};
/**
* When fling runnable runs, it resets this to false. Any method along the path until the end of its run() can set this to true
* to abort any remaining fling. For example, if we've reached either the leftmost or rightmost item, we will set this to true.
*/
@SuppressWarnings("unused")
private boolean mShouldStopFling;
/**
* The currently selected item's child.
*/
private View mSelectedChild;
/**
* Whether to continuously callback on the item selected listener during a fling.
*/
private boolean mShouldCallbackDuringFling = false;
/**
* Whether to callback when an item that is not selected is clicked.
*/
private boolean mShouldCallbackOnUnselectedItemClick = true;
/**
* If true, do not callback to item selected listener.
*/
private boolean mSuppressSelectionChanged = true;
/**
* If true, we have received the "invoke" (center or enter buttons) key down. This is checked before we action on the "invoke"
* key up, and is subsequently cleared.
*/
private boolean mReceivedInvokeKeyDown;
/** The m context menu info. */
private AdapterContextMenuInfo mContextMenuInfo;
/**
* If true, this onScroll is the first for this user's drag (remember, a drag sends many onScrolls).
*/
private boolean mIsFirstScroll;
/**
* If true, mFirstPosition is the position of the rightmost child, and the children are ordered right to left.
*/
private boolean mIsRtl = true;
/** The m last motion value. */
private int mLastMotionValue;
/**
* Instantiates a new gallery.
*
* @param context
* the context
*/
public Gallery( Context context ) {
this( context, null );
}
/**
* Instantiates a new gallery.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public Gallery( Context context, AttributeSet attrs ) {
this( context, attrs, R.attr.galleryStyle );
}
/**
* Instantiates a new gallery.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public Gallery( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
mGestureDetector = new GestureDetector( context, this );
mGestureDetector.setIsLongpressEnabled( false );
ViewConfiguration configuration = ViewConfiguration.get( context );
mTouchSlop = configuration.getScaledTouchSlop();
if ( android.os.Build.VERSION.SDK_INT > 8 ) {
try {
mFlingRunnable = (IFlingRunnable) ReflectionUtils.newInstance( "com.aviary.android.feather.widget.Fling9Runnable",
new Class<?>[] { FlingRunnableView.class, int.class }, this, mAnimationDuration );
} catch ( ReflectionException e ) {
mFlingRunnable = new Fling8Runnable( this, mAnimationDuration );
}
} else {
mFlingRunnable = new Fling8Runnable( this, mAnimationDuration );
}
Log.d( VIEW_LOG_TAG, "fling class: " + mFlingRunnable.getClass().getName() );
try {
mVibrator = (Vibrator) context.getSystemService( Context.VIBRATOR_SERVICE );
} catch ( Exception e ) {
Log.e( TAG, e.toString() );
}
if ( mVibrator != null ) {
setVibrationEnabled( true );
}
}
@Override
public synchronized void setVibrationEnabled( boolean value ) {
if ( !value ) {
mVibrationHandler = null;
} else {
if ( null == mVibrationHandler ) {
mVibrationHandler = new Handler() {
@Override
public void handleMessage( Message msg ) {
super.handleMessage( msg );
switch ( msg.what ) {
case MSG_VIBRATE:
try {
mVibrator.vibrate( 10 );
} catch ( SecurityException e ) {
// missing VIBRATE permission
}
}
}
};
}
}
}
@Override
@SuppressLint("HandlerLeak")
public synchronized boolean getVibrationEnabled() {
return mVibrationHandler != null;
}
/**
* Sets the on items scroll listener.
*
* @param value
* the new on items scroll listener
*/
public void setOnItemsScrollListener( OnItemsScrollListener value ) {
mItemsScrollListener = value;
}
/**
* Sets the auto scroll to center.
*
* @param value
* the new auto scroll to center
*/
public void setAutoScrollToCenter( boolean value ) {
mAutoScrollToCenter = value;
}
/**
* Whether or not to callback on any {@link #getOnItemSelectedListener()} while the items are being flinged. If false, only the
* final selected item will cause the callback. If true, all items between the first and the final will cause callbacks.
*
* @param shouldCallback
* Whether or not to callback on the listener while the items are being flinged.
*/
public void setCallbackDuringFling( boolean shouldCallback ) {
mShouldCallbackDuringFling = shouldCallback;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#onDetachedFromWindow()
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeCallbacks( mScrollSelectionNotifier );
}
/**
* Whether or not to callback when an item that is not selected is clicked. If false, the item will become selected (and
* re-centered). If true, the {@link #getOnItemClickListener()} will get the callback.
*
* @param shouldCallback
* Whether or not to callback on the listener when a item that is not selected is clicked.
* @hide
*/
public void setCallbackOnUnselectedItemClick( boolean shouldCallback ) {
mShouldCallbackOnUnselectedItemClick = shouldCallback;
}
/**
* Sets how long the transition animation should run when a child view changes position. Only relevant if animation is turned on.
*
* @param animationDurationMillis
* The duration of the transition, in milliseconds.
*
* @attr ref android.R.styleable#Gallery_animationDuration
*/
public void setAnimationDuration( int animationDurationMillis ) {
mAnimationDuration = animationDurationMillis;
}
/**
* Sets the spacing between items in a Gallery.
*
* @param spacing
* The spacing in pixels between items in the Gallery
* @attr ref android.R.styleable#Gallery_spacing
*/
public void setSpacing( int spacing ) {
mSpacing = spacing;
}
/**
* Sets the alpha of items that are not selected in the Gallery.
*
* @param unselectedAlpha
* the alpha for the items that are not selected.
*
* @attr ref android.R.styleable#Gallery_unselectedAlpha
*/
public void setUnselectedAlpha( float unselectedAlpha ) {
mUnselectedAlpha = unselectedAlpha;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#getChildStaticTransformation(android.view.View, android.view.animation.Transformation)
*/
@Override
protected boolean getChildStaticTransformation( View child, Transformation t ) {
t.clear();
t.setAlpha( child == mSelectedChild ? 1.0f : mUnselectedAlpha );
return true;
}
/*
* (non-Javadoc)
*
* @see android.view.View#computeHorizontalScrollExtent()
*/
@Override
protected int computeHorizontalScrollExtent() {
// Only 1 item is considered to be selected
return 1;
}
/*
* (non-Javadoc)
*
* @see android.view.View#computeHorizontalScrollOffset()
*/
@Override
protected int computeHorizontalScrollOffset() {
return mSelectedPosition;
}
/*
* (non-Javadoc)
*
* @see android.view.View#computeHorizontalScrollRange()
*/
@Override
protected int computeHorizontalScrollRange() {
// Scroll range is the same as the item count
return mItemCount;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#checkLayoutParams(android.view.ViewGroup.LayoutParams)
*/
@Override
protected boolean checkLayoutParams( ViewGroup.LayoutParams p ) {
return p instanceof LayoutParams;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#generateLayoutParams(android.view.ViewGroup.LayoutParams)
*/
@Override
protected ViewGroup.LayoutParams generateLayoutParams( ViewGroup.LayoutParams p ) {
return new LayoutParams( p );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#generateLayoutParams(android.util.AttributeSet)
*/
@Override
public ViewGroup.LayoutParams generateLayoutParams( AttributeSet attrs ) {
return new LayoutParams( getContext(), attrs );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AbsSpinner#generateDefaultLayoutParams()
*/
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
/*
* Gallery expects Gallery.LayoutParams.
*/
return new Gallery.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int l, int t, int r, int b ) {
super.onLayout( changed, l, t, r, b );
/*
* Remember that we are in layout to prevent more layout request from being generated.
*/
mInLayout = true;
layout( 0, false, changed );
mInLayout = false;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AbsSpinner#getChildHeight(android.view.View)
*/
@Override
int getChildHeight( View child ) {
return child.getMeasuredHeight();
}
/**
* Tracks a motion scroll. In reality, this is used to do just about any movement to items (touch scroll, arrow-key scroll, set
* an item as selected).
*
* @param deltaX
* Change in X from the previous event.
*/
@Override
public void trackMotionScroll( int delta ) {
int deltaX = mFlingRunnable.getLastFlingX() - delta;
// Pretend that each frame of a fling scroll is a touch scroll
if ( delta > 0 ) {
mDownTouchPosition = mIsRtl ? ( mFirstPosition + getChildCount() - 1 ) : mFirstPosition;
// Don't fling more than 1 screen
delta = Math.min( getWidth() - mPaddingLeft - mPaddingRight - 1, delta );
} else {
mDownTouchPosition = mIsRtl ? mFirstPosition : ( mFirstPosition + getChildCount() - 1 );
// Don't fling more than 1 screen
delta = Math.max( -( getWidth() - mPaddingRight - mPaddingLeft - 1 ), delta );
}
if ( getChildCount() == 0 ) {
return;
}
boolean toLeft = deltaX < 0;
int limitedDeltaX = deltaX; // getLimitedMotionScrollAmount(toLeft, deltaX);
int realDeltaX = getLimitedMotionScrollAmount( toLeft, deltaX );
if ( realDeltaX != deltaX ) {
// mFlingRunnable.springBack( realDeltaX );
limitedDeltaX = realDeltaX;
}
if ( limitedDeltaX != deltaX ) {
mFlingRunnable.endFling( false );
if ( limitedDeltaX == 0 ) onFinishedMovement();
}
offsetChildrenLeftAndRight( limitedDeltaX );
detachOffScreenChildren( toLeft );
if ( toLeft ) {
// If moved left, there will be empty space on the right
fillToGalleryRight();
} else {
// Similarly, empty space on the left
fillToGalleryLeft();
}
// Clear unused views
// mRecycler.clear();
// mRecyclerInvalidItems.clear();
setSelectionToCenterChild();
onScrollChanged( 0, 0, 0, 0 ); // dummy values, View's implementation does not use these.
invalidate();
}
/**
* Gets the limited motion scroll amount.
*
* @param motionToLeft
* the motion to left
* @param deltaX
* the delta x
* @return the limited motion scroll amount
*/
int getLimitedMotionScrollAmount( boolean motionToLeft, int deltaX ) {
int extremeItemPosition = motionToLeft != mIsRtl ? mItemCount - 1 : 0;
View extremeChild = getChildAt( extremeItemPosition - mFirstPosition );
if ( extremeChild == null ) {
return deltaX;
}
int extremeChildCenter = getCenterOfView( extremeChild )
+ ( motionToLeft ? extremeChild.getWidth() / 2 : -extremeChild.getWidth() / 2 );
int galleryCenter = getCenterOfGallery();
if ( motionToLeft ) {
if ( extremeChildCenter <= galleryCenter ) {
// The extreme child is past his boundary point!
return 0;
}
} else {
if ( extremeChildCenter >= galleryCenter ) {
// The extreme child is past his boundary point!
return 0;
}
}
int centerDifference = galleryCenter - extremeChildCenter;
return motionToLeft ? Math.max( centerDifference, deltaX ) : Math.min( centerDifference, deltaX );
}
/**
* Gets the limited motion scroll amount2.
*
* @param motionToLeft
* the motion to left
* @param deltaX
* the delta x
* @return the limited motion scroll amount2
*/
int getLimitedMotionScrollAmount2( boolean motionToLeft, int deltaX ) {
int extremeItemPosition = motionToLeft != mIsRtl ? mItemCount - 1 : 0;
View extremeChild = getChildAt( extremeItemPosition - mFirstPosition );
if ( extremeChild == null ) {
return deltaX;
}
int extremeChildCenter = getCenterOfView( extremeChild )
+ ( motionToLeft ? extremeChild.getWidth() / 2 : -extremeChild.getWidth() / 2 );
int galleryCenter = getCenterOfGallery();
int centerDifference = galleryCenter - extremeChildCenter;
return motionToLeft ? Math.max( centerDifference, deltaX ) : Math.min( centerDifference, deltaX );
}
/**
* Gets the over scroll delta.
*
* @param motionToLeft
* the motion to left
* @param deltaX
* the delta x
* @return the over scroll delta
*/
int getOverScrollDelta( boolean motionToLeft, int deltaX ) {
int extremeItemPosition = motionToLeft != mIsRtl ? mItemCount - 1 : 0;
View extremeChild = getChildAt( extremeItemPosition - mFirstPosition );
if ( extremeChild == null ) {
return 0;
}
int extremeChildCenter = getCenterOfView( extremeChild );
int galleryCenter = getCenterOfGallery();
if ( motionToLeft ) {
if ( extremeChildCenter < galleryCenter ) {
return extremeChildCenter - galleryCenter;
}
} else {
if ( extremeChildCenter > galleryCenter ) {
return galleryCenter - extremeChildCenter;
}
}
return 0;
}
protected void onOverScrolled( int scrollX, int scrollY, boolean clampedX, boolean clampedY ) {}
/**
* Offset the horizontal location of all children of this view by the specified number of pixels.
*
* @param offset
* the number of pixels to offset
*/
private void offsetChildrenLeftAndRight( int offset ) {
for ( int i = getChildCount() - 1; i >= 0; i-- ) {
getChildAt( i ).offsetLeftAndRight( offset );
}
}
/**
* Gets the center of gallery.
*
* @return The center of this Gallery.
*/
private int getCenterOfGallery() {
return ( getWidth() - mPaddingLeft - mPaddingRight ) / 2 + mPaddingLeft;
}
/**
* Gets the center of view.
*
* @param view
* the view
* @return The center of the given view.
*/
private static int getCenterOfView( View view ) {
return view.getLeft() + view.getWidth() / 2;
}
/**
* Detaches children that are off the screen (i.e.: Gallery bounds).
*
* @param toLeft
* Whether to detach children to the left of the Gallery, or to the right.
*/
private void detachOffScreenChildren( boolean toLeft ) {
int numChildren = getChildCount();
int firstPosition = mFirstPosition;
int start = 0;
int count = 0;
if ( toLeft ) {
final int galleryLeft = mPaddingLeft;
for ( int i = 0; i < numChildren; i++ ) {
int n = mIsRtl ? ( numChildren - 1 - i ) : i;
final View child = getChildAt( n );
if ( child.getRight() >= galleryLeft ) {
break;
} else {
start = n;
count++;
int viewType = mAdapter.getItemViewType( firstPosition + n );
mRecycleBin.get( viewType ).add( child );
//if ( firstPosition + n < 0 ) {
// mRecyclerInvalidItems.put( firstPosition + n, child );
//} else {
// mRecycler.put( firstPosition + n, child );
//}
}
}
if ( !mIsRtl ) {
start = 0;
}
} else {
final int galleryRight = getWidth() - mPaddingRight;
for ( int i = numChildren - 1; i >= 0; i-- ) {
int n = mIsRtl ? numChildren - 1 - i : i;
final View child = getChildAt( n );
if ( child.getLeft() <= galleryRight ) {
break;
} else {
start = n;
count++;
int viewType = mAdapter.getItemViewType( firstPosition + n );
mRecycleBin.get( viewType ).add( child );
//if ( firstPosition + n >= mItemCount ) {
// mRecyclerInvalidItems.put( firstPosition + n, child );
//} else {
// mRecycler.put( firstPosition + n, child );
//}
}
}
if ( mIsRtl ) {
start = 0;
}
}
detachViewsFromParent( start, count );
if ( toLeft != mIsRtl ) {
mFirstPosition += count;
}
}
/**
* Scrolls the items so that the selected item is in its 'slot' (its center is the gallery's center).
*/
@Override
public void scrollIntoSlots() {
if ( getChildCount() == 0 || mSelectedChild == null ) return;
if ( mAutoScrollToCenter ) {
int selectedCenter = getCenterOfView( mSelectedChild );
int targetCenter = getCenterOfGallery();
int scrollAmount = targetCenter - selectedCenter;
if ( scrollAmount != 0 ) {
mFlingRunnable.startUsingDistance( 0, -scrollAmount );
// fireVibration();
} else {
onFinishedMovement();
}
} else {
onFinishedMovement();
}
}
/**
* Scrolls the items so that the selected item is in its 'slot' (its center is the gallery's center).
*
* @return true, if is over scrolled
*/
private boolean isOverScrolled() {
if ( getChildCount() < 2 || mSelectedChild == null ) return false;
if ( mSelectedPosition == 0 || mSelectedPosition == mItemCount - 1 ) {
int selectedCenter0 = getCenterOfView( mSelectedChild );
int targetCenter = getCenterOfGallery();
if ( mSelectedPosition == 0 && selectedCenter0 > targetCenter ) return true;
if ( ( mSelectedPosition == mItemCount - 1 ) && selectedCenter0 < targetCenter ) return true;
}
return false;
}
/**
* On finished movement.
*/
private void onFinishedMovement() {
if ( isDown ) return;
if ( mSuppressSelectionChanged ) {
mSuppressSelectionChanged = false;
// We haven't been callbacking during the fling, so do it now
super.selectionChanged();
}
scrollCompleted();
invalidate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#selectionChanged()
*/
@Override
void selectionChanged() {
if ( !mSuppressSelectionChanged ) {
super.selectionChanged();
}
}
/**
* Looks for the child that is closest to the center and sets it as the selected child.
*/
private void setSelectionToCenterChild() {
View selView = mSelectedChild;
if ( mSelectedChild == null ) return;
int galleryCenter = getCenterOfGallery();
// Common case where the current selected position is correct
if ( selView.getLeft() <= galleryCenter && selView.getRight() >= galleryCenter ) {
return;
}
// TODO better search
int closestEdgeDistance = Integer.MAX_VALUE;
int newSelectedChildIndex = 0;
for ( int i = getChildCount() - 1; i >= 0; i-- ) {
View child = getChildAt( i );
if ( child.getLeft() <= galleryCenter && child.getRight() >= galleryCenter ) {
// This child is in the center
newSelectedChildIndex = i;
break;
}
int childClosestEdgeDistance = Math.min( Math.abs( child.getLeft() - galleryCenter ),
Math.abs( child.getRight() - galleryCenter ) );
if ( childClosestEdgeDistance < closestEdgeDistance ) {
closestEdgeDistance = childClosestEdgeDistance;
newSelectedChildIndex = i;
}
}
int newPos = mFirstPosition + newSelectedChildIndex;
if ( newPos != mSelectedPosition ) {
newPos = Math.min( Math.max( newPos, 0 ), mItemCount - 1 );
setSelectedPositionInt( newPos, true );
setNextSelectedPositionInt( newPos );
checkSelectionChanged();
}
}
/**
* Creates and positions all views for this Gallery.
* <p>
* We layout rarely, most of the time {@link #trackMotionScroll(int)} takes care of repositioning, adding, and removing children.
*
* @param delta
* Change in the selected position. +1 means the selection is moving to the right, so views are scrolling to the left.
* -1 means the selection is moving to the left.
* @param animate
* the animate
*/
@Override
void layout( int delta, boolean animate, boolean changed ) {
mIsRtl = false;
int childrenLeft = mSpinnerPadding.left;
int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left - mSpinnerPadding.right;
if ( mDataChanged ) {
handleDataChanged();
}
// Handle an empty gallery by removing all views.
if ( mItemCount == 0 ) {
resetList();
return;
}
// Update to the new selected position.
if ( mNextSelectedPosition >= 0 ) {
setSelectedPositionInt( mNextSelectedPosition, animate );
}
// All views go in recycler while we are in layout
recycleAllViews();
// Clear out old views
// removeAllViewsInLayout();
detachAllViewsFromParent();
/*
* These will be used to give initial positions to views entering the gallery as we scroll
*/
mRightMost = 0;
mLeftMost = 0;
// Make selected view and center it
/*
* mFirstPosition will be decreased as we add views to the left later on. The 0 for x will be offset in a couple lines down.
*/
mFirstPosition = mSelectedPosition;
View sel = makeAndAddView( mSelectedPosition, 0, 0, true );
// Put the selected child in the center
int selectedOffset = childrenLeft + ( childrenWidth / 2 ) - ( sel.getWidth() / 2 );
sel.offsetLeftAndRight( selectedOffset );
fillToGalleryRight();
fillToGalleryLeft();
// Flush any cached views that did not get reused above
//mRecycler.clear();
//mRecyclerInvalidItems.clear();
emptySubRecycler();
invalidate();
checkSelectionChanged();
mDataChanged = false;
mNeedSync = false;
setNextSelectedPositionInt( mSelectedPosition );
updateSelectedItemMetadata( animate, changed );
}
/**
* Fill to gallery left.
*/
private void fillToGalleryLeft() {
if ( mIsRtl ) {
fillToGalleryLeftRtl();
} else {
fillToGalleryLeftLtr();
}
}
/**
* Fill to gallery left rtl.
*/
private void fillToGalleryLeftRtl() {
int itemSpacing = mSpacing;
int galleryLeft = mPaddingLeft;
int numChildren = getChildCount();
// Set state for initial iteration
View prevIterationView = getChildAt( numChildren - 1 );
int curPosition;
int curRightEdge;
if ( prevIterationView != null ) {
curPosition = mFirstPosition + numChildren;
curRightEdge = prevIterationView.getLeft() - itemSpacing;
} else {
// No children available!
mFirstPosition = curPosition = mItemCount - 1;
curRightEdge = getRight() - getLeft() - mPaddingRight;
mShouldStopFling = true;
}
while ( curRightEdge > galleryLeft && curPosition < mItemCount ) {
prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curRightEdge, false );
// Set state for next iteration
curRightEdge = prevIterationView.getLeft() - itemSpacing;
curPosition++;
}
}
/**
* Fill to gallery left ltr.
*/
private void fillToGalleryLeftLtr() {
int itemSpacing = mSpacing;
int galleryLeft = mPaddingLeft;
// Set state for initial iteration
View prevIterationView = getChildAt( 0 );
int curPosition;
int curRightEdge;
if ( prevIterationView != null ) {
curPosition = mFirstPosition - 1;
curRightEdge = prevIterationView.getLeft() - itemSpacing;
} else {
// No children available!
curPosition = 0;
curRightEdge = getRight() - getLeft() - mPaddingRight;
mShouldStopFling = true;
}
while ( curRightEdge > galleryLeft /* && curPosition >= 0 */) {
prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curRightEdge, false );
// Remember some state
mFirstPosition = curPosition;
// Set state for next iteration
curRightEdge = prevIterationView.getLeft() - itemSpacing;
curPosition--;
}
}
/**
* Fill to gallery right.
*/
private void fillToGalleryRight() {
if ( mIsRtl ) {
fillToGalleryRightRtl();
} else {
fillToGalleryRightLtr();
}
}
/**
* Fill to gallery right rtl.
*/
private void fillToGalleryRightRtl() {
int itemSpacing = mSpacing;
int galleryRight = getRight() - getLeft() - mPaddingRight;
// Set state for initial iteration
View prevIterationView = getChildAt( 0 );
int curPosition;
int curLeftEdge;
if ( prevIterationView != null ) {
curPosition = mFirstPosition - 1;
curLeftEdge = prevIterationView.getRight() + itemSpacing;
} else {
curPosition = 0;
curLeftEdge = mPaddingLeft;
mShouldStopFling = true;
}
while ( curLeftEdge < galleryRight && curPosition >= 0 ) {
prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curLeftEdge, true );
// Remember some state
mFirstPosition = curPosition;
// Set state for next iteration
curLeftEdge = prevIterationView.getRight() + itemSpacing;
curPosition--;
}
}
/**
* Fill to gallery right ltr.
*/
private void fillToGalleryRightLtr() {
int itemSpacing = mSpacing;
int galleryRight = getRight() - getLeft() - mPaddingRight;
int numChildren = getChildCount();
// Set state for initial iteration
View prevIterationView = getChildAt( numChildren - 1 );
int curPosition;
int curLeftEdge;
if ( prevIterationView != null ) {
curPosition = mFirstPosition + numChildren;
curLeftEdge = prevIterationView.getRight() + itemSpacing;
} else {
mFirstPosition = curPosition = mItemCount - 1;
curLeftEdge = mPaddingLeft;
mShouldStopFling = true;
}
while ( curLeftEdge < galleryRight /* && curPosition < numItems */) {
prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curLeftEdge, true );
// Set state for next iteration
curLeftEdge = prevIterationView.getRight() + itemSpacing;
curPosition++;
}
}
/**
* 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 gallery for the view to obtain
* @param offset
* Offset from the selected position
* @param x
* X-coordinate indicating where this view should be placed. This will either be the left or right edge of the view,
* depending on the fromLeft parameter
* @param fromLeft
* Are we positioning views based on the left edge? (i.e., building from left to right)?
* @return A view that has been added to the gallery
*/
private View makeAndAddView( int position, int offset, int x, boolean fromLeft ) {
View child;
int viewType = mAdapter.getItemViewType( position );
if ( !mDataChanged ) {
child = mRecycleBin.get( viewType ).poll();
/*
if ( valid ) {
child = mRecycler.get( position );
} else {
child = mRecyclerInvalidItems.get( position );
}
*/
if ( child != null ) {
// Can reuse an existing view
child = mAdapter.getView( position, child, this );
int childLeft = child.getLeft();
// Remember left and right edges of where views have been placed
mRightMost = Math.max( mRightMost, childLeft + child.getMeasuredWidth() );
mLeftMost = Math.min( mLeftMost, childLeft );
// Position the view
setUpChild( child, offset, x, fromLeft );
return child;
}
}
// Nothing found in the recycler -- ask the adapter for a view
child = mAdapter.getView( position, null, this );
// Position the view
setUpChild( child, offset, x, fromLeft );
return child;
}
public void invalidateViews() {
int count = getChildCount();
for ( int i = 0; i < count; i++ ) {
View child = getChildAt( i );
mAdapter.getView( mFirstPosition + i, child, this );
}
}
/**
* Helper for makeAndAddView to set the position of a view and fill out its layout parameters.
*
* @param child
* The view to position
* @param offset
* Offset from the selected position
* @param x
* X-coordinate indicating where this view should be placed. This will either be the left or right edge of the view,
* depending on the fromLeft parameter
* @param fromLeft
* Are we positioning views based on the left edge? (i.e., building from left to right)?
*/
private void setUpChild( View child, int offset, int x, boolean fromLeft ) {
// Respect layout params that are already in the view. Otherwise
// make some up...
Gallery.LayoutParams lp = (Gallery.LayoutParams) child.getLayoutParams();
if ( lp == null ) {
lp = (Gallery.LayoutParams) generateDefaultLayoutParams();
}
addViewInLayout( child, fromLeft != mIsRtl ? -1 : 0, lp );
if ( mAutoSelectChild ) child.setSelected( offset == 0 );
// 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 = calculateTop( child, true );
int childBottom = childTop + child.getMeasuredHeight();
int width = child.getMeasuredWidth();
if ( fromLeft ) {
childLeft = x;
childRight = childLeft + width;
} else {
childLeft = x - width;
childRight = x;
}
child.layout( childLeft, childTop, childRight, childBottom );
}
/**
* Figure out vertical placement based on mGravity.
*
* @param child
* Child to place
* @param duringLayout
* the during layout
* @return Where the top of the child should be
*/
private int calculateTop( View child, boolean duringLayout ) {
int myHeight = duringLayout ? getMeasuredHeight() : getHeight();
int childHeight = duringLayout ? child.getMeasuredHeight() : child.getHeight();
int childTop = 0;
switch ( mGravity ) {
case Gravity.TOP:
childTop = mSpinnerPadding.top;
break;
case Gravity.CENTER_VERTICAL:
int availableSpace = myHeight - mSpinnerPadding.bottom - mSpinnerPadding.top - childHeight;
childTop = mSpinnerPadding.top + ( availableSpace / 2 );
break;
case Gravity.BOTTOM:
childTop = myHeight - mSpinnerPadding.bottom - childHeight;
break;
}
return childTop;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
// Give everything to the gesture detector
boolean retValue = mGestureDetector.onTouchEvent( event );
int action = event.getAction();
if ( action == MotionEvent.ACTION_UP ) {
// Helper method for lifted finger
onUp();
} else if ( action == MotionEvent.ACTION_CANCEL ) {
onCancel();
}
return retValue;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp( MotionEvent e ) {
if ( mDownTouchPosition >= 0 && mDownTouchPosition < mItemCount ) {
// An item tap should make it selected, so scroll to this child.
scrollToChild( mDownTouchPosition - mFirstPosition );
// Also pass the click so the client knows, if it wants to.
if ( mShouldCallbackOnUnselectedItemClick || mDownTouchPosition == mSelectedPosition ) {
performItemClick( mDownTouchView, mDownTouchPosition, mAdapter.getItemId( mDownTouchPosition ) );
}
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
if ( !mShouldCallbackDuringFling ) {
// We want to suppress selection changes
// Remove any future code to set mSuppressSelectionChanged = false
removeCallbacks( mDisableSuppressSelectionChangedRunnable );
// This will get reset once we scroll into slots
if ( !mSuppressSelectionChanged ) mSuppressSelectionChanged = true;
}
// Fling the gallery!
int initialVelocity = (int) -velocityX / 2;
int initialX = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
mFlingRunnable.startUsingVelocity( initialX, initialVelocity );
return true;
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
/*
* Now's a good time to tell our parent to stop intercepting our events! The user has moved more than the slop amount, since
* GestureDetector ensures this before calling this method. Also, if a parent is more interested in this touch's events than
* we are, it would have intercepted them by now (for example, we can assume when a Gallery is in the ListView, a vertical
* scroll would not end up in this method since a ListView would have intercepted it by now).
*/
getParent().requestDisallowInterceptTouchEvent( true );
// As the user scrolls, we want to callback selection changes so related-
// info on the screen is up-to-date with the gallery's selection
if ( !mShouldCallbackDuringFling ) {
if ( mIsFirstScroll ) {
if ( !mSuppressSelectionChanged ) mSuppressSelectionChanged = true;
postDelayed( mDisableSuppressSelectionChangedRunnable, SCROLL_TO_FLING_UNCERTAINTY_TIMEOUT );
if ( mItemsScrollListener != null ) {
int selection = this.getSelectedItemPosition();
if ( selection >= 0 ) {
View v = getSelectedView();
mItemsScrollListener.onScrollStarted( this, v, selection, getAdapter().getItemId( selection ) );
}
}
}
} else {
if ( mSuppressSelectionChanged ) mSuppressSelectionChanged = false;
}
// Track the motion
if ( mIsFirstScroll ) {
if ( distanceX > 0 )
distanceX -= mTouchSlop;
else
distanceX += mTouchSlop;
}
int delta = -1 * (int) distanceX;
float limitedDelta = getOverScrollDelta( delta < 0, delta );
if ( limitedDelta != 0 ) {
delta = (int) ( delta / Math.max( 1, Math.abs( limitedDelta / 10 ) ) );
}
trackMotionScroll( -delta );
mIsFirstScroll = false;
return true;
}
/** The is down. */
private boolean isDown;
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown( MotionEvent e ) {
isDown = true;
// Kill any existing fling/scroll
mFlingRunnable.stop( false );
// Get the item's view that was touched
mDownTouchPosition = pointToPosition( (int) e.getX(), (int) e.getY() );
if ( mDownTouchPosition >= 0 && mDownTouchPosition < mItemCount ) {
mDownTouchView = getChildAt( mDownTouchPosition - mFirstPosition );
mDownTouchView.setPressed( true );
}
// Reset the multiple-scroll tracking state
mIsFirstScroll = true;
// Must return true to get matching events for this down event.
return true;
}
/**
* Called when a touch event's action is MotionEvent.ACTION_UP.
*/
void onUp() {
isDown = false;
if ( mFlingRunnable.isFinished() ) {
scrollIntoSlots();
} else {
if ( isOverScrolled() ) {
scrollIntoSlots();
}
}
dispatchUnpress();
}
/**
* Called when a touch event's action is MotionEvent.ACTION_CANCEL.
*/
void onCancel() {
onUp();
}
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress( MotionEvent e ) {
if ( mDownTouchPosition < 0 || mDownTouchPosition <= mItemCount ) {
return;
}
performHapticFeedback( HapticFeedbackConstants.LONG_PRESS );
long id = getItemIdAtPosition( mDownTouchPosition );
dispatchLongPress( mDownTouchView, mDownTouchPosition, id );
}
// Unused methods from GestureDetector.OnGestureListener below
/*
* (non-Javadoc)
*
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress( MotionEvent e ) {}
// Unused methods from GestureDetector.OnGestureListener above
/**
* Dispatch press.
*
* @param child
* the child
*/
private void dispatchPress( View child ) {
if ( child != null ) {
child.setPressed( true );
}
setPressed( true );
}
/**
* Dispatch unpress.
*/
private void dispatchUnpress() {
for ( int i = getChildCount() - 1; i >= 0; i-- ) {
getChildAt( i ).setPressed( false );
}
setPressed( false );
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#dispatchSetSelected(boolean)
*/
@Override
public void dispatchSetSelected( boolean selected ) {
/*
* We don't want to pass the selected state given from its parent to its children since this widget itself has a selected
* state to give to its children.
*/
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#dispatchSetPressed(boolean)
*/
@Override
protected void dispatchSetPressed( boolean pressed ) {
// Show the pressed state on the selected child
if ( mSelectedChild != null ) {
mSelectedChild.setPressed( pressed );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#getContextMenuInfo()
*/
@Override
protected ContextMenuInfo getContextMenuInfo() {
return mContextMenuInfo;
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#showContextMenuForChild(android.view.View)
*/
@Override
public boolean showContextMenuForChild( View originalView ) {
final int longPressPosition = getPositionForView( originalView );
if ( longPressPosition < 0 ) {
return false;
}
final long longPressId = mAdapter.getItemId( longPressPosition );
return dispatchLongPress( originalView, longPressPosition, longPressId );
}
/*
* (non-Javadoc)
*
* @see android.view.View#showContextMenu()
*/
@Override
public boolean showContextMenu() {
if ( isPressed() && mSelectedPosition >= 0 ) {
int index = mSelectedPosition - mFirstPosition;
View v = getChildAt( index );
return dispatchLongPress( v, mSelectedPosition, mSelectedRowId );
}
return false;
}
/**
* Dispatch long press.
*
* @param view
* the view
* @param position
* the position
* @param id
* the id
* @return true, if successful
*/
private boolean dispatchLongPress( View view, int position, long id ) {
boolean handled = false;
if ( mOnItemLongClickListener != null ) {
handled = mOnItemLongClickListener.onItemLongClick( this, mDownTouchView, mDownTouchPosition, id );
}
if ( !handled ) {
mContextMenuInfo = new AdapterContextMenuInfo( view, position, id );
handled = super.showContextMenuForChild( this );
}
if ( handled ) {
performHapticFeedback( HapticFeedbackConstants.LONG_PRESS );
}
return handled;
}
/**
* Handles left, right, and clicking.
*
* @param keyCode
* the key code
* @param event
* the event
* @return true, if successful
* @see android.view.View#onKeyDown
*/
@Override
public boolean onKeyDown( int keyCode, KeyEvent event ) {
switch ( keyCode ) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if ( movePrevious() ) {
playSoundEffect( SoundEffectConstants.NAVIGATION_LEFT );
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if ( moveNext() ) {
playSoundEffect( SoundEffectConstants.NAVIGATION_RIGHT );
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
mReceivedInvokeKeyDown = true;
// fallthrough to default handling
}
return false;
}
@Override
public boolean dispatchKeyEvent( KeyEvent event ) {
boolean handled = event.dispatch( this, null, null );
return handled;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onKeyUp(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyUp( int keyCode, KeyEvent event ) {
switch ( keyCode ) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER: {
if ( mReceivedInvokeKeyDown ) {
if ( mItemCount > 0 ) {
dispatchPress( mSelectedChild );
postDelayed( new Runnable() {
@Override
public void run() {
dispatchUnpress();
}
}, ViewConfiguration.getPressedStateDuration() );
int selectedIndex = mSelectedPosition - mFirstPosition;
performItemClick( getChildAt( selectedIndex ), mSelectedPosition, mAdapter.getItemId( mSelectedPosition ) );
}
}
// Clear the flag
mReceivedInvokeKeyDown = false;
return true;
}
}
return false;
}
/**
* Move previous.
*
* @return true, if successful
*/
boolean movePrevious() {
if ( mItemCount > 0 && mSelectedPosition > 0 ) {
scrollToChild( mSelectedPosition - mFirstPosition - 1 );
return true;
} else {
return false;
}
}
/**
* Move next.
*
* @return true, if successful
*/
boolean moveNext() {
if ( mItemCount > 0 && mSelectedPosition < mItemCount - 1 ) {
scrollToChild( mSelectedPosition - mFirstPosition + 1 );
return true;
} else {
return false;
}
}
/**
* Scroll to child.
*
* @param childPosition
* the child position
* @return true, if successful
*/
private boolean scrollToChild( int childPosition ) {
View child = getChildAt( childPosition );
if ( child != null ) {
if ( mItemsScrollListener != null ) {
int selection = this.getSelectedItemPosition();
if ( selection >= 0 ) {
View v = getSelectedView();
mItemsScrollListener.onScrollStarted( this, v, selection, getAdapter().getItemId( selection ) );
}
}
int distance = getCenterOfGallery() - getCenterOfView( child );
mFlingRunnable.startUsingDistance( 0, -distance );
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.widget.AdapterView#setSelectedPositionInt(int)
*/
void setSelectedPositionInt( int position, boolean animate ) {
super.setSelectedPositionInt( position );
updateSelectedItemMetadata( animate, false );
}
/**
* Update selected item metadata.
*/
private void updateSelectedItemMetadata( boolean animate, boolean changed ) {
View oldSelectedChild = mSelectedChild;
View child = mSelectedChild = getChildAt( mSelectedPosition - mFirstPosition );
if ( child == null ) {
return;
}
if ( mAutoSelectChild ) child.setSelected( true );
if ( mItemsScrollListener != null ) {
mItemsScrollListener.onScroll( this, child, mSelectedPosition, getAdapter().getItemId( mSelectedPosition ) );
}
// fire vibration
if ( mSelectedPosition != mLastMotionValue && animate ) {
fireVibration();
}
mLastMotionValue = mSelectedPosition;
child.setFocusable( true );
if ( hasFocus() ) {
child.requestFocus();
}
// We unfocus the old child down here so the above hasFocus check
// returns true
if ( oldSelectedChild != null && oldSelectedChild != child ) {
// Make sure its drawable state doesn't contain 'selected'
if ( mAutoSelectChild ) oldSelectedChild.setSelected( false );
// Make sure it is not focusable anymore, since otherwise arrow keys
// can make this one be focused
oldSelectedChild.setFocusable( false );
if ( !animate && changed ) scrollCompleted();
}
}
/**
* Fire vibration.
*/
private void fireVibration() {
if ( mVibrationHandler != null ) {
mVibrationHandler.sendEmptyMessage( MSG_VIBRATE );
}
}
/**
* Describes how the child views are aligned.
*
* @param gravity
* the new gravity
* @attr ref android.R.styleable#Gallery_gravity
*/
public void setGravity( int gravity ) {
if ( mGravity != gravity ) {
mGravity = gravity;
requestLayout();
}
}
/*
* (non-Javadoc)
*
* @see android.view.ViewGroup#getChildDrawingOrder(int, int)
*/
@Override
protected int getChildDrawingOrder( int childCount, int i ) {
int selectedIndex = mSelectedPosition - mFirstPosition;
// Just to be safe
if ( selectedIndex < 0 ) return i;
if ( i == childCount - 1 ) {
// Draw the selected child last
return selectedIndex;
} else if ( i >= selectedIndex ) {
// Move the children after the selected child earlier one
return i + 1;
} else {
// Keep the children before the selected child the same
return i;
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onFocusChanged(boolean, int, android.graphics.Rect)
*/
@Override
protected void onFocusChanged( boolean gainFocus, int direction, Rect previouslyFocusedRect ) {
super.onFocusChanged( gainFocus, direction, previouslyFocusedRect );
/*
* The gallery shows focus by focusing the selected item. So, give focus to our selected item instead. We steal keys from our
* selected item elsewhere.
*/
if ( gainFocus && mSelectedChild != null ) {
mSelectedChild.requestFocus( direction );
if ( mAutoSelectChild ) mSelectedChild.setSelected( true );
}
}
/** The m scroll selection notifier. */
ScrollSelectionNotifier mScrollSelectionNotifier;
/**
* The Class ScrollSelectionNotifier.
*/
private class ScrollSelectionNotifier implements Runnable {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if ( mDataChanged ) {
if ( getAdapter() != null ) {
post( this );
}
} else {
fireOnScrollCompleted();
}
}
}
/**
* Scroll completed.
*/
void scrollCompleted() {
if ( mItemsScrollListener != 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 ( mScrollSelectionNotifier == null ) {
mScrollSelectionNotifier = new ScrollSelectionNotifier();
}
post( mScrollSelectionNotifier );
} else {
fireOnScrollCompleted();
}
}
}
/**
* Fire on scroll completed.
*/
private void fireOnScrollCompleted() {
if ( mItemsScrollListener == null ) return;
int selection = this.getSelectedItemPosition();
if ( selection >= 0 && selection < mItemCount ) {
View v = getSelectedView();
mItemsScrollListener.onScrollFinished( this, v, selection, getAdapter().getItemId( selection ) );
}
}
/**
* Gallery extends LayoutParams to provide a place to hold current Transformation information along with previous
* position/transformation info.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* Instantiates a new layout params.
*
* @param c
* the c
* @param attrs
* the attrs
*/
public LayoutParams( Context c, AttributeSet attrs ) {
super( c, attrs );
}
/**
* Instantiates a new layout params.
*
* @param w
* the w
* @param h
* the h
*/
public LayoutParams( int w, int h ) {
super( w, h );
}
/**
* Instantiates a new layout params.
*
* @param source
* the source
*/
public LayoutParams( ViewGroup.LayoutParams source ) {
super( source );
}
}
@Override
public int getMinX() {
return 0;
}
@Override
public int getMaxX() {
return Integer.MAX_VALUE;
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.ImageViewTouch;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable;
// TODO: Auto-generated Javadoc
/**
* The Class ImageViewSpotDraw.
*/
public class ImageViewSpotDraw extends ImageViewTouch {
/**
* The Enum TouchMode.
*/
public static enum TouchMode {
/** The IMAGE. */
IMAGE,
/** The DRAW. */
DRAW
};
/**
* The listener interface for receiving onDraw events. The class that is interested in processing a onDraw event implements this
* interface, and the object created with that class is registered with a component using the component's
* <code>addOnDrawListener<code> method. When
* the onDraw event occurs, that object's appropriate
* method is invoked.
*
* @see OnDrawEvent
*/
public static interface OnDrawListener {
/**
* On draw start.
*
* @param points
* the points
* @param radius
* the radius
*/
void onDrawStart( float points[], int radius );
/**
* On drawing.
*
* @param points
* the points
* @param radius
* the radius
*/
void onDrawing( float points[], int radius );
/**
* On draw end.
*/
void onDrawEnd();
};
/** The m paint. */
protected Paint mPaint;
/** The m current scale. */
protected float mCurrentScale = 1;
/** The m brush size. */
protected float mBrushSize = 30;
/** The tmp path. */
protected Path tmpPath = new Path();
/** The m canvas. */
protected Canvas mCanvas;
/** The m touch mode. */
protected TouchMode mTouchMode = TouchMode.DRAW;
/** The m y. */
protected float mX, mY;
protected float mStartX, mStartY;
/** The m identity matrix. */
protected Matrix mIdentityMatrix = new Matrix();
/** The m inverted matrix. */
protected Matrix mInvertedMatrix = new Matrix();
/** The Constant TOUCH_TOLERANCE. */
protected static final float TOUCH_TOLERANCE = 2;
/** The m draw listener. */
private OnDrawListener mDrawListener;
/** draw restriction **/
private double mRestiction = 0;
/**
* Instantiates a new image view spot draw.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public ImageViewSpotDraw( Context context, AttributeSet attrs ) {
super( context, attrs );
}
/**
* Sets the on draw start listener.
*
* @param listener
* the new on draw start listener
*/
public void setOnDrawStartListener( OnDrawListener listener ) {
mDrawListener = listener;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#init()
*/
@Override
protected void init() {
super.init();
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mPaint.setFilterBitmap( false );
mPaint.setDither( true );
mPaint.setColor( 0x66FFFFCC );
mPaint.setStyle( Paint.Style.STROKE );
mPaint.setStrokeCap( Paint.Cap.ROUND );
tmpPath = new Path();
}
public void setDrawLimit( double value ) {
mRestiction = value;
}
/**
* Sets the brush size.
*
* @param value
* the new brush size
*/
public void setBrushSize( float value ) {
mBrushSize = value;
if ( mPaint != null ) {
mPaint.setStrokeWidth( mBrushSize );
}
}
/**
* Gets the draw mode.
*
* @return the draw mode
*/
public TouchMode getDrawMode() {
return mTouchMode;
}
/**
* Sets the draw mode.
*
* @param mode
* the new draw mode
*/
public void setDrawMode( TouchMode mode ) {
if ( mode != mTouchMode ) {
mTouchMode = mode;
onDrawModeChanged();
}
}
/**
* On draw mode changed.
*/
protected void onDrawModeChanged() {
if ( mTouchMode == TouchMode.DRAW ) {
Matrix m1 = new Matrix( getImageMatrix() );
mInvertedMatrix.reset();
float[] v1 = getMatrixValues( m1 );
m1.invert( m1 );
float[] v2 = getMatrixValues( m1 );
mInvertedMatrix.postTranslate( -v1[Matrix.MTRANS_X], -v1[Matrix.MTRANS_Y] );
mInvertedMatrix.postScale( v2[Matrix.MSCALE_X], v2[Matrix.MSCALE_Y] );
mCanvas.setMatrix( mInvertedMatrix );
mCurrentScale = getScale();
mPaint.setStrokeWidth( mBrushSize );
}
}
/**
* Gets the paint.
*
* @return the paint
*/
public Paint getPaint() {
return mPaint;
}
/**
* Sets the paint.
*
* @param paint
* the new paint
*/
public void setPaint( Paint paint ) {
mPaint.set( paint );
}
/*
* (non-Javadoc)
*
* @see android.widget.ImageView#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
canvas.drawPath( tmpPath, mPaint );
}
public RectF getImageRect() {
if ( getDrawable() != null ) {
return new RectF( 0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight() );
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onBitmapChanged(android.graphics.drawable.Drawable)
*/
@Override
protected void onBitmapChanged( Drawable drawable ) {
super.onBitmapChanged( drawable );
if ( drawable != null && ( drawable instanceof IBitmapDrawable ) ) {
mCanvas = new Canvas();
mCanvas.drawColor( 0 );
onDrawModeChanged();
}
}
/** The m moved. */
private boolean mMoved = false;
/**
* Touch_start.
*
* @param x
* the x
* @param y
* the y
*/
private void touch_start( float x, float y ) {
mMoved = false;
tmpPath.reset();
tmpPath.moveTo( x, y );
mX = x;
mY = y;
mStartX = x;
mStartY = y;
if ( mDrawListener != null ) {
float mappedPoints[] = new float[2];
mappedPoints[0] = x;
mappedPoints[1] = y;
mInvertedMatrix.mapPoints( mappedPoints );
tmpPath.lineTo( x + .1f, y );
mDrawListener.onDrawStart( mappedPoints, (int) ( mBrushSize / mCurrentScale ) );
}
}
/**
* Touch_move.
*
* @param x
* the x
* @param y
* the y
*/
private void touch_move( float x, float y ) {
float dx = Math.abs( x - mX );
float dy = Math.abs( y - mY );
if ( dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE ) {
if ( !mMoved ) {
tmpPath.setLastPoint( mX, mY );
}
mMoved = true;
if ( mRestiction > 0 ) {
double r = Math.sqrt( Math.pow( x - mStartX, 2 ) + Math.pow( y - mStartY, 2 ) );
double theta = Math.atan2( y - mStartY, x - mStartX );
final float w = getWidth();
final float h = getHeight();
double scale = ( mRestiction / mCurrentScale ) / (double) ( w + h ) / ( mBrushSize / mCurrentScale );
double rNew = Math.log( r * scale + 1 ) / scale;
x = (float) ( mStartX + rNew * Math.cos( theta ) );
y = (float) ( mStartY + rNew * Math.sin( theta ) );
}
tmpPath.quadTo( mX, mY, ( x + mX ) / 2, ( y + mY ) / 2 );
mX = x;
mY = y;
}
if ( mDrawListener != null ) {
float mappedPoints[] = new float[2];
mappedPoints[0] = x;
mappedPoints[1] = y;
mInvertedMatrix.mapPoints( mappedPoints );
mDrawListener.onDrawing( mappedPoints, (int) ( mBrushSize / mCurrentScale ) );
}
}
/**
* Touch_up.
*/
private void touch_up() {
tmpPath.reset();
if ( mDrawListener != null ) {
mDrawListener.onDrawEnd();
}
}
/**
* Gets the matrix values.
*
* @param m
* the m
* @return the matrix values
*/
public static float[] getMatrixValues( Matrix m ) {
float[] values = new float[9];
m.getValues( values );
return values;
}
/*
* (non-Javadoc)
*
* @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent( MotionEvent event ) {
if ( mTouchMode == TouchMode.DRAW && event.getPointerCount() == 1 ) {
float x = event.getX();
float y = event.getY();
switch ( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
touch_start( x, y );
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move( x, y );
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
} else {
if ( mTouchMode == TouchMode.IMAGE )
return super.onTouchEvent( event );
else
return false;
}
}
}
| Java |
package com.aviary.android.feather.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
/**
* acts a an swipe gesture overylay for a view
*/
public class SwipeView extends View {
public static interface OnSwipeListener {
// allow classes to implement as they wish when they overlay a SwipeView
public void onSwipe( boolean leftToRight );
}
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private OnSwipeListener mOnSwipeListener;
View.OnTouchListener gestureListener;
private GestureDetector gestureDetector;
public SwipeView( Context context ) {
super( context );
// TODO Auto-generated constructor stub
gestureDetector = new GestureDetector( new SwipeDetector() );
gestureListener = new View.OnTouchListener() {
public boolean onTouch( View v, MotionEvent event ) {
return gestureDetector.onTouchEvent( event );
}
};
this.setOnTouchListener( gestureListener );
}
public SwipeView( Context context, AttributeSet attrs ) {
super( context, attrs );
// TODO Auto-generated constructor stub
gestureDetector = new GestureDetector( new SwipeDetector() );
gestureListener = new View.OnTouchListener() {
public boolean onTouch( View v, MotionEvent event ) {
return gestureDetector.onTouchEvent( event );
}
};
this.setOnTouchListener( gestureListener );
}
public SwipeView( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
// TODO Auto-generated constructor stub
gestureDetector = new GestureDetector( new SwipeDetector() );
gestureListener = new View.OnTouchListener() {
public boolean onTouch( View v, MotionEvent event ) {
return gestureDetector.onTouchEvent( event );
}
};
this.setOnTouchListener( gestureListener );
}
public OnSwipeListener getOnSwipeListener() {
return mOnSwipeListener;
}
public void setOnSwipeListener( OnSwipeListener swipeDetector ) {
mOnSwipeListener = swipeDetector;
}
public class SwipeDetector extends SimpleOnGestureListener {
@Override
public boolean onDoubleTap( MotionEvent e ) {
return false;
}
@Override
public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) {
return false;
}
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) {
try {
if ( Math.abs( e1.getY() - e2.getY() ) > SWIPE_MAX_OFF_PATH ) return false;
// right to left swipe
if ( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) {
if ( mOnSwipeListener != null ) {
mOnSwipeListener.onSwipe( false );
}
}
// left to right swipe
else if ( e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) {
if ( mOnSwipeListener != null ) {
mOnSwipeListener.onSwipe( true );
}
}
} catch ( Exception e ) {
// nothing
}
return false;
}
}
}
| Java |
package com.aviary.android.feather.widget;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.easing.Expo;
import it.sephiroth.android.library.imagezoom.easing.Linear;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews.RemoteView;
import com.aviary.android.feather.R;
import com.aviary.android.feather.library.graphics.Point2D;
import com.aviary.android.feather.library.log.LoggerFactory;
import com.aviary.android.feather.library.log.LoggerFactory.Logger;
import com.aviary.android.feather.library.log.LoggerFactory.LoggerType;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
// TODO: Auto-generated Javadoc
/**
* Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or
* content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and
* provides various display options such as scaling and tinting.
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
* @attr ref android.R.styleable#ImageView_src
* @attr ref android.R.styleable#ImageView_maxWidth
* @attr ref android.R.styleable#ImageView_maxHeight
* @attr ref android.R.styleable#ImageView_tint
* @attr ref android.R.styleable#ImageView_scaleType
* @attr ref android.R.styleable#ImageView_cropToPadding
*/
@SuppressLint("NewApi")
@RemoteView
public class AdjustImageView extends View {
/** The Constant LOG_TAG. */
static final String LOG_TAG = "rotate";
// settable by the client
/** The m uri. */
private Uri mUri;
/** The m resource. */
private int mResource = 0;
/** The m matrix. */
private Matrix mMatrix;
/** The m scale type. */
private ScaleType mScaleType;
/** The m adjust view bounds. */
private boolean mAdjustViewBounds = false;
/** The m max width. */
private int mMaxWidth = Integer.MAX_VALUE;
/** The m max height. */
private int mMaxHeight = Integer.MAX_VALUE;
// these are applied to the drawable
/** The m color filter. */
private ColorFilter mColorFilter;
/** The m alpha. */
private int mAlpha = 255;
/** The m view alpha scale. */
private int mViewAlphaScale = 256;
/** The m color mod. */
private boolean mColorMod = false;
/** The m drawable. */
private Drawable mDrawable = null;
/** The m state. */
private int[] mState = null;
/** The m merge state. */
private boolean mMergeState = false;
/** The m level. */
private int mLevel = 0;
/** The m drawable width. */
private int mDrawableWidth;
/** The m drawable height. */
private int mDrawableHeight;
/** The m draw matrix. */
private Matrix mDrawMatrix = null;
private Matrix mTempMatrix = new Matrix();
/** The m rotate matrix. */
private Matrix mRotateMatrix = new Matrix();
/** The m flip matrix. */
private Matrix mFlipMatrix = new Matrix();
// Avoid allocations...
/** The m temp src. */
private RectF mTempSrc = new RectF();
/** The m temp dst. */
private RectF mTempDst = new RectF();
/** The m crop to padding. */
private boolean mCropToPadding;
/** The m baseline. */
private int mBaseline = -1;
/** The m baseline align bottom. */
private boolean mBaselineAlignBottom = false;
/** The m have frame. */
private boolean mHaveFrame;
/** The m easing. */
private Easing mEasing = new Expo();
/** View is in the reset state. */
boolean isReset = false;
/** reset animation time. */
int resetAnimTime = 200;
Path mClipPath = new Path();
Path mInversePath = new Path();
Rect mViewDrawRect = new Rect();
RectF mViewInvertRect = new RectF();
Paint mOutlinePaint = new Paint();
Paint mOutlineFill = new Paint();
RectF mDrawRect;
PointF mCenter = new PointF();
Path mLinesPath = new Path();
Paint mLinesPaint = new Paint();
Paint mLinesPaintShadow = new Paint();
// Drawable Drawable;
Drawable mStraightenDrawable;
int handleWidth, handleHeight;
final int grid_rows = 8;
final int grid_cols = 8;
private boolean mEnableFreeRotate;
static Logger logger = LoggerFactory.getLogger( "rotate", LoggerType.ConsoleLoggerType );
/**
* Sets the reset anim duration.
*
* @param value
* the new reset anim duration
*/
public void setResetAnimDuration( int value ) {
resetAnimTime = value;
}
public void setEnableFreeRotate( boolean value ) {
mEnableFreeRotate = value;
}
public boolean isFreeRotateEnabled() {
return mEnableFreeRotate;
}
/**
* The listener interface for receiving onReset events. The class that is interested in processing a onReset event implements
* this interface, and the object created with that class is registered with a component using the component's
* <code>addOnResetListener<code> method. When
* the onReset event occurs, that object's appropriate
* method is invoked.
*
* @see OnResetEvent
*/
public interface OnResetListener {
/**
* On reset complete.
*/
void onResetComplete();
}
/** The m reset listener. */
private OnResetListener mResetListener;
/**
* Sets the on reset listener.
*
* @param listener
* the new on reset listener
*/
public void setOnResetListener( OnResetListener listener ) {
mResetListener = listener;
}
/** The Constant sScaleTypeArray. */
@SuppressWarnings("unused")
private static final ScaleType[] sScaleTypeArray = {
ScaleType.MATRIX, ScaleType.FIT_XY, ScaleType.FIT_START, ScaleType.FIT_CENTER, ScaleType.FIT_END, ScaleType.CENTER,
ScaleType.CENTER_CROP, ScaleType.CENTER_INSIDE };
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
*/
public AdjustImageView( Context context ) {
super( context );
initImageView();
}
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public AdjustImageView( Context context, AttributeSet attrs ) {
this( context, attrs, 0 );
}
/**
* Instantiates a new adjust image view.
*
* @param context
* the context
* @param attrs
* the attrs
* @param defStyle
* the def style
*/
public AdjustImageView( Context context, AttributeSet attrs, int defStyle ) {
super( context, attrs, defStyle );
initImageView();
}
/**
* Sets the easing.
*
* @param value
* the new easing
*/
public void setEasing( Easing value ) {
mEasing = value;
}
int mOutlinePaintAlpha, mOutlineFillAlpha, mLinesAlpha, mLinesShadowAlpha;
/**
* Inits the image view.
*/
private void initImageView() {
mMatrix = new Matrix();
mScaleType = ScaleType.FIT_CENTER;
Context context = getContext();
int highlight_color = context.getResources().getColor( R.color.feather_rotate_highlight_stroke_color );
int highlight_stroke_internal_color = context.getResources().getColor( R.color.feather_rotate_highlight_grid_stroke_color );
int highlight_stroke_internal_width = context.getResources()
.getInteger( R.integer.feather_rotate_highlight_grid_stroke_width );
int highlight_outside_color = context.getResources().getColor( R.color.feather_rotate_highlight_outside );
int highlight_stroke_width = context.getResources().getInteger( R.integer.feather_rotate_highlight_stroke_width );
mOutlinePaint.setStrokeWidth( highlight_stroke_width );
mOutlinePaint.setStyle( Paint.Style.STROKE );
mOutlinePaint.setAntiAlias( true );
mOutlinePaint.setColor( highlight_color );
mOutlineFill.setStyle( Paint.Style.FILL );
mOutlineFill.setAntiAlias( false );
mOutlineFill.setColor( highlight_outside_color );
mOutlineFill.setDither( false );
try {
ReflectionUtils.invokeMethod( mOutlineFill, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaint.setStrokeWidth( highlight_stroke_internal_width );
mLinesPaint.setAntiAlias( false );
mLinesPaint.setDither( false );
mLinesPaint.setStyle( Paint.Style.STROKE );
mLinesPaint.setColor( highlight_stroke_internal_color );
try {
ReflectionUtils.invokeMethod( mLinesPaint, "setHinting", new Class<?>[] { int.class }, 0 );
} catch ( ReflectionException e ) {}
mLinesPaintShadow.setStrokeWidth( highlight_stroke_internal_width );
mLinesPaintShadow.setAntiAlias( true );
mLinesPaintShadow.setColor( Color.BLACK );
mLinesPaintShadow.setStyle( Paint.Style.STROKE );
mLinesPaintShadow.setMaskFilter( new BlurMaskFilter( 2, Blur.NORMAL ) );
mOutlineFillAlpha = mOutlineFill.getAlpha();
mOutlinePaintAlpha = mOutlinePaint.getAlpha();
mLinesAlpha = mLinesPaint.getAlpha();
mLinesShadowAlpha = mLinesPaintShadow.getAlpha();
mOutlinePaint.setAlpha( 0 );
mOutlineFill.setAlpha( 0 );
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
android.content.res.Resources resources = getContext().getResources();
mStraightenDrawable = resources.getDrawable( R.drawable.feather_straighten_knob );
double w = mStraightenDrawable.getIntrinsicWidth();
double h = mStraightenDrawable.getIntrinsicHeight();
handleWidth = (int) Math.ceil( w / 2.0 );
handleHeight = (int) Math.ceil( h / 2.0 );
}
/*
* (non-Javadoc)
*
* @see android.view.View#verifyDrawable(android.graphics.drawable.Drawable)
*/
@Override
protected boolean verifyDrawable( Drawable dr ) {
return mDrawable == dr || super.verifyDrawable( dr );
}
/*
* (non-Javadoc)
*
* @see android.view.View#invalidateDrawable(android.graphics.drawable.Drawable)
*/
@Override
public void invalidateDrawable( Drawable dr ) {
if ( dr == mDrawable ) {
/*
* we invalidate the whole view in this case because it's very hard to know where the drawable actually is. This is made
* complicated because of the offsets and transformations that can be applied. In theory we could get the drawable's bounds
* and run them through the transformation and offsets, but this is probably not worth the effort.
*/
invalidate();
} else {
super.invalidateDrawable( dr );
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onSetAlpha(int)
*/
@Override
protected boolean onSetAlpha( int alpha ) {
if ( getBackground() == null ) {
int scale = alpha + ( alpha >> 7 );
if ( mViewAlphaScale != scale ) {
mViewAlphaScale = scale;
mColorMod = true;
applyColorMod();
}
return true;
}
return false;
}
private PointF getCenter() {
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
return new PointF( (float) vwidth / 2, (float) vheight / 2 );
}
private RectF getViewRect() {
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
return new RectF( 0, 0, vwidth, vheight );
}
private RectF getImageRect() {
return new RectF( 0, 0, mDrawableWidth, mDrawableHeight );
}
private void onTouchStart() {
if ( mFadeHandlerStarted ) {
fadeinGrid( 300 );
} else {
fadeinOutlines( 600 );
}
}
/**
* private void onTouchMove( float x, float y ) { if ( isDown ) { PointF current = new PointF( x, y ); PointF center =
* getCenter();
*
* float angle = (float) Point2D.angle360( originalAngle - Point2D.angleBetweenPoints( center, current ) );
*
* logger.log( "ANGLE: " + angle + " .. " + getAngle90( angle ) );
*
* setImageRotation( angle, false ); mRotation = angle; invalidate(); } }
*/
private void setImageRotation( double angle, boolean invert ) {
PointF center = getCenter();
Matrix tempMatrix = new Matrix( mDrawMatrix );
RectF src = getImageRect();
RectF dst = getViewRect();
tempMatrix.setRotate( (float) angle, center.x, center.y );
tempMatrix.mapRect( src );
tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) );
float[] scale = getMatrixScale( tempMatrix );
float fScale = Math.min( scale[0], scale[1] );
if ( invert ) {
mRotateMatrix.setRotate( (float) angle, center.x, center.y );
mRotateMatrix.postScale( fScale, fScale, center.x, center.y );
} else {
mRotateMatrix.setScale( fScale, fScale, center.x, center.y );
mRotateMatrix.postRotate( (float) angle, center.x, center.y );
}
}
private void onTouchUp() {
invalidate();
fadeoutGrid( 300 );
}
boolean straightenStarted = false;
double previousStraightenAngle = 0;
double prevGrowth = 1;
double currentNewPosition;
boolean testStraighten = true;
double prevGrowthAngle = 0;
float currentGrowth = 0;
Matrix mStraightenMatrix = new Matrix();
double previousAngle = 0;
boolean intersectPoints = true;
boolean portrait = false;
int orientation = 0; // the orientation of the screen, whether in landscape or portrait
public double getGrowthFactor() {
return prevGrowth;
}
public double getStraightenAngle() {
return previousStraightenAngle;
}
/**
*
* Calculates the new angle and size of of the image through matrix and geometric operations
*
* @param angleDifference
* - difference between previous angle and current angle
* @param direction
* - if there is an increase or decrease in angle
* @param newPosition
* - the new destination angle
*/
private void setStraightenRotation( double newPosition ) {
logger.info( "setStraightenRotation: " + newPosition + ", prev: " + previousStraightenAngle );
// angle here is the difference between previous angle and new angle
// you need to take advantage of the third parameter, newPosition
double growthFactor = 1;
//newPosition = newPosition / 2;
currentNewPosition = newPosition;
PointF center = getCenter();
mStraightenMatrix.postRotate( (float) -previousStraightenAngle, center.x, center.y );
mStraightenMatrix.postRotate( (float) newPosition, center.x, center.y );
previousStraightenAngle = newPosition;
double divideGrowth = 1 / prevGrowth;
mStraightenMatrix.postScale( (float) divideGrowth, (float) divideGrowth, center.x, center.y );
prevGrowthAngle = newPosition;
if ( portrait ) {
// this algorithm works slightly differently between landscape and portrait images because of the proportions
final double sin_rad = Math.sin( Math.toRadians( currentNewPosition ) );
final double cos_rad = Math.cos( Math.toRadians( currentNewPosition ) );
float[] testPoint = {
(float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ),
(float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ),
(float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ),
(float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ) };
mStraightenMatrix.mapPoints( testPoint );
/**
* ax = trueRect.left+getPaddingLeft(); ay = trueRect.top+getPaddingTop(); bx = trueRect.right+getPaddingRight(); by =
* trueRect.top+getPaddingTop(); cx = trueRect.left+getPaddingLeft(); cy = trueRect.bottom+getPaddingBottom(); dx =
* trueRect.right+getPaddingRight(); dy = trueRect.bottom+getPaddingBottom();
*/
float x1 = (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() );
float y1 = (float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingTop() );
float x2 = (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() );
float y2 = (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() );
float x3 = testPoint[2];
float y3 = testPoint[3];
float x4 = testPoint[6];
float y4 = testPoint[7];
double numerator2 = ( x1 * y2 - y1 * x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 * y4 - y3 * x4 );
double denominator2 = ( ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) );
double Px = imageCaptureRegion.right + getPaddingRight();
double Py = ( numerator2 ) / ( denominator2 ) + getPaddingBottom();
orientation = getResources().getConfiguration().orientation;
if ( orientation == Configuration.ORIENTATION_LANDSCAPE && newPosition > 0 ) {
Py = ( numerator2 ) / ( denominator2 ) + sin_rad * getPaddingBottom();
}
double dx = Px - x2;
double dy = Py - y2;
if ( newPosition < 0 ) {
dx = Px - x1;
dy = Py - y1;
}
double distance = Math.sqrt( dx * dx + dy * dy );
double amountNeededToGrow = ( 2 * distance * ( Math.sin( Math.toRadians( Math.abs( newPosition ) ) ) ) );
distance = FloatMath.sqrt( ( testPoint[0] - testPoint[2] ) * ( testPoint[0] - testPoint[2] ) );
if ( newPosition != 0 ) {
growthFactor = ( distance + amountNeededToGrow ) / distance;
mStraightenMatrix.postScale( (float) growthFactor, (float) growthFactor, center.x, center.y );
} else {
growthFactor = 1;
}
// intersectx = (float) Px;
// intersecty = (float) Py;
}
else {
final double sin_rad = Math.sin( Math.toRadians( currentNewPosition ) );
final double cos_rad = Math.cos( Math.toRadians( currentNewPosition ) );
float[] testPoint = {
(float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ),
(float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ),
(float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ),
(float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ),
(float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ) };
mStraightenMatrix.mapPoints( testPoint );
/**
* ax = testPoint[0]; ay = testPoint[1]; bx = testPoint[2]; by = testPoint[3]; cx = testPoint[4]; cy = testPoint[5]; dx =
* testPoint[6]; dy = testPoint[7];
*/
float x1 = (float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() );
float y1 = (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() );
float x2 = (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() );
float y2 = (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() );
float x3 = testPoint[4];
float y3 = testPoint[5];
float x4 = testPoint[6];
float y4 = testPoint[7];
double numerator1 = ( x1 * y2 - y1 * x2 ) * ( x3 - x4 ) - ( x1 - x2 ) * ( x3 * y4 - y3 * x4 );
double denominator1 = ( ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) );
double Px = ( numerator1 ) / ( denominator1 ) + getPaddingLeft();
double Py = imageCaptureRegion.bottom + getPaddingBottom();
double dx = Px - x1;
double dy = Py - y1;
if ( newPosition < 0 ) {
dx = Px - x2;
dy = Py - y2;
}
double distance = Math.sqrt( dx * dx + dy * dy );
double amountNeededToGrow = ( 2 * distance * ( Math.sin( Math.toRadians( Math.abs( newPosition ) ) ) ) );
distance = FloatMath.sqrt( ( testPoint[5] - testPoint[1] ) * ( testPoint[5] - testPoint[1] ) );
if ( newPosition != 0 ) {
growthFactor = ( distance + amountNeededToGrow ) / distance;
mStraightenMatrix.postScale( (float) growthFactor, (float) growthFactor, center.x, center.y );
} else {
growthFactor = 1;
}
// intersectx = (float) Px;
// intersecty = (float) Py;
}
// now the resize-grow stuff
prevGrowth = growthFactor;
}
/**
*
* The top level call for the straightening of the image
*
* @param newPosition
* - the destination angle for the image
* @param durationMs
* - animation time
* @param direction
* - if there is increase or decrease of angle of rotation
*/
public void straighten( final double newPosition, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
straightenStarted = true;
invalidate();
mHandler.post( new Runnable() {
@Override
public void run() {
/**
* If, for example, the current rotation position is 2 degrees and then we want the original photo to be rotated 45
* degrees, we can simply rotate the current photo 43 degrees...
*/
setStraightenRotation( newPosition );
invalidate();
mRunning = false;
}
} );
}
/**
*
* The top level call for the straightening of the image
*
* @param newPosition
* - the destination angle for the image
* @param durationMs
* - animation time
* @param direction
* - if there is increase or decrease of angle of rotation
*/
public void straightenBy( final double newPosition, final int durationMs ) {
logger.info( "straightenBy: " + newPosition + ", duration: " + durationMs );
if ( mRunning ) {
return;
}
mRunning = true;
straightenStarted = true;
final long startTime = System.currentTimeMillis();
final double destRotation = getStraightenAngle() + newPosition;
final double srcRotation = getStraightenAngle();
logger.info( "destRotation: " + destRotation );
invalidate();
mHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
double new_rotation = (mEasing.easeInOut( currentMs, 0, newPosition, durationMs ));
logger.log( "straightenBy... new_rotation: " + new_rotation );
logger.log( "time: " + currentMs );
setStraightenRotation( srcRotation + new_rotation );
invalidate();
if( currentMs < durationMs ){
mHandler.post( this );
} else {
setStraightenRotation( destRotation );
invalidate();
mRunning = false;
if( isReset ){
straightenStarted = false;
onReset();
}
}
}
} );
}
private float mLastTouchX;
private float mPosX;
Rect testRect = new Rect( 0, 0, 0, 0 );
final int straightenDuration = 50;
int previousPosition = 0;
boolean initTool = true;
@Override
public boolean onTouchEvent( MotionEvent ev ) {
if ( !mEnableFreeRotate ) return true;
final int action = ev.getAction();
if ( initStraighten ) {
resetStraighten();
}
switch ( action ) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
onTouchStart();
// Remember where we started
mLastTouchX = x;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
// Calculate the distance moved
final float dx = x - mLastTouchX;
// Move the object
mPosX += dx;
// Remember this touch position for the next move event
mLastTouchX = x;
Rect bounds = mStraightenDrawable.getBounds();
Rect straightenMoveRegion = new Rect( (int) imageCaptureRegion.left + getPaddingLeft(), bounds.top - 50,
(int) imageCaptureRegion.right + getPaddingRight(), bounds.bottom + 70 );
testRect = new Rect( straightenMoveRegion );
if ( straightenMoveRegion.contains( (int) x, (int) y ) ) {
// if the move is within the straighten tool touch bounds
if ( mPosX > imageCaptureRegion.right ) {
mPosX = imageCaptureRegion.right;
}
if ( mPosX < imageCaptureRegion.left ) {
mPosX = imageCaptureRegion.left;
}
mStraightenDrawable.setBounds( (int) ( mPosX - handleWidth ), (int) ( imageCaptureRegion.bottom - handleHeight ),
(int) ( mPosX + handleWidth ), (int) ( imageCaptureRegion.bottom + handleHeight ) );
// now get the angle from the distance
double midPoint = getCenter().x;
double maxAngle = ( 45 * imageCaptureRegion.right ) / midPoint - 45;
double tempAngle = ( 45 * mPosX ) / midPoint - 45;
double angle = ( 45 * tempAngle ) / maxAngle;
straighten( angle/2, straightenDuration );
}
// Invalidate to request a redraw
invalidate();
break;
}
case MotionEvent.ACTION_UP: {
onTouchUp();
break;
}
}
return true;
}
private double getRotationFromMatrix( Matrix matrix ) {
float[] pts = { 0, 0, 0, -100 };
matrix.mapPoints( pts );
double angle = Point2D.angleBetweenPoints( pts[0], pts[1], pts[2], pts[3], 0 );
return -angle;
}
/**
* Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
*
* @param adjustViewBounds
* Whether to adjust the bounds of this view to presrve the original aspect ratio of the drawable
*
* @attr ref android.R.styleable#ImageView_adjustViewBounds
*/
public void setAdjustViewBounds( boolean adjustViewBounds ) {
mAdjustViewBounds = adjustViewBounds;
if ( adjustViewBounds ) {
setScaleType( ScaleType.FIT_CENTER );
}
}
/**
* An optional argument to supply a maximum width for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been set
* to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.
*
* <p>
* Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image
* to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)}
* to determine how to fit the image within the bounds.
* </p>
*
* @param maxWidth
* maximum width for this view
*
* @attr ref android.R.styleable#ImageView_maxWidth
*/
public void setMaxWidth( int maxWidth ) {
mMaxWidth = maxWidth;
}
/**
* An optional argument to supply a maximum height for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been
* set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT.
*
* <p>
* Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image
* to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)}
* to determine how to fit the image within the bounds.
* </p>
*
* @param maxHeight
* maximum height for this view
*
* @attr ref android.R.styleable#ImageView_maxHeight
*/
public void setMaxHeight( int maxHeight ) {
mMaxHeight = maxHeight;
}
/**
* Return the view's drawable, or null if no drawable has been assigned.
*
* @return the drawable
*/
public Drawable getDrawable() {
return mDrawable;
}
/**
* Sets a drawable as the content of this ImageView.
*
* <p class="note">
* This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using
*
* @param resId
* the resource identifier of the the drawable {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead.
* </p>
* @attr ref android.R.styleable#ImageView_src
*/
public void setImageResource( int resId ) {
if ( mUri != null || mResource != resId ) {
updateDrawable( null );
mResource = resId;
mUri = null;
resolveUri();
requestLayout();
invalidate();
}
}
/**
* Sets the content of this ImageView to the specified Uri.
*
* <p class="note">
* This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using
*
* @param uri
* The Uri of an image {@link #setImageDrawable(android.graphics.drawable.Drawable)} or
* {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead.
* </p>
*/
public void setImageURI( Uri uri ) {
if ( mResource != 0 || ( mUri != uri && ( uri == null || mUri == null || !uri.equals( mUri ) ) ) ) {
updateDrawable( null );
mResource = 0;
mUri = uri;
resolveUri();
requestLayout();
invalidate();
}
}
/**
* Sets a drawable as the content of this ImageView.
*
* @param drawable
* The drawable to set
*/
public void setImageDrawable( Drawable drawable ) {
if ( mDrawable != drawable ) {
mResource = 0;
mUri = null;
int oldWidth = mDrawableWidth;
int oldHeight = mDrawableHeight;
updateDrawable( drawable );
if ( oldWidth != mDrawableWidth || oldHeight != mDrawableHeight ) {
requestLayout();
}
invalidate();
}
}
/**
* Sets a Bitmap as the content of this ImageView.
*
* @param bm
* The bitmap to set
*/
public void setImageBitmap( Bitmap bm ) {
// if this is used frequently, may handle bitmaps explicitly
// to reduce the intermediate drawable object
setImageDrawable( new BitmapDrawable( getContext().getResources(), bm ) );
}
/**
* Sets the image state.
*
* @param state
* the state
* @param merge
* the merge
*/
public void setImageState( int[] state, boolean merge ) {
mState = state;
mMergeState = merge;
if ( mDrawable != null ) {
refreshDrawableState();
resizeFromDrawable();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#setSelected(boolean)
*/
@Override
public void setSelected( boolean selected ) {
super.setSelected( selected );
resizeFromDrawable();
}
/**
* Sets the image level, when it is constructed from a {@link android.graphics.drawable.LevelListDrawable}.
*
* @param level
* The new level for the image.
*/
public void setImageLevel( int level ) {
mLevel = level;
if ( mDrawable != null ) {
mDrawable.setLevel( level );
resizeFromDrawable();
}
}
/**
* Options for scaling the bounds of an image to the bounds of this view.
*/
public enum ScaleType {
/**
* Scale using the image matrix when drawing. The image matrix can be set using {@link ImageView#setImageMatrix(Matrix)}. From
* XML, use this syntax: <code>android:scaleType="matrix"</code>.
*/
MATRIX( 0 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#FILL}. From XML, use this syntax: <code>android:scaleType="fitXY"</code>.
*/
FIT_XY( 1 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#START}. From XML, use this syntax: <code>android:scaleType="fitStart"</code>
* .
*/
FIT_START( 2 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#CENTER}. From XML, use this syntax:
* <code>android:scaleType="fitCenter"</code>.
*/
FIT_CENTER( 3 ),
/**
* Scale the image using {@link Matrix.ScaleToFit#END}. From XML, use this syntax: <code>android:scaleType="fitEnd"</code>.
*/
FIT_END( 4 ),
/**
* Center the image in the view, but perform no scaling. From XML, use this syntax: <code>android:scaleType="center"</code>.
*/
CENTER( 5 ),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will
* be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view.
* From XML, use this syntax: <code>android:scaleType="centerCrop"</code>.
*/
CENTER_CROP( 6 ),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will
* be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view.
* From XML, use this syntax: <code>android:scaleType="centerInside"</code>.
*/
CENTER_INSIDE( 7 );
/**
* Instantiates a new scale type.
*
* @param ni
* the ni
*/
ScaleType( int ni ) {
nativeInt = ni;
}
/** The native int. */
final int nativeInt;
}
/**
* Controls how the image should be resized or moved to match the size of this ImageView.
*
* @param scaleType
* The desired scaling mode.
*
* @attr ref android.R.styleable#ImageView_scaleType
*/
public void setScaleType( ScaleType scaleType ) {
if ( scaleType == null ) {
throw new NullPointerException();
}
if ( mScaleType != scaleType ) {
mScaleType = scaleType;
setWillNotCacheDrawing( mScaleType == ScaleType.CENTER );
requestLayout();
invalidate();
}
}
/**
* Return the current scale type in use by this ImageView.
*
* @return the scale type
* @see ImageView.ScaleType
* @attr ref android.R.styleable#ImageView_scaleType
*/
public ScaleType getScaleType() {
return mScaleType;
}
/**
* Return the view's optional matrix. This is applied to the view's drawable when it is drawn. If there is not matrix, this
* method will return null. Do not change this matrix in place. If you want a different matrix applied to the drawable, be sure
* to call setImageMatrix().
*
* @return the image matrix
*/
public Matrix getImageMatrix() {
return mMatrix;
}
/**
* Sets the image matrix.
*
* @param matrix
* the new image matrix
*/
public void setImageMatrix( Matrix matrix ) {
// collaps null and identity to just null
if ( matrix != null && matrix.isIdentity() ) {
matrix = null;
}
// don't invalidate unless we're actually changing our matrix
if ( matrix == null && !mMatrix.isIdentity() || matrix != null && !mMatrix.equals( matrix ) ) {
mMatrix.set( matrix );
configureBounds();
invalidate();
}
}
/**
* Resolve uri.
*/
private void resolveUri() {
if ( mDrawable != null ) {
return;
}
Resources rsrc = getResources();
if ( rsrc == null ) {
return;
}
Drawable d = null;
if ( mResource != 0 ) {
try {
d = rsrc.getDrawable( mResource );
} catch ( Exception e ) {
Log.w( LOG_TAG, "Unable to find resource: " + mResource, e );
// Don't try again.
mUri = null;
}
} else if ( mUri != null ) {
String scheme = mUri.getScheme();
if ( ContentResolver.SCHEME_ANDROID_RESOURCE.equals( scheme ) ) {
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) || ContentResolver.SCHEME_FILE.equals( scheme ) ) {
try {
d = Drawable.createFromStream( getContext().getContentResolver().openInputStream( mUri ), null );
} catch ( Exception e ) {
Log.w( LOG_TAG, "Unable to open content: " + mUri, e );
}
} else {
d = Drawable.createFromPath( mUri.toString() );
}
if ( d == null ) {
System.out.println( "resolveUri failed on bad bitmap uri: " + mUri );
// Don't try again.
mUri = null;
}
} else {
return;
}
updateDrawable( d );
}
/*
* (non-Javadoc)
*
* @see android.view.View#onCreateDrawableState(int)
*/
@Override
public int[] onCreateDrawableState( int extraSpace ) {
if ( mState == null ) {
return super.onCreateDrawableState( extraSpace );
} else if ( !mMergeState ) {
return mState;
} else {
return mergeDrawableStates( super.onCreateDrawableState( extraSpace + mState.length ), mState );
}
}
/**
* Update drawable.
*
* @param d
* the d
*/
private void updateDrawable( Drawable d ) {
if ( mDrawable != null ) {
mDrawable.setCallback( null );
unscheduleDrawable( mDrawable );
}
mDrawable = d;
if ( d != null ) {
d.setCallback( this );
if ( d.isStateful() ) {
d.setState( getDrawableState() );
}
d.setLevel( mLevel );
mDrawableWidth = d.getIntrinsicWidth();
mDrawableHeight = d.getIntrinsicHeight();
applyColorMod();
configureBounds();
} else {
mDrawableWidth = mDrawableHeight = -1;
}
}
/**
* Resize from drawable.
*/
private void resizeFromDrawable() {
Drawable d = mDrawable;
if ( d != null ) {
int w = d.getIntrinsicWidth();
if ( w < 0 ) w = mDrawableWidth;
int h = d.getIntrinsicHeight();
if ( h < 0 ) h = mDrawableHeight;
if ( w != mDrawableWidth || h != mDrawableHeight ) {
mDrawableWidth = w;
mDrawableHeight = h;
requestLayout();
}
}
}
/** The Constant sS2FArray. */
private static final Matrix.ScaleToFit[] sS2FArray = {
Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END };
/**
* Scale type to scale to fit.
*
* @param st
* the st
* @return the matrix. scale to fit
*/
private static Matrix.ScaleToFit scaleTypeToScaleToFit( ScaleType st ) {
// ScaleToFit enum to their corresponding Matrix.ScaleToFit values
return sS2FArray[st.nativeInt - 1];
}
/*
* (non-Javadoc)
*
* @see android.view.View#onLayout(boolean, int, int, int, int)
*/
@Override
protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
super.onLayout( changed, left, top, right, bottom );
if ( changed ) {
mHaveFrame = true;
double oldRotation = mRotation;
boolean flip_h = getHorizontalFlip();
boolean flip_v = getVerticalFlip();
configureBounds();
if ( flip_h || flip_v ) {
flip( flip_h, flip_v );
}
if ( oldRotation != 0 ) {
setImageRotation( oldRotation, false );
mRotation = oldRotation;
}
invalidate();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
resolveUri();
int w;
int h;
// Desired aspect ratio of the view's contents (not including padding)
float desiredAspect = 0.0f;
// We are allowed to change the view's width
boolean resizeWidth = false;
// We are allowed to change the view's height
boolean resizeHeight = false;
final int widthSpecMode = MeasureSpec.getMode( widthMeasureSpec );
final int heightSpecMode = MeasureSpec.getMode( heightMeasureSpec );
if ( mDrawable == null ) {
// If no drawable, its intrinsic size is 0.
mDrawableWidth = -1;
mDrawableHeight = -1;
w = h = 0;
} else {
w = mDrawableWidth;
h = mDrawableHeight;
if ( w <= 0 ) w = 1;
if ( h <= 0 ) h = 1;
if ( mDrawableHeight > mDrawableWidth ) {
portrait = true;
}
orientation = getResources().getConfiguration().orientation;
// We are supposed to adjust view bounds to match the aspect
// ratio of our drawable. See if that is possible.
if ( mAdjustViewBounds ) {
resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
desiredAspect = (float) w / (float) h;
}
}
int pleft = getPaddingLeft();
int pright = getPaddingRight();
int ptop = getPaddingTop();
int pbottom = getPaddingBottom();
int widthSize;
int heightSize;
if ( resizeWidth || resizeHeight ) {
/*
* If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at
* least one dimension.
*/
// Get the max possible width given our constraints
widthSize = resolveAdjustedSize( w + pleft + pright, mMaxWidth, widthMeasureSpec );
// Get the max possible height given our constraints
heightSize = resolveAdjustedSize( h + ptop + pbottom, mMaxHeight, heightMeasureSpec );
if ( desiredAspect != 0.0f ) {
// See what our actual aspect ratio is
float actualAspect = (float) ( widthSize - pleft - pright ) / ( heightSize - ptop - pbottom );
if ( Math.abs( actualAspect - desiredAspect ) > 0.0000001 ) {
boolean done = false;
// Try adjusting width to be proportional to height
if ( resizeWidth ) {
int newWidth = (int) ( desiredAspect * ( heightSize - ptop - pbottom ) ) + pleft + pright;
if ( newWidth <= widthSize ) {
widthSize = newWidth;
done = true;
}
}
// Try adjusting height to be proportional to width
if ( !done && resizeHeight ) {
int newHeight = (int) ( ( widthSize - pleft - pright ) / desiredAspect ) + ptop + pbottom;
if ( newHeight <= heightSize ) {
heightSize = newHeight;
}
}
}
}
} else {
/*
* We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just
* measure in the normal way.
*/
w += pleft + pright;
h += ptop + pbottom;
w = Math.max( w, getSuggestedMinimumWidth() );
h = Math.max( h, getSuggestedMinimumHeight() );
widthSize = resolveSize( w, widthMeasureSpec );
heightSize = resolveSize( h, heightMeasureSpec );
}
setMeasuredDimension( widthSize, heightSize );
// drawResource();
}
/**
* Resolve adjusted size.
*
* @param desiredSize
* the desired size
* @param maxSize
* the max size
* @param measureSpec
* the measure spec
* @return the int
*/
private int resolveAdjustedSize( int desiredSize, int maxSize, int measureSpec ) {
int result = desiredSize;
int specMode = MeasureSpec.getMode( measureSpec );
int specSize = MeasureSpec.getSize( measureSpec );
switch ( specMode ) {
case MeasureSpec.UNSPECIFIED:
/*
* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves.
*/
result = Math.min( desiredSize, maxSize );
break;
case MeasureSpec.AT_MOST:
// Parent says we can be as big as we want, up to specSize.
// Don't be larger than specSize, and don't be larger than
// the max size imposed on ourselves.
result = Math.min( Math.min( desiredSize, specSize ), maxSize );
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
/**
* Configure bounds.
*/
private void configureBounds() {
if ( mDrawable == null || !mHaveFrame ) {
return;
}
int dwidth = mDrawableWidth;
int dheight = mDrawableHeight;
int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
boolean fits = ( dwidth < 0 || vwidth == dwidth ) && ( dheight < 0 || vheight == dheight );
if ( dwidth <= 0 || dheight <= 0 || ScaleType.FIT_XY == mScaleType ) {
/*
* If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view.
*/
mDrawable.setBounds( 0, 0, vwidth, vheight );
mDrawMatrix = null;
} else {
// We need to do the scaling ourself, so have the drawable
// use its native size.
mDrawable.setBounds( 0, 0, dwidth, dheight );
if ( ScaleType.MATRIX == mScaleType ) {
// Use the specified matrix as-is.
if ( mMatrix.isIdentity() ) {
mDrawMatrix = null;
} else {
mDrawMatrix = mMatrix;
}
} else if ( fits ) {
// The bitmap fits exactly, no transform needed.
mDrawMatrix = null;
} else if ( ScaleType.CENTER == mScaleType ) {
// Center bitmap in view, no scaling.
mDrawMatrix = mMatrix;
mDrawMatrix.setTranslate( (int) ( ( vwidth - dwidth ) * 0.5f + 0.5f ), (int) ( ( vheight - dheight ) * 0.5f + 0.5f ) );
} else if ( ScaleType.CENTER_CROP == mScaleType ) {
mDrawMatrix = mMatrix;
float scale;
float dx = 0, dy = 0;
if ( dwidth * vheight > vwidth * dheight ) {
scale = (float) vheight / (float) dheight;
dx = ( vwidth - dwidth * scale ) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = ( vheight - dheight * scale ) * 0.5f;
}
mDrawMatrix.setScale( scale, scale );
mDrawMatrix.postTranslate( (int) ( dx + 0.5f ), (int) ( dy + 0.5f ) );
} else if ( ScaleType.CENTER_INSIDE == mScaleType ) {
mDrawMatrix = mMatrix;
float scale;
float dx;
float dy;
if ( dwidth <= vwidth && dheight <= vheight ) {
scale = 1.0f;
} else {
scale = Math.min( (float) vwidth / (float) dwidth, (float) vheight / (float) dheight );
}
dx = (int) ( ( vwidth - dwidth * scale ) * 0.5f + 0.5f );
dy = (int) ( ( vheight - dheight * scale ) * 0.5f + 0.5f );
mDrawMatrix.setScale( scale, scale );
mDrawMatrix.postTranslate( dx, dy );
} else {
// Generate the required transform.
mTempSrc.set( 0, 0, dwidth, dheight );
mTempDst.set( 0, 0, vwidth, vheight );
mDrawMatrix = mMatrix;
mDrawMatrix.setRectToRect( mTempSrc, mTempDst, scaleTypeToScaleToFit( mScaleType ) );
mCurrentScale = getMatrixScale( mDrawMatrix )[0];
Matrix tempMatrix = new Matrix( mMatrix );
RectF src = new RectF();
RectF dst = new RectF();
src.set( 0, 0, dheight, dwidth );
dst.set( 0, 0, vwidth, vheight );
tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) );
tempMatrix = new Matrix( mDrawMatrix );
tempMatrix.invert( tempMatrix );
float invertScale = getMatrixScale( tempMatrix )[0];
mDrawMatrix.postScale( invertScale, invertScale, vwidth / 2, vheight / 2 );
mRotateMatrix.reset();
mStraightenMatrix.reset();
mFlipMatrix.reset();
mFlipType = FlipType.FLIP_NONE.nativeInt;
mRotation = 0;
mRotateMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 );
// mStraightenMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 );
mDrawRect = getImageRect();
mCenter = getCenter();
}
}
}
/*
* (non-Javadoc)
*
* @see android.view.View#drawableStateChanged()
*/
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
Drawable d = mDrawable;
if ( d != null && d.isStateful() ) {
d.setState( getDrawableState() );
}
}
@Override
protected void onDraw( Canvas canvas ) {
super.onDraw( canvas );
if ( mDrawable == null ) {
return; // couldn't resolve the URI
}
if ( mDrawableWidth == 0 || mDrawableHeight == 0 ) {
return; // nothing to draw (empty bounds)
}
final int mPaddingTop = getPaddingTop();
final int mPaddingLeft = getPaddingLeft();
final int mPaddingBottom = getPaddingBottom();
final int mPaddingRight = getPaddingRight();
if ( mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0 ) {
mDrawable.draw( canvas );
} else {
int saveCount = canvas.getSaveCount();
canvas.save();
if ( mCropToPadding ) {
final int scrollX = getScrollX();
final int scrollY = getScrollY();
canvas.clipRect( scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + getRight() - getLeft() - mPaddingRight,
scrollY + getBottom() - getTop() - mPaddingBottom );
}
canvas.translate( mPaddingLeft, mPaddingTop );
if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix );
if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix );
//
if ( mStraightenMatrix != null ) canvas.concat( mStraightenMatrix );
if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix );
mDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
if ( mEnableFreeRotate ) {
mDrawRect = getImageRect();
getDrawingRect( mViewDrawRect );
mClipPath.reset();
mInversePath.reset();
mLinesPath.reset();
float[] points = new float[] {
mDrawRect.left, mDrawRect.top, mDrawRect.right, mDrawRect.top, mDrawRect.right, mDrawRect.bottom, mDrawRect.left,
mDrawRect.bottom };
mTempMatrix.set( mDrawMatrix );
mTempMatrix.postConcat( mRotateMatrix );
mTempMatrix.postConcat( mStraightenMatrix );
mTempMatrix.mapPoints( points );
mViewInvertRect.set( mViewDrawRect );
mViewInvertRect.top -= mPaddingLeft;
mViewInvertRect.left -= mPaddingTop;
mInversePath.addRect( mViewInvertRect, Path.Direction.CW );
double sx = Point2D.distance( points[2], points[3], points[0], points[1] );
double sy = Point2D.distance( points[6], points[7], points[0], points[1] );
double angle = getAngle90( mRotation );
RectF rect;
if ( initStraighten ) {
if ( angle < 45 ) {
rect = crop( (float) sx, (float) sy, angle, mDrawableWidth, mDrawableHeight, mCenter, null );
} else {
rect = crop( (float) sx, (float) sy, angle, mDrawableHeight, mDrawableWidth, mCenter, null );
}
float colStep = (float) rect.height() / grid_cols;
float rowStep = (float) rect.width() / grid_rows;
for ( int i = 1; i < grid_cols; i++ ) {
// mLinesPath.addRect( (int)rect.left, (int)(rect.top + colStep * i), (int)rect.right, (int)(rect.top + colStep *
// i) + 3, Path.Direction.CW );
mLinesPath.moveTo( (int) rect.left, (int) ( rect.top + colStep * i ) );
mLinesPath.lineTo( (int) rect.right, (int) ( rect.top + colStep * i ) );
}
for ( int i = 1; i < grid_rows; i++ ) {
// mLinesPath.addRect( (int)(rect.left + rowStep * i), (int)rect.top, (int)(rect.left + rowStep * i) + 3,
// (int)rect.bottom, Path.Direction.CW );
mLinesPath.moveTo( (int) ( rect.left + rowStep * i ), (int) rect.top );
mLinesPath.lineTo( (int) ( rect.left + rowStep * i ), (int) rect.bottom );
}
imageCaptureRegion = rect;
PointF center = getCenter();
mStraightenDrawable.setBounds( (int) ( center.x - handleWidth ), (int) ( imageCaptureRegion.bottom - handleHeight ),
(int) ( center.x + handleWidth ), (int) ( imageCaptureRegion.bottom + handleHeight ) );
mPosX = center.x;
initStraighten = false;
} else {
rect = imageCaptureRegion;
float colStep = (float) rect.height() / grid_cols;
float rowStep = (float) rect.width() / grid_rows;
for ( int i = 1; i < grid_cols; i++ ) {
// mLinesPath.addRect( (int)rect.left, (int)(rect.top + colStep * i), (int)rect.right, (int)(rect.top + colStep *
// i) + 3, Path.Direction.CW );
mLinesPath.moveTo( (int) rect.left, (int) ( rect.top + colStep * i ) );
mLinesPath.lineTo( (int) rect.right, (int) ( rect.top + colStep * i ) );
}
for ( int i = 1; i < grid_rows; i++ ) {
// mLinesPath.addRect( (int)(rect.left + rowStep * i), (int)rect.top, (int)(rect.left + rowStep * i) + 3,
// (int)rect.bottom, Path.Direction.CW );
mLinesPath.moveTo( (int) ( rect.left + rowStep * i ), (int) rect.top );
mLinesPath.lineTo( (int) ( rect.left + rowStep * i ), (int) rect.bottom );
}
}
mClipPath.addRect( rect, Path.Direction.CW );
mInversePath.addRect( rect, Path.Direction.CCW );
saveCount = canvas.save();
canvas.translate( mPaddingLeft, mPaddingTop );
canvas.drawPath( mInversePath, mOutlineFill );
// canvas.drawPath( mLinesPath, mLinesPaintShadow );
canvas.drawPath( mLinesPath, mLinesPaint );
canvas.drawPath( mClipPath, mOutlinePaint );
// if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix );
// if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix );
// if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix );
// mResizeDrawable.setBounds( (int) mDrawRect.right - handleWidth, (int) mDrawRect.bottom - handleHeight, (int)
// mDrawRect.right + handleWidth, (int) mDrawRect.bottom + handleHeight );
// mResizeDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
saveCount = canvas.save();
canvas.translate( mPaddingLeft, mPaddingTop );
// mResizeDrawable.setBounds( (int)(points[4] - handleWidth), (int)(points[5] - handleHeight), (int)(points[4] +
// handleWidth), (int)(points[5] + handleHeight) );
// mResizeDrawable.draw( canvas );
mStraightenDrawable.draw( canvas );
canvas.restoreToCount( saveCount );
}
/**
* if(intersectPoints){ //intersectPaint.setColor(Color.YELLOW); //canvas.drawCircle(intersectx, intersecty, 10,
* intersectPaint); //canvas.drawLine(trueRect.left + getPaddingLeft(), trueRect.bottom + getPaddingBottom(),
* trueRect.right + getPaddingRight(), trueRect.bottom+ getPaddingBottom(), intersectPaint); //canvas.drawRect(testRect,
* intersectPaint); }
*/
}
}
float ax = 0;
float ay = 0;
float bx = 0;
float by = 0;
float cx = 0;
float cy = 0;
float dx = 0;
float dy = 0;
float intersectx = 0;
float intersecty = 0;
Paint intersectPaint = new Paint();
RectF imageCaptureRegion = null;
boolean initStraighten = true;
Matrix rotateCopy;
boolean firstDraw = true;
Handler mFadeHandler = new Handler();
boolean mFadeHandlerStarted;
public void setInitStraighten( boolean value ) {
initStraighten = value;
}
protected void fadeinGrid( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final float startAlpha = mLinesPaint.getAlpha();
final float startAlphaShadow = mLinesPaintShadow.getAlpha();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_lines = (float) easing.easeNone( currentMs, startAlpha, mLinesAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, startAlphaShadow, mLinesShadowAlpha, durationMs );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mLinesPaint.setAlpha( mLinesAlpha );
mLinesPaintShadow.setAlpha( mLinesShadowAlpha );
invalidate();
}
}
} );
}
protected void fadeoutGrid( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final float startAlpha = mLinesPaint.getAlpha();
final float startAlphaShadow = mLinesPaintShadow.getAlpha();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_lines = (float) easing.easeNone( currentMs, 0, startAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, startAlphaShadow, durationMs );
mLinesPaint.setAlpha( (int) startAlpha - (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) startAlphaShadow - (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
invalidate();
}
}
} );
}
protected void fadeinOutlines( final int durationMs ) {
if ( mFadeHandlerStarted ) return;
mFadeHandlerStarted = true;
final long startTime = System.currentTimeMillis();
final Linear easing = new Linear();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_fill = (float) easing.easeNone( currentMs, 0, mOutlineFillAlpha, durationMs );
float new_alpha_paint = (float) easing.easeNone( currentMs, 0, mOutlinePaintAlpha, durationMs );
float new_alpha_lines = (float) easing.easeNone( currentMs, 0, mLinesAlpha, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, mLinesShadowAlpha, durationMs );
mOutlineFill.setAlpha( (int) new_alpha_fill );
mOutlinePaint.setAlpha( (int) new_alpha_paint );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
mOutlineFill.setAlpha( mOutlineFillAlpha );
mOutlinePaint.setAlpha( mOutlinePaintAlpha );
mLinesPaint.setAlpha( mLinesAlpha );
mLinesPaintShadow.setAlpha( mLinesShadowAlpha );
invalidate();
}
}
} );
}
protected void fadeoutOutlines( final int durationMs ) {
final long startTime = System.currentTimeMillis();
final Linear easing = new Linear();
final int alpha1 = mOutlineFill.getAlpha();
final int alpha2 = mOutlinePaint.getAlpha();
final int alpha3 = mLinesPaint.getAlpha();
final int alpha4 = mLinesPaintShadow.getAlpha();
mFadeHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_alpha_fill = (float) easing.easeNone( currentMs, alpha1, 0, durationMs );
float new_alpha_paint = (float) easing.easeNone( currentMs, alpha2, 0, durationMs );
float new_alpha_lines = (float) easing.easeNone( currentMs, alpha3, 0, durationMs );
float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, alpha4, 0, durationMs );
mOutlineFill.setAlpha( (int) new_alpha_fill );
mOutlinePaint.setAlpha( (int) new_alpha_paint );
mLinesPaint.setAlpha( (int) new_alpha_lines );
mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow );
invalidate();
if ( currentMs < durationMs ) {
mFadeHandler.post( this );
} else {
hideOutlines();
}
}
} );
}
protected void hideOutlines() {
mFadeHandlerStarted = false;
mOutlineFill.setAlpha( 0 );
mOutlinePaint.setAlpha( 0 );
mLinesPaint.setAlpha( 0 );
mLinesPaintShadow.setAlpha( 0 );
invalidate();
}
static double getAngle90( double value ) {
double rotation = Point2D.angle360( value );
double angle = rotation;
if ( rotation >= 270 ) {
angle = 360 - rotation;
} else if ( rotation >= 180 ) {
angle = rotation - 180;
} else if ( rotation > 90 ) {
angle = 180 - rotation;
}
return angle;
}
RectF crop( float originalWidth, float originalHeight, double angle, float targetWidth, float targetHeight, PointF center,
Canvas canvas ) {
double radians = Point2D.radians( angle );
PointF[] original = new PointF[] {
new PointF( 0, 0 ), new PointF( originalWidth, 0 ), new PointF( originalWidth, originalHeight ),
new PointF( 0, originalHeight ) };
Point2D.translate( original, -originalWidth / 2, -originalHeight / 2 );
PointF[] rotated = new PointF[original.length];
System.arraycopy( original, 0, rotated, 0, original.length );
Point2D.rotate( rotated, radians );
if ( angle >= 0 ) {
PointF[] ray = new PointF[] { new PointF( 0, 0 ), new PointF( -targetWidth / 2, -targetHeight / 2 ) };
PointF[] bound = new PointF[] { rotated[0], rotated[3] };
// Top Left intersection.
PointF intersectTL = Point2D.intersection( ray, bound );
PointF[] ray2 = new PointF[] { new PointF( 0, 0 ), new PointF( targetWidth / 2, -targetHeight / 2 ) };
PointF[] bound2 = new PointF[] { rotated[0], rotated[1] };
// Top Right intersection.
PointF intersectTR = Point2D.intersection( ray2, bound2 );
// Pick the intersection closest to the origin
PointF intersect = new PointF( Math.max( intersectTL.x, -intersectTR.x ), Math.max( intersectTL.y, intersectTR.y ) );
RectF newRect = new RectF( intersect.x, intersect.y, -intersect.x, -intersect.y );
newRect.offset( center.x, center.y );
if ( canvas != null ) { // debug
Point2D.translate( rotated, center.x, center.y );
Point2D.translate( ray, center.x, center.y );
Point2D.translate( ray2, center.x, center.y );
Paint paint = new Paint( Paint.ANTI_ALIAS_FLAG );
paint.setColor( 0x66FFFF00 );
paint.setStyle( Paint.Style.STROKE );
paint.setStrokeWidth( 2 );
// draw rotated
drawRect( rotated, canvas, paint );
paint.setColor( Color.GREEN );
drawLine( ray, canvas, paint );
paint.setColor( Color.BLUE );
drawLine( ray2, canvas, paint );
paint.setColor( Color.CYAN );
drawLine( bound, canvas, paint );
paint.setColor( Color.WHITE );
drawLine( bound2, canvas, paint );
paint.setColor( Color.GRAY );
canvas.drawRect( newRect, paint );
}
return newRect;
} else {
throw new IllegalArgumentException( "angle cannot be < 0" );
}
}
void drawLine( PointF[] line, Canvas canvas, Paint paint ) {
canvas.drawLine( line[0].x, line[0].y, line[1].x, line[1].y, paint );
}
void drawRect( PointF[] rect, Canvas canvas, Paint paint ) {
// draw rotated
Path path = new Path();
path.moveTo( rect[0].x, rect[0].y );
path.lineTo( rect[1].x, rect[1].y );
path.lineTo( rect[2].x, rect[2].y );
path.lineTo( rect[3].x, rect[3].y );
path.lineTo( rect[0].x, rect[0].y );
canvas.drawPath( path, paint );
}
/**
* <p>
* Return the offset of the widget's text baseline from the widget's top boundary.
* </p>
*
* @return the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported.
*/
@Override
public int getBaseline() {
if ( mBaselineAlignBottom ) {
return getMeasuredHeight();
} else {
return mBaseline;
}
}
/**
* <p>
* Set the offset of the widget's text baseline from the widget's top boundary. This value is overridden by the
*
* @param baseline
* The baseline to use, or -1 if none is to be provided. {@link #setBaselineAlignBottom(boolean)} property.
* </p>
* @see #setBaseline(int)
* @attr ref android.R.styleable#ImageView_baseline
*/
public void setBaseline( int baseline ) {
if ( mBaseline != baseline ) {
mBaseline = baseline;
requestLayout();
}
}
/**
* Set whether to set the baseline of this view to the bottom of the view. Setting this value overrides any calls to setBaseline.
*
* @param aligned
* If true, the image view will be baseline aligned with based on its bottom edge.
*
* @attr ref android.R.styleable#ImageView_baselineAlignBottom
*/
public void setBaselineAlignBottom( boolean aligned ) {
if ( mBaselineAlignBottom != aligned ) {
mBaselineAlignBottom = aligned;
requestLayout();
}
}
/**
* Return whether this view's baseline will be considered the bottom of the view.
*
* @return the baseline align bottom
* @see #setBaselineAlignBottom(boolean)
*/
public boolean getBaselineAlignBottom() {
return mBaselineAlignBottom;
}
/**
* Set a tinting option for the image.
*
* @param color
* Color tint to apply.
* @param mode
* How to apply the color. The standard mode is {@link PorterDuff.Mode#SRC_ATOP}
*
* @attr ref android.R.styleable#ImageView_tint
*/
public final void setColorFilter( int color, PorterDuff.Mode mode ) {
setColorFilter( new PorterDuffColorFilter( color, mode ) );
}
/**
* Set a tinting option for the image. Assumes {@link PorterDuff.Mode#SRC_ATOP} blending mode.
*
* @param color
* Color tint to apply.
* @attr ref android.R.styleable#ImageView_tint
*/
public final void setColorFilter( int color ) {
setColorFilter( color, PorterDuff.Mode.SRC_ATOP );
}
/**
* Clear color filter.
*/
public final void clearColorFilter() {
setColorFilter( null );
}
/**
* Apply an arbitrary colorfilter to the image.
*
* @param cf
* the colorfilter to apply (may be null)
*/
public void setColorFilter( ColorFilter cf ) {
if ( mColorFilter != cf ) {
mColorFilter = cf;
mColorMod = true;
applyColorMod();
invalidate();
}
}
/**
* Sets the alpha.
*
* @param alpha
* the new alpha
*/
public void setAlpha( int alpha ) {
alpha &= 0xFF; // keep it legal
if ( mAlpha != alpha ) {
mAlpha = alpha;
mColorMod = true;
applyColorMod();
invalidate();
}
}
/**
* Apply color mod.
*/
private void applyColorMod() {
// Only mutate and apply when modifications have occurred. This should
// not reset the mColorMod flag, since these filters need to be
// re-applied if the Drawable is changed.
if ( mDrawable != null && mColorMod ) {
mDrawable = mDrawable.mutate();
mDrawable.setColorFilter( mColorFilter );
mDrawable.setAlpha( mAlpha * mViewAlphaScale >> 8 );
}
}
/** The m handler. */
protected Handler mHandler = new Handler();
/** The m rotation. */
protected double mRotation = 0;
/** The m current scale. */
protected float mCurrentScale = 0;
/** The m running. */
protected boolean mRunning = false;
/**
* Rotate90.
*
* @param cw
* the cw
* @param durationMs
* the duration ms
*/
public void rotate90( boolean cw, int durationMs ) {
final double destRotation = ( cw ? 90 : -90 );
rotateBy( destRotation, durationMs );
hideOutlines();
portrait = !portrait;
}
public boolean getStraightenStarted() {
return straightenStarted;
}
/**
* Rotate to.
*
* @param cw
* the cw
* @param durationMs
* the duration ms
*/
protected void rotateBy( final double deltaRotation, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
final long startTime = System.currentTimeMillis();
final double destRotation = mRotation + deltaRotation;
final double srcRotation = mRotation;
setImageRotation( mRotation, false );
invalidate();
mHandler.post( new Runnable() {
@SuppressWarnings("unused")
float old_scale = 0;
@SuppressWarnings("unused")
float old_rotation = 0;
@Override
public void run() {
long now = System.currentTimeMillis();
float currentMs = Math.min( durationMs, now - startTime );
float new_rotation = (float) mEasing.easeInOut( currentMs, 0, deltaRotation, durationMs );
mRotation = Point2D.angle360( srcRotation + new_rotation );
setImageRotation( mRotation, false );
old_rotation = new_rotation;
initStraighten = true;
invalidate();
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
mRotation = Point2D.angle360( destRotation );
setImageRotation( mRotation, true );
initStraighten = true;
invalidate();
printDetails();
mRunning = false;
if ( isReset ) {
onReset();
}
}
}
} );
if ( straightenStarted && !isReset ) {
initStraighten = true;
resetStraighten();
invalidate();
}
}
private void resetStraighten() {
mStraightenMatrix.reset();
straightenStarted = false;
previousStraightenAngle = 0;
prevGrowth = 1;
prevGrowthAngle = 0;
currentNewPosition = 0;
testStraighten = true;
currentGrowth = 0;
previousAngle = 0;
}
/**
* Prints the details.
*/
public void printDetails() {
Log.i( LOG_TAG, "details:" );
Log.d( LOG_TAG, " flip horizontal: "
+ ( ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt ) );
Log.d( LOG_TAG, " flip vertical: " + ( ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt ) );
Log.d( LOG_TAG, " rotation: " + mRotation );
Log.d( LOG_TAG, "--------" );
}
/**
* Flip.
*
* @param horizontal
* the horizontal
* @param durationMs
* the duration ms
*/
public void flip( boolean horizontal, int durationMs ) {
flipTo( horizontal, durationMs );
hideOutlines();
}
/** The m camera enabled. */
private boolean mCameraEnabled;
/**
* Sets the camera enabled.
*
* @param value
* the new camera enabled
*/
public void setCameraEnabled( final boolean value ) {
if ( android.os.Build.VERSION.SDK_INT >= 14 && value )
mCameraEnabled = value;
else
mCameraEnabled = false;
}
/**
* Flip to.
*
* @param horizontal
* the horizontal
* @param durationMs
* the duration ms
*/
protected void flipTo( final boolean horizontal, final int durationMs ) {
if ( mRunning ) {
return;
}
mRunning = true;
final long startTime = System.currentTimeMillis();
final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int vheight = getHeight() - getPaddingTop() - getPaddingBottom();
final float centerx = vwidth / 2;
final float centery = vheight / 2;
final Camera camera = new Camera();
mHandler.post( new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
double currentMs = Math.min( durationMs, now - startTime );
if ( mCameraEnabled ) {
float degrees = (float) ( 0 + ( ( -180 - 0 ) * ( currentMs / durationMs ) ) );
camera.save();
if ( horizontal ) {
camera.rotateY( degrees );
} else {
camera.rotateX( degrees );
}
camera.getMatrix( mFlipMatrix );
camera.restore();
mFlipMatrix.preTranslate( -centerx, -centery );
mFlipMatrix.postTranslate( centerx, centery );
} else {
double new_scale = mEasing.easeInOut( currentMs, 1, -2, durationMs );
if ( horizontal )
mFlipMatrix.setScale( (float) new_scale, 1, centerx, centery );
else
mFlipMatrix.setScale( 1, (float) new_scale, centerx, centery );
}
invalidate();
if ( currentMs < durationMs ) {
mHandler.post( this );
} else {
if ( horizontal ) {
mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt;
mDrawMatrix.postScale( -1, 1, centerx, centery );
} else {
mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt;
mDrawMatrix.postScale( 1, -1, centerx, centery );
}
mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), centerx, centery );
mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) );
mFlipMatrix.reset();
invalidate();
printDetails();
mRunning = false;
if ( isReset ) {
onReset();
}
}
}
} );
if ( straightenStarted && !isReset ) {
initStraighten = true;
resetStraighten();
invalidate();
}
}
private void flip( boolean horizontal, boolean vertical ) {
invalidate();
PointF center = getCenter();
if ( horizontal ) {
mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt;
mDrawMatrix.postScale( -1, 1, center.x, center.y );
}
if ( vertical ) {
mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt;
mDrawMatrix.postScale( 1, -1, center.x, center.y );
}
mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), center.x, center.y );
mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) );
mFlipMatrix.reset();
}
/** The m matrix values. */
protected final float[] mMatrixValues = new float[9];
/**
* Gets the value.
*
* @param matrix
* the matrix
* @param whichValue
* the which value
* @return the value
*/
protected float getValue( Matrix matrix, int whichValue ) {
matrix.getValues( mMatrixValues );
return mMatrixValues[whichValue];
}
/**
* Gets the matrix scale.
*
* @param matrix
* the matrix
* @return the matrix scale
*/
protected float[] getMatrixScale( Matrix matrix ) {
float[] result = new float[2];
result[0] = getValue( matrix, Matrix.MSCALE_X );
result[1] = getValue( matrix, Matrix.MSCALE_Y );
return result;
}
/** The m flip type. */
protected int mFlipType = FlipType.FLIP_NONE.nativeInt;
/**
* The Enum FlipType.
*/
public enum FlipType {
/** The FLI p_ none. */
FLIP_NONE( 1 << 0 ),
/** The FLI p_ horizontal. */
FLIP_HORIZONTAL( 1 << 1 ),
/** The FLI p_ vertical. */
FLIP_VERTICAL( 1 << 2 );
/**
* Instantiates a new flip type.
*
* @param ni
* the ni
*/
FlipType( int ni ) {
nativeInt = ni;
}
/** The native int. */
public final int nativeInt;
}
/*
* (non-Javadoc)
*
* @see android.view.View#getRotation()
*/
public float getRotation() {
return (float) mRotation;
}
/**
* Gets the horizontal flip.
*
* @return the horizontal flip
*/
public boolean getHorizontalFlip() {
if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) {
return ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt;
}
return false;
}
/**
* Gets the vertical flip.
*
* @return the vertical flip
*/
public boolean getVerticalFlip() {
if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) {
return ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt;
}
return false;
}
/**
* Gets the flip type.
*
* @return the flip type
*/
public int getFlipType() {
return mFlipType;
}
/**
* Checks if is running.
*
* @return true, if is running
*/
public boolean isRunning() {
return mRunning;
}
/**
* Reset the image to the original state.
*/
public void reset() {
isReset = true;
onReset();
}
/**
* On reset.
*/
private void onReset() {
if ( isReset ) {
double rotation = (double) getRotation();
double straightenRotation = getStraightenAngle();
boolean resetStraighten = getStraightenStarted();
straightenStarted = false;
rotation = rotation%360;
if( rotation > 180 ){
rotation = rotation - 360;
}
final boolean hflip = getHorizontalFlip();
final boolean vflip = getVerticalFlip();
boolean handled = false;
initStraighten = false;
invalidate();
if ( rotation != 0 || resetStraighten ) {
if( resetStraighten ){
straightenBy( -straightenRotation, resetAnimTime );
} else {
rotateBy( -rotation, resetAnimTime );
}
handled = true;
}
if ( hflip ) {
flip( true, resetAnimTime );
handled = true;
}
if ( vflip ) {
flip( false, resetAnimTime );
handled = true;
}
if ( !handled ) {
fireOnResetComplete();
}
}
}
/**
* Fire on reset complete.
*/
private void fireOnResetComplete() {
if ( mResetListener != null ) {
mResetListener.onResetComplete();
}
}
/**
*
*/
@Override
protected void onConfigurationChanged( Configuration newConfig ) {
// TODO
// During straighten, we must bring it to the start if orientation is changed
orientation = getResources().getConfiguration().orientation;
initStraighten = true;
invalidate();
if ( straightenStarted ) {
initStraighten = true;
resetStraighten();
invalidate();
}
}
} | Java |
package com.aviary.android.feather.widget;
abstract class IFlingRunnable implements Runnable {
public static interface FlingRunnableView {
boolean removeCallbacks( Runnable action );
boolean post( Runnable action );
void scrollIntoSlots();
void trackMotionScroll( int newX );
int getMinX();
int getMaxX();
}
protected int mLastFlingX;
protected boolean mShouldStopFling;
protected FlingRunnableView mParent;
protected int mAnimationDuration;
protected static final String LOG_TAG = "fling";
public IFlingRunnable( FlingRunnableView parent, int animationDuration ) {
mParent = parent;
mAnimationDuration = animationDuration;
}
public int getLastFlingX() {
return mLastFlingX;
}
protected void startCommon() {
mParent.removeCallbacks( this );
}
public void stop( boolean scrollIntoSlots ) {
mParent.removeCallbacks( this );
endFling( scrollIntoSlots );
}
public void startUsingDistance( int initialX, int distance ) {
if ( distance == 0 ) return;
startCommon();
mLastFlingX = initialX;
_startUsingDistance( mLastFlingX, distance );
mParent.post( this );
}
public void startUsingVelocity( int initialX, int initialVelocity ) {
if ( initialVelocity == 0 ) return;
startCommon();
mLastFlingX = initialX;
_startUsingVelocity( mLastFlingX, initialVelocity );
mParent.post( this );
}
protected void endFling( boolean scrollIntoSlots ) {
forceFinished( true );
mLastFlingX = 0;
if ( scrollIntoSlots ) {
mParent.scrollIntoSlots();
}
}
@Override
public void run() {
mShouldStopFling = false;
final boolean more = computeScrollOffset();
int x = getCurrX();
mParent.trackMotionScroll( x );
if ( more && !mShouldStopFling ) {
mLastFlingX = x;
mParent.post( this );
} else {
endFling( true );
}
}
public abstract boolean springBack( int startX, int startY, int minX, int maxX, int minY, int maxY );
protected abstract boolean computeScrollOffset();
protected abstract int getCurrX();
public abstract float getCurrVelocity();
protected abstract void forceFinished( boolean finished );
protected abstract void _startUsingVelocity( int initialX, int velocity );
protected abstract void _startUsingDistance( int initialX, int distance );
public abstract boolean isFinished();
}
| Java |
package com.aviary.android.feather.graphics;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
/**
* The Class ToolIconsDrawable.
*/
public class ToolIconsDrawable extends StateListDrawable {
Drawable mDrawable;
final static int state_pressed = android.R.attr.state_pressed;
/** The white color filter. */
ColorMatrixColorFilter whiteColorFilter = new ColorMatrixColorFilter( new float[] {
1, 0, 0, 0, 255, 0, 1, 0, 0, 255, 0, 0, 1, 0, 255, 0, 0, 0, 1, 0, } );
/**
* Instantiates a new tool icons drawable.
*
* @param res
* the res
* @param resId
* the res id
*/
public ToolIconsDrawable( Resources res, int resId ) {
super();
mDrawable = res.getDrawable( resId );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#onBoundsChange(android.graphics.Rect)
*/
@Override
protected void onBoundsChange( Rect bounds ) {
super.onBoundsChange( bounds );
mDrawable.setBounds( bounds );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#getIntrinsicHeight()
*/
@Override
public int getIntrinsicHeight() {
if ( mDrawable != null ) return mDrawable.getIntrinsicHeight();
return super.getIntrinsicHeight();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#getIntrinsicWidth()
*/
@Override
public int getIntrinsicWidth() {
if ( mDrawable != null ) return mDrawable.getIntrinsicWidth();
return super.getIntrinsicWidth();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
if ( mDrawable != null ) {
mDrawable.draw( canvas );
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {
if ( mDrawable != null ) mDrawable.setAlpha( alpha );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.DrawableContainer#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {
if ( mDrawable != null ) {
mDrawable.setColorFilter( cf );
}
invalidateSelf();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.StateListDrawable#onStateChange(int[])
*/
@Override
protected boolean onStateChange( int[] state ) {
boolean pressed = false;
if ( state != null && state.length > 0 ) {
for ( int i = 0; i < state.length; i++ ) {
if ( state[i] == state_pressed ) {
pressed = true;
break;
}
}
}
boolean result = pressed != mPressed;
setPressed( pressed );
return result;
}
/** The m pressed. */
private boolean mPressed;
/**
* Sets the pressed.
*
* @param value
* the new pressed
*/
public void setPressed( boolean value ) {
if ( value ) {
setColorFilter( whiteColorFilter );
} else {
setColorFilter( null );
}
mPressed = value;
}
}
| Java |
package com.aviary.android.feather.graphics;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable.Orientation;
/**
* Draw a linear gradient.
*
* @author alessandro
*/
public class LinearGradientDrawable extends Drawable {
private final Paint mFillPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
private float mCornerRadius = 0;
private boolean mRectIsDirty = true;
private int mAlpha = 0xFF; // modified by the caller
private boolean mDither = true;
private ColorFilter mColorFilter;
private Orientation mOrientation = Orientation.LEFT_RIGHT;
private int[] mColors;
private float[] mPositions;
private final RectF mRect = new RectF();
/**
* Instantiates a new linear gradient drawable.
*
* @param orientation
* the orientation
* @param colors
* the colors
* @param positions
* the positions
*/
public LinearGradientDrawable( Orientation orientation, int[] colors, float[] positions ) {
mOrientation = orientation;
mColors = colors;
mPositions = positions;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
if ( !ensureValidRect() ) return;
mFillPaint.setAlpha( mAlpha );
mFillPaint.setDither( mDither );
mFillPaint.setColorFilter( mColorFilter );
if ( mCornerRadius > 0 ) {
float rad = mCornerRadius;
float r = Math.min( mRect.width(), mRect.height() ) * 0.5f;
if ( rad > r ) {
rad = r;
}
canvas.drawRoundRect( mRect, rad, rad, mFillPaint );
} else {
canvas.drawRect( mRect, mFillPaint );
}
}
/**
* Ensure valid rect.
*
* @return true, if successful
*/
private boolean ensureValidRect() {
if ( mRectIsDirty ) {
mRectIsDirty = false;
Rect bounds = getBounds();
float inset = 0;
mRect.set( bounds.left + inset, bounds.top + inset, bounds.right - inset, bounds.bottom - inset );
final int[] colors = mColors;
if ( colors != null ) {
RectF r = mRect;
float x0, x1, y0, y1;
final float level = 1.0f;
switch ( mOrientation ) {
case TOP_BOTTOM:
x0 = r.left;
y0 = r.top;
x1 = x0;
y1 = level * r.bottom;
break;
case TR_BL:
x0 = r.right;
y0 = r.top;
x1 = level * r.left;
y1 = level * r.bottom;
break;
case RIGHT_LEFT:
x0 = r.right;
y0 = r.top;
x1 = level * r.left;
y1 = y0;
break;
case BR_TL:
x0 = r.right;
y0 = r.bottom;
x1 = level * r.left;
y1 = level * r.top;
break;
case BOTTOM_TOP:
x0 = r.left;
y0 = r.bottom;
x1 = x0;
y1 = level * r.top;
break;
case BL_TR:
x0 = r.left;
y0 = r.bottom;
x1 = level * r.right;
y1 = level * r.top;
break;
case LEFT_RIGHT:
x0 = r.left;
y0 = r.top;
x1 = level * r.right;
y1 = y0;
break;
default:/* TL_BR */
x0 = r.left;
y0 = r.top;
x1 = level * r.right;
y1 = level * r.bottom;
break;
}
mFillPaint.setShader( new LinearGradient( x0, y0, x1, y1, colors, mPositions, Shader.TileMode.CLAMP ) );
}
}
return !mRect.isEmpty();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect)
*/
@Override
protected void onBoundsChange( Rect r ) {
super.onBoundsChange( r );
mRectIsDirty = true;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {
if ( alpha != mAlpha ) {
mAlpha = alpha;
invalidateSelf();
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setDither(boolean)
*/
@Override
public void setDither( boolean dither ) {
if ( dither != mDither ) {
mDither = dither;
invalidateSelf();
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {
if ( cf != mColorFilter ) {
mColorFilter = cf;
invalidateSelf();
}
}
/**
* Sets the corner radius.
*
* @param radius
* the new corner radius
*/
public void setCornerRadius( float radius ) {
mCornerRadius = radius;
invalidateSelf();
}
}
| Java |
package com.aviary.android.feather.graphics;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.Callback;
import com.aviary.android.feather.widget.Gallery;
/**
* Default {@link Gallery} drawable which accept a {@link Drawable} as overlay.
*
* @author alessandro
* @see DefaultGalleryCheckboxDrawable
*/
public class OverlayGalleryCheckboxDrawable extends DefaultGalleryCheckboxDrawable implements Callback {
protected Drawable mOverlayDrawable;
protected float mBottomOffset;
protected float mPaddingW;
protected float mPaddingH;
/**
* Instantiates a new overlay gallery checkbox drawable.
*
* @param res
* {@link Context} resource manager
* @param pressed
* pressed state
* @param drawable
* drawable used as overlay
* @param bottomOffset
* value from 0.0 to 1.0. It's the maximum height of the overlay. According to this value the size and the center of
* the overlay drawable will change.
* @param padding
* padding of the overlay drawable
*/
public OverlayGalleryCheckboxDrawable( Resources res, boolean pressed, Drawable drawable, float bottomOffset, float padding ) {
this( res, pressed, drawable, bottomOffset, padding, padding );
}
public OverlayGalleryCheckboxDrawable( Resources res, boolean pressed, Drawable drawable, float bottomOffset, float paddingW,
float paddingH ) {
super( res, pressed );
mOverlayDrawable = drawable;
mBottomOffset = bottomOffset;
mPaddingW = paddingW;
mPaddingH = paddingH;
if ( mOverlayDrawable != null ) mOverlayDrawable.setCallback( this );
}
@Override
protected void onBoundsChange( Rect bounds ) {
super.onBoundsChange( bounds );
if ( mOverlayDrawable != null ) {
final float maxHeight = bounds.height() * mBottomOffset;
final int paddingW = (int) ( mPaddingW * bounds.width() );
final int paddingH = (int) ( mPaddingH * maxHeight );
Rect mBoundsRect = new Rect( paddingW, paddingH, bounds.width() - paddingW, (int) maxHeight - paddingH );
mOverlayDrawable.setBounds( mBoundsRect );
}
}
@Override
public void draw( Canvas canvas ) {
super.draw( canvas );
if ( mOverlayDrawable != null ) {
mOverlayDrawable.draw( canvas );
}
}
@Override
public void invalidateDrawable( Drawable arg0 ) {
invalidateSelf();
}
@Override
public void scheduleDrawable( Drawable arg0, Runnable arg1, long arg2 ) {
}
@Override
public void unscheduleDrawable( Drawable arg0, Runnable arg1 ) {}
}
| Java |
package com.aviary.android.feather.graphics;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import com.aviary.android.feather.R;
import com.aviary.android.feather.widget.Gallery;
/**
* Default checkbox drawable for {@link Gallery} views.<br />
* Draw a checkbox drawable in order to simulate a checkbox component.<br/>
*
* @author alessandro
*
*/
public class CropCheckboxDrawable extends OverlayGalleryCheckboxDrawable {
/** The default drawable. */
protected Drawable mCropDrawable;
/**
* Instantiates a new crop checkbox drawable.
*
* @param res
* the res
* @param pressed
* the pressed
* @param resId
* the res id
* @param bottomOffset
* the bottom offset
* @param padding
* the padding
*/
public CropCheckboxDrawable( Resources res, boolean pressed, int resId, float bottomOffset, float paddingW, float paddingH ) {
this( res, pressed, res.getDrawable( resId ), bottomOffset, paddingW, paddingH );
}
/**
* Instantiates a new crop checkbox drawable.
*
* @param res
* the res
* @param pressed
* the pressed
* @param drawable
* the drawable
* @param bottomOffset
* the bottom offset
* @param padding
* the padding
*/
public CropCheckboxDrawable( Resources res, boolean pressed, Drawable drawable, float bottomOffset, float paddingW,
float paddingH ) {
super( res, pressed, drawable, bottomOffset, paddingW, paddingH );
mCropDrawable = res.getDrawable( pressed ? R.drawable.feather_crop_checkbox_selected
: R.drawable.feather_crop_checkbox_unselected );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.graphics.OverlayGalleryCheckboxDrawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
super.draw( canvas );
mCropDrawable.draw( canvas );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.graphics.OverlayGalleryCheckboxDrawable#onBoundsChange(android.graphics.Rect)
*/
@Override
protected void onBoundsChange( Rect rect ) {
super.onBoundsChange( rect );
int left = (int) ( rect.width() * 0.2831 );
int top = (int) ( rect.height() * 0.6708 );
int right = (int) ( rect.width() * 0.7433 );
int bottom = (int) ( rect.height() * 0.8037 );
mCropDrawable.setBounds( left, top, right, bottom );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {}
}
| Java |
package com.aviary.android.feather.graphics;
import java.lang.ref.WeakReference;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class ExternalFilterPackDrawable extends Drawable {
Paint mPaint;
Matrix mMatrix;
Matrix mDrawMatrix = new Matrix();
Paint mDrawPaint = new Paint();
static final int defaultWidth = 161;
static final int defaultHeight = 250;
final int bitmapWidth;
final int bitmapHeight;
float xRatio;
float yRatio;
private String mTitle, mShortTitle;
private int mNumEffects;
private int mColor;
private WeakReference<Bitmap> mShadowBitmap;
private WeakReference<Bitmap> mEffectBitmap;
public ExternalFilterPackDrawable( String title, String shortTitle, int numEffects, int color, Typeface typeFace, Bitmap shadow,
Bitmap effect ) {
super();
mMatrix = new Matrix();
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mPaint.setSubpixelText( true );
mPaint.setAntiAlias( true );
mPaint.setDither( true );
mPaint.setFilterBitmap( true );
bitmapWidth = effect.getWidth();
bitmapHeight = effect.getHeight();
Log.d( "xxx", "size: " + bitmapWidth + "x" + bitmapHeight );
xRatio = (float) defaultWidth / bitmapWidth;
yRatio = (float) defaultHeight / bitmapHeight;
mShadowBitmap = new WeakReference<Bitmap>( shadow );
mEffectBitmap = new WeakReference<Bitmap>( effect );
mTitle = title;
mShortTitle = shortTitle;
mNumEffects = numEffects < 0 ? 6 : numEffects;
mColor = color;
if ( null != typeFace ) {
mPaint.setTypeface( typeFace );
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
@Override
protected void onBoundsChange( Rect bounds ) {
super.onBoundsChange( bounds );
}
@Override
public void draw( Canvas canvas ) {
drawInternal( canvas );
}
@Override
public int getIntrinsicWidth() {
return bitmapWidth;
}
@Override
public int getIntrinsicHeight() {
return bitmapHeight;
}
private void drawInternal( Canvas canvas ) {
final int leftTextSize = (int) ( 32 / xRatio );
final int titleTextSize = (int) ( 26 / yRatio );
Bitmap bmp;
// SHADOW
mMatrix.reset();
if ( null != mShadowBitmap ) {
bmp = mShadowBitmap.get();
if ( null != bmp ) {
canvas.drawBitmap( bmp, mMatrix, mPaint );
}
}
// colored background
mPaint.setColor( mColor );
canvas.drawRect( 17 / xRatio, 37 / yRatio, 145 / xRatio, 225 / yRatio, mPaint );
int saveCount = canvas.save( Canvas.MATRIX_SAVE_FLAG );
canvas.rotate( 90 );
// SHORT TITLE
mPaint.setColor( Color.BLACK );
mPaint.setTextSize( leftTextSize );
canvas.drawText( mShortTitle, 66 / xRatio, -26 / yRatio, mPaint );
// TITLE
mPaint.setTextSize( titleTextSize );
canvas.drawText( mTitle, 69 / xRatio, -88 / yRatio, mPaint );
// NUM EFFECTS
mPaint.setARGB( 255, 35, 31, 42 );
canvas.drawRect( 135 / yRatio, -16 / xRatio, 216 / yRatio, -57 / xRatio, mPaint );
mPaint.setColor( Color.WHITE );
mPaint.setTextSize( leftTextSize );
String text = mNumEffects + "fx";
int numEffectsLength = String.valueOf( mNumEffects ).length();
canvas.drawText( text, ( 160 - ( numEffectsLength * 10 ) ) / xRatio, -26 / yRatio, mPaint );
// restore canvas
canvas.restoreToCount( saveCount );
// cannister
if ( null != mEffectBitmap ) {
bmp = mEffectBitmap.get();
if ( null != bmp ) {
canvas.drawBitmap( bmp, mMatrix, mPaint );
}
}
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha( int alpha ) {}
@Override
public void setColorFilter( ColorFilter cf ) {}
@Override
public void setBounds( int left, int top, int right, int bottom ) {
Log.d( "xxx", "setBounds: " + left + ", " + top + ", " + right + ", " + bottom );
super.setBounds( left, top, right, bottom );
}
}
| Java |
package com.aviary.android.feather.graphics;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
/**
* Draw a bitmap repeated horizontally and scaled vertically.
*
* @author alessandro
*/
public class RepeatableHorizontalDrawable extends Drawable {
private Paint mPaint = new Paint();
private Rect mRect = new Rect();
private Matrix mMatrix = new Matrix();
private Bitmap mBitmap = null;
private Shader mShader;
/**
* Construct a new {@link RepeatableHorizontalDrawable} instance.
*
* @param resources
* the current Context {@link Resources} used to extract the resource
* @param resId
* the {@link BitmapDrawable} resource used to draw
*/
public RepeatableHorizontalDrawable( Resources resources, int resId ) {
try {
Bitmap bitmap = ( (BitmapDrawable) resources.getDrawable( resId ) ).getBitmap();
init( bitmap );
} catch ( Exception e ) {}
}
public static Drawable createFromView( View view ) {
Drawable drawable = view.getBackground();
if ( null != drawable ) {
if ( drawable instanceof BitmapDrawable ) {
Bitmap bitmap = ( (BitmapDrawable) drawable ).getBitmap();
return new RepeatableHorizontalDrawable( bitmap );
}
}
return drawable;
}
public RepeatableHorizontalDrawable( Bitmap bitmap ) {
init( bitmap );
}
private void init( Bitmap bitmap ) {
mBitmap = bitmap;
if ( mBitmap != null ) {
mShader = new BitmapShader( mBitmap, TileMode.REPEAT, TileMode.CLAMP );
mPaint.setShader( mShader );
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
if ( null != mBitmap ) {
copyBounds( mRect );
canvas.drawPaint( mPaint );
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect)
*/
@Override
protected void onBoundsChange( Rect bounds ) {
super.onBoundsChange( bounds );
if ( null != mBitmap ) {
mMatrix.setScale( 1, (float) bounds.height() / mBitmap.getHeight() );
mShader.setLocalMatrix( mMatrix );
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {
mPaint.setAlpha( alpha );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {
mPaint.setColorFilter( cf );
}
}
| Java |
package com.aviary.android.feather.graphics;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable;
/**
* The Class StickerBitmapDrawable.
*/
public class StickerBitmapDrawable extends Drawable implements IBitmapDrawable {
protected Bitmap mBitmap;
protected Paint mPaint;
protected Paint mShadowPaint;
protected Rect srcRect;
protected Rect dstRect;
protected ColorFilter blackColorFilter, whiteColorFilter;
protected int mInset;
/**
* Instantiates a new sticker bitmap drawable.
*
* @param b
* the b
* @param inset
* the inset
*/
public StickerBitmapDrawable( Bitmap b, int inset ) {
mBitmap = b;
mPaint = new Paint();
mPaint.setAntiAlias( true );
mPaint.setDither( true );
mPaint.setFilterBitmap( false );
mInset = inset;
mShadowPaint = new Paint( mPaint );
mShadowPaint.setAntiAlias( true );
srcRect = new Rect( 0, 0, b.getWidth(), b.getHeight() );
dstRect = new Rect();
blackColorFilter = new ColorMatrixColorFilter( new float[] { 1, 0, 0, -255, 0, 0, 1, 0, -255, 0, 0, 0, 1, -255, 0, 0, 0, 0, 0.3f, 0, } );
whiteColorFilter = new ColorMatrixColorFilter( new float[] { 1, 0, 0, 0, 255, 0, 1, 0, 0, 255, 0, 0, 1, 0, 255, 0, 0, 0, 1, 0, } );
mShadowPaint.setColorFilter( blackColorFilter );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
dstRect.set( srcRect );
dstRect.inset( -mInset / 2, -mInset / 2 );
dstRect.offset( mInset / 2 + 1, mInset / 2 + 1 );
canvas.drawBitmap( mBitmap, srcRect, dstRect, mShadowPaint );
mPaint.setColorFilter( whiteColorFilter );
dstRect.offset( -1, -1 );
canvas.drawBitmap( mBitmap, srcRect, dstRect, mPaint );
mPaint.setColorFilter( null );
canvas.drawBitmap( mBitmap, mInset / 2, mInset / 2, mPaint );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {
mPaint.setColorFilter( cf );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getIntrinsicWidth()
*/
@Override
public int getIntrinsicWidth() {
return mBitmap.getWidth() + ( mInset * 2 );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getIntrinsicHeight()
*/
@Override
public int getIntrinsicHeight() {
return mBitmap.getHeight() + ( mInset * 2 );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getMinimumWidth()
*/
@Override
public int getMinimumWidth() {
return mBitmap.getWidth() + ( mInset * 2 );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getMinimumHeight()
*/
@Override
public int getMinimumHeight() {
return mBitmap.getHeight() + ( mInset * 2 );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable#getBitmap()
*/
@Override
public Bitmap getBitmap() {
return mBitmap;
}
} | Java |
package com.aviary.android.feather.graphics;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
/**
* Default drawable used to display the {@link Toast} preview for panels like the RedEye panel, Whiten, etc..
*
* @author alessandro
*
*/
public class PreviewCircleDrawable extends Drawable {
Paint mPaint;
float mRadius;
/**
* Instantiates a new preview circle drawable.
*
* @param radius
* the radius
*/
public PreviewCircleDrawable( final float radius ) {
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mPaint.setFilterBitmap( false );
mPaint.setDither( true );
mPaint.setStrokeWidth( 10.0f );
mPaint.setStyle( Paint.Style.STROKE );
mPaint.setColor( Color.WHITE );
mRadius = radius;
}
/**
* Sets the paint.
*
* @param value
* the new paint
*/
public void setPaint( Paint value ) {
mPaint.set( value );
}
/**
* Sets the Paint style.
*
* @param value
* the new style
*/
public void setStyle( Paint.Style value ) {
mPaint.setStyle( value );
}
/**
* Sets the radius.
*
* @param value
* the new radius
*/
public void setRadius( float value ) {
mRadius = value;
invalidateSelf();
}
/**
* Sets the color.
*
* @param color
* the new color
*/
public void setColor( int color ) {
mPaint.setColor( color );
}
/**
* Sets the blur.
*
* @param value
* the new blur
*/
public void setBlur( int value ) {
if ( value > 0 ) {
mPaint.setMaskFilter( new BlurMaskFilter( value, Blur.NORMAL ) );
} else {
mPaint.setMaskFilter( null );
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( final Canvas canvas ) {
final RectF rect = new RectF( getBounds() );
canvas.drawCircle( rect.centerX(), rect.centerY(), mRadius, mPaint );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( final int alpha ) {}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( final ColorFilter cf ) {}
}; | Java |
package com.aviary.android.feather.graphics;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
/**
* Drawable used as overlay {@link Drawable} in conjunction with {@link OverlayGalleryCheckboxDrawable}.<br />
* Create a circle drawable using radius and blur_size.
*
* @author alessandro
*
*/
public class GalleryCircleDrawable extends Drawable {
private Paint mPaint;
private Paint mShadowPaint;
final int mShadowOffset = 3;
float mStrokeWidth = 5.0f;
float mRadius, mOriginalRadius;
float centerX, centerY;
/**
* Instantiates a new gallery circle drawable.
*
* @param radius
* Radius of the circle
* @param blur_size
* blur size, if > 0 create a blur mask around the circle
*/
public GalleryCircleDrawable( float radius, int blur_size ) {
super();
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mPaint.setStrokeWidth( mStrokeWidth );
mPaint.setStyle( Paint.Style.STROKE );
mPaint.setColor( Color.WHITE );
mShadowPaint = new Paint( mPaint );
mShadowPaint.setColor( Color.BLACK );
update( radius, blur_size );
}
/**
* Sets the stroke width.
*
* @param value
* the new stroke width
*/
public void setStrokeWidth( float value ) {
mStrokeWidth = value;
mPaint.setStrokeWidth( mStrokeWidth );
invalidateSelf();
}
/**
* Update.
*
* @param radius
* the radius
* @param blur_size
* the blur_size
*/
public void update( float radius, int blur_size ) {
mOriginalRadius = radius;
if ( blur_size > 0 )
mPaint.setMaskFilter( new BlurMaskFilter( blur_size, Blur.NORMAL ) );
else
mPaint.setMaskFilter( null );
invalidateSelf();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
canvas.drawCircle( centerX, centerY + mShadowOffset, mRadius, mShadowPaint );
canvas.drawCircle( centerX, centerY, mRadius, mPaint );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect)
*/
@Override
protected void onBoundsChange( Rect rect ) {
super.onBoundsChange( rect );
invalidateSelf();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#invalidateSelf()
*/
@Override
public void invalidateSelf() {
super.invalidateSelf();
invalidate();
}
/**
* Invalidate.
*/
protected void invalidate() {
Rect rect = getBounds();
int minSize = Math.max( 1, Math.min( rect.width(), rect.height() ) );
mRadius = ( (float) minSize * mOriginalRadius ) / 2;
centerX = rect.centerX();
centerY = rect.centerY();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {}
}
| Java |
package com.aviary.android.feather.graphics;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import com.aviary.android.feather.R;
import com.aviary.android.feather.widget.Gallery;
/**
* Default Drawable used for all the Views created inside a {@link Gallery}.<br/ >
* This drawable will only draw the default background based on the pressed state.<br />
* Note that this {@link Drawable} should be used inside a {@link StateListDrawable} instance.
*
* @author alessandro
*
*/
public class DefaultGalleryCheckboxDrawable extends Drawable {
private Paint mPaint;
protected Rect mRect;
private int backgroundColor; // 0xFF2e2e2e - 0xFF404040
private int borderColor; // 0xff535353 - 0xFF626262
/**
* Instantiates a new default gallery checkbox drawable.
*
* @param res
* {@link Context} resource manager
* @param pressed
* pressed state. it will affect the background colors
*/
public DefaultGalleryCheckboxDrawable( Resources res, boolean pressed ) {
super();
mPaint = new Paint( Paint.ANTI_ALIAS_FLAG );
mRect = new Rect();
if ( pressed ) {
backgroundColor = res.getColor( R.color.feather_crop_adapter_background_selected );
borderColor = res.getColor( R.color.feather_crop_adapter_border_selected );
} else {
backgroundColor = res.getColor( R.color.feather_crop_adapter_background_normal );
borderColor = res.getColor( R.color.feather_crop_adapter_border_normal );
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
copyBounds( mRect );
mPaint.setColor( backgroundColor );
canvas.drawPaint( mPaint );
mPaint.setColor( Color.BLACK );
canvas.drawRect( 0, 0, 1, mRect.bottom, mPaint );
canvas.drawRect( mRect.right - 1, 0, mRect.right, mRect.bottom, mPaint );
mPaint.setColor( borderColor );
canvas.drawRect( 1, 0, 3, mRect.bottom, mPaint );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aviary.android.feather.graphics;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.util.AttributeSet;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.library.utils.ReflectionUtils;
import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException;
/**
* Rotate Drawable.
*/
public class AnimatedRotateDrawable extends Drawable implements Drawable.Callback, Runnable, Animatable {
private AnimatedRotateState mState;
private boolean mMutated;
private float mCurrentDegrees;
private float mIncrement;
private boolean mRunning;
/**
* Instantiates a new animated rotate drawable.
*/
public AnimatedRotateDrawable() {
this( null, null );
}
/**
* Instantiates a new animated rotate drawable.
*
* @param res
* the res
* @param resId
* the res id
*/
public AnimatedRotateDrawable( Resources res, int resId ) {
this( res, resId, 8, 100 );
}
public AnimatedRotateDrawable( Resources res, int resId, int frames, int duration ) {
this( null, null );
final float pivotX = 0.5f;
final float pivotY = 0.5f;
final boolean pivotXRel = true;
final boolean pivotYRel = true;
setFramesCount( frames );
setFramesDuration( duration );
Drawable drawable = null;
if ( resId > 0 ) {
drawable = res.getDrawable( resId );
}
final AnimatedRotateState rotateState = mState;
rotateState.mDrawable = drawable;
rotateState.mPivotXRel = pivotXRel;
rotateState.mPivotX = pivotX;
rotateState.mPivotYRel = pivotYRel;
rotateState.mPivotY = pivotY;
init();
if ( drawable != null ) {
drawable.setCallback( this );
}
}
/**
* Instantiates a new animated rotate drawable.
*
* @param rotateState
* the rotate state
* @param res
* the res
*/
private AnimatedRotateDrawable( AnimatedRotateState rotateState, Resources res ) {
mState = new AnimatedRotateState( rotateState, this, res );
init();
}
/**
* Initialize
*/
private void init() {
final AnimatedRotateState state = mState;
mIncrement = 360.0f / state.mFramesCount;
final Drawable drawable = state.mDrawable;
if ( drawable != null ) {
drawable.setFilterBitmap( true );
if ( drawable instanceof BitmapDrawable ) {
( (BitmapDrawable) drawable ).setAntiAlias( true );
}
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas)
*/
@Override
public void draw( Canvas canvas ) {
int saveCount = canvas.save();
final AnimatedRotateState st = mState;
final Drawable drawable = st.mDrawable;
final Rect bounds = drawable.getBounds();
int w = bounds.right - bounds.left;
int h = bounds.bottom - bounds.top;
float px = st.mPivotXRel ? ( w * st.mPivotX ) : st.mPivotX;
float py = st.mPivotYRel ? ( h * st.mPivotY ) : st.mPivotY;
canvas.rotate( mCurrentDegrees, px + bounds.left, py + bounds.top );
drawable.draw( canvas );
canvas.restoreToCount( saveCount );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Animatable#start()
*/
@Override
public void start() {
if ( !mRunning ) {
mRunning = true;
nextFrame();
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Animatable#stop()
*/
@Override
public void stop() {
mRunning = false;
unscheduleSelf( this );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Animatable#isRunning()
*/
@Override
public boolean isRunning() {
return mRunning;
}
/**
* Next frame.
*/
private void nextFrame() {
unscheduleSelf( this );
scheduleSelf( this, SystemClock.uptimeMillis() + mState.mFrameDuration );
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
mCurrentDegrees += mIncrement;
if ( mCurrentDegrees > ( 360.0f - mIncrement ) ) {
mCurrentDegrees = 0.0f;
}
invalidateSelf();
nextFrame();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setVisible(boolean, boolean)
*/
@Override
public boolean setVisible( boolean visible, boolean restart ) {
mState.mDrawable.setVisible( visible, restart );
boolean changed = super.setVisible( visible, restart );
if ( visible ) {
if ( changed || restart ) {
mCurrentDegrees = 0.0f;
nextFrame();
}
} else {
unscheduleSelf( this );
}
return changed;
}
/**
* Returns the drawable rotated by this RotateDrawable.
*
* @return the drawable
*/
public Drawable getDrawable() {
return mState.mDrawable;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getChangingConfigurations()
*/
@Override
public int getChangingConfigurations() {
return super.getChangingConfigurations() | mState.mChangingConfigurations | mState.mDrawable.getChangingConfigurations();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setAlpha(int)
*/
@Override
public void setAlpha( int alpha ) {
mState.mDrawable.setAlpha( alpha );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter)
*/
@Override
public void setColorFilter( ColorFilter cf ) {
mState.mDrawable.setColorFilter( cf );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getOpacity()
*/
@Override
public int getOpacity() {
return mState.mDrawable.getOpacity();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable.Callback#invalidateDrawable(android.graphics.drawable.Drawable)
*/
@Override
public void invalidateDrawable( Drawable who ) {
if ( Constants.ANDROID_SDK > 10 ) {
Callback callback;
try {
callback = (Callback) ReflectionUtils.invokeMethod( this, "getCallback" );
} catch ( ReflectionException e ) {
return;
}
if ( callback != null ) {
callback.invalidateDrawable( this );
}
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable.Callback#scheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable,
* long)
*/
@Override
public void scheduleDrawable( Drawable who, Runnable what, long when ) {
if ( Constants.ANDROID_SDK > 10 ) {
Callback callback;
try {
callback = (Callback) ReflectionUtils.invokeMethod( this, "getCallback" );
} catch ( ReflectionException e ) {
return;
}
if ( callback != null ) {
callback.scheduleDrawable( this, what, when );
}
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable.Callback#unscheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable)
*/
@Override
public void unscheduleDrawable( Drawable who, Runnable what ) {
if ( Constants.ANDROID_SDK > 10 ) {
Callback callback;
try {
callback = (Callback) ReflectionUtils.invokeMethod( this, "getCallback" );
} catch ( ReflectionException e ) {
return;
}
if ( callback != null ) {
callback.unscheduleDrawable( this, what );
}
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getPadding(android.graphics.Rect)
*/
@Override
public boolean getPadding( Rect padding ) {
return mState.mDrawable.getPadding( padding );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#isStateful()
*/
@Override
public boolean isStateful() {
return mState.mDrawable.isStateful();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect)
*/
@Override
protected void onBoundsChange( Rect bounds ) {
mState.mDrawable.setBounds( bounds.left, bounds.top, bounds.right, bounds.bottom );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getIntrinsicWidth()
*/
@Override
public int getIntrinsicWidth() {
return mState.mDrawable.getIntrinsicWidth();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getIntrinsicHeight()
*/
@Override
public int getIntrinsicHeight() {
return mState.mDrawable.getIntrinsicHeight();
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#getConstantState()
*/
@Override
public ConstantState getConstantState() {
if ( mState.canConstantState() ) {
mState.mChangingConfigurations = getChangingConfigurations();
return mState;
}
return null;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#inflate(android.content.res.Resources, org.xmlpull.v1.XmlPullParser,
* android.util.AttributeSet)
*/
@Override
public void inflate( Resources r, XmlPullParser parser, AttributeSet attrs ) throws XmlPullParserException, IOException {}
/**
* Sets the frames count.
*
* @param framesCount
* the new frames count
*/
public void setFramesCount( int framesCount ) {
mState.mFramesCount = framesCount;
mIncrement = 360.0f / mState.mFramesCount;
}
/**
* Sets the frames duration.
*
* @param framesDuration
* the new frames duration
*/
public void setFramesDuration( int framesDuration ) {
mState.mFrameDuration = framesDuration;
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable#mutate()
*/
@Override
public Drawable mutate() {
if ( !mMutated && super.mutate() == this ) {
mState.mDrawable.mutate();
mMutated = true;
}
return this;
}
final static class AnimatedRotateState extends Drawable.ConstantState {
Drawable mDrawable;
int mChangingConfigurations;
boolean mPivotXRel;
float mPivotX;
boolean mPivotYRel;
float mPivotY;
int mFrameDuration;
int mFramesCount;
private boolean mCanConstantState;
private boolean mCheckedConstantState;
/**
* Instantiates a new animated rotate state.
*
* @param source
* the source
* @param owner
* the owner
* @param res
* the res
*/
public AnimatedRotateState( AnimatedRotateState source, AnimatedRotateDrawable owner, Resources res ) {
if ( source != null ) {
if ( res != null ) {
mDrawable = source.mDrawable.getConstantState().newDrawable( res );
} else {
mDrawable = source.mDrawable.getConstantState().newDrawable();
}
mDrawable.setCallback( owner );
mPivotXRel = source.mPivotXRel;
mPivotX = source.mPivotX;
mPivotYRel = source.mPivotYRel;
mPivotY = source.mPivotY;
mFramesCount = source.mFramesCount;
mFrameDuration = source.mFrameDuration;
mCanConstantState = mCheckedConstantState = true;
}
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable.ConstantState#newDrawable()
*/
@Override
public Drawable newDrawable() {
return new AnimatedRotateDrawable( this, null );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable.ConstantState#newDrawable(android.content.res.Resources)
*/
@Override
public Drawable newDrawable( Resources res ) {
return new AnimatedRotateDrawable( this, res );
}
/*
* (non-Javadoc)
*
* @see android.graphics.drawable.Drawable.ConstantState#getChangingConfigurations()
*/
@Override
public int getChangingConfigurations() {
return mChangingConfigurations;
}
/**
* Can constant state.
*
* @return true, if successful
*/
public boolean canConstantState() {
if ( !mCheckedConstantState ) {
mCanConstantState = mDrawable.getConstantState() != null;
mCheckedConstantState = true;
}
return mCanConstantState;
}
}
}
| Java |
package android.view.ext;
/**
* Linearly distributes satellites in the given total degree.
*
* @author Siyamed SINIR
*
*/
public class LinearDegreeProvider implements IDegreeProvider {
public float[] getDegrees(int count, float totalDegrees){
if(count < 1){
return new float[]{};
}
if(count == 1){
return new float[]{45};
}
float[] result = null;
int tmpCount = count-1;
result = new float[count];
float delta = totalDegrees / tmpCount;
for(int index=0; index<count; index++){
int tmpIndex = index;
result[index] = tmpIndex * delta;
}
return result;
}
}
| Java |
package android.view.ext;
/**
* Interface for providing degrees between satellites.
*
* @author Siyamed SINIR
*
*/
public interface IDegreeProvider {
public float[] getDegrees(int count, float totalDegrees);
}
| Java |
package android.view.ext;
import android.content.Context;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.view.ext.R;
/**
* Factory class for creating satellite in/out animations
*
* @author Siyamed SINIR
*
*/
public class SatelliteAnimationCreator {
public static Animation createItemInAnimation(Context context, int index, long expandDuration, int x, int y){
RotateAnimation rotate = new RotateAnimation(720, 0,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setInterpolator(context, R.anim.sat_item_in_rotate_interpolator);
rotate.setDuration(expandDuration);
TranslateAnimation translate = new TranslateAnimation(x, 0, y, 0);
long delay = 250;
if(expandDuration <= 250){
delay = expandDuration / 3;
}
long duration = 400;
if((expandDuration-delay) > duration){
duration = expandDuration-delay;
}
translate.setDuration(duration);
translate.setStartOffset(delay);
translate.setInterpolator(context, R.anim.sat_item_anticipate_interpolator);
AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
long alphaDuration = 10;
if(expandDuration < 10){
alphaDuration = expandDuration / 10;
}
alphaAnimation.setDuration(alphaDuration);
alphaAnimation.setStartOffset((delay + duration) - alphaDuration);
AnimationSet animationSet = new AnimationSet(false);
animationSet.setFillAfter(false);
animationSet.setFillBefore(true);
animationSet.setFillEnabled(true);
animationSet.addAnimation(alphaAnimation);
animationSet.addAnimation(rotate);
animationSet.addAnimation(translate);
animationSet.setStartOffset(30*index);
animationSet.start();
animationSet.startNow();
return animationSet;
}
public static Animation createItemOutAnimation(Context context, int index, long expandDuration, int x, int y){
AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
long alphaDuration = 60;
if(expandDuration < 60){
alphaDuration = expandDuration / 4;
}
alphaAnimation.setDuration(alphaDuration);
alphaAnimation.setStartOffset(0);
TranslateAnimation translate = new TranslateAnimation(0, x, 0, y);
translate.setStartOffset(0);
translate.setDuration(expandDuration);
translate.setInterpolator(context, R.anim.sat_item_overshoot_interpolator);
RotateAnimation rotate = new RotateAnimation(0f, 360f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setInterpolator(context, R.anim.sat_item_out_rotate_interpolator);
long duration = 100;
if(expandDuration <= 150){
duration = expandDuration / 3;
}
rotate.setDuration(expandDuration-duration);
rotate.setStartOffset(duration);
AnimationSet animationSet = new AnimationSet(false);
animationSet.setFillAfter(false);
animationSet.setFillBefore(true);
animationSet.setFillEnabled(true);
//animationSet.addAnimation(alphaAnimation);
//animationSet.addAnimation(rotate);
animationSet.addAnimation(translate);
animationSet.setStartOffset(30*index);
return animationSet;
}
public static Animation createMainButtonAnimation(Context context){
return AnimationUtils.loadAnimation(context, R.anim.sat_main_rotate_left);
}
public static Animation createMainButtonInverseAnimation(Context context){
return AnimationUtils.loadAnimation(context, R.anim.sat_main_rotate_right);
}
public static Animation createItemClickAnimation(Context context){
return AnimationUtils.loadAnimation(context, R.anim.sat_item_anim_click);
}
public static int getTranslateX(float degree, int distance){
return Double.valueOf(distance * Math.cos(Math.toRadians(degree))).intValue();
}
public static int getTranslateY(float degree, int distance){
return Double.valueOf(-1 * distance * Math.sin(Math.toRadians(degree))).intValue();
}
}
| Java |
package android.view.ext;
/**
* Default provider for degrees between satellites. For number of satellites up to 3
* tries to keep satellites centered in the given total degrees. For number equal and
* bigger than four, distirbutes evenly using min and max degrees.
*
* @author Siyamed SINIR
*
*/
public class DefaultDegreeProvider implements IDegreeProvider {
public float[] getDegrees(int count, float totalDegrees){
if(count < 1)
{
return new float[]{};
}
float[] result = null;
int tmpCount = 0;
if(count < 4){
tmpCount = count+1;
}else{
tmpCount = count-1;
}
result = new float[count];
float delta = totalDegrees / tmpCount;
for(int index=0; index<count; index++){
int tmpIndex = index;
if(count < 4){
tmpIndex = tmpIndex+1;
}
result[index] = tmpIndex * delta;
}
return result;
}
}
| Java |
package android.view.ext;
/**
* Provide the degree between each satellite as an array of degrees. Can be provided to
* {@link SatelliteMenu} as a parameter.
*
* @author Siyamed SINIR
*
*/
public class ArrayDegreeProvider implements IDegreeProvider {
private float[] degrees;
public ArrayDegreeProvider(float[] degrees) {
this.degrees = degrees;
}
public float[] getDegrees(int count, float totalDegrees){
if(degrees == null || degrees.length != count){
throw new IllegalArgumentException("Provided delta degrees and the action count are not the same.");
}
return degrees;
}
}
| Java |
package android.view.ext;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.widget.ImageView;
/**
* Menu Item.
*
* TODO: tell about usage
*
* @author Siyamed SINIR
*
*/
public class SatelliteMenuItem {
private int id;
private int imgResourceId;
private Drawable imgDrawable;
private ImageView view;
private ImageView cloneView;
private Animation outAnimation;
private Animation inAnimation;
private Animation clickAnimation;
private int finalX;
private int finalY;
public SatelliteMenuItem(int id, int imgResourceId) {
this.imgResourceId = imgResourceId;
this.id = id;
}
public SatelliteMenuItem(int id, Drawable imgDrawable) {
this.imgDrawable = imgDrawable;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getImgResourceId() {
return imgResourceId;
}
public void setImgResourceId(int imgResourceId) {
this.imgResourceId = imgResourceId;
}
public Drawable getImgDrawable() {
return imgDrawable;
}
public void setImgDrawable(Drawable imgDrawable) {
this.imgDrawable = imgDrawable;
}
void setView(ImageView view) {
this.view = view;
}
ImageView getView() {
return view;
}
void setInAnimation(Animation inAnimation) {
this.inAnimation = inAnimation;
}
Animation getInAnimation() {
return inAnimation;
}
void setOutAnimation(Animation outAnimation) {
this.outAnimation = outAnimation;
}
Animation getOutAnimation() {
return outAnimation;
}
void setFinalX(int finalX) {
this.finalX = finalX;
}
void setFinalY(int finalY) {
this.finalY = finalY;
}
int getFinalX() {
return finalX;
}
int getFinalY() {
return finalY;
}
void setCloneView(ImageView cloneView) {
this.cloneView = cloneView;
}
ImageView getCloneView() {
return cloneView;
}
void setClickAnimation(Animation clickAnim) {
this.clickAnimation = clickAnim;
}
Animation getClickAnimation() {
return clickAnimation;
}
} | Java |
package android.view.ext;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Provides a "Path" like menu for android. ??
*
* TODO: tell about usage
*
* @author Siyamed SINIR
*
*/
public class SatelliteMenu extends FrameLayout {
private static final int DEFAULT_SATELLITE_DISTANCE = 200;
private static final float DEFAULT_TOTAL_SPACING_DEGREES = 90f;
private static final boolean DEFAULT_CLOSE_ON_CLICK = true;
private static final int DEFAULT_EXPAND_DURATION = 400;
private Animation mainRotateRight;
private Animation mainRotateLeft;
private ImageView imgMain;
private SateliteClickedListener itemClickedListener;
private InternalSatelliteOnClickListener internalItemClickListener;
private List<SatelliteMenuItem> menuItems = new ArrayList<SatelliteMenuItem>();
private Map<View, SatelliteMenuItem> viewToItemMap = new HashMap<View, SatelliteMenuItem>();
private AtomicBoolean plusAnimationActive = new AtomicBoolean(false);
// ?? how to save/restore?
private IDegreeProvider gapDegreesProvider = new DefaultDegreeProvider();
//States of these variables are saved
private boolean rotated = false;
private int measureDiff = 0;
//States of these variables are saved - Also configured from XML
private float totalSpacingDegree = DEFAULT_TOTAL_SPACING_DEGREES;
private int satelliteDistance = DEFAULT_SATELLITE_DISTANCE;
private int expandDuration = DEFAULT_EXPAND_DURATION;
private boolean closeItemsOnClick = DEFAULT_CLOSE_ON_CLICK;
public SatelliteMenu(Context context) {
super(context);
init(context, null, 0);
}
public SatelliteMenu(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public SatelliteMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
LayoutInflater.from(context).inflate(R.layout.sat_main, this, true);
imgMain = (ImageView) findViewById(R.id.sat_main);
if(attrs != null){
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SatelliteMenu, defStyle, 0);
satelliteDistance = typedArray.getDimensionPixelSize(R.styleable.SatelliteMenu_satelliteDistance, DEFAULT_SATELLITE_DISTANCE);
totalSpacingDegree = typedArray.getFloat(R.styleable.SatelliteMenu_totalSpacingDegree, DEFAULT_TOTAL_SPACING_DEGREES);
closeItemsOnClick = typedArray.getBoolean(R.styleable.SatelliteMenu_closeOnClick, DEFAULT_CLOSE_ON_CLICK);
expandDuration = typedArray.getInt(R.styleable.SatelliteMenu_expandDuration, DEFAULT_EXPAND_DURATION);
//float satelliteDistance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 170, getResources().getDisplayMetrics());
typedArray.recycle();
}
mainRotateLeft = SatelliteAnimationCreator.createMainButtonAnimation(context);
mainRotateRight = SatelliteAnimationCreator.createMainButtonInverseAnimation(context);
Animation.AnimationListener plusAnimationListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
plusAnimationActive.set(false);
}
};
mainRotateLeft.setAnimationListener(plusAnimationListener);
mainRotateRight.setAnimationListener(plusAnimationListener);
imgMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SatelliteMenu.this.onClick();
}
});
internalItemClickListener = new InternalSatelliteOnClickListener(this);
}
private void onClick() {
if (plusAnimationActive.compareAndSet(false, true)) {
if (!rotated) {
imgMain.startAnimation(mainRotateLeft);
for (SatelliteMenuItem item : menuItems) {
item.getView().startAnimation(item.getOutAnimation());
}
} else {
imgMain.startAnimation(mainRotateRight);
for (SatelliteMenuItem item : menuItems) {
item.getView().startAnimation(item.getInAnimation());
}
}
rotated = !rotated;
}
}
private void openItems() {
if (plusAnimationActive.compareAndSet(false, true)) {
if (!rotated) {
imgMain.startAnimation(mainRotateLeft);
for (SatelliteMenuItem item : menuItems) {
item.getView().startAnimation(item.getOutAnimation());
}
}
rotated = !rotated;
}
}
private void closeItems() {
if (plusAnimationActive.compareAndSet(false, true)) {
if (rotated) {
imgMain.startAnimation(mainRotateRight);
for (SatelliteMenuItem item : menuItems) {
item.getView().startAnimation(item.getInAnimation());
}
}
rotated = !rotated;
}
}
public void addItems(List<SatelliteMenuItem> items) {
menuItems.addAll(items);
this.removeView(imgMain);
TextView tmpView = new TextView(getContext());
tmpView.setLayoutParams(new FrameLayout.LayoutParams(0, 0));
float[] degrees = getDegrees(menuItems.size());
int index = 0;
for (SatelliteMenuItem menuItem : menuItems) {
int finalX = SatelliteAnimationCreator.getTranslateX(
degrees[index], satelliteDistance);
int finalY = SatelliteAnimationCreator.getTranslateY(
degrees[index], satelliteDistance);
ImageView itemView = (ImageView) LayoutInflater.from(getContext())
.inflate(R.layout.sat_item_cr, this, false);
ImageView cloneView = (ImageView) LayoutInflater.from(getContext())
.inflate(R.layout.sat_item_cr, this, false);
itemView.setTag(menuItem.getId());
cloneView.setVisibility(View.GONE);
itemView.setVisibility(View.GONE);
cloneView.setOnClickListener(internalItemClickListener);
cloneView.setTag(Integer.valueOf(menuItem.getId()));
FrameLayout.LayoutParams layoutParams = getLayoutParams(cloneView);
layoutParams.bottomMargin = Math.abs(finalY);
layoutParams.leftMargin = Math.abs(finalX);
cloneView.setLayoutParams(layoutParams);
if (menuItem.getImgResourceId() > 0) {
itemView.setImageResource(menuItem.getImgResourceId());
cloneView.setImageResource(menuItem.getImgResourceId());
} else if (menuItem.getImgDrawable() != null) {
itemView.setImageDrawable(menuItem.getImgDrawable());
cloneView.setImageDrawable(menuItem.getImgDrawable());
}
Animation itemOut = SatelliteAnimationCreator.createItemOutAnimation(getContext(), index,expandDuration, finalX, finalY);
Animation itemIn = SatelliteAnimationCreator.createItemInAnimation(getContext(), index, expandDuration, finalX, finalY);
Animation itemClick = SatelliteAnimationCreator.createItemClickAnimation(getContext());
menuItem.setView(itemView);
menuItem.setCloneView(cloneView);
menuItem.setInAnimation(itemIn);
menuItem.setOutAnimation(itemOut);
menuItem.setClickAnimation(itemClick);
menuItem.setFinalX(finalX);
menuItem.setFinalY(finalY);
itemIn.setAnimationListener(new SatelliteAnimationListener(itemView, true, viewToItemMap));
itemOut.setAnimationListener(new SatelliteAnimationListener(itemView, false, viewToItemMap));
itemClick.setAnimationListener(new SatelliteItemClickAnimationListener(this, menuItem.getId()));
this.addView(itemView);
this.addView(cloneView);
viewToItemMap.put(itemView, menuItem);
viewToItemMap.put(cloneView, menuItem);
index++;
}
this.addView(imgMain);
}
private float[] getDegrees(int count) {
return gapDegreesProvider.getDegrees(count, totalSpacingDegree);
}
private void recalculateMeasureDiff() {
int itemWidth = 0;
if (menuItems.size() > 0) {
itemWidth = menuItems.get(0).getView().getWidth();
}
measureDiff = Float.valueOf(satelliteDistance * 0.2f).intValue()
+ itemWidth;
}
private void resetItems() {
if (menuItems.size() > 0) {
List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(
menuItems);
menuItems.clear();
this.removeAllViews();
addItems(items);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
recalculateMeasureDiff();
int totalHeight = imgMain.getHeight() + satelliteDistance + measureDiff;
int totalWidth = imgMain.getWidth() + satelliteDistance + measureDiff;
setMeasuredDimension(totalWidth, totalHeight);
}
private static class SatelliteItemClickAnimationListener implements Animation.AnimationListener {
private WeakReference<SatelliteMenu> menuRef;
private int tag;
public SatelliteItemClickAnimationListener(SatelliteMenu menu, int tag) {
this.menuRef = new WeakReference<SatelliteMenu>(menu);
this.tag = tag;
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
SatelliteMenu menu = menuRef.get();
if(menu != null && menu.closeItemsOnClick){
menu.close();
if(menu.itemClickedListener != null){
menu.itemClickedListener.eventOccured(tag);
}
}
}
}
private static class SatelliteAnimationListener implements Animation.AnimationListener {
private WeakReference<View> viewRef;
private boolean isInAnimation;
private Map<View, SatelliteMenuItem> viewToItemMap;
public SatelliteAnimationListener(View view, boolean isIn, Map<View, SatelliteMenuItem> viewToItemMap) {
this.viewRef = new WeakReference<View>(view);
this.isInAnimation = isIn;
this.viewToItemMap = viewToItemMap;
}
@Override
public void onAnimationStart(Animation animation) {
if (viewRef != null) {
View view = viewRef.get();
if (view != null) {
SatelliteMenuItem menuItem = viewToItemMap.get(view);
if (isInAnimation) {
menuItem.getView().setVisibility(View.VISIBLE);
menuItem.getCloneView().setVisibility(View.GONE);
} else {
menuItem.getCloneView().setVisibility(View.GONE);
menuItem.getView().setVisibility(View.VISIBLE);
}
}
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (viewRef != null) {
View view = viewRef.get();
if (view != null) {
SatelliteMenuItem menuItem = viewToItemMap.get(view);
if (isInAnimation) {
menuItem.getView().setVisibility(View.GONE);
menuItem.getCloneView().setVisibility(View.GONE);
} else {
menuItem.getCloneView().setVisibility(View.VISIBLE);
menuItem.getView().setVisibility(View.GONE);
}
}
}
}
}
public Map<View, SatelliteMenuItem> getViewToItemMap() {
return viewToItemMap;
}
private static FrameLayout.LayoutParams getLayoutParams(View view) {
return (FrameLayout.LayoutParams) view.getLayoutParams();
}
private static class InternalSatelliteOnClickListener implements View.OnClickListener {
private WeakReference<SatelliteMenu> menuRef;
public InternalSatelliteOnClickListener(SatelliteMenu menu) {
this.menuRef = new WeakReference<SatelliteMenu>(menu);
}
@Override
public void onClick(View v) {
SatelliteMenu menu = menuRef.get();
if(menu != null){
SatelliteMenuItem menuItem = menu.getViewToItemMap().get(v);
v.startAnimation(menuItem.getClickAnimation());
}
}
}
/**
* Sets the click listener for satellite items.
*
* @param itemClickedListener
*/
public void setOnItemClickedListener(SateliteClickedListener itemClickedListener) {
this.itemClickedListener = itemClickedListener;
}
/**
* Defines the algorithm to define the gap between each item.
* Note: Calling before adding items is strongly recommended.
*
* @param gapDegreeProvider
*/
public void setGapDegreeProvider(IDegreeProvider gapDegreeProvider) {
this.gapDegreesProvider = gapDegreeProvider;
resetItems();
}
/**
* Defines the total space between the initial and final item in degrees.
* Note: Calling before adding items is strongly recommended.
*
* @param totalSpacingDegree The degree between initial and final items.
*/
public void setTotalSpacingDegree(float totalSpacingDegree) {
this.totalSpacingDegree = totalSpacingDegree;
resetItems();
}
/**
* Sets the distance of items from the center in pixels.
* Note: Calling before adding items is strongly recommended.
*
* @param distance the distance of items to center in pixels.
*/
public void setSatelliteDistance(int distance) {
this.satelliteDistance = distance;
resetItems();
}
/**
* Sets the duration for expanding and collapsing the items in miliseconds.
* Note: Calling before adding items is strongly recommended.
*
* @param expandDuration the duration for expanding and collapsing the items in miliseconds.
*/
public void setExpandDuration(int expandDuration) {
this.expandDuration = expandDuration;
resetItems();
}
/**
* Sets the image resource for the center button.
*
* @param resource The image resource.
*/
public void setMainImage(int resource) {
this.imgMain.setImageResource(resource);
}
/**
* Sets the image drawable for the center button.
*
* @param resource The image drawable.
*/
public void setMainImage(Drawable drawable) {
this.imgMain.setImageDrawable(drawable);
}
/**
* Defines if the menu shall collapse the items when an item is clicked. Default value is true.
*
* @param closeItemsOnClick
*/
public void setCloseItemsOnClick(boolean closeItemsOnClick) {
this.closeItemsOnClick = closeItemsOnClick;
}
/**
* The listener class for item click event.
* @author Siyamed SINIR
*/
public interface SateliteClickedListener {
/**
* When an item is clicked, informs with the id of the item, which is given while adding the items.
*
* @param id The id of the item.
*/
public void eventOccured(int id);
}
/**
* Expand the menu items.
*/
public void expand() {
openItems();
}
/**
* Collapse the menu items
*/
public void close() {
closeItems();
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.rotated = rotated;
ss.totalSpacingDegree = totalSpacingDegree;
ss.satelliteDistance = satelliteDistance;
ss.measureDiff = measureDiff;
ss.expandDuration = expandDuration;
ss.closeItemsOnClick = closeItemsOnClick;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
rotated = ss.rotated;
totalSpacingDegree = ss.totalSpacingDegree;
satelliteDistance = ss.satelliteDistance;
measureDiff = ss.measureDiff;
expandDuration = ss.expandDuration;
closeItemsOnClick = ss.closeItemsOnClick;
super.onRestoreInstanceState(ss.getSuperState());
}
static class SavedState extends BaseSavedState {
boolean rotated;
private float totalSpacingDegree;
private int satelliteDistance;
private int measureDiff;
private int expandDuration;
private boolean closeItemsOnClick;
SavedState(Parcelable superState) {
super(superState);
}
public SavedState(Parcel in) {
super(in);
rotated = Boolean.valueOf(in.readString());
totalSpacingDegree = in.readFloat();
satelliteDistance = in.readInt();
measureDiff = in.readInt();
expandDuration = in.readInt();
closeItemsOnClick = Boolean.valueOf(in.readString());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(Boolean.toString(rotated));
out.writeFloat(totalSpacingDegree);
out.writeInt(satelliteDistance);
out.writeInt(measureDiff);
out.writeInt(expandDuration);
out.writeString(Boolean.toString(closeItemsOnClick));
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| Java |
/*
* 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 android.net.http;
import java.security.cert.X509Certificate;
/**
* One or more individual SSL errors and the associated SSL certificate
*/
public class SslError {
/**
* Individual SSL errors (in the order from the least to the most severe):
*/
/**
* The certificate is not yet valid
*/
public static final int SSL_NOTYETVALID = 0;
/**
* The certificate has expired
*/
public static final int SSL_EXPIRED = 1;
/**
* Hostname mismatch
*/
public static final int SSL_IDMISMATCH = 2;
/**
* The certificate authority is not trusted
*/
public static final int SSL_UNTRUSTED = 3;
/**
* The number of different SSL errors (update if you add a new SSL error!!!)
*/
public static final int SSL_MAX_ERROR = 4;
/**
* The SSL error set bitfield (each individual error is an bit index;
* multiple individual errors can be OR-ed)
*/
int mErrors;
/**
* The SSL certificate associated with the error set
*/
SslCertificate mCertificate;
/**
* Creates a new SSL error set object
* @param error The SSL error
* @param certificate The associated SSL certificate
*/
public SslError(int error, SslCertificate certificate) {
addError(error);
mCertificate = certificate;
}
/**
* Creates a new SSL error set object
* @param error The SSL error
* @param certificate The associated SSL certificate
*/
public SslError(int error, X509Certificate certificate) {
addError(error);
mCertificate = new SslCertificate(certificate);
}
/**
* @return The SSL certificate associated with the error set
*/
public SslCertificate getCertificate() {
return mCertificate;
}
/**
* Adds the SSL error to the error set
* @param error The SSL error to add
* @return True iff the error being added is a known SSL error
*/
public boolean addError(int error) {
boolean rval = (0 <= error && error < SslError.SSL_MAX_ERROR);
if (rval) {
mErrors |= (0x1 << error);
}
return rval;
}
/**
* @param error The SSL error to check
* @return True iff the set includes the error
*/
public boolean hasError(int error) {
boolean rval = (0 <= error && error < SslError.SSL_MAX_ERROR);
if (rval) {
rval = ((mErrors & (0x1 << error)) != 0);
}
return rval;
}
/**
* @return The primary, most severe, SSL error in the set
*/
public int getPrimaryError() {
if (mErrors != 0) {
// go from the most to the least severe errors
for (int error = SslError.SSL_MAX_ERROR - 1; error >= 0; --error) {
if ((mErrors & (0x1 << error)) != 0) {
return error;
}
}
}
return 0;
}
/**
* @return A String representation of this SSL error object
* (used mostly for debugging).
*/
public String toString() {
return "primary error: " + getPrimaryError() +
" certificate: " + getCertificate();
}
}
| Java |
/*
* 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 android.webkit;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Message;
import android.view.KeyEvent;
public class WebViewClient {
/**
* Give the host application a chance to take over the control when a new
* url is about to be loaded in the current WebView. If WebViewClient is not
* provided, by default WebView will ask Activity Manager to choose the
* proper handler for the url. If WebViewClient is provided, return true
* means the host application handles the url, while return false means the
* current WebView handles the url.
*
* @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @return True if the host application wants to leave the current WebView
* and handle the url itself, otherwise return false.
*/
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
/**
* Notify the host application that a page has started loading. This method
* is called once for each main frame load so a page with iframes or
* framesets will call onPageStarted one time for the main frame. This also
* means that onPageStarted will not be called when the contents of an
* embedded frame changes, i.e. clicking a link whose target is an iframe.
*
* @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @param favicon The favicon for this page if it already exists in the
* database.
*/
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
/**
* Notify the host application that a page has finished loading. This method
* is called only for main frame. When onPageFinished() is called, the
* rendering picture may not be updated yet. To get the notification for the
* new Picture, use {@link WebView.PictureListener#onNewPicture}.
*
* @param view The WebView that is initiating the callback.
* @param url The url of the page.
*/
public void onPageFinished(WebView view, String url) {
}
/**
* Notify the host application that the WebView will load the resource
* specified by the given url.
*
* @param view The WebView that is initiating the callback.
* @param url The url of the resource the WebView will load.
*/
public void onLoadResource(WebView view, String url) {
}
/**
* Notify the host application that there have been an excessive number of
* HTTP redirects. As the host application if it would like to continue
* trying to load the resource. The default behavior is to send the cancel
* message.
*
* @param view The WebView that is initiating the callback.
* @param cancelMsg The message to send if the host wants to cancel
* @param continueMsg The message to send if the host wants to continue
* @deprecated This method is no longer called. When the WebView encounters
* a redirect loop, it will cancel the load.
*/
public void onTooManyRedirects(WebView view, Message cancelMsg,
Message continueMsg) {
cancelMsg.sendToTarget();
}
// These ints must match up to the hidden values in EventHandler.
/** Generic error */
public static final int ERROR_UNKNOWN = -1;
/** Server or proxy hostname lookup failed */
public static final int ERROR_HOST_LOOKUP = -2;
/** Unsupported authentication scheme (not basic or digest) */
public static final int ERROR_UNSUPPORTED_AUTH_SCHEME = -3;
/** User authentication failed on server */
public static final int ERROR_AUTHENTICATION = -4;
/** User authentication failed on proxy */
public static final int ERROR_PROXY_AUTHENTICATION = -5;
/** Failed to connect to the server */
public static final int ERROR_CONNECT = -6;
/** Failed to read or write to the server */
public static final int ERROR_IO = -7;
/** Connection timed out */
public static final int ERROR_TIMEOUT = -8;
/** Too many redirects */
public static final int ERROR_REDIRECT_LOOP = -9;
/** Unsupported URI scheme */
public static final int ERROR_UNSUPPORTED_SCHEME = -10;
/** Failed to perform SSL handshake */
public static final int ERROR_FAILED_SSL_HANDSHAKE = -11;
/** Malformed URL */
public static final int ERROR_BAD_URL = -12;
/** Generic file error */
public static final int ERROR_FILE = -13;
/** File not found */
public static final int ERROR_FILE_NOT_FOUND = -14;
/** Too many requests during this load */
public static final int ERROR_TOO_MANY_REQUESTS = -15;
/**
* Report an error to the host application. These errors are unrecoverable
* (i.e. the main resource is unavailable). The errorCode parameter
* corresponds to one of the ERROR_* constants.
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
}
/**
* As the host application if the browser should resend data as the
* requested page was a result of a POST. The default is to not resend the
* data.
*
* @param view The WebView that is initiating the callback.
* @param dontResend The message to send if the browser should not resend
* @param resend The message to send if the browser should resend data
*/
public void onFormResubmission(WebView view, Message dontResend,
Message resend) {
dontResend.sendToTarget();
}
/**
* Notify the host application to update its visited links database.
*
* @param view The WebView that is initiating the callback.
* @param url The url being visited.
* @param isReload True if this url is being reloaded.
*/
public void doUpdateVisitedHistory(WebView view, String url,
boolean isReload) {
}
/**
* Notify the host application to handle a ssl certificate error request
* (display the error to the user and ask whether to proceed or not). The
* host application has to call either handler.cancel() or handler.proceed()
* as the connection is suspended and waiting for the response. The default
* behavior is to cancel the load.
*
* @param view The WebView that is initiating the callback.
* @param handler An SslErrorHandler object that will handle the user's
* response.
* @param error The SSL error object.
*/
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
handler.cancel();
}
/**
* Notify the host application to handle an authentication request. The
* default behavior is to cancel the request.
*
* @param view The WebView that is initiating the callback.
* @param handler The HttpAuthHandler that will handle the user's response.
* @param host The host requiring authentication.
* @param realm A description to help store user credentials for future
* visits.
*/
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.cancel();
}
/**
* Give the host application a chance to handle the key event synchronously.
* e.g. menu shortcut key events need to be filtered this way. If return
* true, WebView will not handle the key event. If return false, WebView
* will always handle the key event, so none of the super in the view chain
* will see the key event. The default behavior returns false.
*
* @param view The WebView that is initiating the callback.
* @param event The key event.
* @return True if the host application wants to handle the key event
* itself, otherwise return false
*/
public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
return false;
}
/**
* Notify the host application that a key was not handled by the WebView.
* Except system keys, WebView always consumes the keys in the normal flow
* or if shouldOverrideKeyEvent returns true. This is called asynchronously
* from where the key is dispatched. It gives the host application an chance
* to handle the unhandled key events.
*
* @param view The WebView that is initiating the callback.
* @param event The key event.
*/
public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
}
/**
* Notify the host application that the scale applied to the WebView has
* changed.
*
* @param view he WebView that is initiating the callback.
* @param oldScale The old scale factor
* @param newScale The new scale factor
*/
public void onScaleChanged(WebView view, float oldScale, float newScale) {
}
}
| Java |
package com.outsourcing.bottle.domain;
public class ExFeedPicItemEntry {
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class AvatarEntry {
private int avatarid;
/**头像显示模式。选择项:显示默认头像(1)、显示非默认头像(2)、不可见锁定头像(3)、增加头像(4)。*/
private int avatar_mode;
private String avatar_middlepic;
private String avatar_bigpic;
public int getAvatarid() {
return avatarid;
}
public void setAvatarid(int avatarid) {
this.avatarid = avatarid;
}
public int getAvatar_mode() {
return avatar_mode;
}
public void setAvatar_mode(int avatar_mode) {
this.avatar_mode = avatar_mode;
}
public String getAvatar_middlepic() {
return avatar_middlepic;
}
public void setAvatar_middlepic(String avatar_middlepic) {
this.avatar_middlepic = avatar_middlepic;
}
public String getAvatar_bigpic() {
return avatar_bigpic;
}
public void setAvatar_bigpic(String avatar_bigpic) {
this.avatar_bigpic = avatar_bigpic;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
/**
*
* @author 06peng
*
*/
public class AlbumListInfo {
public AlbumListInfo() {
super();
}
private ResponseResult results;
private FriendEntry user_info;
private List<AlbumEntry> albums_list;
private int rscount;
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public FriendEntry getUser_info() {
return user_info;
}
public void setUser_info(FriendEntry user_info) {
this.user_info = user_info;
}
public List<AlbumEntry> getAlbums_list() {
return albums_list;
}
public void setAlbums_list(List<AlbumEntry> albums_list) {
this.albums_list = albums_list;
}
public int getRscount() {
return rscount;
}
public void setRscount(int rscount) {
this.rscount = rscount;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class ExPicOuidInfoEntry {
private String onickname;
private int osex;
private String oavatar;
private String ocountry;
private String ocity;
private String omemo;
private String odoing;
private int oalbum_visible;
private int oprofile_visible;
public String getOnickname() {
return onickname;
}
public void setOnickname(String onickname) {
this.onickname = onickname;
}
public int getOsex() {
return osex;
}
public void setOsex(int osex) {
this.osex = osex;
}
public String getOavatar() {
return oavatar;
}
public void setOavatar(String oavatar) {
this.oavatar = oavatar;
}
public String getOcountry() {
return ocountry;
}
public void setOcountry(String ocountry) {
this.ocountry = ocountry;
}
public String getOcity() {
return ocity;
}
public void setOcity(String ocity) {
this.ocity = ocity;
}
public String getOmemo() {
return omemo;
}
public void setOmemo(String omemo) {
this.omemo = omemo;
}
public String getOdoing() {
return odoing;
}
public void setOdoing(String odoing) {
this.odoing = odoing;
}
public int getOalbum_visible() {
return oalbum_visible;
}
public void setOalbum_visible(int oalbum_visible) {
this.oalbum_visible = oalbum_visible;
}
public int getOprofile_visible() {
return oprofile_visible;
}
public void setOprofile_visible(int oprofile_visible) {
this.oprofile_visible = oprofile_visible;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class ExchangeTimelineShowTipsEntry {
private int show_sendbt_tips;
private int show_gainbt_tips;
public int getShow_sendbt_tips() {
return show_sendbt_tips;
}
public void setShow_sendbt_tips(int show_sendbt_tips) {
this.show_sendbt_tips = show_sendbt_tips;
}
public int getShow_gainbt_tips() {
return show_gainbt_tips;
}
public void setShow_gainbt_tips(int show_gainbt_tips) {
this.show_gainbt_tips = show_gainbt_tips;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class SchoolEntry {
private int schoolid;
private String school;
public int getSchoolid() {
return schoolid;
}
public void setSchoolid(int schoolid) {
this.schoolid = schoolid;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class LanguageConfig {
private String bottle_throw_tips_en;
private String bottle_throw_tips_2_en;
private String bottle_gain_tips_en;
private String bottle_gain_tips_2_en;
private String exchange_profile_tip_en;
private String exchange_profile_tip_2_en;
private String exchange_profile_intro_en;
private String exchange_photo_tip_en;
private String exchange_photo_tip_2_en;
private String exchange_photo_intro_en;
private String without_btfriend_tip_en;
private String without_btfriend_tip_2_en;
private String without_friend_tip_en;
private String without_friend_tip_2_en;
private String without_maybeknow_tip_en;
private String without_maybeknow_tip_invite_en;
private String without_maybeknow_tip_setup_en;
private String without_maybeknow_tip_mobile_en;
private String bottle_throw_tips_cn;
private String bottle_throw_tips_2_cn;
private String bottle_gain_tips_cn;
private String bottle_gain_tips_2_cn;
private String exchange_profile_tip_cn;
private String exchange_profile_tip_2_cn;
private String exchange_profile_intro_cn;
private String exchange_photo_tip_cn;
private String exchange_photo_tip_2_cn;
private String exchange_photo_intro_cn;
private String without_btfriend_tip_cn;
private String without_btfriend_tip_2_cn;
private String without_friend_tip_cn;
private String without_friend_tip_2_cn;
private String without_maybeknow_tip_cn;
private String without_maybeknow_tip_invite_cn;
private String without_maybeknow_tip_setup_cn;
private String without_maybeknow_tip_mobile_cn;
public String getBottle_throw_tips_en() {
return bottle_throw_tips_en;
}
public void setBottle_throw_tips_en(String bottle_throw_tips_en) {
this.bottle_throw_tips_en = bottle_throw_tips_en;
}
public String getBottle_throw_tips_2_en() {
return bottle_throw_tips_2_en;
}
public void setBottle_throw_tips_2_en(String bottle_throw_tips_2_en) {
this.bottle_throw_tips_2_en = bottle_throw_tips_2_en;
}
public String getBottle_gain_tips_en() {
return bottle_gain_tips_en;
}
public void setBottle_gain_tips_en(String bottle_gain_tips_en) {
this.bottle_gain_tips_en = bottle_gain_tips_en;
}
public String getBottle_gain_tips_2_en() {
return bottle_gain_tips_2_en;
}
public void setBottle_gain_tips_2_en(String bottle_gain_tips_2_en) {
this.bottle_gain_tips_2_en = bottle_gain_tips_2_en;
}
public String getExchange_profile_tip_en() {
return exchange_profile_tip_en;
}
public void setExchange_profile_tip_en(String exchange_profile_tip_en) {
this.exchange_profile_tip_en = exchange_profile_tip_en;
}
public String getExchange_profile_tip_2_en() {
return exchange_profile_tip_2_en;
}
public void setExchange_profile_tip_2_en(String exchange_profile_tip_2_en) {
this.exchange_profile_tip_2_en = exchange_profile_tip_2_en;
}
public String getExchange_profile_intro_en() {
return exchange_profile_intro_en;
}
public void setExchange_profile_intro_en(String exchange_profile_intro_en) {
this.exchange_profile_intro_en = exchange_profile_intro_en;
}
public String getExchange_photo_tip_en() {
return exchange_photo_tip_en;
}
public void setExchange_photo_tip_en(String exchange_photo_tip_en) {
this.exchange_photo_tip_en = exchange_photo_tip_en;
}
public String getExchange_photo_tip_2_en() {
return exchange_photo_tip_2_en;
}
public void setExchange_photo_tip_2_en(String exchange_photo_tip_2_en) {
this.exchange_photo_tip_2_en = exchange_photo_tip_2_en;
}
public String getExchange_photo_intro_en() {
return exchange_photo_intro_en;
}
public void setExchange_photo_intro_en(String exchange_photo_intro_en) {
this.exchange_photo_intro_en = exchange_photo_intro_en;
}
public String getWithout_btfriend_tip_en() {
return without_btfriend_tip_en;
}
public void setWithout_btfriend_tip_en(String without_btfriend_tip_en) {
this.without_btfriend_tip_en = without_btfriend_tip_en;
}
public String getWithout_btfriend_tip_2_en() {
return without_btfriend_tip_2_en;
}
public void setWithout_btfriend_tip_2_en(String without_btfriend_tip_2_en) {
this.without_btfriend_tip_2_en = without_btfriend_tip_2_en;
}
public String getWithout_friend_tip_en() {
return without_friend_tip_en;
}
public void setWithout_friend_tip_en(String without_friend_tip_en) {
this.without_friend_tip_en = without_friend_tip_en;
}
public String getWithout_friend_tip_2_en() {
return without_friend_tip_2_en;
}
public void setWithout_friend_tip_2_en(String without_friend_tip_2_en) {
this.without_friend_tip_2_en = without_friend_tip_2_en;
}
public String getWithout_maybeknow_tip_en() {
return without_maybeknow_tip_en;
}
public void setWithout_maybeknow_tip_en(String without_maybeknow_tip_en) {
this.without_maybeknow_tip_en = without_maybeknow_tip_en;
}
public String getWithout_maybeknow_tip_invite_en() {
return without_maybeknow_tip_invite_en;
}
public void setWithout_maybeknow_tip_invite_en(
String without_maybeknow_tip_invite_en) {
this.without_maybeknow_tip_invite_en = without_maybeknow_tip_invite_en;
}
public String getWithout_maybeknow_tip_setup_en() {
return without_maybeknow_tip_setup_en;
}
public void setWithout_maybeknow_tip_setup_en(
String without_maybeknow_tip_setup_en) {
this.without_maybeknow_tip_setup_en = without_maybeknow_tip_setup_en;
}
public String getWithout_maybeknow_tip_mobile_en() {
return without_maybeknow_tip_mobile_en;
}
public void setWithout_maybeknow_tip_mobile_en(
String without_maybeknow_tip_mobile_en) {
this.without_maybeknow_tip_mobile_en = without_maybeknow_tip_mobile_en;
}
public String getBottle_throw_tips_cn() {
return bottle_throw_tips_cn;
}
public void setBottle_throw_tips_cn(String bottle_throw_tips_cn) {
this.bottle_throw_tips_cn = bottle_throw_tips_cn;
}
public String getBottle_throw_tips_2_cn() {
return bottle_throw_tips_2_cn;
}
public void setBottle_throw_tips_2_cn(String bottle_throw_tips_2_cn) {
this.bottle_throw_tips_2_cn = bottle_throw_tips_2_cn;
}
public String getBottle_gain_tips_cn() {
return bottle_gain_tips_cn;
}
public void setBottle_gain_tips_cn(String bottle_gain_tips_cn) {
this.bottle_gain_tips_cn = bottle_gain_tips_cn;
}
public String getBottle_gain_tips_2_cn() {
return bottle_gain_tips_2_cn;
}
public void setBottle_gain_tips_2_cn(String bottle_gain_tips_2_cn) {
this.bottle_gain_tips_2_cn = bottle_gain_tips_2_cn;
}
public String getExchange_profile_tip_cn() {
return exchange_profile_tip_cn;
}
public void setExchange_profile_tip_cn(String exchange_profile_tip_cn) {
this.exchange_profile_tip_cn = exchange_profile_tip_cn;
}
public String getExchange_profile_tip_2_cn() {
return exchange_profile_tip_2_cn;
}
public void setExchange_profile_tip_2_cn(String exchange_profile_tip_2_cn) {
this.exchange_profile_tip_2_cn = exchange_profile_tip_2_cn;
}
public String getExchange_profile_intro_cn() {
return exchange_profile_intro_cn;
}
public void setExchange_profile_intro_cn(String exchange_profile_intro_cn) {
this.exchange_profile_intro_cn = exchange_profile_intro_cn;
}
public String getExchange_photo_tip_cn() {
return exchange_photo_tip_cn;
}
public void setExchange_photo_tip_cn(String exchange_photo_tip_cn) {
this.exchange_photo_tip_cn = exchange_photo_tip_cn;
}
public String getExchange_photo_tip_2_cn() {
return exchange_photo_tip_2_cn;
}
public void setExchange_photo_tip_2_cn(String exchange_photo_tip_2_cn) {
this.exchange_photo_tip_2_cn = exchange_photo_tip_2_cn;
}
public String getExchange_photo_intro_cn() {
return exchange_photo_intro_cn;
}
public void setExchange_photo_intro_cn(String exchange_photo_intro_cn) {
this.exchange_photo_intro_cn = exchange_photo_intro_cn;
}
public String getWithout_btfriend_tip_cn() {
return without_btfriend_tip_cn;
}
public void setWithout_btfriend_tip_cn(String without_btfriend_tip_cn) {
this.without_btfriend_tip_cn = without_btfriend_tip_cn;
}
public String getWithout_btfriend_tip_2_cn() {
return without_btfriend_tip_2_cn;
}
public void setWithout_btfriend_tip_2_cn(String without_btfriend_tip_2_cn) {
this.without_btfriend_tip_2_cn = without_btfriend_tip_2_cn;
}
public String getWithout_friend_tip_cn() {
return without_friend_tip_cn;
}
public void setWithout_friend_tip_cn(String without_friend_tip_cn) {
this.without_friend_tip_cn = without_friend_tip_cn;
}
public String getWithout_friend_tip_2_cn() {
return without_friend_tip_2_cn;
}
public void setWithout_friend_tip_2_cn(String without_friend_tip_2_cn) {
this.without_friend_tip_2_cn = without_friend_tip_2_cn;
}
public String getWithout_maybeknow_tip_cn() {
return without_maybeknow_tip_cn;
}
public void setWithout_maybeknow_tip_cn(String without_maybeknow_tip_cn) {
this.without_maybeknow_tip_cn = without_maybeknow_tip_cn;
}
public String getWithout_maybeknow_tip_invite_cn() {
return without_maybeknow_tip_invite_cn;
}
public void setWithout_maybeknow_tip_invite_cn(
String without_maybeknow_tip_invite_cn) {
this.without_maybeknow_tip_invite_cn = without_maybeknow_tip_invite_cn;
}
public String getWithout_maybeknow_tip_setup_cn() {
return without_maybeknow_tip_setup_cn;
}
public void setWithout_maybeknow_tip_setup_cn(
String without_maybeknow_tip_setup_cn) {
this.without_maybeknow_tip_setup_cn = without_maybeknow_tip_setup_cn;
}
public String getWithout_maybeknow_tip_mobile_cn() {
return without_maybeknow_tip_mobile_cn;
}
public void setWithout_maybeknow_tip_mobile_cn(
String without_maybeknow_tip_mobile_cn) {
this.without_maybeknow_tip_mobile_cn = without_maybeknow_tip_mobile_cn;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class StickEntry {
private int paster_id;
private String paster_url;
public String getPaster_url() {
return paster_url;
}
public void setPaster_url(String paster_url) {
this.paster_url = paster_url;
}
public int getPaster_id() {
return paster_id;
}
public void setPaster_id(int paster_id) {
this.paster_id = paster_id;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
/**
* 初始化瓶子
* @author 06peng
*
*/
public class InitBottleInfo {
private ResponseResult results;
private List<BottleTypeEntry> bttypes_list;
private List<BottleNetTypeEntry> nettypes_list;
private List<FriendLevelEntry> flevels_list;
private OtherConfigEntry other_config;
private LanguageConfig language_config;
public InitBottleInfo(ResponseResult results,
List<BottleTypeEntry> bttypes_list,
List<BottleNetTypeEntry> nettypes_list,
List<FriendLevelEntry> flevels_list,
OtherConfigEntry other_config) {
super();
this.results = results;
this.bttypes_list = bttypes_list;
this.nettypes_list = nettypes_list;
this.flevels_list = flevels_list;
this.other_config = other_config;
}
public InitBottleInfo() {
super();
}
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public List<BottleTypeEntry> getBttypes_list() {
return bttypes_list;
}
public void setBttypes_list(List<BottleTypeEntry> bttypes_list) {
this.bttypes_list = bttypes_list;
}
public List<BottleNetTypeEntry> getNettypes_list() {
return nettypes_list;
}
public void setNettypes_list(List<BottleNetTypeEntry> nettypes_list) {
this.nettypes_list = nettypes_list;
}
public List<FriendLevelEntry> getFlevels_list() {
return flevels_list;
}
public void setFlevels_list(List<FriendLevelEntry> flevels_list) {
this.flevels_list = flevels_list;
}
public OtherConfigEntry getOther_config() {
return other_config;
}
public void setOther_config(OtherConfigEntry other_config) {
this.other_config = other_config;
}
public LanguageConfig getLanguage_config() {
return language_config;
}
public void setLanguage_config(LanguageConfig language_config) {
this.language_config = language_config;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class UrlConfig {
public static final String url = "http://www.mobibottle.com/";
/**地图纠偏接口*/
public static final String search_offset = "http://www.mobibottle.com/openapi/search_offset.json";
/**首页-初始化瓶子配置信息*/
public static final String init_config = "http://www.mobibottle.com/openapi/init_config.json";
/**绑定登录*/
public static final String bind_login = "http://www.mobibottle.com/openapi/bind_login.json";
public static final String check_bind = "http://www.mobibottle.com/openapi/check_bind.json";
/**登录*/
public static final String login = "http://www.mobibottle.com/openapi/login.json";
/**绑定注册*/
public static final String bind_register = "http://www.mobibottle.com/openapi/bind_register.json";
/**获取扔瓶子的权限*/
public static final String get_sendbt_priv = "http://www.mobibottle.com/openapi/get_sendbt_priv.json";
/**获取捞瓶子的权限*/
public static final String get_usenet_priv = "http://www.mobibottle.com/openapi/get_usenet_priv.json";
/**获取用户好友、瓶友*/
public static final String get_selectusers = "http://www.mobibottle.com/openapi/get_selectusers.json";
/**捞瓶子*/
public static final String gain_bt = "http://www.mobibottle.com/openapi/gain_bt.json";
/**重设密码*/
public static final String reset_password = "http://www.mobibottle.com/openapi/reset_password.json";
/**提交表单信息*/
public static final String submit_form = "http://www.mobibottle.com/openapi/submit_form.json";
/**获取登录用户的信息*/
public static final String get_loginuser_info = "http://www.mobibottle.com/openapi/get_loginuser_info.json";
/**获取瓶子timeline信息*/
public static final String get_bt_timeline = "http://www.mobibottle.com/openapi/get_bt_timeline.json";
/**喜欢瓶子操作接口*/
public static final String likeop_bt = "http://www.mobibottle.com/openapi/likeop_bt.json";
/**打开瓶子接口*/
public static final String open_bt = "http://www.mobibottle.com/openapi/open_bt.json";
/**获取瓶子权限*/
public static final String get_sendsinglebt_priv = "http://www.mobibottle.com/openapi/get_sendsinglebt_priv.json";
/**丢弃瓶子接口*/
public static final String discard_bt = "http://www.mobibottle.com/openapi/discard_bt.json";
/**获取特定瓶子类型可选的瓶子标签*/
public static final String get_bttags = "http://www.mobibottle.com/openapi/get_bttags.json";
/*******************新增 贴图**********************/
/**清除位置信息接口*/
public static final String delete_location = "http://www.mobibottle.com/openapi/delete_location.json";
/**设置瓶子照片涂鸦权限接口*/
public static final String set_btpic_paint = "http://www.mobibottle.com/openapi/set_btpic_paint.json";
/**购买贴纸目录接口*/
public static final String pasterdir_pay = "http://www.mobibottle.com/openapi/pasterdir_pay.json";
/**获取贴纸目录下贴纸列表接口*/
public static final String get_pasters_list = "http://www.mobibottle.com/openapi/get_pasters_list.json";
/*******************1.2.1 查看瓶子详细**********************/
/**瓶子查看信息*/
public static final String get_btinfo = "http://www.mobibottle.com/openapi/get_btinfo.json";
/**特定瓶子喜欢列表*/
public static final String get_bt_likeslist = "http://www.mobibottle.com/openapi/get_bt_likeslist.json";
/**特定瓶子动态+评论列表*/
public static final String get_bt_feedslist = "http://www.mobibottle.com/openapi/get_bt_feedslist.json";
/**查看静态地图*/
public static final String map_static_url = "http://maps.google.com/maps/api/staticmap";
/**获取特定瓶子位置相关动态列表接口*/
public static final String get_bt_feedslocation="http://www.mobibottle.com/openapi/get_bt_feedslocation.json";
/**获取照片交换中照片评论动态信息接口*/
public static final String get_picex_picfeeds="http://www.mobibottle.com/openapi/get_picex_picfeeds.json";
/************************2.1 交换*****************************/
/**交换接口*/
public static final String get_ex_timeline ="http://www.mobibottle.com/openapi/get_ex_timeline.json";
/**拒绝资料交换接口*/
public static final String reject_infoex = "http://www.mobibottle.com/openapi/reject_infoex.json";
/**同意资料交换*/
public static final String accept_infoex="http://www.mobibottle.com/openapi/accept_infoex.json";
/**设置资料可见接口*/
public static final String visible_infoex="http://www.mobibottle.com/openapi/visible_infoex.json";
/**设置资料不可见接口*/
public static final String invisible_infoex="http://www.mobibottle.com/openapi/invisible_infoex.json";
/**拒绝照片交换接口*/
public static final String reject_picex="http://www.mobibottle.com/openapi/reject_picex.json";
/**设置相册不可见接口*/
public static final String invisible_picex = "http://www.mobibottle.com/openapi/invisible_picex.json";
/**设置相册可见接口*/
public static final String visible_picex = "http://www.mobibottle.com/openapi/visible_picex.json";
/**喜欢交换中的照片操作接口*/
public static final String likeop_picex = "http://www.mobibottle.com/openapi/likeop_picex.json";
/**获取照片交换会话信息接口*/
public static final String get_picex ="http://www.mobibottle.com/openapi/get_picex.json";
/**获取资料交换会话信息接口*/
public static final String get_infoex ="http://www.mobibottle.com/openapi/get_infoex.json";
/**设置交换照片涂鸦权限接口*/
public static final String set_expic_paint ="http://www.mobibottle.com/openapi/set_expic_paint.json";
/***********************3.1 瓶友**********************************/
/**获取瓶友列表*/
public static final String get_btfs_list = "http://www.mobibottle.com/openapi/get_btfs_list.json";
/**获取好友列表接口*/
public static final String get_friends_list = "http://www.mobibottle.com/openapi/get_friends_list.json";
/**可能认识好友*/
public static final String get_maybeknows_list="http://www.mobibottle.com/openapi/get_maybeknows_list.json";
/**好友申请前检测接口*/
public static final String check_friendapply ="http://www.mobibottle.com/openapi/check_friendapply.json";
/******************************************************/
/**获取我的好友动态列表接口*/
public static final String get_my_feedslist = "http://www.mobibottle.com/openapi/get_my_feedslist.json";
/**注销*/
public static final String logout = "http://www.mobibottle.com/openapi/logout.json";
/**设置头像*/
public static final String set_avatar = "http://www.mobibottle.com/openapi/set_avatar.json";
/**获取跟某用户是否有资料或者照片交换会话接口*/
public static final String get_has_exs = "http://www.mobibottle.com/openapi/get_has_exs.json";
/**用户档案信息接口*/
public static final String get_user_profile = "http://www.mobibottle.com/openapi/get_user_profileinfo.json";
/**获取个人空间信息接口*/
public static final String get_space_info = "http://www.mobibottle.com/openapi/get_space_info.json";
/**获取对方相册、资料是否对你可见*/
public static final String check_ouser_visible = "http://www.mobibottle.com/openapi/check_ouser_visible.json";
/**获取某用户相关的瓶子动态列表接口*/
public static final String get_user_btfeedslist = "http://www.mobibottle.com/openapi/get_user_btfeedslist.json";
/**获取某用户的好友动态列表接口*/
public static final String get_user_feedslist = "http://www.mobibottle.com/openapi/get_user_feedslist.json";
/**设置好友分组接口*/
public static final String set_friendgroup = "http://www.mobibottle.com/openapi/set_friendgroup.json";
/**取消好友接口*/
public static final String cancel_friend = "http://www.mobibottle.com/openapi/cancel_friend.json";
/**开放平台邀请接口*/
public static final String open_invite = "http://www.mobibottle.com/openapi/open_invite.json";
/**开放平台同步好友接口*/
public static final String open_syncfriends = "http://www.mobibottle.com/openapi/open_syncfriends.json";
/**开放平台取消绑定接口*/
public static final String open_unbind = "http://www.mobibottle.com/openapi/open_unbind.json";
/**获取分组信息*/
public static final String get_groups_info = "http://www.mobibottle.com/openapi/get_groups_info.json";
/**修改分组名称*/
public static final String set_groupname = "http://www.mobibottle.com/openapi/set_groupname.json";
/**获取用户基本资料*/
public static final String get_basic_info = "http://www.mobibottle.com/openapi/get_basic_info.json";
/**设置基本资料*/
public static final String set_basic_info = "http://www.mobibottle.com/openapi/set_basic_info.json";
/**搜索城市*/
public static final String search_city = "http://www.mobibottle.com/openapi/search_city.json";
/**获取职业信息列表*/
public static final String get_careers_list = "http://www.mobibottle.com/openapi/get_careers_list.json";
/**修改密码*/
public static final String set_password_info = "http://www.mobibottle.com/openapi/set_password_info.json";
/**获取联系信息*/
public static final String get_contact_info = "http://www.mobibottle.com/openapi/get_contact_info.json";
/**修改联系信息*/
public static final String set_contact_info = "http://www.mobibottle.com/openapi/set_contact_info.json";
/**获取公司信息*/
public static final String get_work_info = "http://www.mobibottle.com/openapi/get_work_info.json";
/**删除公司信息*/
public static final String delete_company_info = "http://www.mobibottle.com/openapi/delete_company_info.json";
/**添加公司工作信息*/
public static final String add_company_info = "http://www.mobibottle.com/openapi/add_company_info.json";
/**获取教育信息*/
public static final String get_edu_info = "http://www.mobibottle.com/openapi/get_edu_info.json";
/**设置教育信息*/
public static final String set_edu_info = "http://www.mobibottle.com/openapi/set_edu_info.json";
/**删除学校信息*/
public static final String delete_school_info = "http://www.mobibottle.com/openapi/delete_school_info.json";
/**搜索学校接口*/
public static final String search_school = "http://www.mobibottle.com/openapi/search_school.json";
/**添加学校教育信息*/
public static final String add_school_info = "http://www.mobibottle.com/openapi/add_school_info.json";
/**获取相册列表*/
public static final String get_albums_list = "http://www.mobibottle.com/openapi/get_albums_list.json";
/**删除相册接口*/
public static final String delete_album = "http://www.mobibottle.com/openapi/delete_album.json";
/**获取相册中照片列表*/
public static final String get_albumpics_list = "http://www.mobibottle.com/openapi/get_albumpics_list.json";
/**获取照片信息*/
public static final String get_pic_info = "http://www.mobibottle.com/openapi/get_pic_info.json";
/**删除照片*/
public static final String delete_pic = "http://www.mobibottle.com/openapi/delete_pic.json";
/**推送通知*/
public static final String push_notice = "http://www.mobibottle.com/openapi/push_notice.json";
/**获取我的通知列表*/
public static final String get_mynoticeslist = "http://www.mobibottle.com/openapi/get_mynoticeslist.json";
/**同意好友申请*/
public static final String accept_friend = "http://www.mobibottle.com/openapi/accept_friend.json";
/**拒绝好友申请*/
public static final String reject_friend = "http://www.mobibottle.com/openapi/reject_friend.json";
/**获取我的消息会话列表*/
public static final String get_mymessage_sessionslist = "http://www.mobibottle.com/openapi/get_mymessage_sessionslist.json";
/**获取我的消息会话列表*/
public static final String get_mymessageslist = "http://www.mobibottle.com/openapi/get_mymessageslist.json";
/**设置黑名单状态*/
public static final String set_blacklist = "http://www.mobibottle.com/openapi/set_blacklist.json";
/**设置为默认头像接口*/
public static final String set_default_avatar = "http://www.mobibottle.com/openapi/set_default_avatar.json";
/**获取当前瓶友等级和积分经验接口*/
public static final String get_user_btlevel = "http://www.mobibottle.com/openapi/get_user_btlevel.json";
/**瓶友等级升级接口*/
public static final String btlevel_upgrade = "http://www.mobibottle.com/openapi/btlevel_upgrade.json";
/**喜欢照片接口*/
public static final String like_photo = "http://www.mobibottle.com/openapi/like_photo.json";
/**获取更多页面的初始化信息*/
public static final String get_more_info = "http://www.mobibottle.com/openapi/get_more_info.json";
/**搜索用户接口*/
public static final String search_users_list = "http://www.mobibottle.com/openapi/search_users_list.json";
/**初始化设置头像和昵称接口*/
public static final String set_avatar_nickname = "http://www.mobibottle.com/openapi/set_avatar_nickname.json";
/**推荐照片给好友*/
public static final String recommend_photo = "http://www.mobibottle.com/openapi/recommend_photo.json";
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
public class ExchangeInformationInfo {
private ResponseResult results;
private ExPicOuidInfoEntry ouid_info;
private ExInfoSessionEntry exs_info;
private List<ExFeedInfoEntry> exfeeds_list;
private int rscount;
public ExchangeInformationInfo() {
super();
}
public ExchangeInformationInfo(ResponseResult results,
ExPicOuidInfoEntry ouid_info, ExInfoSessionEntry exs_info,
List<ExFeedInfoEntry> exfeeds_list, int rscount) {
super();
this.results = results;
this.ouid_info = ouid_info;
this.exs_info = exs_info;
this.exfeeds_list = exfeeds_list;
this.rscount = rscount;
}
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public ExPicOuidInfoEntry getOuid_info() {
return ouid_info;
}
public void setOuid_info(ExPicOuidInfoEntry ouid_info) {
this.ouid_info = ouid_info;
}
public ExInfoSessionEntry getExs_info() {
return exs_info;
}
public void setExs_info(ExInfoSessionEntry exs_info) {
this.exs_info = exs_info;
}
public List<ExFeedInfoEntry> getExfeeds_list() {
return exfeeds_list;
}
public void setExfeeds_list(List<ExFeedInfoEntry> exfeeds_list) {
this.exfeeds_list = exfeeds_list;
}
public int getRscount() {
return rscount;
}
public void setRscount(int rscount) {
this.rscount = rscount;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
public class BottleTagInfo {
private List<BottleTagEntry> bttags_list;
private ResponseResult results;
public List<BottleTagEntry> getBttags_list() {
return bttags_list;
}
public void setBttags_list(List<BottleTagEntry> bttags_list) {
this.bttags_list = bttags_list;
}
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
* 瓶子标签
* @author 06peng
*
*/
public class BottleTagEntry {
private int tagid;
private int is_default;
private String content;
public int getTagid() {
return tagid;
}
public void setTagid(int tagid) {
this.tagid = tagid;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class LocationEntry {
private double latitude;
private double longitude;
private String country;
private String province;
private String city;
private String area;
private String locationName;
private String address;
private String type;
private String reference;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
/**
*
* @author 06peng
*
*/
public class SpaceEntry {
private int uid;
private String nickname;
private int sex;
/**空间类型。选择项:好友空间(0)、瓶友空间(1)、陌生人空间(2)、我的空间(3)*/
private int space_type;
private int album_visible;
private int info_visible;
private String avatar;
private String avatar_small;
private String country;
private String city;
private String memo;
private String doing;
private String relation_twitter;
private String relation_facebook;
private String relation_sina;
private String relation_tqq;
private String relation_renren;
private String relation_douban;
private String relation_qq;
private String relation_schoolmate;
private String relation_sameresidecity;
private String relation_samebirthcity;
private String relation_sameworkcity;
private String relation_mobile;
private String groupname;
private int credit;
private int exp;
private int ttcredit;
private int ttexp;
private String level;
/**
* 照片交换按钮是否显示。选择项:不显示(0)、显示蓝色按钮(1)、显示红色按钮(2)
*/
private int picex_show;
/**
* 资料交换按钮是否显示。选择项:不显示(0)、显示蓝色按钮(1)、显示红色按钮(2)
*/
private int infoex_show;
/**
* 加好友取消好友按钮是否显示。选择项:不显示(0)、显示蓝色加好友按钮(1)、显示红色加好友按钮(2)、显示灰色取消好友按钮(3)
*/
private int friend_show;
/**
* 拉黑取消拉黑按钮是否显示。选择项:不显示(0)、显示灰色拉黑按钮(1)、显示黑色取消拉黑按钮(2)
*/
private int blacklist_show;
/**
* 点击效果菜单的私信按钮,跳转的模式。选择项:
* (0)跳转到3.9.消息列表.html、
* (1)跳转到3.10.消息会话查看.html、
* (2)跳转到0.1.留言(照片+定位+转载).html发私信模式
*/
private int sendmsg_mode;
private List<AvatarEntry> avatars_list;
public SpaceEntry() {
super();
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getSpace_type() {
return space_type;
}
public void setSpace_type(int space_type) {
this.space_type = space_type;
}
public int getAlbum_visible() {
return album_visible;
}
public void setAlbum_visible(int album_visible) {
this.album_visible = album_visible;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getDoing() {
return doing;
}
public void setDoing(String doing) {
this.doing = doing;
}
public String getRelation_twitter() {
return relation_twitter;
}
public void setRelation_twitter(String relation_twitter) {
this.relation_twitter = relation_twitter;
}
public String getRelation_facebook() {
return relation_facebook;
}
public void setRelation_facebook(String relation_facebook) {
this.relation_facebook = relation_facebook;
}
public String getRelation_sina() {
return relation_sina;
}
public void setRelation_sina(String relation_sina) {
this.relation_sina = relation_sina;
}
public String getRelation_tqq() {
return relation_tqq;
}
public void setRelation_tqq(String relation_tqq) {
this.relation_tqq = relation_tqq;
}
public String getRelation_renren() {
return relation_renren;
}
public void setRelation_renren(String relation_renren) {
this.relation_renren = relation_renren;
}
public String getRelation_douban() {
return relation_douban;
}
public void setRelation_douban(String relation_douban) {
this.relation_douban = relation_douban;
}
public String getRelation_qq() {
return relation_qq;
}
public void setRelation_qq(String relation_qq) {
this.relation_qq = relation_qq;
}
public String getRelation_schoolmate() {
return relation_schoolmate;
}
public void setRelation_schoolmate(String relation_schoolmate) {
this.relation_schoolmate = relation_schoolmate;
}
public String getRelation_sameresidecity() {
return relation_sameresidecity;
}
public void setRelation_sameresidecity(String relation_sameresidecity) {
this.relation_sameresidecity = relation_sameresidecity;
}
public String getRelation_samebirthcity() {
return relation_samebirthcity;
}
public void setRelation_samebirthcity(String relation_samebirthcity) {
this.relation_samebirthcity = relation_samebirthcity;
}
public String getRelation_sameworkcity() {
return relation_sameworkcity;
}
public void setRelation_sameworkcity(String relation_sameworkcity) {
this.relation_sameworkcity = relation_sameworkcity;
}
public String getGroupname() {
return groupname;
}
public void setGroupname(String groupname) {
this.groupname = groupname;
}
public String getAvatar_small() {
return avatar_small;
}
public void setAvatar_small(String avatar_small) {
this.avatar_small = avatar_small;
}
public String getRelation_mobile() {
return relation_mobile;
}
public void setRelation_mobile(String relation_mobile) {
this.relation_mobile = relation_mobile;
}
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getTtcredit() {
return ttcredit;
}
public void setTtcredit(int ttcredit) {
this.ttcredit = ttcredit;
}
public int getTtexp() {
return ttexp;
}
public void setTtexp(int ttexp) {
this.ttexp = ttexp;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public int getPicex_show() {
return picex_show;
}
public void setPicex_show(int picex_show) {
this.picex_show = picex_show;
}
public int getInfoex_show() {
return infoex_show;
}
public void setInfoex_show(int infoex_show) {
this.infoex_show = infoex_show;
}
public int getFriend_show() {
return friend_show;
}
public void setFriend_show(int friend_show) {
this.friend_show = friend_show;
}
public int getBlacklist_show() {
return blacklist_show;
}
public void setBlacklist_show(int blacklist_show) {
this.blacklist_show = blacklist_show;
}
public int getSendmsg_mode() {
return sendmsg_mode;
}
public void setSendmsg_mode(int sendmsg_mode) {
this.sendmsg_mode = sendmsg_mode;
}
public int getInfo_visible() {
return info_visible;
}
public void setInfo_visible(int info_visible) {
this.info_visible = info_visible;
}
public List<AvatarEntry> getAvatars_list() {
return avatars_list;
}
public void setAvatars_list(List<AvatarEntry> avatars_list) {
this.avatars_list = avatars_list;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
/**
*
* @author 06peng
*
*/
public class CareerEntry {
private int career_classid;
private String career_class;
private List<SubCareerEntry> subcareers_list;
public int getCareer_classid() {
return career_classid;
}
public void setCareer_classid(int career_classid) {
this.career_classid = career_classid;
}
public String getCareer_class() {
return career_class;
}
public void setCareer_class(String career_class) {
this.career_class = career_class;
}
public List<SubCareerEntry> getSubcareers_list() {
return subcareers_list;
}
public void setSubcareers_list(List<SubCareerEntry> subcareers_list) {
this.subcareers_list = subcareers_list;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class SpaceBottleFeedEntry {
private int btid;
private int btfeed_uid;
private String btfeed_nickname;
private String btfeed_avatar;
private String btfeed_content;
private String btfeed_time;
private String btfeed_location;
private float btfeed_lng;
private float btfeed_lat;
public int getBtid() {
return btid;
}
public void setBtid(int btid) {
this.btid = btid;
}
public int getBtfeed_uid() {
return btfeed_uid;
}
public void setBtfeed_uid(int btfeed_uid) {
this.btfeed_uid = btfeed_uid;
}
public String getBtfeed_nickname() {
return btfeed_nickname;
}
public void setBtfeed_nickname(String btfeed_nickname) {
this.btfeed_nickname = btfeed_nickname;
}
public String getBtfeed_avatar() {
return btfeed_avatar;
}
public void setBtfeed_avatar(String btfeed_avatar) {
this.btfeed_avatar = btfeed_avatar;
}
public String getBtfeed_content() {
return btfeed_content;
}
public void setBtfeed_content(String btfeed_content) {
this.btfeed_content = btfeed_content;
}
public String getBtfeed_time() {
return btfeed_time;
}
public void setBtfeed_time(String btfeed_time) {
this.btfeed_time = btfeed_time;
}
public String getBtfeed_location() {
return btfeed_location;
}
public void setBtfeed_location(String btfeed_location) {
this.btfeed_location = btfeed_location;
}
public float getBtfeed_lng() {
return btfeed_lng;
}
public void setBtfeed_lng(float btfeed_lng) {
this.btfeed_lng = btfeed_lng;
}
public float getBtfeed_lat() {
return btfeed_lat;
}
public void setBtfeed_lat(float btfeed_lat) {
this.btfeed_lat = btfeed_lat;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class OtherConfigEntry {
private int feedback_uid;
private int qq_enable;
private int weibo_enable;
private int tencent_enable;
private int renren_enable;
private int douban_enable;
private int twitter_enable;
private int facebook_enable;
private int register_enable;
private String last_android_version;
public int getFeedback_uid() {
return feedback_uid;
}
public void setFeedback_uid(int feedback_uid) {
this.feedback_uid = feedback_uid;
}
public int getQq_enable() {
return qq_enable;
}
public void setQq_enable(int qq_enable) {
this.qq_enable = qq_enable;
}
public int getWeibo_enable() {
return weibo_enable;
}
public void setWeibo_enable(int weibo_enable) {
this.weibo_enable = weibo_enable;
}
public int getTencent_enable() {
return tencent_enable;
}
public void setTencent_enable(int tencent_enable) {
this.tencent_enable = tencent_enable;
}
public int getRenren_enable() {
return renren_enable;
}
public void setRenren_enable(int renren_enable) {
this.renren_enable = renren_enable;
}
public int getDouban_enable() {
return douban_enable;
}
public void setDouban_enable(int douban_enable) {
this.douban_enable = douban_enable;
}
public int getTwitter_enable() {
return twitter_enable;
}
public void setTwitter_enable(int twitter_enable) {
this.twitter_enable = twitter_enable;
}
public int getFacebook_enable() {
return facebook_enable;
}
public void setFacebook_enable(int facebook_enable) {
this.facebook_enable = facebook_enable;
}
public int getRegister_enable() {
return register_enable;
}
public void setRegister_enable(int register_enable) {
this.register_enable = register_enable;
}
public String getLast_android_version() {
return last_android_version;
}
public void setLast_android_version(String last_android_version) {
this.last_android_version = last_android_version;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
/**
*
* @author 06peng
*
*/
public class FriendFeedInfo {
private ResponseResult results;
private List<FriendFeedEntry> feeds_list;
private int rscount;
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public List<FriendFeedEntry> getFeeds_list() {
return feeds_list;
}
public void setFeeds_list(List<FriendFeedEntry> feeds_list) {
this.feeds_list = feeds_list;
}
public int getRscount() {
return rscount;
}
public void setRscount(int rscount) {
this.rscount = rscount;
}
public FriendFeedInfo() {
super();
}
}
| Java |
package com.outsourcing.bottle.domain;
public class PasterDirConfigEntry {
private int pasterdir_id;
private String pasterdir_name_cn;
private String pasterdir_name_en;
private String pasterdir_coverurl;
private int credit;
private int ttcredit;
private int btf_level;
private String useterm;
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
public int getTtcredit() {
return ttcredit;
}
public void setTtcredit(int ttcredit) {
this.ttcredit = ttcredit;
}
public int getBtf_level() {
return btf_level;
}
public void setBtf_level(int btf_level) {
this.btf_level = btf_level;
}
public String getUseterm() {
return useterm;
}
public void setUseterm(String useterm) {
this.useterm = useterm;
}
public int getUnlocked() {
return unlocked;
}
public void setUnlocked(int unlocked) {
this.unlocked = unlocked;
}
private int unlocked;
public int getPasterdir_id() {
return pasterdir_id;
}
public void setPasterdir_id(int pasterdir_id) {
this.pasterdir_id = pasterdir_id;
}
public String getPasterdir_name_cn() {
return pasterdir_name_cn;
}
public void setPasterdir_name_cn(String pasterdir_name_cn) {
this.pasterdir_name_cn = pasterdir_name_cn;
}
public String getPasterdir_name_en() {
return pasterdir_name_en;
}
public void setPasterdir_name_en(String pasterdir_name_en) {
this.pasterdir_name_en = pasterdir_name_en;
}
public String getPasterdir_coverurl() {
return pasterdir_coverurl;
}
public void setPasterdir_coverurl(String pasterdir_coverurl) {
this.pasterdir_coverurl = pasterdir_coverurl;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class BottleFriendEntry {
private int btf_uid;
private String btf_nickname;
private int btf_sex;
private String btf_avatar;
private String btf_country;
private String btf_city;
private String btf_memo;
private String btf_doing;
private int btf_isfriend;
private int btid;
private int bttypeid;
private String feed_nickname;
private String feed_content;
private String feed_time;
private String feed_location;
private float feed_lng;
private float feed_lat;
private String feed_distance;
public int getBtf_uid() {
return btf_uid;
}
public void setBtf_uid(int btf_uid) {
this.btf_uid = btf_uid;
}
public String getBtf_nickname() {
return btf_nickname;
}
public void setBtf_nickname(String btf_nickname) {
this.btf_nickname = btf_nickname;
}
public int getBtf_sex() {
return btf_sex;
}
public void setBtf_sex(int btf_sex) {
this.btf_sex = btf_sex;
}
public String getBtf_avatar() {
return btf_avatar;
}
public void setBtf_avatar(String btf_avatar) {
this.btf_avatar = btf_avatar;
}
public String getBtf_country() {
return btf_country;
}
public void setBtf_country(String btf_country) {
this.btf_country = btf_country;
}
public String getBtf_city() {
return btf_city;
}
public void setBtf_city(String btf_city) {
this.btf_city = btf_city;
}
public String getBtf_memo() {
return btf_memo;
}
public void setBtf_memo(String btf_memo) {
this.btf_memo = btf_memo;
}
public String getBtf_doing() {
return btf_doing;
}
public void setBtf_doing(String btf_doing) {
this.btf_doing = btf_doing;
}
public int getBtf_isfriend() {
return btf_isfriend;
}
public void setBtf_isfriend(int btf_isfriend) {
this.btf_isfriend = btf_isfriend;
}
public int getBtid() {
return btid;
}
public void setBtid(int btid) {
this.btid = btid;
}
public int getBttypeid() {
return bttypeid;
}
public void setBttypeid(int bttypeid) {
this.bttypeid = bttypeid;
}
public String getFeed_nickname() {
return feed_nickname;
}
public void setFeed_nickname(String feed_nickname) {
this.feed_nickname = feed_nickname;
}
public String getFeed_content() {
return feed_content;
}
public void setFeed_content(String feed_content) {
this.feed_content = feed_content;
}
public String getFeed_time() {
return feed_time;
}
public void setFeed_time(String feed_time) {
this.feed_time = feed_time;
}
public String getFeed_location() {
return feed_location;
}
public void setFeed_location(String feed_location) {
this.feed_location = feed_location;
}
public float getFeed_lng() {
return feed_lng;
}
public void setFeed_lng(float feed_lng) {
this.feed_lng = feed_lng;
}
public float getFeed_lat() {
return feed_lat;
}
public void setFeed_lat(float feed_lat) {
this.feed_lat = feed_lat;
}
public String getFeed_distance() {
return feed_distance;
}
public void setFeed_distance(String feed_distance) {
this.feed_distance = feed_distance;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class BottleFeedListEntry {
private int feed_uid;
private int feed_type;
private String feed_nickname;
private String feed_avatar;
private int commentid;
private String feed_content;
private String feed_replycomment;
private String feed_commentpic;
private String feed_commentpic_big;
private String feed_commentpic_tuya;
private String feed_time;
private String feed_location;
private int feed_isnew;
private float feed_lng;
private float feed_lat;
private int location_delete_enable;
private int location_objtype;
private int location_objid;
public int getFeed_uid() {
return feed_uid;
}
public void setFeed_uid(int feed_uid) {
this.feed_uid = feed_uid;
}
public int getFeed_type() {
return feed_type;
}
public void setFeed_type(int feed_type) {
this.feed_type = feed_type;
}
public String getFeed_nickname() {
return feed_nickname;
}
public void setFeed_nickname(String feed_nickname) {
this.feed_nickname = feed_nickname;
}
public String getFeed_avatar() {
return feed_avatar;
}
public void setFeed_avatar(String feed_avatar) {
this.feed_avatar = feed_avatar;
}
public int getCommentid() {
return commentid;
}
public void setCommentid(int commentid) {
this.commentid = commentid;
}
public String getFeed_content() {
return feed_content;
}
public void setFeed_content(String feed_content) {
this.feed_content = feed_content;
}
public String getFeed_replycomment() {
return feed_replycomment;
}
public void setFeed_replycomment(String feed_replycomment) {
this.feed_replycomment = feed_replycomment;
}
public String getFeed_commentpic() {
return feed_commentpic;
}
public void setFeed_commentpic(String feed_commentpic) {
this.feed_commentpic = feed_commentpic;
}
public String getFeed_commentpic_big() {
return feed_commentpic_big;
}
public void setFeed_commentpic_big(String feed_commentpic_big) {
this.feed_commentpic_big = feed_commentpic_big;
}
public String getFeed_time() {
return feed_time;
}
public void setFeed_time(String feed_time) {
this.feed_time = feed_time;
}
public String getFeed_location() {
return feed_location;
}
public void setFeed_location(String feed_location) {
this.feed_location = feed_location;
}
public float getFeed_lng() {
return feed_lng;
}
public void setFeed_lng(float feed_lng) {
this.feed_lng = feed_lng;
}
public float getFeed_lat() {
return feed_lat;
}
public void setFeed_lat(float feed_lat) {
this.feed_lat = feed_lat;
}
public int getFeed_isnew() {
return feed_isnew;
}
public void setFeed_isnew(int feed_isnew) {
this.feed_isnew = feed_isnew;
}
public String getFeed_commentpic_tuya() {
return feed_commentpic_tuya;
}
public void setFeed_commentpic_tuya(String feed_commentpic_tuya) {
this.feed_commentpic_tuya = feed_commentpic_tuya;
}
public int getLocation_delete_enable() {
return location_delete_enable;
}
public void setLocation_delete_enable(int location_delete_enable) {
this.location_delete_enable = location_delete_enable;
}
public int getLocation_objtype() {
return location_objtype;
}
public void setLocation_objtype(int location_objtype) {
this.location_objtype = location_objtype;
}
public int getLocation_objid() {
return location_objid;
}
public void setLocation_objid(int location_objid) {
this.location_objid = location_objid;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
public class MyFriendInfo {
private ResponseResult results;
private List<GroupFriendEntry> groups_list;
private List<MyFriendEntry> friends_list;
private int rscount;
public MyFriendInfo() {
super();
}
public MyFriendInfo(ResponseResult results,
List<GroupFriendEntry> groups_list,
List<MyFriendEntry> friends_list, int rscount) {
super();
this.results = results;
this.groups_list = groups_list;
this.friends_list = friends_list;
this.rscount = rscount;
}
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public List<GroupFriendEntry> getGroups_list() {
return groups_list;
}
public void setGroups_list(List<GroupFriendEntry> groups_list) {
this.groups_list = groups_list;
}
public List<MyFriendEntry> getFriends_list() {
return friends_list;
}
public void setFriends_list(List<MyFriendEntry> friends_list) {
this.friends_list = friends_list;
}
public int getRscount() {
return rscount;
}
public void setRscount(int rscount) {
this.rscount = rscount;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class LoginUserInfoEntry {
private int basicinfo_fullfill;
private String basicinfo_tip;
private String avatar;
private String nickname;
private String doing;
private int facebookok;
private int twitterok;
private int qqok;
private int sinaok;
private int tqqok;
private int renrenok;
private int doubanok;
public int getBasicinfo_fullfill() {
return basicinfo_fullfill;
}
public void setBasicinfo_fullfill(int basicinfo_fullfill) {
this.basicinfo_fullfill = basicinfo_fullfill;
}
public String getBasicinfo_tip() {
return basicinfo_tip;
}
public void setBasicinfo_tip(String basicinfo_tip) {
this.basicinfo_tip = basicinfo_tip;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getDoing() {
return doing;
}
public void setDoing(String doing) {
this.doing = doing;
}
public int getFacebookok() {
return facebookok;
}
public void setFacebookok(int facebookok) {
this.facebookok = facebookok;
}
public int getTwitterok() {
return twitterok;
}
public void setTwitterok(int twitterok) {
this.twitterok = twitterok;
}
public int getQqok() {
return qqok;
}
public void setQqok(int qqok) {
this.qqok = qqok;
}
public int getSinaok() {
return sinaok;
}
public void setSinaok(int sinaok) {
this.sinaok = sinaok;
}
public int getTqqok() {
return tqqok;
}
public void setTqqok(int tqqok) {
this.tqqok = tqqok;
}
public int getRenrenok() {
return renrenok;
}
public void setRenrenok(int renrenok) {
this.renrenok = renrenok;
}
public int getDoubanok() {
return doubanok;
}
public void setDoubanok(int doubanok) {
this.doubanok = doubanok;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
public class BottleFriendInfo {
private ResponseResult results;
private List<BottleFriendEntry> btfs_list;
private int rscount;
public BottleFriendInfo() {
super();
}
public BottleFriendInfo(ResponseResult results,List<BottleFriendEntry> btfs_list, int rscount) {
super();
this.results = results;
this.setBtfs_list(btfs_list);
this.rscount = rscount;
}
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public int getRscount() {
return rscount;
}
public void setRscount(int rscount) {
this.rscount = rscount;
}
public void setBtfs_list(List<BottleFriendEntry> btfs_list) {
this.btfs_list = btfs_list;
}
public List<BottleFriendEntry> getBtfs_list() {
return btfs_list;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
public class BottleTimelineInfo {
private ResponseResult results;
private BottleTimelineShowTipsEntry showtips;
private List<BottleEntry> bts_list;
private int bts_count;
public BottleTimelineInfo(){
}
public BottleTimelineInfo(ResponseResult results,BottleTimelineShowTipsEntry showtips,List<BottleEntry> bts_list,int bts_count){
this.results = results;
this.showtips = showtips;
this.bts_list = bts_list;
this.bts_count = bts_count;
}
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public BottleTimelineShowTipsEntry getShowtips() {
return showtips;
}
public void setShowtips(BottleTimelineShowTipsEntry showtips) {
this.showtips = showtips;
}
public List<BottleEntry> getBts_list() {
return bts_list;
}
public void setBts_list(List<BottleEntry> bts_list) {
this.bts_list = bts_list;
}
public int getBts_count() {
return bts_count;
}
public void setBts_count(int bts_count) {
this.bts_count = bts_count;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class UserBtLevelEntry {
private int credit;
private int exp;
private int ttcredit;
private int ttexp;
private String level_url;
private int show_upgrade;
public int getCredit() {
return credit;
}
public void setCredit(int credit) {
this.credit = credit;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getTtcredit() {
return ttcredit;
}
public void setTtcredit(int ttcredit) {
this.ttcredit = ttcredit;
}
public int getTtexp() {
return ttexp;
}
public void setTtexp(int ttexp) {
this.ttexp = ttexp;
}
public String getLevel_url() {
return level_url;
}
public void setLevel_url(String level_url) {
this.level_url = level_url;
}
public int getShow_upgrade() {
return show_upgrade;
}
public void setShow_upgrade(int show_upgrade) {
this.show_upgrade = show_upgrade;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class BottleFeedEntry {
private int feed_uid;
private int feed_type;
private String feed_nickname;
private String feed_avatar;
private String feed_content;
/*************新增*******************/
private String feed_replycomment;
private String feed_commentpic;
private String feed_commentpic_big;
private String feed_commentpic_tuya;
/********************************/
private String feed_time;
private String feed_location;
private int feed_isnew;
private float feed_lng;
private float feed_lat;
public int getFeed_uid() {
return feed_uid;
}
public void setFeed_uid(int feed_uid) {
this.feed_uid = feed_uid;
}
public int getFeed_type() {
return feed_type;
}
public void setFeed_type(int feed_type) {
this.feed_type = feed_type;
}
public String getFeed_nickname() {
return feed_nickname;
}
public void setFeed_nickname(String feed_nickname) {
this.feed_nickname = feed_nickname;
}
public String getFeed_avatar() {
return feed_avatar;
}
public void setFeed_avatar(String feed_avatar) {
this.feed_avatar = feed_avatar;
}
public String getFeed_content() {
return feed_content;
}
public void setFeed_content(String feed_content) {
this.feed_content = feed_content;
}
public String getFeed_time() {
return feed_time;
}
public void setFeed_time(String feed_time) {
this.feed_time = feed_time;
}
public String getFeed_location() {
return feed_location;
}
public void setFeed_location(String feed_location) {
this.feed_location = feed_location;
}
public float getFeed_lng() {
return feed_lng;
}
public void setFeed_lng(float feed_lng) {
this.feed_lng = feed_lng;
}
public float getFeed_lat() {
return feed_lat;
}
public void setFeed_lat(float feed_lat) {
this.feed_lat = feed_lat;
}
public int getFeed_isnew() {
return feed_isnew;
}
public void setFeed_isnew(int feed_isnew) {
this.feed_isnew = feed_isnew;
}
public String getFeed_replycomment() {
return feed_replycomment;
}
public void setFeed_replycomment(String feed_replycomment) {
this.feed_replycomment = feed_replycomment;
}
public String getFeed_commentpic() {
return feed_commentpic;
}
public void setFeed_commentpic(String feed_commentpic) {
this.feed_commentpic = feed_commentpic;
}
public String getFeed_commentpic_big() {
return feed_commentpic_big;
}
public void setFeed_commentpic_big(String feed_commentpic_big) {
this.feed_commentpic_big = feed_commentpic_big;
}
public String getFeed_commentpic_tuya() {
return feed_commentpic_tuya;
}
public void setFeed_commentpic_tuya(String feed_commentpic_tuya) {
this.feed_commentpic_tuya = feed_commentpic_tuya;
}
}
| Java |
package com.outsourcing.bottle.domain;
/**
*
* @author 06peng
*
*/
public class ShowtipsEntry {
private String show_config;
public String getShow_config() {
return show_config;
}
public void setShow_config(String show_config) {
this.show_config = show_config;
}
}
| Java |
package com.outsourcing.bottle.domain;
public class BottleFeedLocationEntry {
private int feed_uid;
private String feed_nickname;
private String feed_avatar;
private String feed_content;
private String feed_time;
private String feed_location;
private int feed_isnew;
private float feed_lng;
private float feed_lat;
private int location_delete_enable;
public int getLocation_delete_enable() {
return location_delete_enable;
}
public void setLocation_delete_enable(int location_delete_enable) {
this.location_delete_enable = location_delete_enable;
}
public int getLocation_objtype() {
return location_objtype;
}
public void setLocation_objtype(int location_objtype) {
this.location_objtype = location_objtype;
}
public int getLocation_objid() {
return location_objid;
}
public void setLocation_objid(int location_objid) {
this.location_objid = location_objid;
}
private int location_objtype;
private int location_objid;
public int getFeed_uid() {
return feed_uid;
}
public void setFeed_uid(int feed_uid) {
this.feed_uid = feed_uid;
}
public String getFeed_nickname() {
return feed_nickname;
}
public void setFeed_nickname(String feed_nickname) {
this.feed_nickname = feed_nickname;
}
public String getFeed_avatar() {
return feed_avatar;
}
public void setFeed_avatar(String feed_avatar) {
this.feed_avatar = feed_avatar;
}
public String getFeed_content() {
return feed_content;
}
public void setFeed_content(String feed_content) {
this.feed_content = feed_content;
}
public String getFeed_time() {
return feed_time;
}
public void setFeed_time(String feed_time) {
this.feed_time = feed_time;
}
public String getFeed_location() {
return feed_location;
}
public void setFeed_location(String feed_location) {
this.feed_location = feed_location;
}
public float getFeed_lng() {
return feed_lng;
}
public void setFeed_lng(float feed_lng) {
this.feed_lng = feed_lng;
}
public float getFeed_lat() {
return feed_lat;
}
public void setFeed_lat(float feed_lat) {
this.feed_lat = feed_lat;
}
public int getFeed_isnew() {
return feed_isnew;
}
public void setFeed_isnew(int feed_isnew) {
this.feed_isnew = feed_isnew;
}
}
| Java |
package com.outsourcing.bottle.domain;
import java.util.List;
/**
*
* @author 06peng
*
*/
public class MyMessageInfo {
private ResponseResult results;
private List<MessageEntry> messages_list;
private OUserInfoEntry ouser_info;
private int rscount;
public ResponseResult getResults() {
return results;
}
public void setResults(ResponseResult results) {
this.results = results;
}
public List<MessageEntry> getMessages_list() {
return messages_list;
}
public void setMessages_list(List<MessageEntry> messages_list) {
this.messages_list = messages_list;
}
public int getRscount() {
return rscount;
}
public void setRscount(int rscount) {
this.rscount = rscount;
}
public MyMessageInfo() {
super();
}
public OUserInfoEntry getOuser_info() {
return ouser_info;
}
public void setOuser_info(OUserInfoEntry ouser_info) {
this.ouser_info = ouser_info;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.