code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.outsourcing.bottle.util;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
/**
*
* @author 06peng
*
*/
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl);
}
| Java |
package com.outsourcing.bottle.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import com.outsourcing.bottle.BasicActivity;
/**
*
* @author 06peng
*
*/
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public Thread.UncaughtExceptionHandler a;
public BasicActivity basicActivity;
public MyUncaughtExceptionHandler(BasicActivity basicActivity) {
this.a = Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
killProcess();
}
private void killProcess() {
String packageName = "com.outsourcing.bottle";
String processId = "";
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec("ps");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inline;
while ((inline = br.readLine()) != null) {
if (inline.contains(packageName)) {
break;
}
}
br.close();
StringTokenizer processInfoTokenizer = new StringTokenizer(inline);
int count = 0;
while (processInfoTokenizer.hasMoreTokens()) {
count++;
processId = processInfoTokenizer.nextToken();
if (count == 2) {
break;
}
}
r.exec("kill -15 " + processId);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import com.outsourcing.bottle.domain.LocationEntry;
/**
* 定位
* @author 06peng
*
*/
public class LocationUtil {
private Context context;
public double latitude;
public double longitude;
public LocationUtil(Context context) {
this.context = context;
}
public LocationEntry locate() {
LocationEntry entry = new LocationEntry();
requestTelLocation();
entry.setLatitude(latitude);
entry.setLongitude(longitude);
return entry;
}
private void requestTelLocation() {
try {
TelephonyManager mTelMan = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String operator = mTelMan.getNetworkOperator();
String mcc = operator.substring(0, 3);
String mnc = operator.substring(3);
GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
int cid = location.getCid();
int lac = location.getLac();
JSONObject tower = new JSONObject();
tower.put("cell_id", cid);
tower.put("location_area_code", lac);
tower.put("mobile_country_code", mcc);
tower.put("mobile_network_code", mnc);
System.out.println(">>>>>>>>>>>>>>>>" + tower.toString());
JSONArray array = new JSONArray();
array.put(tower);
List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
Iterator<NeighboringCellInfo> iter = list.iterator();
NeighboringCellInfo cellInfo;
JSONObject tempTower;
while (iter.hasNext()) {
cellInfo = iter.next();
tempTower = new JSONObject();
try {
tempTower.put("cell_id", cellInfo.getCid());
tempTower.put("location_area_code", cellInfo.getLac());
tempTower.put("mobile_country_code", mcc);
tempTower.put("mobile_network_code", mnc);
} catch (JSONException e) {
e.printStackTrace();
}
array.put(tempTower);
}
JSONObject object = createJSONObject("cell_towers", array);
requestLocation(object);
} catch (Exception e) {
e.printStackTrace();
}
}
private void requestLocation(JSONObject object) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
try {
StringEntity entity = new StringEntity(object.toString());
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuffer buffer = new StringBuffer();
String result = br.readLine();
while (result != null) {
buffer.append(result);
result = br.readLine();
}
JSONObject obj = new JSONObject(buffer.toString());
JSONObject locationObj = obj.getJSONObject("location");
latitude = locationObj.getDouble("latitude");
longitude = locationObj.getDouble("longitude");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private JSONObject createJSONObject(String arrayName, JSONArray array) {
JSONObject object = new JSONObject();
try {
object.put("version", "1.1.0");
object.put("host", "maps.google.com");
object.put(arrayName, array);
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ListView;
/**
*
* @author 06peng
*
*/
public class Utility {
private static final String TAG = Utility.class.getSimpleName();
/** apikey is required http://developers.aviary.com/ */
public static final String API_KEY = "xxxxx";
public static void setListViewHeightBasedOnChildren(ListView listView) {
Adapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
params.height += 60;
listView.setLayoutParams(params);
}
public static boolean isExternalStorageAvilable() {
String state = Environment.getExternalStorageState();
if ( Environment.MEDIA_MOUNTED.equals( state ) ) {
return true;
}
return false;
}
/**
* Return a new image file. Name is based on the current time. Parent folder will be the one created with createFolders
*
* @return
* @see #createFolders()
*/
@SuppressLint("NewApi")
public static File getNextFileName() {
File baseDir = Environment.getExternalStorageDirectory();
// if ( android.os.Build.VERSION.SDK_INT < 8 ) {
// baseDir = Environment.getExternalStorageDirectory();
// } else {
// baseDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES );
// }
if ( baseDir == null ) return Environment.getExternalStorageDirectory();
Log.d( TAG, "Pictures folder: " + baseDir.getAbsolutePath() );
File aviaryFolder = new File( baseDir, AppContext.EDITIMG_PATH );
if(aviaryFolder.exists()){
return new File( aviaryFolder, "upload.jpeg" );
}else {
aviaryFolder.mkdir();
return new File( aviaryFolder, "upload.jpeg" );
}
}
public static String getTime(Date date) {
TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
Calendar calendar = Calendar.getInstance(t);
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int min = calendar.get(Calendar.MINUTE);
int ss = calendar.get(Calendar.SECOND);
String time = year + "-" + (month < 10 ? "0" : "") + month + '-'
+ (day < 10 ? "0" : "") + day + ' ' + (hour < 10 ? "0" : "")
+ hour + ':' + (min < 10 ? "0" : "") + min + ":"
+ (ss < 10 ? "0" : "") + ss;
return time;
}
public static String getDate() {
TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone
Calendar calendar = Calendar.getInstance(t);
calendar.setTimeInMillis(System.currentTimeMillis());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String date = year + "-" + (month < 10 ? "0" : "") + month + '-'
+ (day < 10 ? "0" : "") + day;
return date;
}
}
| Java |
package com.outsourcing.bottle.util;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.ui.HomeActivity;
/**
*
* @author 06peng
*
*/
public class BottleService extends Service {
private ServiceBinder serviceBinder = new ServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
@Override
public void onStart(Intent intent, int startId) {
showNotification(getString(R.string.app_name));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@SuppressWarnings("deprecation")
public void showNotification(String mes) {
CharSequence from = mes;
CharSequence message = "";
Intent intent;
if (AppContext.getContext() == null) {
intent = new Intent(this, HomeActivity.class);
}
else {
intent = new Intent(this, AppContext.getContext().getClass());
}
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, 0);
Notification notif = new Notification(R.drawable.logo, mes, System.currentTimeMillis());
notif.flags = Notification.FLAG_ONGOING_EVENT;
notif.setLatestEventInfo(this, from, message, contentIntent);
this.startForeground(R.drawable.logo, notif);
}
public class ServiceBinder extends Binder {
public BottleService getService() {
return BottleService.this;
}
}
}
| 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.outsourcing.bottle.util;
import java.io.Closeable;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.view.View.OnClickListener;
import com.aviary.android.feather.MonitoredActivity;
/**
* Collection of utility functions used in this package.
*/
public class Util {
public static final int DIRECTION_LEFT = 0;
public static final int DIRECTION_RIGHT = 1;
public static final int DIRECTION_UP = 2;
public static final int DIRECTION_DOWN = 3;
private static OnClickListener sNullOnClickListener;
private Util() {
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees,
(float) b.getWidth() / 2, (float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(
b, 0, 0, b.getWidth(), b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {
// We have no memory to rotate. Return the original bitmap.
}
}
return b;
}
/*
* Compute the sample size as a function of minSideLength
* and maxNumOfPixels.
* minSideLength is used to specify that minimal width or height of a
* bitmap.
* maxNumOfPixels is used to specify the maximal size in pixels that is
* tolerable in terms of memory usage.
*
* The function returns a sample size based on the constraints.
* Both size and minSideLength can be passed in as IImage.UNCONSTRAINED,
* which indicates no care of the corresponding constraint.
* The functions prefers returning a sample size that
* generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED.
*
* Also, the function rounds up the sample size to a power of 2 or multiple
* of 8 because BitmapFactory only honors sample size this way.
* For example, BitmapFactory downsamples an image by 2 even though the
* request is 3. So we round up the sample size to avoid OOM.
*/
// public static int computeSampleSize(BitmapFactory.Options options,
// int minSideLength, int maxNumOfPixels) {
// int initialSize = computeInitialSampleSize(options, minSideLength,
// maxNumOfPixels);
//
// int roundedSize;
// if (initialSize <= 8) {
// roundedSize = 1;
// while (roundedSize < initialSize) {
// roundedSize <<= 1;
// }
// } else {
// roundedSize = (initialSize + 7) / 8 * 8;
// }
//
// return roundedSize;
// }
// private static int computeInitialSampleSize(BitmapFactory.Options options,
// int minSideLength, int maxNumOfPixels) {
// double w = options.outWidth;
// double h = options.outHeight;
//
// int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 :
// (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
// int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 :
// (int) Math.min(Math.floor(w / minSideLength),
// Math.floor(h / minSideLength));
//
// if (upperBound < lowerBound) {
// // return the larger one when there is no overlapping zone.
// return lowerBound;
// }
//
// if ((maxNumOfPixels == IImage.UNCONSTRAINED) &&
// (minSideLength == IImage.UNCONSTRAINED)) {
// return 1;
// } else if (minSideLength == IImage.UNCONSTRAINED) {
// return lowerBound;
// } else {
// return upperBound;
// }
// }
// Whether we should recycle the input (unless the output is the input).
public static final boolean RECYCLE_INPUT = true;
public static final boolean NO_RECYCLE_INPUT = false;
public static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, boolean scaleUp, boolean recycle) {
int deltaX = source.getWidth() - targetWidth;
int deltaY = source.getHeight() - targetHeight;
if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
/*
* In this case the bitmap is smaller, at least in one dimension,
* than the target. Transform it by placing as much of the image
* as possible into the target and leaving the top/bottom or
* left/right (or both) black.
*/
Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b2);
int deltaXHalf = Math.max(0, deltaX / 2);
int deltaYHalf = Math.max(0, deltaY / 2);
Rect src = new Rect(deltaXHalf, deltaYHalf,
deltaXHalf + Math.min(targetWidth, source.getWidth()),
deltaYHalf + Math.min(targetHeight, source.getHeight()));
int dstX = (targetWidth - src.width()) / 2;
int dstY = (targetHeight - src.height()) / 2;
Rect dst = new Rect( dstX, dstY, targetWidth - dstX, targetHeight - dstY);
c.drawBitmap(source, src, dst, null);
if (recycle) {
source.recycle();
}
return b2;
}
float bitmapWidthF = source.getWidth();
float bitmapHeightF = source.getHeight();
float bitmapAspect = bitmapWidthF / bitmapHeightF;
float viewAspect = (float) targetWidth / targetHeight;
if (bitmapAspect > viewAspect) {
float scale = targetHeight / bitmapHeightF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
} else {
float scale = targetWidth / bitmapWidthF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
}
Bitmap b1;
if (scaler != null) {
// this is used for minithumb and crop, so we want to filter here.
b1 = Bitmap.createBitmap(source, 0, 0,
source.getWidth(), source.getHeight(), scaler, true);
} else {
b1 = source;
}
if (recycle && b1 != source) {
source.recycle();
}
int dx1 = Math.max(0, b1.getWidth() - targetWidth);
int dy1 = Math.max(0, b1.getHeight() - targetHeight);
Bitmap b2 = Bitmap.createBitmap( b1, dx1 / 2, dy1 / 2, targetWidth, targetHeight);
if (b2 != b1) {
if (recycle || b1 != source) {
b1.recycle();
}
}
return b2;
}
public static <T> int indexOf(T [] array, T s) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(s)) {
return i;
}
}
return -1;
}
public static void closeSilently(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// do nothing
}
}
public static void closeSilently(ParcelFileDescriptor c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// do nothing
}
}
/**
* Make a bitmap from a given Uri.
*
* @param uri
*/
// public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
// Uri uri, ContentResolver cr, boolean useNative) {
// ParcelFileDescriptor input = null;
// try {
// input = cr.openFileDescriptor(uri, "r");
// BitmapFactory.Options options = null;
// if (useNative) {
// options = createNativeAllocOptions();
// }
// return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, input,
// options);
// } catch (IOException ex) {
// return null;
// } finally {
// closeSilently(input);
// }
// }
// public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
// ParcelFileDescriptor pfd, boolean useNative) {
// BitmapFactory.Options options = null;
// if (useNative) {
// options = createNativeAllocOptions();
// }
// return makeBitmap(minSideLength, maxNumOfPixels, null, null, pfd,
// options);
// }
// public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
// Uri uri, ContentResolver cr, ParcelFileDescriptor pfd,
// BitmapFactory.Options options) {
// try {
// if (pfd == null) pfd = makeInputStream(uri, cr);
// if (pfd == null) return null;
// if (options == null) options = new BitmapFactory.Options();
//
// FileDescriptor fd = pfd.getFileDescriptor();
// options.inJustDecodeBounds = true;
// BitmapManager.instance().decodeFileDescriptor(fd, options);
// if (options.mCancel || options.outWidth == -1
// || options.outHeight == -1) {
// return null;
// }
// options.inSampleSize = computeSampleSize(
// options, minSideLength, maxNumOfPixels);
// options.inJustDecodeBounds = false;
//
// options.inDither = false;
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// return BitmapManager.instance().decodeFileDescriptor(fd, options);
// } catch (OutOfMemoryError ex) {
// Log.e(TAG, "Got oom exception ", ex);
// return null;
// } finally {
// closeSilently(pfd);
// }
// }
// private static ParcelFileDescriptor makeInputStream(
// Uri uri, ContentResolver cr) {
// try {
// return cr.openFileDescriptor(uri, "r");
// } catch (IOException ex) {
// return null;
// }
// }
public static synchronized OnClickListener getNullOnClickListener() {
if (sNullOnClickListener == null) {
sNullOnClickListener = new OnClickListener() {
public void onClick(View v) {
}
};
}
return sNullOnClickListener;
}
public static void Assert(boolean cond) {
if (!cond) {
throw new AssertionError();
}
}
public static boolean equals(String a, String b) {
// return true if both string are null or the content equals
return a == b || a.equals(b);
}
private static class BackgroundJob
extends MonitoredActivity.LifeCycleAdapter implements Runnable {
private final MonitoredActivity mActivity;
private final ProgressDialog mDialog;
private final Runnable mJob;
private final Handler mHandler;
private final Runnable mCleanupRunner = new Runnable() {
public void run() {
mActivity.removeLifeCycleListener(BackgroundJob.this);
if (mDialog.getWindow() != null) mDialog.dismiss();
}
};
public BackgroundJob(MonitoredActivity activity, Runnable job,
ProgressDialog dialog, Handler handler) {
mActivity = activity;
mDialog = dialog;
mJob = job;
mActivity.addLifeCycleListener(this);
mHandler = handler;
}
public void run() {
try {
mJob.run();
} finally {
mHandler.post(mCleanupRunner);
}
}
@Override
public void onActivityDestroyed(MonitoredActivity activity) {
// We get here only when the onDestroyed being called before
// the mCleanupRunner. So, run it now and remove it from the queue
mCleanupRunner.run();
mHandler.removeCallbacks(mCleanupRunner);
}
@Override
public void onActivityStopped(MonitoredActivity activity) {
mDialog.hide();
}
@Override
public void onActivityStarted(MonitoredActivity activity) {
mDialog.show();
}
}
public static void startBackgroundJob(MonitoredActivity activity,
String title, String message, Runnable job, Handler handler) {
// Make the progress dialog uncancelable, so that we can gurantee
// the thread will be done before the activity getting destroyed.
ProgressDialog dialog = ProgressDialog.show(
activity, title, message, true, false);
new Thread(new BackgroundJob(activity, job, dialog, handler)).start();
}
// // Returns an intent which is used for "set as" menu items.
// public static Intent createSetAsIntent(IImage image) {
// Uri u = image.fullSizeImageUri();
// Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
// intent.setDataAndType(u, image.getMimeType());
// intent.putExtra("mimeType", image.getMimeType());
// return intent;
// }
//
// // Returns Options that set the puregeable flag for Bitmap decode.
// public static BitmapFactory.Options createNativeAllocOptions() {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inNativeAlloc = true;
// return options;
// }
}
| Java |
package com.outsourcing.bottle.util;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));// Last
// argument
// true
// for
// LRU
// ordering
private long size = 0;// current allocated size
private long limit = 1000000;// max memory in bytes
public MemoryCache() {
// use 25% of available heap size
// setLimit(Runtime.getRuntime().maxMemory()/4);
setLimit(Runtime.getRuntime().maxMemory() / 8);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit + " long");
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
// NullPointerException sometimes happen here
// http://code.google.com/p/osmdroid/issues/detail?id=78
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();// least
// recently
// accessed
// item
// will
// be
// the
// first
// one
// iterated
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
cache.clear();
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
} | Java |
package com.outsourcing.bottle.util;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.SplashActivity;
import com.outsourcing.bottle.domain.PlatformBindConfig;
/**
*
* @author 06peng
*
*/
public class HttpUtils {
private static final String tag = HttpUtils.class.getSimpleName();
/**
* POST请求
* @param mContext
* @param url
* @param paramsMap
* @return
*/
public static String doPost(Context mContext, String url, Map<String, String> paramsMap) {
BaseHttpClient client = BaseHttpClient.newInstance(mContext, tag);
HttpPost request = null;
InputStream entityStream = null;
String result = null;
try {
request = new HttpPost(url);
paramsMap.put("sitekey", PlatformBindConfig.Sitekey);
paramsMap.put("clitype", "2");
paramsMap.put("language", String.valueOf(AppContext.language));
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> m : paramsMap.entrySet()) {
params.add(new BasicNameValuePair(m.getKey(), m.getValue()));
}
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.d(tag, "request-url="+url + (params != null ? params.toString() : null));
// LogUtils.fileLog(url, "参数:" + (params != null ? params.toString() : null));
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
entityStream = response.getEntity().getContent();
result = convertStreamToString(entityStream);
}
Log.d(tag, "request-statusCode=" + statusCode);
} catch (Exception e) {
request.abort();
e.printStackTrace();
} finally {
closeStream(entityStream);
closeClient(client);
}
Log.d(tag, "result="+result);
// LogUtils.fileLog(url, "返回结果:" + result);
return result;
}
public static String doGet(String path) throws Exception {
if (AppContext.getContext() instanceof BasicActivity) {
BasicActivity activity = (BasicActivity) AppContext.getContext();
if (!ServiceUtils.isConnectInternet(activity)) {
activity.onToast(activity.getString(R.string.connect_error));
return null;
}
} else if (AppContext.getContext() instanceof SplashActivity){
SplashActivity activity = (SplashActivity) AppContext.getContext();
if (!ServiceUtils.isConnectInternet(activity)) {
activity.onToast(activity.getString(R.string.connect_error));
return null;
}
}
InputStream inStream = null;
String result = null;
HttpGet httpRequest = new HttpGet(path);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 6000);
HttpResponse httpResponse = httpClient.execute(httpRequest);
System.out.println("doGet path:" + path);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
inStream = httpResponse.getEntity().getContent();
result = new String(ServiceUtils.readStream(inStream));
} else {
throw new Exception("conn exception");
}
// LogUtils.fileLog(path + "请求结果", result);
return result;
}
/**
* multipart/form-data
* @param actionUrl
* @param params
* @param files
* @return
* @throws Exception
*/
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws Exception {
BasicActivity activity = (BasicActivity) AppContext.getContext();
if (!ServiceUtils.isConnectInternet(activity)) {
activity.onToast(activity.getString(R.string.connect_error));
return null;
}
Log.d(tag, "request-url=" + actionUrl);
String result = null;
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(60 * 1000); // 缓存的最长时间
conn.setConnectTimeout(60 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
params.put("sitekey", PlatformBindConfig.Sitekey);
params.put("clitype", "2");
params.put("language", String.valueOf(AppContext.language));
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
Log.i("httptest","test"+sb.toString());
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
Log.i("httptest","testend");
InputStream in = null;
// 发送文件数据
if (files != null) {
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"upload.jpg\"" + LINEND);
sb1.append("Content-Type: image/jpeg; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
Log.i("httptest:pic","test"+sb1.toString());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
}
// 得到响应码
int res = conn.getResponseCode();
Log.i(tag, res + "-----------------1");
if (res == 200) {
in = conn.getInputStream();
result = HttpUtils.convertStreamToString(in);
}
outStream.close();
conn.disconnect();
Log.d(tag, "result="+result);
return result;
}
/**
* 请求图片
*
* @param mContext
* @param url
* @return
*/
public static Bitmap getBitmapFromUrl(Context mContext, String url) {
BasicActivity activity = (BasicActivity) AppContext.getContext();
if (!ServiceUtils.isConnectInternet(activity)) {
activity.onToast(activity.getString(R.string.connect_error));
return null;
}
BaseHttpClient client = BaseHttpClient.newInstance(mContext, tag);
HttpGet request = null;
InputStream ins = null;
try {
request = new HttpGet(url);
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
ins = response.getEntity().getContent();
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
return BitmapFactory.decodeStream(ins, null, opt);
}
} catch (Exception e) {
request.abort();
e.printStackTrace();
return null;
} finally {
closeStream(ins);
closeClient(client);
}
return null;
}
/**
* 请求地图图片
*
* @param mContext
* @param url
* @return
*/
public static Bitmap getMapBitmapFromUrl(Context mContext, String url) {
BasicActivity activity = (BasicActivity) AppContext.getContext();
if (!ServiceUtils.isConnectInternet(activity)) {
activity.onToast(activity.getString(R.string.connect_error));
return null;
}
BaseHttpClient client = BaseHttpClient.newInstance(mContext, tag);
HttpGet request = null;
InputStream ins = null;
try {
request = new HttpGet(url);
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
ins = response.getEntity().getContent();
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
opt.inPurgeable = true;
opt.inInputShareable = true;
return BitmapFactory.decodeStream(ins, null, opt);
}
} catch (Exception e) {
request.abort();
e.printStackTrace();
return null;
} finally {
closeStream(ins);
closeClient(client);
}
return null;
}
private static void closeClient(BaseHttpClient client) {
if (client != null) {
client.close();
client = null;
}
}
static String convertStreamToString(InputStream is) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8 * 1024);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
sb.delete(0, sb.length());
} finally {
closeStream(is);
}
return sb.toString();
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.UUID;
import java.util.Vector;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class FileManager {
/**
* 添加日志
* @param str
* @return
*/
public synchronized static boolean addLog(String str)
{
str=Utility.getTime(new Date(System.currentTimeMillis()))+"--------------->:"+str;
System.out.println(str);
str=str+" \n";
FileOperation fp = null;
try{
fp = new FileOperation("Log", null);
fp.initFile(Utility.getDate()+"log");
if(fp.extraAddLine(str.getBytes()))
{
System.gc();
return true;
}else {
System.gc();
return false;
}
}catch (OutOfMemoryError error) {
error.printStackTrace();
return false;
} catch(Exception e)
{
e.printStackTrace();
return false;
}finally
{
if(fp!=null)
{
fp.closeFile();
}
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.android.ShellCommand;
import com.android.ShellCommand.CommandResult;
import com.outsourcing.bottle.R;
/**
*
* @author 06peng
*
*/
public class CrashHandler implements UncaughtExceptionHandler {
/** Debug Log tag */
public static final String TAG = "CrashHandler";
/**
* 是否开启日志输出,在Debug状态下开启, 在Release状态下关闭以提示程序性能
* */
public static final boolean DEBUG = true;
/** 系统默认的UncaughtException处理类 */
private Thread.UncaughtExceptionHandler mDefaultHandler;
/** CrashHandler实例 */
private static CrashHandler INSTANCE;
/** 程序的Context对象 */
private Context mContext;
/** 保证只有一个CrashHandler实例 */
private CrashHandler() {
}
public static final String UPLOADED = "uploaded";// 已上传
/** 获取CrashHandler实例 ,单例模式 */
public static CrashHandler getInstance() {
if (INSTANCE == null) {
INSTANCE = new CrashHandler();
}
return INSTANCE;
}
/**
* 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
*
* @param ctx
*/
public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
// Sleep一会后结束程序
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e(TAG, "Error : ", e);
}
ActivityManager.finishAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return true;
}
// 使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, mContext.getString(R.string.system_error), Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
// 保存错误报告文件
ex.printStackTrace();
saveCrashInfoToFile();
return true;
}
/**
* 保存错误报告文件
*/
public void saveCrashInfoToFile() {
try {
File file = new File(android.os.Environment
.getExternalStorageDirectory().getPath() + "/" + AppContext.SD_PATH + "/crashlog/");
if (!file.exists()) {
file.mkdirs();
}
file = null;
} catch (Exception e) {
e.printStackTrace();
}
ShellCommand sc = new ShellCommand();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Date curDate = new Date(System.currentTimeMillis());
String str = formatter.format(curDate);
CommandResult cr = sc.normal.runWaitFor("logcat -d *:W/System.err >> " + str + ".txt");
System.out.println("command result>>>" + cr.exit_value);
if (cr.success()) {
try {
File file = new File(android.os.Environment.getExternalStorageDirectory().getPath()
+ "/" + AppContext.SD_PATH + "/crashlog/" + str + ".txt");
if (!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(("T3;" + new SimpleDateFormat("yyyyMMddHHmm").format(System.currentTimeMillis()) + ';'
+ AppContext.getInstance().getLogin_uid() + "/" + str + ":" + cr.stdout).getBytes());
fos.flush();
fos.close();
file = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} | Java |
package com.outsourcing.bottle.util;
/**
*
* @author 06peng
*
*/
public class StringUtil {
/**
* 把字符串数组用逗号隔开
* @param arrays
* @return
*/
public static String ArraysToString(String[] arrays) {
String result = "";
if (arrays != null && arrays.length > 0) {
for (String value : arrays) {
result += value + ",";
}
result = result.substring(0, result.length() - 1);
}
return result;
}
public static String intArraysToString(int[] arrays) {
String result = "";
if (arrays != null && arrays.length > 0) {
for (int value : arrays) {
result += value + " ";
}
result = result.substring(0, result.length() - 1);
}
return result;
}
public static boolean isBlank(String str) {
return str == null || str.equals("");
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
}
| Java |
package com.outsourcing.bottle.util;
import android.app.Service;
import android.content.DialogInterface;
import com.outsourcing.bottle.BasicActivity;
/**
*
* @author 06peng
*
*/
public final class CommandTaskEvent extends CommandTask<Object, Object, Object> {
BasicUIEvent uiEvent;
BasicActivity context;
String tips;
public CommandTaskEvent(BasicUIEvent basicUIEvent, BasicActivity context, String tips) {
uiEvent = basicUIEvent;
this.context = context;
this.tips = tips;
}
@Override
public Object doInBackground(Object... params) {
uiEvent.execute(Integer.parseInt(params[0].toString()),params[1]);
return null;
}
Service service;
public CommandTaskEvent(BasicUIEvent basicUIEvent,Service service) {
uiEvent = basicUIEvent;
this.service=service;
}
public void onPreExecute() {
super.onPreExecute();
if (tips != null && context != null) {
context.loading(tips);
context.dialog
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// 取消事件监听, 同时取消现场访问
if (!isCancelled()) {
cancel(true);
}
}
});
}
}
@Override
public void onPostExecute(Object result) {
super.onPostExecute(result);
if (tips != null) {
if (context != null && !context.isFinishing()) {
context.destroyDialog();
}
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.outsourcing.bottle.BasicActivity;
public class ImageLoader {
private int mThumbSize;
private static final String TAG = ImageLoader.class.getSimpleName();
MemoryCache memoryCache = new MemoryCache();
public ImageFileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context, String path) {
fileCache = new ImageFileCache(context, path);
executorService = Executors.newFixedThreadPool(10);
}
// final int stub_id = R.drawable.stub;
public void DisplayImage(String url, ImageView imageView, int stub_id) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null){
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} else {
queuePhoto(url, imageView, stub_id);
imageView.setImageResource(stub_id);
imageView.invalidate();
}
}
public void DisplayImage(String url, ImageView imageView,int stub_id, int mThumbSize) {
this.mThumbSize = mThumbSize;
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} else {
queuePhoto(url, imageView,stub_id);
imageView.setImageResource(stub_id);
imageView.invalidate();
}
}
private void queuePhoto(String url, ImageView imageView, int stub_id) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p, stub_id));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null){
ServiceUtils.dout(TAG + " from SD cache:"+url);
return b;
}
Bitmap bitmap = null;
// from web
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
ServiceUtils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
if (null != bitmap) {
ServiceUtils.dout(TAG + " getBitmap by url");
}
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return bitmap;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
Bitmap bitmap = null;
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return bitmap= BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
return bitmap;
}
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
int stub_id;
PhotosLoader(PhotoToLoad photoToLoad, int stub_id) {
this.stub_id = stub_id;
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
if (mThumbSize != 0) {
bmp = BitmapUtils.resizeBitmap(bmp, mThumbSize, mThumbSize);
}
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad,stub_id);
// Activity a = (Activity) photoToLoad.imageView.getContext();
((BasicActivity) AppContext.getContext()).runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
int stub_id;
public BitmapDisplayer(Bitmap b, PhotoToLoad p, int stub_id) {
this.stub_id = stub_id;
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null) {
photoToLoad.imageView.setImageBitmap(bitmap);
// photoToLoad.imageView.requestFocus();
// photoToLoad.imageView.requestFocusFromTouch();
photoToLoad.imageView.invalidate();
ServiceUtils.dout("BitmapDisplayer :imageView.setImageBitmap");
} else {
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
* 实现图片的异步载入显示
* @author 06peng
*
*/
public class AsyncImageLoader {
/**
* 软引用对象,在响应内存需要时,由垃圾回收器决定是否清除此对象。软引用对象最常用于实现内存敏感的缓存。
*/
private HashMap<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imageUrl, final ImageView imageView, final ImageCallback imagecallback){
if(imageCache.containsKey(imageUrl)){
//从缓存中读取
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if(drawable != null){
return drawable;
}
}
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
imagecallback.imageLoaded((Drawable)msg.obj, imageView, imageUrl);
}
};
new Thread(){
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
public static Drawable loadImageFromUrl(String urlPath){
URL url;
InputStream is = null;
try{
url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
is = conn.getInputStream();
}catch(Exception e){
e.printStackTrace();
}
Drawable drawable = Drawable.createFromStream(is, "src");
return drawable;
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.outsourcing.bottle.util;
// NOTE: upstream of this class is android.util.LruCache, changes below
// expose trimToSize() to be called externally.
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Static library version of {@link android.util.LruCache}. Used to write apps
* that run on API levels prior to 12. When running on API level 12 or above,
* this implementation is still used; it does not try to switch to the
* framework's implementation. See the framework SDK documentation for a class
* overview.
*/
public class LruCache<K, V> {
private final LinkedHashMap<K, V> map;
/** Size of this cache in units. Not necessarily the number of elements. */
private int size;
private int maxSize;
private int putCount;
private int createCount;
private int evictionCount;
private int hitCount;
private int missCount;
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this cache.
*/
public LruCache(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
this.maxSize = maxSize;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
}
/**
* Returns the value for {@code key} if it exists in the cache or can be
* created by {@code #create}. If a value was returned, it is moved to the
* head of the queue. This returns null if a value is not cached and cannot
* be created.
*/
public final V get(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
mapValue = map.get(key);
if (mapValue != null) {
hitCount++;
return mapValue;
}
missCount++;
}
/*
* Attempt to create a value. This may take a long time, and the map
* may be different when create() returns. If a conflicting value was
* added to the map while create() was working, we leave that value in
* the map and release the created value.
*/
V createdValue = create(key);
if (createdValue == null) {
return null;
}
synchronized (this) {
createCount++;
mapValue = map.put(key, createdValue);
if (mapValue != null) {
// There was a conflict so undo that last put
map.put(key, mapValue);
} else {
size += safeSizeOf(key, createdValue);
}
}
if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
trimToSize(maxSize);
return createdValue;
}
}
/**
* Caches {@code value} for {@code key}. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by {@code key}.
*/
public final V put(K key, V value) {
if (key == null || value == null) {
throw new NullPointerException("key == null || value == null");
}
V previous;
synchronized (this) {
putCount++;
size += safeSizeOf(key, value);
previous = map.put(key, value);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);
return previous;
}
/**
* @param maxSize the maximum size of the cache before returning. May be -1
* to evict even 0-sized elements.
*/
public void trimToSize(int maxSize) {
while (true) {
K key;
V value;
synchronized (this) {
if (size < 0 || (map.isEmpty() && size != 0)) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
if (size <= maxSize || map.isEmpty()) {
break;
}
Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
/**
* Removes the entry for {@code key} if it exists.
*
* @return the previous value mapped by {@code key}.
*/
public final V remove(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V previous;
synchronized (this) {
previous = map.remove(key);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, null);
}
return previous;
}
/**
* Called for entries that have been evicted or removed. This method is
* invoked when a value is evicted to make space, removed by a call to
* {@link #remove}, or replaced by a call to {@link #put}. The default
* implementation does nothing.
*
* <p>The method is called without synchronization: other threads may
* access the cache while this method is executing.
*
* @param evicted true if the entry is being removed to make space, false
* if the removal was caused by a {@link #put} or {@link #remove}.
* @param newValue the new value for {@code key}, if it exists. If non-null,
* this removal was caused by a {@link #put}. Otherwise it was caused by
* an eviction or a {@link #remove}.
*/
protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}
/**
* Called after a cache miss to compute a value for the corresponding key.
* Returns the computed value or null if no value can be computed. The
* default implementation returns null.
*
* <p>The method is called without synchronization: other threads may
* access the cache while this method is executing.
*
* <p>If a value for {@code key} exists in the cache when this method
* returns, the created value will be released with {@link #entryRemoved}
* and discarded. This can occur when multiple threads request the same key
* at the same time (causing multiple values to be created), or when one
* thread calls {@link #put} while another is creating a value for the same
* key.
*/
protected V create(K key) {
return null;
}
private int safeSizeOf(K key, V value) {
int result = sizeOf(key, value);
if (result < 0) {
throw new IllegalStateException("Negative size: " + key + "=" + value);
}
return result;
}
/**
* Returns the size of the entry for {@code key} and {@code value} in
* user-defined units. The default implementation returns 1 so that size
* is the number of entries and max size is the maximum number of entries.
*
* <p>An entry's size must not change while it is in the cache.
*/
protected int sizeOf(K key, V value) {
return 1;
}
/**
* Clear the cache, calling {@link #entryRemoved} on each removed entry.
*/
public final void evictAll() {
trimToSize(-1); // -1 will evict 0-sized elements
}
/**
* For caches that do not override {@link #sizeOf}, this returns the number
* of entries in the cache. For all other caches, this returns the sum of
* the sizes of the entries in this cache.
*/
public synchronized final int size() {
return size;
}
/**
* For caches that do not override {@link #sizeOf}, this returns the maximum
* number of entries in the cache. For all other caches, this returns the
* maximum sum of the sizes of the entries in this cache.
*/
public synchronized final int maxSize() {
return maxSize;
}
/**
* Returns the number of times {@link #get} returned a value.
*/
public synchronized final int hitCount() {
return hitCount;
}
/**
* Returns the number of times {@link #get} returned null or required a new
* value to be created.
*/
public synchronized final int missCount() {
return missCount;
}
/**
* Returns the number of times {@link #create(Object)} returned a value.
*/
public synchronized final int createCount() {
return createCount;
}
/**
* Returns the number of times {@link #put} was called.
*/
public synchronized final int putCount() {
return putCount;
}
/**
* Returns the number of values that have been evicted.
*/
public synchronized final int evictionCount() {
return evictionCount;
}
/**
* Returns a copy of the current contents of the cache, ordered from least
* recently accessed to most recently accessed.
*/
public synchronized final Map<K, V> snapshot() {
return new LinkedHashMap<K, V>(map);
}
@Override public synchronized final String toString() {
int accesses = hitCount + missCount;
int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;
return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
maxSize, hitCount, missCount, hitPercent);
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Log;
/**
*
* @author 06peng
*
*/
public class ImageThumbnail {
private static final String TAG = ImageThumbnail.class.getSimpleName();
//计算缩放比
public static float reckonThumbnail(int oldWidth, int oldHeight, int newWidth, int newHeight) {
if ((oldHeight > newHeight && oldWidth > newWidth)
|| (oldHeight <= newHeight && oldWidth > newWidth)) {
float be = (float) (oldWidth / (float) newWidth);
if (be <= 1)
be = 1;
return be;
} else if (oldHeight > newHeight && oldWidth <= newWidth) {
float be = (float) (oldHeight / (float) newHeight);
if (be <= 1)
be = 1;
return be;
}
return 1;
}
/**
* @param photoPath --原图路经
* @param aFile --保存缩图
* @param newWidth --缩图宽度
* @param newHeight --缩图高度
*/
public static boolean bitmapToFile(String photoPath, File aFile, int newWidth, int newHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
options.inJustDecodeBounds = false;
//计算缩放比
options.inSampleSize = (int) reckonThumbnail(options.outWidth, options.outHeight, newWidth, newHeight);
bitmap = BitmapFactory.decodeFile(photoPath, options);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] photoBytes = baos.toByteArray();
if (aFile.exists()) {
aFile.delete();
}
aFile.createNewFile();
FileOutputStream fos = new FileOutputStream(aFile);
fos.write(photoBytes);
fos.flush();
fos.close();
return true;
} catch (Exception e1) {
e1.printStackTrace();
if (aFile.exists()) {
aFile.delete();
}
Log.e("Bitmap To File Fail", e1.toString());
return false;
}
}
public static Bitmap PicZoom(Bitmap bmp, int width, int height) {
int bmpWidth = bmp.getWidth();
int bmpHeght = bmp.getHeight();
Matrix matrix = new Matrix();
matrix.postScale((float) width / bmpWidth, (float) height / bmpHeght);
return Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeght, matrix, true);
}
public static Bitmap bitmapZoom(Bitmap bitmap) {
Bitmap curBitmap = null;
double maxSize = 200.00; //图片允许最大空间 (KB)
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bitmapStream);
double curBitmapSize = bitmapStream.toByteArray().length / 1024;
//判断bitmap占用空间是否大于maxSize
if (curBitmapSize > maxSize) {
double scale = curBitmapSize / maxSize;
curBitmap = changeBitampSize(bitmap, bitmap.getWidth() / Math.sqrt(scale), bitmap.getHeight() / Math.sqrt(scale));
} else {
curBitmap = bitmap;
}
return curBitmap;
}
/***
* bgimage : 图片资源
* width : 目标宽度
* height : 目标高度
*/
public static Bitmap changeBitampSize(Bitmap bitmap, double width, double height) {
Matrix matrix = new Matrix();
// 获取这个图片的宽和高
float curWidth = bitmap.getWidth();
float curHeight = bitmap.getHeight();
// 计算宽高缩放率
float scaleWidth = ((float) width) / curWidth;
float scaleHeight = ((float) height) / curHeight;
// 缩放图片
matrix.postScale(scaleWidth, scaleHeight);
Bitmap curBitmap = Bitmap.createBitmap(bitmap, 0, 0, (int) curWidth, (int) curHeight, matrix, true);
return curBitmap;
}
/**
* 通过BitmapFactory.Options压缩图片
* @param inputStream1
* @param inputStream2
* @param requiredWidth
* @return
*/
public static Bitmap decodeStream(InputStream inputStream1,
InputStream inputStream2, int requiredWidth) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inPreferredConfig = Bitmap.Config.RGB_565;
BitmapFactory.decodeStream(inputStream1, null, o);
final int REQUIRED_SIZE = requiredWidth;
int width_tmp = o.outWidth;
int hight_tmp = o.outHeight;
inputStream1.close();
int scale = 2;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || hight_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
hight_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileManager.addLog(TAG+":decodeStream...>o2.inSampleSize:"+scale);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream2, null, o2);
inputStream2.close();
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param bmpOrg
* @param requestPx
* @param heightRequestFlag false不按高压缩,ture按高判断压缩
* @return
*/
public static Bitmap getCompressBmp(Bitmap bmpOrg, int requestPx, boolean heightRequestFlag) {
if (bmpOrg != null) {
int width = bmpOrg.getWidth();
int height = bmpOrg.getHeight();
if (width != requestPx) {
float wh = ((float) width) / height;
int newWidth = 0;
int newheight = 0;
if (heightRequestFlag) {
if (width > height) {
newWidth = requestPx;
newheight = (int) (newWidth / wh);
} else {
newheight = requestPx;
newWidth = (int) (newheight * wh);
}
} else {
newWidth = requestPx;
newheight = (int) (newWidth / wh);
}
float sw = ((float) newWidth) / width;
float sh = ((float) newheight) / height;
Matrix matrix = new Matrix();
matrix.postScale(sw, sh);
Bitmap resizeBitmap = Bitmap.createBitmap(bmpOrg, 0, 0, width, height, matrix, true);
if (!bmpOrg.isRecycled()) {
bmpOrg.recycle();
bmpOrg = null;
}
return resizeBitmap;
}
return bmpOrg;
}
return null;
}
/**
* Bitmap保存到本地
* @param bmpOrg
* @param fileDir
* @param fileName
* @param imageQuelity
* @throws Exception
*/
public static void compress(Context context, Bitmap bmpOrg,
int imageQuelity, String file) throws Exception {
bmpOrg.compress(Bitmap.CompressFormat.JPEG, imageQuelity,
new FileOutputStream(file));
}
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {
ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
}
| Java |
package com.outsourcing.bottle.util;
import android.content.Context;
import android.text.TextUtils;
/**
*
* @author 06peng
*
*/
public class TextUtil {
public static Context ctx_for_getResString;
public static void setCtxForGetResString(Context ctx) {
ctx_for_getResString = ctx;
}
/**
* 获取res字符串资源
*
* @param ctx
* @param str
* @return
*/
public static String R(String str) {
if (ctx_for_getResString == null)
return str;
String rs = "";
int i = ctx_for_getResString.getResources().getIdentifier(str,
"string", ctx_for_getResString.getPackageName());
rs = ctx_for_getResString.getResources().getString(i);
return rs;
}
public static String htmlEncode(String s) {
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
switch (c) {
case '<':
sb.append("<"); //$NON-NLS-1$
break;
case '>':
sb.append(">"); //$NON-NLS-1$
break;
case '&':
sb.append("&"); //$NON-NLS-1$
break;
case '\'':
sb.append("'"); //$NON-NLS-1$
break;
case '"':
sb.append("""); //$NON-NLS-1$
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* 检测英文,数字,下划线
*
* @param Account
* @return
*/
public static boolean checkLoginAccount(String account) {
boolean valid = true;
if (TextUtils.isEmpty(account))
return false;
for (int i = 0; i < account.length(); i++) {
char ch = account.charAt(i);
if (Character.isLetterOrDigit(ch) || ch == '_') {
continue;
} else {
valid = false;
break;
}
}
return valid;
}
public static boolean isValidEmail(String email) {
if (TextUtils.isEmpty(email))
return false;
return email
.matches("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
}
public static boolean notEmpty(String str) {
if (str != null && !str.equals("")) {
return true;
} else {
return false;
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import com.outsourcing.bottle.BasicActivity;
/**
*
* @author 06peng
*
*/
public class ActivityManager {
private static List<Activity> activities = new ArrayList<Activity>();
public static synchronized void addActivity(Activity activity) {
activities.add(activity);
}
public static synchronized void removeActivity(Activity activity) {
activities.remove(activity);
}
public static final synchronized List<Activity> getActivities() {
return activities;
}
public static synchronized void finishAll() {
try {
for (Activity activity : activities) {
if (!(activity.isChild() || activity.isFinishing()))
((BasicActivity) activity).finishAll();
}
activities.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
/**
*
* @author 06peng
*
*/
public class CustomMultiPartEntity extends MultipartEntity {
private final ProgressListener listener;
public CustomMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public CustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out, final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.lang.ref.WeakReference;
import android.content.Context;
/**
* 全局类
*
* @author 06peng
*
*/
public class AppContext {
public static boolean FIRTH_INIT = false;
private int OAUTH_TYPE;
public static final int oauth_bind = 10011;
public static boolean auto_locate = false;
public int getOAUTH_TYPE() {
return OAUTH_TYPE;
}
public void setOAUTH_TYPE(int oAUTH_TYPE) {
OAUTH_TYPE = oAUTH_TYPE;
}
private static AppContext instance = new AppContext();
public static AppContext getInstance() {
if (instance == null) {
instance = new AppContext();
}
return instance;
}
public static final String UNAVAILABLE = "unavailable";
public static final String AVAILABLE = "available";
/**
* 获取 系统上下文
*/
private WeakReference<Context> context;
/**
* 获取 系统上下文
*
* @return
*/
public static Context getContext() {
if (getInstance().context == null) {
return null;
}
return getInstance().context.get();
}
/**
* 设置 系统上下文
*
* @return
*/
public static void setContext(Context contextx) {
getInstance().context = null;
getInstance().context = new WeakReference<Context>(contextx);
}
public static int language;
/**
* 1 CN
* 0 en
* @param language
*/
public static void setLanguage(int language) {
AppContext.language = language;
}
private double longitude = 0.0d;
private double latitude = 0.0d;
public static final int GPS_LOCATE_TIMEOUT = 1000001;
public static final int START_GPS_LOCATE = 1000002;
public static final int GPS_LOCATE_SUCCESS = 1000003;
public static final int NETWORK_LOCATE_SUCCESS = 1000004;
public static final String SD_PATH = "mobibottle";
public static final String EDITIMG_PATH = SD_PATH + "/upload";
/**瓶子类型相关图片路径*/
public static final String BOTTLE_CONFIG = SD_PATH + "/bottleconfig";
/**贴图目录相关图片路径*/
public static final String PasterDir = SD_PATH + "/bottleconfig/pasterdir";
/**Bottle Timeline相关图片路径*/
public static final String BottleTimelineIcon = SD_PATH + "/bttimeline";
/**用户头像缓存*/
public static final String UserAvatarIcon = SD_PATH + "/user_avatar";
private int login_uid;
private String login_token;
private String deviceId;
private int currentItem;
private boolean isFromExchangeTime;
private boolean isFromBottleTime;
private boolean isFromBtFriend;
private boolean isBottleDetailActNeedRefresh;
private String strImgUrlFromAviary;
public int getLogin_uid() {
return login_uid;
}
public void setLogin_uid(int login_uid) {
this.login_uid = login_uid;
}
public String getLogin_token() {
return login_token;
}
public void setLogin_token(String login_token) {
this.login_token = login_token;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public int getCurrentItem() {
return currentItem;
}
public void setCurrentItem(int currentItem) {
this.currentItem = currentItem;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
/**跳转到“选择用户”界面的类型*/
/**从“扔瓶子”跳转*/
public static final int CHOOSE_FRIEND_THROWBOTTLE_TYPE = 1;
/**从“交换资料”跳转*/
public static final int CHOOSE_FRIEND_EXCHANGE_INFO_TYPE = 2;
/**从“交换照片”跳转*/
public static final int CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE = 3;
/**从“转发瓶子给好友”跳转*/
public static final int CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE = 4;
/**转发照片给好友*/
public static final int CHOOSE_FRIEND_FORWARD_PHOTO_TYPE = 5;
public static final String SEND_BT = "send_bt"; //扔瓶子
public static final String REPLY_BT = "reply_bt"; //回复瓶子
public static final String COPYMANUAL_BT = "copymanual_bt"; //手动传递瓶子
public static final String TRANSMIT_BT = "transmit_bt"; //转载瓶子
public static final String REPLY_INFOEX = "reply_infoex"; //回应资料交换 包含了:回应资料交换、发起资料交换两个功能。
public static final String APPLY_PICEX = "apply_picex"; //发起照片交换
public static final String REPLY_PICEX = "reply_picex"; //回应照片交换 包含了回应照片交换、接受照片交换两个功能。
public static final String REPLYPIC_PICEX = "replypic_picex"; //回应照片交换中的照片
public static final String FORWARPIC_PICEX = "forwardpic_picex"; //转发照片交换中的照片
public static final String REPLY_PHOTO = "reply_photo"; //评论相册照片
public static final String REPLY_COMMENT = "reply_comment"; //回复评论
public static final String APPLY_FRIEND = "apply_friend"; //申请加好友
public static final String SEND_MESSAGE = "send_message"; //发表私信
public static final String ADD_ALBUM = "add_album"; //添加相册
public static final String EDIT_ALBUM = "edit_album"; //编辑相册
public static final String UPLOAD_PHOTO = "upload_photo"; //上传照片
public static final String EDIT_PHOTO = "edit_photo"; //编辑相册
public static final String EDIT_MEMO = "edit_memo"; //编辑用户备注
public static final String SET_DOING = "set_doing"; //设置心情
public static final String FORWARD_BT = "forward_bt";
public static final String FORWARD_PHOTO = "forward_photo";
public static final String PAINT_BT = "paint_bt";
public static final String PAINT_PICEX = "paint_picex";
public static final String PAINT_PHOTO = "paint_photo";
public void setFromBottleTime(boolean isFromBottleTime) {
this.isFromBottleTime = isFromBottleTime;
}
public boolean isFromBottleTime() {
return isFromBottleTime;
}
public void setFromExchangeTime(boolean isFromExchangeTime) {
this.isFromExchangeTime = isFromExchangeTime;
}
public boolean isFromExchangeTime() {
return isFromExchangeTime;
}
public void setFromBtFriend(boolean isFromBtFriend) {
this.isFromBtFriend = isFromBtFriend;
}
public boolean isFromBtFriend() {
return isFromBtFriend;
}
public void setFromExchangePicDetail(boolean fromExchangePicDetail) {
this.fromExchangePicDetail = fromExchangePicDetail;
}
public boolean isFromExchangePicDetail() {
return fromExchangePicDetail;
}
private boolean fromExchangePicDetail;
private boolean fromExchangeTimeToChangeFriend;
public boolean isFromExchangeTimeToChangeFriend() {
return fromExchangeTimeToChangeFriend;
}
public void setFromExchangeTimeToChangeFriend(boolean b) {
this.fromExchangeTimeToChangeFriend = b;
}
private boolean isFromExchangePicSession = false;
private boolean isFromBottleSingle = false;
public String getStrImgUrlFromAviary() {
return strImgUrlFromAviary;
}
public void setStrImgUrlFromAviary(String strImgUrlFromAviary) {
this.strImgUrlFromAviary = strImgUrlFromAviary;
}
private boolean gotoMaybeKown;
private boolean gotoMyfriend;
public boolean isGotoMaybeKown() {
return gotoMaybeKown;
}
public void setGotoMaybeKown(boolean gotoMaybeKown) {
this.gotoMaybeKown = gotoMaybeKown;
}
public boolean isGotoMyfriend() {
return gotoMyfriend;
}
public void setGoToMyfriend(boolean togoMyfriend) {
this.gotoMyfriend = togoMyfriend;
}
public boolean isBottleDetailActNeedRefresh() {
return isBottleDetailActNeedRefresh;
}
public void setBottleDetailActNeedRefresh(boolean isBottleDetailActNeedRefresh) {
this.isBottleDetailActNeedRefresh = isBottleDetailActNeedRefresh;
}
private boolean fromUserPhotoActivity = false;
public boolean isFromUserPhotoActivity() {
return fromUserPhotoActivity;
}
public void setFromUserPhotoActivity(boolean fromUserPhotoActivity) {
this.fromUserPhotoActivity = fromUserPhotoActivity;
}
public boolean isFromExchangePicSession() {
return isFromExchangePicSession;
}
public void setFromExchangePicSession(boolean isFromExchangePicSession) {
this.isFromExchangePicSession = isFromExchangePicSession;
}
public boolean isFromBottleSingle() {
return isFromBottleSingle;
}
public void setFromBottleSingle(boolean isFromBottleSingle) {
this.isFromBottleSingle = isFromBottleSingle;
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
/**
* Http连接的相关方法
* @author 林乐鹏
* @version 2011-05-26
*
*/
public class HttpUtil {
/**
* 发送http请求
* @param urlPath 请求路径
* @param requestType 请求类型
* @param requestParams 请求参数,如果没有参数,则为null
* @return
*/
public static String sendRequest(String urlPath, String requestType, String requestParams) {
URL url = null;
HttpURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
String result = null;
try {
url = new URL(urlPath);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setReadTimeout(10 * 1000);
conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
conn.setRequestProperty("Connection", "keep-alive");
os = conn.getOutputStream();
if (requestParams != null) {
os.write(requestParams.getBytes());
os.flush();
}
if (200 == conn.getResponseCode()) {
is = conn.getInputStream();
byte[] temp = readStream(is);
result = new String(temp);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static byte[] readStream(InputStream is) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
is.close();
return os.toByteArray();
}
/**
* 通过URL获取网络位图
*
* @param url
* @return
*/
public static BitmapDrawable getImage(String path) {
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
BitmapDrawable bmpDrawable = null;
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
bmpDrawable = new BitmapDrawable(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) conn.disconnect();
}
return bmpDrawable;
}
/**
* 根据图片路径下载图片并转化成Bitmap
* @param path
* @return
*/
public static Bitmap downImage(String path){
Bitmap bitmap = null;
try {
URL uri = new URL(path);
HttpURLConnection conn = (HttpURLConnection)uri.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 下载图片到SD卡
* @param imagePath
*/
public static void downLoadImageToSD(String imagePath){
URL url;
try {
url = new URL(imagePath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
File file = getFile(imagePath);
FileOutputStream fs = new FileOutputStream(file);
fs.write(data);
fs.close();
}else{
System.out.println("请求失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据文件名在SD卡创建目录
* @param path
* @return
*/
public static File getFile(String path){
String sdPath = Environment.getExternalStorageDirectory() + "/";
File dir = new File(sdPath + "mobi/download");
if(!dir.exists()){
dir.mkdirs();
}
File file = new File(dir + File.separator + path.substring(path.lastIndexOf("/") + 1));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
/**
* 判断是否存在网络问题
* @param activity
* @return
*/
public static boolean isConnectInternet(Activity activity) {
ConnectivityManager conManager=(ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
if(networkInfo != null){
return networkInfo.isAvailable();
}
return false;
}
public static interface HttpRequestErrorHandler {
void handleError(int actionId, Exception e);
}
}
| Java |
package com.outsourcing.bottle.util;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
/**
*
* @author 06peng
*
*/
public class LocationThread extends Thread {
private LocationManager lm;
private LocationListener locationListener = null;
final long TIMEOUT = 10000;
public BottleApplication app;
public boolean isrun = false;
private int iPos = 0;
/**
* 是否gps地位成功
*/
private boolean isGpsSendSuccess;
private Handler msgHandler;
private Looper waitingLoop;
public LocationThread(Handler msgHandler, LocationManager lm) {
this.msgHandler = msgHandler;
this.lm = lm;
msgHandler.sendEmptyMessage(AppContext.START_GPS_LOCATE);
}
@Override
public void run() {
FileManager.addLog("LocationThread run()--->start");
isGpsSendSuccess = false;
try {
Looper.prepare();
waitingLoop = Looper.myLooper();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (!isGpsSendSuccess) {
msgHandler.sendEmptyMessage(AppContext.GPS_LOCATE_TIMEOUT);
stopConnectionThread();
}
}
}, TIMEOUT);
System.out.println("send timeout");
GpsStatus.Listener statusListener = new GpsStatus.Listener() {
@Override
public void onGpsStatusChanged(int event) {
if (event == GpsStatus.GPS_EVENT_FIRST_FIX) {
} else if (event == GpsStatus.GPS_EVENT_STOPPED) {
} else if (event == GpsStatus.GPS_EVENT_STARTED) {
} else if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
GpsStatus mGpsStatus = lm.getGpsStatus(null);
Iterable<GpsSatellite> itGpsStatellites = mGpsStatus.getSatellites();
Iterator<GpsSatellite> it = itGpsStatellites.iterator();
iPos = 0;
while (it.hasNext()) {
iPos++;
}
FileManager.addLog(">>>>>>>>>>>>>>>>>>>>星数:" + iPos);
}
}
};
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
try {
if (location != null) {
if (AppContext.getInstance().getLongitude()!= location.getLongitude() || AppContext.getInstance().getLatitude() != location.getLatitude()) {
isGpsSendSuccess = true;
AppContext.getInstance().setLongitude(location.getLongitude());
AppContext.getInstance().setLatitude(location.getLatitude());
msgHandler.sendEmptyMessage(AppContext.GPS_LOCATE_SUCCESS);
stopConnectionThread();
FileManager.addLog("GpsSendSuccess===>long=" + location.getLongitude() + " lat:" + location.getLatitude());
}
}
} catch (Exception e) {
FileManager.addLog(getClass().getSimpleName()
+ ".java:onLocationChanged(Location location)" + " Exception=" + e.toString());
isGpsSendSuccess = false;
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
lm.addGpsStatusListener(statusListener);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 2, locationListener, waitingLoop);
Looper.loop();
lm.removeGpsStatusListener(statusListener);
lm.removeUpdates(locationListener);
FileManager.addLog(getClass().getSimpleName() + ".java:run() GpsDone");
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopConnectionThread() {
try {
FileManager.addLog(getClass().getSimpleName() + ": stopConnectionThread()");
if (waitingLoop != null) {
waitingLoop.quit();
waitingLoop = null;
}
} catch (Exception e) {
FileManager.addLog(getClass().getSimpleName()
+ ".java:stopConnectionThread()" + " Exception=" + e.toString());
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.ui.ExpandEditActivity;
import com.outsourcing.bottle.util.CustomMultiPartEntity.ProgressListener;
/**
* 提交数据
* @author 06peng
*
*/
public class SubmitTask extends AsyncTask<String, Integer, Integer> {
private static final String tag = SubmitTask.class.getSimpleName();
private ExpandEditActivity context;
private Handler handler;
private File mFile;
private Map<String, String> paramsMap;
private long totalSize;
private ProgressBar progressBar;
private AlertDialog alert;
private TextView tv;
public SubmitTask(ExpandEditActivity context, Handler handler, Map<String, String> paramsMap) {
this.context = context;
this.handler = handler;
this.paramsMap = paramsMap;
initParams();
}
public SubmitTask(ExpandEditActivity context, Handler handler, Map<String, String> paramsMap, File mFile) {
this.context = context;
this.handler = handler;
this.mFile = mFile;
this.paramsMap = paramsMap;
initParams();
}
private void initParams() {
paramsMap.put("sitekey", PlatformBindConfig.Sitekey);
paramsMap.put("clitype", "2");
paramsMap.put("language", String.valueOf(AppContext.language));
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mFile != null) {
LinearLayout ll = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.layout_load, null);
progressBar = (ProgressBar) ll.findViewById(R.id.down_pb);
tv = (TextView) ll.findViewById(R.id.tv);
Builder builder = new AlertDialog.Builder(context);
builder.setView(ll);
builder.setTitle(context.getString(R.string.uploading));
alert = builder.create();
alert.show();
} else {
((BasicActivity) context).loading("");
}
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mFile != null) {
alert.cancel();
} else {
((BasicActivity) context).destroyDialog();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
tv.setText(context.getString(R.string.processing) + values[0] + "%");
}
@Override
protected Integer doInBackground(String... arg0) {
String result = null;
try {
if (mFile != null) {
if (paramsMap.get("form_type").equals(AppContext.SEND_BT)) {
result = submitFileByEntity();
if (result != null) {
sendBtResult(result);
}
} else if (paramsMap.get("form_type").equals(AppContext.UPLOAD_PHOTO)) {
result = submitFileByEntity();
if (result != null) {
JSONObject object = new JSONObject(result);
JSONObject resultObj = object.getJSONObject("results");
int success = resultObj.getInt("success");
if (success == 0) {
String errmsg = resultObj.getString("errmsg");
Message msg = Message.obtain(handler, context.error, errmsg);
handler.sendMessage(msg);
} else {
String successmsg = resultObj.getString("successmsg");
context.picid = resultObj.getInt("picid");
Message msg = Message.obtain(handler, context.do_success, successmsg);
handler.sendMessage(msg);
}
}
} else {
result = submitFileByEntity();
submitResult(result);
}
} else {
if (paramsMap.get("form_type").equals(AppContext.SEND_BT)) {
result = doPost();
sendBtResult(result);
} else if (paramsMap.get("form_type").equals(AppContext.ADD_ALBUM)) {
result = doPost();
if (result != null) {
JSONObject object = new JSONObject(result);
JSONObject resultObj = object.getJSONObject("results");
int success = resultObj.getInt("success");
if (success == 0) {
String errmsg = resultObj.getString("errmsg");
Message msg = Message.obtain(handler, context.error, errmsg);
handler.sendMessage(msg);
} else {
String successmsg = resultObj.getString("successmsg");
context.albumid = resultObj.getInt("albumid");
Message msg = Message.obtain(handler, context.do_success, successmsg);
handler.sendMessage(msg);
}
}
} else {
result = doPost();
submitResult(result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void sendBtResult(String result) {
try {
JSONObject object = new JSONObject(result);
JSONObject resultObj = object.getJSONObject("results");
int success = resultObj.getInt("success");
if (success == 0) {
String errmsg = resultObj.getString("errmsg");
Message msg = Message.obtain(handler, context.send_bt_error, errmsg);
handler.sendMessage(msg);
} else {
String successmsg = resultObj.getString("successmsg");
int gainbt_type = resultObj.getInt("pickbt_type");
String gainbt_msg = resultObj.getString("sendbt_msg");
Object[] objs = new Object[3];
objs[0] = successmsg;
objs[1] = gainbt_type;
objs[2] = gainbt_msg;
Message msg = Message.obtain(handler, context.send_bt_success, objs);
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void submitResult(String result) {
try {
if (result != null) {
JSONObject object = new JSONObject(result);
JSONObject resultObj = object.getJSONObject("results");
int success = resultObj.getInt("success");
if (success == 0) {
String errmsg = resultObj.getString("errmsg");
Message msg = Message.obtain(handler, context.error, errmsg);
handler.sendMessage(msg);
} else {
String successmsg = resultObj.getString("successmsg");
Message msg = Message.obtain(handler, context.do_success, successmsg);
handler.sendMessage(msg);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String doPost() {
BaseHttpClient client = BaseHttpClient.newInstance(context, tag);
HttpPost request = null;
InputStream entityStream = null;
String result = null;
try {
request = new HttpPost(UrlConfig.submit_form);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> m : paramsMap.entrySet()) {
params.add(new BasicNameValuePair(m.getKey(), m.getValue()));
}
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.d(tag, "request-url="+UrlConfig.submit_form + (params != null ? params.toString() : null));
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
entityStream = response.getEntity().getContent();
result = convertStreamToString(entityStream);
}
Log.d(tag, "request-statusCode=" + statusCode);
} catch (Exception e) {
request.abort();
e.printStackTrace();
} finally {
closeStream(entityStream);
closeClient(client);
}
Log.d(tag, "result="+result);
return result;
}
protected String submitFile() {
String result = null;
try {
long length = 0;
int progress;
int bytesRead, bytesAvailable, bufferSize;
long totalSize;
byte[] buffer;
int maxBufferSize = 10 * 1024;// 10KB
BasicActivity activity = (BasicActivity) context;
if (!ServiceUtils.isConnectInternet(activity)) {
activity.onToast(activity.getString(R.string.connect_error));
return null;
}
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(UrlConfig.submit_form);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(60 * 1000); // 缓存的最长时间
conn.setConnectTimeout(60 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
Log.i("httptest", "test" + sb.toString());
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
Log.i("httptest", "testend");
InputStream in = null;
// 发送文件数据
if (mFile != null) {
totalSize = mFile.length();
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"upload.jpg\"" + LINEND);
sb1.append("Content-Type: image/jpeg; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
FileInputStream fileInputStream = new FileInputStream(mFile);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);//设置每次写入的大小
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outStream.write(buffer, 0, bufferSize);
length += bufferSize;
Thread.sleep(500);
progress = (int) ((length * 100) / totalSize);
publishProgress(progress,(int)length);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outStream.write(LINEND.getBytes());
Log.i("httptest:pic", "test" + sb1.toString());
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
publishProgress(100,(int)length);
}
// 得到响应码
int res = conn.getResponseCode();
Log.i(tag, res + "-----------------");
if (res == 200) {
in = conn.getInputStream();
result = HttpUtils.convertStreamToString(in);
}
outStream.close();
conn.disconnect();
Log.d(tag, "result=" + result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String submitFileByEntity() {
System.out.println("upload file begin >>>>>>>>>>>>>>>>>>>");
long time = System.currentTimeMillis();
String serverResponse = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(UrlConfig.submit_form);
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(
new ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// We use FileBody to transfer an image
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
multipartContent.addPart(entry.getKey(), new StringBody(entry.getValue() == null ? "" : entry.getValue()));
}
multipartContent.addPart("pic", new FileBody(mFile));
totalSize = multipartContent.getContentLength();
// Send it
httpPost.setEntity(multipartContent);
HttpResponse response = httpClient.execute(httpPost, httpContext);
serverResponse = EntityUtils.toString(response.getEntity());
System.out.println("upload file end >>>>>>>>>>>>>>>>>>>" + (System.currentTimeMillis() - time));
System.out.println("------------------>>>>>>>>>>>>>>>" + serverResponse);
System.out.println("<<<<<<<<<<<<<<<------------------" + serverResponse);
} catch (Exception e) {
e.printStackTrace();
}
return serverResponse;
}
static String convertStreamToString(InputStream is) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8 * 1024);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
sb.delete(0, sb.length());
} finally {
closeStream(is);
}
return sb.toString();
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void closeClient(BaseHttpClient client) {
if (client != null) {
client.close();
client = null;
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.File;
import android.content.Context;
import com.outsourcing.bottle.domain.UrlConfig;
public class ImageFileCache {
private File cacheDir;
public ImageFileCache(Context context, String path){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), path);
else
cacheDir = context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
//I identify images by hashcode. Not a perfect solution, good for the demo.
// String filename=String.valueOf(url.hashCode());
//Another possible solution (thanks to grantland)
// String filename = URLEncoder.encode(url);
String filename = convertUrlToFileName(url);
File f = new File(cacheDir, filename);
return f;
}
private String convertUrlToFileName(String url) {
String filename = url;
if (filename.indexOf("?") != -1) {
filename = filename.substring(0, filename.indexOf("?"));
}
filename = filename.replace(UrlConfig.url, "");
filename = filename.replace("/", ".");
String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
if (suffix.equals("jpg")) {
filename = filename.replace("jpg", "dat");
} else if (suffix.equals("gif")) {
filename = filename.replace("gif", "dat");
} else if (suffix.equals("jpeg")) {
filename = filename.replace("jpeg", "dat");
} else if (suffix.equals("png")) {
filename = filename.replace("png", "dat");
}
return filename;
}
public void clear(){
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f:files)
f.delete();
}
} | Java |
package com.outsourcing.bottle.util;
import java.util.Comparator;
import com.outsourcing.bottle.domain.BottleFeedEntry;
/**
*
* @author 06peng
*
*/
public class ComparatorForComment implements Comparator<BottleFeedEntry> {
@Override
public int compare(BottleFeedEntry entry1, BottleFeedEntry entry2) {
return 0;
}
}
| Java |
package com.outsourcing.bottle.util;
/**
* @author 06peng
*
*/
public abstract interface BasicUIEvent {
public abstract void execute(int mes, Object obj);
}
| Java |
package com.outsourcing.bottle.util;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
/**
* 后台执行任务的类
* @author 06peng
*
* @param <Params>
* @param <Progress>
* @param <Result>
*/
public abstract class CommandTask<Params, Progress, Result> {
private static final String LOG_TAG = "UserTask";
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 10;
private static final int KEEP_ALIVE = 3000;
/**
* BlockingQueue,如果BlockQueue是空的,
* 从BlockingQueue取东西的操作将会被阻断进入等待状态,
* 直到BlockingQueue进了东西才会被唤醒.同样,如果BlockingQueue是满的,
* 任何试图往里存东西的操作也会被阻断进入等待状态,
* 直到BlockingQueue里有空间才会被唤醒继续操作.
* 使用BlockingQueue的关键技术点如下:
1.BlockingQueue定义的常用方法如下:
1)add(anObject):把anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则抛出异常
2)offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false.
3)put(anObject):把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续.
4)poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null
5)take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止
2.BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类
1)ArrayBlockingQueue:规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的.
2)LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,
所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的
3)PriorityBlockingQueue:类似于LinkedBlockQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数的Comparator决定的顺序.
4)SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的.
3.LinkedBlockingQueue和ArrayBlockingQueue比较起来,它们背后所用的数据结构不一样,导致LinkedBlockingQueue的数据吞吐量要大于ArrayBlockingQueue,
但在线程数量很大时其性能的可预见性低于ArrayBlockingQueue.
*/
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE);
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
/**
* AtomicInteger,一个提供原子操作的Integer的类。
* 在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,
* 不可避免的会用到synchronized关键字。
* 而AtomicInteger则通过一种线程安全的加减操作接口。
*
* 获取当前的值 public final int get()
* 取当前的值,并设置新的值 public final int getAndSet(int newValue)
* 获取当前的值,并自增 public final int getAndIncrement()
* 获取当前的值,并自减 public final int getAndDecrement()
* 获取当前的值,并加上预期的值 public final int getAndAdd(int delta)
*/
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "UserTask #" + mCount.getAndIncrement());
}
};
/**
* 线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为:
* ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
* long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
*
* corePoolSize: 线程池维护线程的最少数量
* maximumPoolSize:线程池维护线程的最大数量
* keepAliveTime: 线程池维护线程所允许的空闲时间
* unit: 线程池维护线程所允许的空闲时间的单位
* workQueue: 线程池所使用的缓冲队列
* handler: 线程池对拒绝任务的处理策略
* 一个任务通过 execute(Runnable)方法被添加到线程池,任务就是一个 Runnable类型的对象,
* 任务的执行方法就是 Runnable类型对象的run()方法。
* 当一个任务通过execute(Runnable)方法欲添加到线程池时:
* 如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
* 如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。
* 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。
* 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。
* 也就是:处理任务的优先级为:
* 核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
* 当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。
* unit可选的参数为java.util.concurrent.TimeUnit中的几个静态属性:
* NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS。
* workQueue我常用的是:java.util.concurrent.ArrayBlockingQueue
* handler有四个选择:
* ThreadPoolExecutor.AbortPolicy()
* 抛出java.util.concurrent.RejectedExecutionException异常
* ThreadPoolExecutor.CallerRunsPolicy()
* 重试添加当前的任务,他会自动重复调用execute()方法
* ThreadPoolExecutor.DiscardOldestPolicy()
* 抛弃旧的任务
* ThreadPoolExecutor.DiscardPolicy()
* 抛弃当前的任务
*
*/
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final int MESSAGE_POST_CANCEL = 0x3;
private static final InternalHandler sHandler = new InternalHandler();
private final WorkerRunnable<Params, Result> mWorker;
/**
* FutureTask类是Future 的一个实现,并实现了Runnable,所以可通过Excutor(线程池) 来执行。
* 也可传递给Thread对象执行。如果在主线程中需要执行比较耗时的操作时,但又不想阻塞主线程时,
* 可以把这些作业交给Future对象在后台完成,当主线程将来需要时,
* 就可以通过Future对象获得后台作业的计算结果或者执行状态。
*/
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
public enum Status {
/**
* 等待运行的线程.
*/
PENDING,
/**
* 运行中的线程.
*/
RUNNING,
/**
* 运行完毕的线程.
*/
FINISHED,
}
/**
* 创建一个新的线程. 被界面主线程调用.
*/
public CommandTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return doInBackground(mParams);
}
};
mFuture = new FutureTask<Result>(mWorker) {
@SuppressWarnings("unchecked")
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new UserTaskResult<Result>(CommandTask.this, (Result[]) null));
message.sendToTarget();
System.out.println("cancel----------------------->");
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new UserTaskResult<Result>(CommandTask.this, result));
message.sendToTarget();
}
};
}
/**
* 返回当前线程的状态
* @return
*/
public final Status getStatus() {
return mStatus;
}
/**
* 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用.
* 后台进程执行的具体计算在这里实现,doInBackground(Params...)是AsyncTask的关键,此方法必须重载。
* 在这个方法内可以使用 publishProgress(Progress...)改变当前的进度值。
* @param params
* @return
*/
public abstract Result doInBackground(Params... params);
/**
* 执行预处理,它运行于UI线程,可以为后台任务做一些准备工作,比如绘制一个进度条控件。
*/
public void onPreExecute() { }
/**
* 此方法在主线程执行,任务执行的结果作为此方法的参数返回。
* 运行于UI线程,可以对后台任务的结果做出处理,结果就是doInBackground(Params...)的返回值。
* 此方法也要经常重载,如果Result为null表明后台任务没有完成(被取消或者出现异常)。
* @param result
*/
public void onPostExecute(Result result) { }
/**
* 运行于UI线程。如果在doInBackground(Params...)中使用了publishProgress(Progress...),
* 就会触发这个方法。在这里可以对进度条控件根据进度值做出具体的响应。
*/
public void onProgressUpdate(Progress... values) { }
/**
* 在界面主线程并在cancel(boolean) 之后调用.
* @see #cancel(boolean)
* @see #isCancelled()
*/
public void onCancelled() { }
/**
* 如果当前任务在正常完成之前被取消返回 true
* @see #cancel(boolean)
*/
public final boolean isCancelled() {
return mFuture.isCancelled();
}
/**
* 如果未开始运行则会被取消运行,如果已经运行则会跑出mayInterruptIfRunning错误并终止运行
* @param mayInterruptIfRunning 如果为true 如果线程正在执行则会被中断,否则,会等待任务完成。
* @return false 如果线程无法取消,很可能是因为已经完成
* true 则相反
*
* @see #isCancelled()
* @see #onCancelled()
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return mFuture.cancel(mayInterruptIfRunning);
}
/**
* 返回结果
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* 在制定时间内等待结果,超出时间则取消任务
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* 自动调用的回调参数
* @param params task的需要的参数.
* @return 返回一个task的实例.
*
*/
public final CommandTask<Params, Progress, Result> execute(Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
sExecutor.execute(mFuture);
return this;
}
/**
* 此方法在doInBackground(Object[])里面当后台计算在运行时在UI线程调用
* 每次调用都会触发通过onProgressUpdate()方法在UI线程显示出来
* @param values UI线程需要的参数
*
* @see #onProgressUpdate (Object[])
* @see #doInBackground(Object[])
*/
protected final void publishProgress(Progress... values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new UserTaskResult<Progress>(this, values)).sendToTarget();
}
private void finish(Result result) {
onPostExecute(result);
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void handleMessage(Message msg) {
UserTaskResult result = (UserTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// 只有一个返回
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
result.mTask.cancel(true);
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
private static class UserTaskResult<Data> {
@SuppressWarnings("rawtypes")
final CommandTask mTask;
final Data[] mData;
@SuppressWarnings("rawtypes")
UserTaskResult(CommandTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
| Java |
package com.outsourcing.bottle.util;
import java.util.HashMap;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import com.ibm.mqtt.IMqttClient;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttPersistence;
import com.ibm.mqtt.MqttPersistenceException;
import com.ibm.mqtt.MqttSimpleCallback;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.PushNoticeInfoTable;
import com.outsourcing.bottle.domain.PushNoticeInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.ui.HomeActivity;
/**
*
* @author 06peng
*
*/
public class BottlePushService extends Service implements Callback {
// this is the log tag
public static final String TAG = "DemoPushService";
// the IP address, where your MQTT broker is running.
private static final String MQTT_HOST = "184.169.168.88";
// private static final String MQTT_HOST = "184.169.141.121";
// the port at which the broker is running.
private static int MQTT_BROKER_PORT_NUM = 1883;
// Let's not use the MQTT persistence.
private static MqttPersistence MQTT_PERSISTENCE = null;
// We don't need to remember any state between the connections, so we use a clean start.
private static boolean MQTT_CLEAN_START = true;
// Let's set the internal keep alive for MQTT to 15 mins. I haven't tested this value much. It could probably be increased.
private static short MQTT_KEEP_ALIVE = 60 * 15;
// Set quality of services to 0 (at most once delivery), since we don't want push notifications
// arrive more than once. However, this means that some messages might get lost (delivery is not guaranteed)
private static int[] MQTT_QUALITIES_OF_SERVICE = { 0 } ;
private static int MQTT_QUALITY_OF_SERVICE = 0;
// The broker should not retain any messages.
private static boolean MQTT_RETAINED_PUBLISH = false;
// MQTT client ID, which is given the broker. In this example, I also use this for the topic header.
// You can use this to run push notifications for multiple apps with one MQTT broker.
public static String MQTT_CLIENT_ID = "tokudu";
// These are the actions for the service (name are descriptive enough)
private static final String ACTION_START = MQTT_CLIENT_ID + ".START";
private static final String ACTION_STOP = MQTT_CLIENT_ID + ".STOP";
private static final String ACTION_KEEPALIVE = MQTT_CLIENT_ID + ".KEEP_ALIVE";
private static final String ACTION_RECONNECT = MQTT_CLIENT_ID + ".RECONNECT";
// Connection log for the push service. Good for debugging.
// Connectivity manager to determining, when the phone loses connection
private ConnectivityManager mConnMan;
// Notification manager to displaying arrived push notifications
private NotificationManager mNotifMan;
// Whether or not the service has been started.
private boolean mStarted;
// This the application level keep-alive interval, that is used by the AlarmManager
// to keep the connection active, even when the device goes to sleep.
private static final long KEEP_ALIVE_INTERVAL = 1000 * 60 * 28;
// Retry intervals, when the connection is lost.
private static final long INITIAL_RETRY_INTERVAL = 1000 * 10;
private static final long MAXIMUM_RETRY_INTERVAL = 1000 * 60 * 30;
// Preferences instance
private SharedPreferences mPrefs;
// We store in the preferences, whether or not the service has been started
public static final String PREF_STARTED = "isStarted";
// We also store the deviceID (target)
public static final String PREF_DEVICE_ID = "deviceID";
// We store the last retry interval
public static final String PREF_RETRY = "retryInterval";
// Notification title
public static String NOTIF_TITLE = "Tokudu";
// Notification id
// This is the instance of an MQTT connection.
private MQTTConnection mConnection;
private long mStartTime;
/*************************************** 华丽的分割线 *********************************************/
private Handler handler;
public static final int PUSH_NOTICE_MSG = 0001;
// Static method to start the service
public static void actionStart(Context ctx) {
Intent i = new Intent(ctx, BottlePushService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}
// Static method to stop the service
public static void actionStop(Context ctx) {
Intent i = new Intent(ctx, BottlePushService.class);
i.setAction(ACTION_STOP);
ctx.startService(i);
}
// Static method to send a keep alive message
public static void actionPing(Context ctx) {
Intent i = new Intent(ctx, BottlePushService.class);
i.setAction(ACTION_KEEPALIVE);
ctx.startService(i);
}
@Override
public void onCreate() {
super.onCreate();
log("Creating service");
mStartTime = System.currentTimeMillis();
handler = new Handler(this);
// Get instances of preferences, connectivity manager and notification manager
mPrefs = getSharedPreferences(TAG, MODE_PRIVATE);
mConnMan = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
mNotifMan = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
/* If our process was reaped by the system for any reason we need
* to restore our state with merely a call to onCreate. We record
* the last "started" value and restore it here if necessary. */
handleCrashedService();
}
// This method does any necessary clean-up need in case the server has been destroyed by the system
// and then restarted
private void handleCrashedService() {
if (wasStarted() == true) {
log("Handling crashed service...");
// stop the keep alives
stopKeepAlives();
// Do a clean start
start();
}
}
@Override
public void onDestroy() {
log("Service destroyed (started=" + mStarted + ")");
// Stop the services, if it has been started
if (mStarted == true) {
stop();
}
}
@Override
public void onStart(Intent intent, int startId) {
log("Service started with intent=" + intent);
// Do an appropriate action based on the intent.
try {
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals(ACTION_STOP) == true) {
stop();
stopSelf();
} else if (intent.getAction().equals(ACTION_START) == true) {
start();
} else if (intent.getAction().equals(ACTION_KEEPALIVE) == true) {
keepAlive();
} else if (intent.getAction().equals(ACTION_RECONNECT) == true) {
if (isNetworkAvailable()) {
reconnectIfNecessary();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
// log helper function
private void log(String message) {
log(message, null);
}
private void log(String message, Throwable e) {
if (e != null) {
// Log.e(TAG, message, e);
} else {
// Log.i(TAG, message);
}
}
// Reads whether or not the service has been started from the preferences
private boolean wasStarted() {
return mPrefs.getBoolean(PREF_STARTED, false);
}
// Sets whether or not the services has been started in the preferences.
private void setStarted(boolean started) {
mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
mStarted = started;
}
private synchronized void start() {
log("Starting service...");
// Do nothing, if the service is already running.
if (mStarted == true) {
Log.w(TAG, "Attempt to start connection that is already active");
return;
}
// Establish an MQTT connection
connect();
// Register a connectivity listener
registerReceiver(mConnectivityChanged, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private synchronized void stop() {
// Do nothing, if the service is not running.
if (mStarted == false) {
Log.w(TAG, "Attempt to stop connection not active.");
return;
}
// Save stopped state in the preferences
setStarted(false);
// Remove the connectivity receiver
unregisterReceiver(mConnectivityChanged);
// Any existing reconnect timers should be removed, since we explicitly stopping the service.
cancelReconnect();
// Destroy the MQTT connection if there is one
if (mConnection != null) {
mConnection.disconnect();
mConnection = null;
}
}
//
private synchronized void connect() {
log("Connecting...");
// fetch the device ID from the preferences.
final String deviceID = mPrefs.getString(PREF_DEVICE_ID, null);
// Create a new connection only if the device id is not NULL
if (deviceID == null) {
log("Device ID not found.");
} else {
new Thread() {
public void run() {
try {
mConnection = new MQTTConnection(MQTT_HOST, deviceID);
} catch (MqttException e) {
// Schedule a reconnect, if we failed to connect
log("MqttException: " + (e.getMessage() != null ? e.getMessage() : "NULL"));
if (isNetworkAvailable()) {
scheduleReconnect(mStartTime);
}
}
setStarted(true);
};
}.start();
}
}
private synchronized void keepAlive() {
new Thread() {
public void run() {
try {
// Send a keep alive, if there is a connection.
if (mStarted == true && mConnection != null) {
mConnection.sendKeepAlive();
}
} catch (MqttException e) {
log("MqttException: " + (e.getMessage() != null? e.getMessage(): "NULL"), e);
mConnection.disconnect();
mConnection = null;
cancelReconnect();
}
};
}.start();
}
// Schedule application level keep-alives using the AlarmManager
private void startKeepAlives() {
Intent i = new Intent();
i.setClass(this, BottlePushService.class);
i.setAction(ACTION_KEEPALIVE);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + KEEP_ALIVE_INTERVAL, KEEP_ALIVE_INTERVAL, pi);
}
// Remove all scheduled keep alives
private void stopKeepAlives() {
Intent i = new Intent();
i.setClass(this, BottlePushService.class);
i.setAction(ACTION_KEEPALIVE);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.cancel(pi);
}
// We schedule a reconnect based on the starttime of the service
public void scheduleReconnect(long startTime) {
// the last keep-alive interval
long interval = mPrefs.getLong(PREF_RETRY, INITIAL_RETRY_INTERVAL);
// Calculate the elapsed time since the start
long now = System.currentTimeMillis();
long elapsed = now - startTime;
// Set an appropriate interval based on the elapsed time since start
if (elapsed < interval) {
interval = Math.min(interval * 4, MAXIMUM_RETRY_INTERVAL);
} else {
interval = INITIAL_RETRY_INTERVAL;
}
log("Rescheduling connection in " + interval + "ms.");
// Save the new internval
mPrefs.edit().putLong(PREF_RETRY, interval).commit();
// Schedule a reconnect using the alarm manager.
Intent i = new Intent();
i.setClass(this, BottlePushService.class);
i.setAction(ACTION_RECONNECT);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC_WAKEUP, now + interval, pi);
}
// Remove the scheduled reconnect
public void cancelReconnect() {
Intent i = new Intent();
i.setClass(this, BottlePushService.class);
i.setAction(ACTION_RECONNECT);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.cancel(pi);
}
private synchronized void reconnectIfNecessary() {
if (mStarted == true && mConnection == null) {
log("Reconnecting...");
connect();
}
}
// This receiver listeners for network changes and updates the MQTT connection
// accordingly
private BroadcastReceiver mConnectivityChanged = new BroadcastReceiver() {
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
// Get network info
NetworkInfo info = (NetworkInfo) intent.getParcelableExtra (ConnectivityManager.EXTRA_NETWORK_INFO);
// Is there connectivity?
boolean hasConnectivity = (info != null && info.isConnected()) ? true : false;
log("Connectivity changed: connected=" + hasConnectivity);
if (hasConnectivity) {
reconnectIfNecessary();
} else if (mConnection != null) {
// if there no connectivity, make sure MQTT connection is destroyed
mConnection.disconnect();
cancelReconnect();
mConnection = null;
}
}
};
// Check if we are online
private boolean isNetworkAvailable() {
NetworkInfo info = mConnMan.getActiveNetworkInfo();
if (info == null) {
return false;
}
return info.isConnected();
}
// This inner class is a wrapper on top of MQTT client.
private class MQTTConnection implements MqttSimpleCallback {
IMqttClient mqttClient = null;
// Creates a new connection given the broker address and initial topic
public MQTTConnection(String brokerHostName, String initTopic) throws MqttException {
// Create connection spec
String mqttConnSpec = "tcp://" + brokerHostName + "@" + MQTT_BROKER_PORT_NUM;
// Create the client and connect
mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
String clientID = MQTT_CLIENT_ID + "/" + mPrefs.getString(PREF_DEVICE_ID, "");
mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
// register this client app has being able to receive messages
mqttClient.registerSimpleHandler(this);
// Subscribe to an initial topic, which is combination of client ID and device ID.
initTopic = MQTT_CLIENT_ID + "/" + initTopic;
subscribeToTopic(initTopic);
log("Connection established to " + brokerHostName + " on topic " + initTopic);
// Save start time
mStartTime = System.currentTimeMillis();
// Star the keep-alives
startKeepAlives();
}
// Disconnect
public void disconnect() {
try {
stopKeepAlives();
mqttClient.disconnect();
} catch (MqttPersistenceException e) {
log("MqttException" + (e.getMessage() != null? e.getMessage():" NULL"), e);
}
}
/*
* Send a request to the message broker to be sent messages published with
* the specified topic name. Wildcards are allowed.
*/
private void subscribeToTopic(String topicName) throws MqttException {
if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
// quick sanity check - don't try and subscribe if we don't have
// a connection
log("Connection error" + "No connection");
} else {
String[] topics = { topicName };
mqttClient.subscribe(topics, MQTT_QUALITIES_OF_SERVICE);
}
}
/*
* Sends a message to the message broker, requesting that it be published
* to the specified topic.
*/
private void publishToTopic(String topicName, String message) throws MqttException {
if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
// quick sanity check - don't try and publish if we don't have
// a connection
log("No connection to public to");
} else {
mqttClient.publish(topicName,
message.getBytes(),
MQTT_QUALITY_OF_SERVICE,
MQTT_RETAINED_PUBLISH);
}
}
/*
* Called if the application loses it's connection to the message broker.
*/
public void connectionLost() throws Exception {
log("Loss of connection" + "connection downed");
stopKeepAlives();
// null itself
mConnection = null;
if (isNetworkAvailable() == true) {
reconnectIfNecessary();
}
}
/*
* Called when we receive a message from the message broker.
*/
public void publishArrived(String topicName, byte[] payload, int qos, boolean retained) {
// Show a notification
String s = new String(payload);
System.out.println(">>>>>>>>>>>>>>>> recieve something:" + s);
new Thread() {
public void run() {
getPushNotice();
};
}.start();
}
public void sendKeepAlive() throws MqttException {
log("Sending keep alive");
// publish to a keep-alive topic
publishToTopic(MQTT_CLIENT_ID + "/keepalive", mPrefs.getString(PREF_DEVICE_ID, ""));
}
}
@SuppressWarnings("deprecation")
public void gotoMsgNotification(String title) {
try {
SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND);
int notice_voice = preferences.getInt("notice_voice", 1);
int vibration = preferences.getInt("vibration", 1);
Notification notify = new Notification(R.drawable.logo, title, System.currentTimeMillis());
notify.flags = Notification.FLAG_AUTO_CANCEL;
notify.flags = Notification.FLAG_SHOW_LIGHTS;
if (notice_voice == 1 && vibration == 1) {
notify.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
} else if (vibration == 1) {
notify.defaults = Notification.DEFAULT_VIBRATE;
} else if (notice_voice == 1) {
notify.defaults = Notification.DEFAULT_SOUND;
}
Intent notificationIntent = new Intent(this, HomeActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.addFlags(Intent.FILL_IN_DATA);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notify.setLatestEventInfo(this, "新消息提醒", "" + title, contentIntent);
mNotifMan.notify(R.drawable.logo + 1, notify);
} catch (Exception e) {
e.printStackTrace();
}
}
int lanauage;
int login_uid = 0;
String login_token = null;
private void getPushNotice() {
String country = getResources().getConfiguration().locale.getCountry();
if (country.equals("CN")) {
lanauage = 1;
} else {
lanauage = 0;
}
if (login_uid == 0) {
SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
login_uid = preferences.getInt("login_uid", 0);
login_token = preferences.getString("login_token", null);
}
String url = UrlConfig.push_notice;
try {
HashMap<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("login_uid", String.valueOf(login_uid));
paramsMap.put("login_token", login_token);
paramsMap.put("language", String.valueOf(lanauage));
String result = HttpUtils.doPost(BottlePushService.this, url, paramsMap);
if (result != null) {
JSONObject obj = new JSONObject(result);
JSONObject resultObj = obj.getJSONObject("results");
if (resultObj.getInt("authok") == 1) {
JSONObject pushObj = obj.getJSONObject("push_notice");
PushNoticeInfoTable table = new PushNoticeInfoTable(this);
PushNoticeInfo pushInfo = new PushNoticeInfo();
table.clearTable();
pushInfo.setMessage_avatar(pushObj.getString("message_avatar"));
pushInfo.setMessage_content(pushObj.getString("message_content"));
pushInfo.setNew_btfeed_count(pushObj.getInt("new_btfeed_count"));
pushInfo.setNew_exfeed_count(pushObj.getInt("new_exfeed_count"));
pushInfo.setNew_message_count(pushObj.getInt("new_message_count"));
pushInfo.setNew_notice_count(pushObj.getInt("new_notice_count"));
pushInfo.setNew_maybeknow_count(pushObj.getInt("new_maybeknow_count"));
table.savePushNoticeInfo(pushInfo, login_uid);
if (pushObj.getInt("new_btfeed_count")
+ pushObj.getInt("new_exfeed_count")
+ pushObj.getInt("new_message_count")
+ pushObj.getInt("new_notice_count")
+ pushObj.getInt("new_maybeknow_count") > 0) {
Message msg = Message.obtain(handler, PUSH_NOTICE_MSG, pushObj.getString("message_content"));
handler.sendMessage(msg);
}
Bundle bundle = new Bundle();
bundle.putInt("notice_count", pushInfo.getNew_notice_count());
bundle.putInt("message_count", pushInfo.getNew_message_count());
bundle.putInt("bottle_feed_count", pushInfo.getNew_btfeed_count());
bundle.putInt("exchange_feed_count", pushInfo.getNew_exfeed_count());
bundle.putString("message_content", pushInfo.getMessage_content());
bundle.putString("message_avatar", pushInfo.getMessage_avatar());
bundle.putInt("maybe_kown_count", pushInfo.getNew_maybeknow_count());
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setAction("push");
sendBroadcast(intent);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case PUSH_NOTICE_MSG:
gotoMsgNotification((String) msg.obj);
break;
default:
break;
}
return false;
}
} | Java |
package com.outsourcing.bottle.util;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
/**
*
* @author 06peng
*
*/
public class GetFileSize {
public long getFileSizes(File f) throws Exception {
long s = 0;
if (f.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(f);
s = fis.available();
} else {
f.createNewFile();
}
return s;
}
public long getFileSize(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSize(flist[i]);
} else {
size = size + flist[i].length();
}
}
return size;
}
public String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
public long getlist(File f) {
long size = 0;
File flist[] = f.listFiles();
size = flist.length;
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getlist(flist[i]);
size--;
}
}
return size;
}
}
| Java |
package com.outsourcing.bottle.util;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.format.Formatter;
import com.outsourcing.bottle.remoteimage.ImageCache;
/**
*
* @author 06peng
*
*/
public class BottleApplication extends Application {
public static BottleApplication mDemoApp;
private ImageCache mImageCache;
public static BottleApplication getInstance() {
return mDemoApp;
}
private ThumbnailCache mLruImageCache;
public ThumbnailCache getLruImageCache() {
return mLruImageCache;
}
@Override
public void onCreate() {
super.onCreate();
mDemoApp = this;
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
mImageCache = new ImageCache();
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
int memoryClassBytes = am.getMemoryClass() * 1024 * 1024;
mLruImageCache = new ThumbnailCache(memoryClassBytes / 10);
}
@Override
public void onTerminate() {
super.onTerminate();
}
public ImageCache getImageCache() {
return mImageCache;
}
/**
* Simple extension that uses {@link Bitmap} instances as keys, using their
* memory footprint in bytes for sizing.
*/
public static class ThumbnailCache extends LruCache<String, Bitmap> {
public ThumbnailCache(int maxSizeBytes) {
super(maxSizeBytes);
}
// @Override
// protected int sizeOf(String key, Bitmap value) {
// return value.getByteCount();
// }
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.aviary.android.feather.library.utils.StringUtils;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.ui.CropImage2Activity;
/**
*
* @author 06peng
*
*/
public class ServiceUtils {
private static final String TAG = ServiceUtils.class.getSimpleName();
public static Drawable drawable = null;
public static URL url;
public static boolean debugFlag = true;
/**
* 根据图片路径下载图片并转化成Bitmap
* @param path
* @return
*/
public static Bitmap downloadImage(String path){
Bitmap bitmap = null;
try {
URL uri = new URL(path);
HttpURLConnection conn = (HttpURLConnection)uri.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 读取输入流数据
* @param is
* @return
* @throws Exception
*/
public static byte[] readStream(InputStream is) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
return os.toByteArray();
}
/**
* 根据图片途径下载图片转化成二进制数据
* @param urlPath
* @return
*/
public static byte[] getImageFromUrlPath(String urlPath) {
byte[] data = null;
URL url;
try {
url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
data = readStream(is);
}else{
System.out.println("请求失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
/**
* 将Drawable转化为Bitmap
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
/**
* 下载图片到SD卡
* @param imagePath
*/
public static void downLoadImage(String imageUrl, String path){
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
if (fileName.indexOf("?") != -1) {
fileName = fileName.substring(0, fileName.indexOf("?"));
}
if (fileName.contains("png")) {
fileName = fileName.replace("png", "dat");
}
File dir = new File(Environment.getExternalStorageDirectory() + "/" + path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir + File.separator + fileName);
if (!file.exists()) {
System.out.println("**********************>>>" + "download image");
URL url;
try {
url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
FileOutputStream fs = new FileOutputStream(file);
fs.write(data);
fs.close();
} else {
System.out.println("请求失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 下载图片到SD卡 加上唯一标识
* @param imagePath
*/
public static void downLoadImage(String imageUrl,String identityId, String path){
String fileName =identityId+"_"+ imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
if (fileName.indexOf("?") != -1) {
fileName = fileName.substring(0, fileName.indexOf("?"));
}
if (fileName.contains("png")) {
fileName = fileName.replace("png", "dat");
}
File dir = new File(Environment.getExternalStorageDirectory() + "/" + path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir + File.separator + fileName);
if (!file.exists()) {
System.out.println("**********************>>>" + "download image");
URL url;
try {
url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
FileOutputStream fs = new FileOutputStream(file);
fs.write(data);
fs.close();
} else {
System.out.println("请求失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取用户头像
* @param imagePath
*/
public static Bitmap getUserHeadImage(String imageUrl, String path){
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
if (fileName.indexOf("?") != -1) {
fileName = fileName.substring(0, fileName.indexOf("?"));
}
File dir = new File(Environment.getExternalStorageDirectory() + "/" + path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir + File.separator + fileName);
if (!file.exists()) {
URL url;
try {
url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
FileOutputStream fs = new FileOutputStream(file);
fs.write(data);
fs.close();
} else {
System.out.println("请求失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return BitmapFactory.decodeFile(file.getPath());
}
/**
* 获取文件
* @param imageUrl
* @param path
* @return
*/
public static byte[] getImageFile(String imageUrl, String path) {
if (imageUrl.contains("png")) {
imageUrl = imageUrl.replace("png", "dat");
}
String imagePath = Environment.getExternalStorageDirectory() + "/" + path;
File file = new File(imagePath + File.separator + imageUrl.substring(imageUrl.lastIndexOf("/") + 1));
if (file == null || !file.exists()) {
return null;
}
int length = (int) file.length();
byte[] b = new byte[length];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(b, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return length != 0 ? b : null;
}
/**
* 获取文件
* @param imageUrl
* @param path
* @return
*/
public static byte[] getImageFileForSticker(String imageUrl, String path) {
String filename = convertUrlToFileName(imageUrl);
File file = new File(Environment.getExternalStorageDirectory() + "/"+path+"/"+ filename);
if (file == null || !file.exists()) {
return null;
}
int length = (int) file.length();
byte[] b = new byte[length];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(b, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return length != 0 ? b : null;
}
/**
* 获取文件
* @param imageUrl
* @param path
* @param indentifyId
* @return
*/
public static byte[] getImageFile(String imageUrl,String indentifyId, String path) {
if (imageUrl.contains("png")) {
imageUrl = imageUrl.replace("png", "dat");
}
String imagePath = Environment.getExternalStorageDirectory() + "/" + path;
File file = new File(imagePath + File.separator + indentifyId+"_"+imageUrl.substring(imageUrl.lastIndexOf("/") + 1));
if (file == null || !file.exists()) {
return null;
}
int length = (int) file.length();
byte[] b = new byte[length];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(b, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return length != 0 ? b : null;
}
public static boolean isConnectInternet(Activity activity) {
ConnectivityManager conManager = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
if (networkInfo != null) {
return networkInfo.isAvailable();
}
return false;
}
public static boolean isConnectInternet(Context context) {
ConnectivityManager conManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
if (networkInfo != null) {
return networkInfo.isAvailable();
}
return false;
}
public static String getContentByStream(InputStream is, long contentLength) {
String content = null;
Reader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder((int)contentLength);
char[] temp = new char[4000];
int len = 0;
while((len = reader.read(temp)) != -1){
builder.append(temp, 0, len);
}
content = builder.toString();
return content;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
is.close();
reader = null;
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static Bitmap bytesToBitmap(byte[] data) {
if (data != null) {
ByteArrayInputStream is = new ByteArrayInputStream(data);
try {
BitmapFactory.Options options1 = new BitmapFactory.Options();
options1.inPurgeable = true;
options1.inInputShareable = true;
options1.inSampleSize = 1;
try {
BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options1, true);
}catch(Exception ex) {
ex.printStackTrace();
}
Bitmap bitmap = (new WeakReference<Bitmap>(
BitmapFactory.decodeStream(is, null, options1))).get();
Bitmap temp = Bitmap.createBitmap(bitmap);
return temp;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
public static byte[] BitmapTobytes(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public static void dout(String str) {
if (debugFlag) {
Log.d("[dout]", "str>>>>>>>>>>>>>" + str);
}
}
public static void dout(String str, String str2) {
if (debugFlag) {
Log.d("[dout]", "str>>>>>>>>>>>>>" + str + " " + str2);
}
}
public static String convertUrlToFileName(String url) {
String filename = url;
if (filename.indexOf("?") != -1) {
filename = filename.substring(0, filename.indexOf("?"));
}
filename = filename.replace(UrlConfig.url, "");
filename = filename.replace("/", ".");
String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
if (suffix.equals("jpg")) {
filename = filename.replace("jpg", "dat");
} else if (suffix.equals("gif")) {
filename = filename.replace("gif", "dat");
} else if (suffix.equals("jpeg")) {
filename = filename.replace("jpeg", "dat");
} else if (suffix.equals("png")) {
filename = filename.replace("png", "dat");
}
return filename;
}
/**
* Once you've chosen an image you can start the feather activity
*
* @param uri
*/
public static void startFeather(Context context, Uri uri , int editType) {
if ( !Utility.isExternalStorageAvilable() ) {
return;
}
// create a temporary file where to store the resulting image
File file = Utility.getNextFileName();
String mOutputFilePath;
if ( null != file ) {
mOutputFilePath = file.getAbsolutePath();
} else {
new AlertDialog.Builder( context ).setTitle( android.R.string.dialog_alert_title ).setMessage( "Failed to create a new File" )
.show();
return;
}
Intent newIntent = new Intent( context, FeatherActivity.class );
newIntent.putExtra( "From_Type", editType );
newIntent.setData( uri );
newIntent.putExtra( "API_KEY", Utility.API_KEY );
newIntent.putExtra( "output", Uri.parse( "file://" + mOutputFilePath ) );
newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() );
newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );
newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );
final DisplayMetrics metrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics( metrics );
int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );
max_size = (int) ( (double) max_size / 0.8 );
newIntent.putExtra( "max-image-size", max_size );
newIntent.putExtra( "effect-enable-borders", true );
String mSessionId = StringUtils.getSha256( System.currentTimeMillis() + Utility.API_KEY );
Log.d( TAG, "session: " + mSessionId + ", size: " + mSessionId.length() );
newIntent.putExtra( "output-hires-session-id", mSessionId );
context.startActivity(newIntent);
}
}
| Java |
package com.outsourcing.bottle.util;
import android.app.Service;
import android.content.Intent;
import com.outsourcing.bottle.BasicActivity;
/**
*
* @author 06peng
*
*/
public class UICore {
private static UICore ins = new UICore();
private BottlePushService service;
private UICore() {
}
public static UICore getInstance() {
if (ins == null) {
ins = new UICore();
}
return ins;
}
public static void eventTask(BasicUIEvent basicUIEvent,
BasicActivity context, int CommandID, String tips, Object obj) {
try {
CommandTaskEvent commandTask = new CommandTaskEvent(basicUIEvent, context, tips);
commandTask.execute((new Object[] { CommandID + "", obj }));
} catch (Exception e) {
e.printStackTrace();
System.out.println("cancel: success!!");
if (context != null)
context.destroyDialog();
}
}
public static void eventTask(BasicUIEvent basicUIEvent, Service service, int CommandID, String tips, Object obj) {
try {
CommandTaskEvent commandTask = new CommandTaskEvent(basicUIEvent, service);
commandTask.execute((new Object[] { CommandID + "", obj }));
} catch (Exception e) {
e.printStackTrace();
System.out.println("cancel: success!!");
}
}
public static void setService(BottlePushService service) {
UICore.getInstance().service = service;
}
public static BottlePushService getService() {
return UICore.getInstance().service;
}
public void closeService() {
if (service != null) {
service.stopService(new Intent(service, BottlePushService.class));
UICore.setService(null);
service = null;
}
}
}
| Java |
package com.outsourcing.bottle.util;
/*
* 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.
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.RequestWrapper;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
*
* @author 06peng
*
*/
public final class BaseHttpClient implements HttpClient {
// Gzip of data shorter than this probably won't be worthwhile
public static long DEFAULT_SYNC_MIN_GZIP_BYTES = 256;
private static final String TAG = "AndroidHttpClient";
/** Set if HTTP requests are blocked from being executed on this thread */
private static final ThreadLocal<Boolean> sThreadBlocked =
new ThreadLocal<Boolean>();
/** Interceptor throws an exception if the executing thread is blocked */
private static final HttpRequestInterceptor sThreadCheckInterceptor =
new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) {
if (sThreadBlocked.get() != null && sThreadBlocked.get()) {
throw new RuntimeException("This thread forbids HTTP requests");
}
}
};
/**
* Create a new HttpClient with reasonable defaults (which you can update).
*
* @param userAgent to report in your HTTP requests.
* @param sessionCache persistent session cache
* @return AndroidHttpClient for you to use for all your requests.
*/
public static BaseHttpClient newInstance(Context mContext, String userAgent) {
HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
// Default connection and socket timeout of 20 seconds. Tweak to taste.
HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
HttpConnectionParams.setSoTimeout(params, 20 * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Don't handle redirects -- return them to the caller. Our code
// often wants to re-POST after a redirect, which we must do ourselves.
HttpClientParams.setRedirecting(params, false);
// Set the specified user agent and register standard protocols.
HttpProtocolParams.setUserAgent(params, userAgent);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager manager =
new ThreadSafeClientConnManager(params, schemeRegistry);
// We use a factory method to modify superclass initialization
// parameters without the funny call-a-static-method dance.
return new BaseHttpClient(mContext, manager, params);
}
//private final HttpClient delegate;
private final DefaultHttpClient delegate;
private RuntimeException mLeakedException = new IllegalStateException(
"AndroidHttpClient created and never closed");
private BaseHttpClient(Context mContext, ClientConnectionManager ccm, HttpParams params) {
this.delegate = new DefaultHttpClient(ccm, params) {
@Override
protected BasicHttpProcessor createHttpProcessor() {
// Add interceptor to prevent making requests from main thread.
BasicHttpProcessor processor = super.createHttpProcessor();
processor.addRequestInterceptor(sThreadCheckInterceptor);
processor.addRequestInterceptor(new CurlLogger());
return processor;
}
@Override
protected HttpContext createHttpContext() {
// Same as DefaultHttpClient.createHttpContext() minus the
// cookie store.
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
return context;
}
};
/*设置代理*/
setProxy(mContext);
}
/**
*
* @param mContext
*/
private void setProxy(Context mContext) {
try {
ContentValues values = new ContentValues();
Cursor cur = mContext.getContentResolver().query(
Uri.parse("content://telephony/carriers/preferapn"), null, null, null, null);
if (cur != null && cur.getCount() > 0) {
if (cur.moveToFirst()) {
int colCount = cur.getColumnCount();
for (int i = 0; i < colCount; i++) {
values.put(cur.getColumnName(i), cur.getString(i));
}
}
cur.close();
}
String proxyHost = (String) values.get("proxy");
if (!TextUtils.isEmpty(proxyHost) && !isWiFiConnected(mContext)) {
int prot = Integer.parseInt(String.valueOf(values.get("port")));
delegate.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, prot),
new UsernamePasswordCredentials((String) values.get("user"), (String) values.get("password")));
HttpHost proxy = new HttpHost(proxyHost, prot);
delegate.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
} catch (Exception e) {
e.printStackTrace();
Log.w(TAG, "set proxy error+++++++++++++++++");
}
}
/**
* 当前连接是否WiFi连接
* @param mContext
* @return
*/
private boolean isWiFiConnected(Context mContext) {
boolean isWifiEnable = false;
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo!=null&&activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
isWifiEnable = true;
}
return isWifiEnable;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if (mLeakedException != null) {
Log.e(TAG, "Leak found", mLeakedException);
mLeakedException = null;
}
}
/**
* Block this thread from executing HTTP requests.
* Used to guard against HTTP requests blocking the main application thread.
* @param blocked if HTTP requests run on this thread should be denied
*/
public static void setThreadBlocked(boolean blocked) {
sThreadBlocked.set(blocked);
}
/**
* Modifies a request to indicate to the server that we would like a
* gzipped response. (Uses the "Accept-Encoding" HTTP header.)
* @param request the request to modify
* @see #getUngzippedContent
*/
public static void modifyRequestToAcceptGzipResponse(HttpRequest request) {
request.addHeader("Accept-Encoding", "gzip");
}
/**
* Gets the input stream from a response entity. If the entity is gzipped
* then this will get a stream over the uncompressed data.
*
* @param entity the entity whose content should be read
* @return the input stream to read from
* @throws IOException
*/
public static InputStream getUngzippedContent(HttpEntity entity) throws IOException {
InputStream responseStream = entity.getContent();
if (responseStream == null)
return responseStream;
Header header = entity.getContentEncoding();
if (header == null)
return responseStream;
String contentEncoding = header.getValue();
if (contentEncoding == null)
return responseStream;
if (contentEncoding.contains("gzip"))
responseStream = new GZIPInputStream(responseStream);
return responseStream;
}
/**
* Release resources associated with this client. You must call this,
* or significant resources (sockets and memory) may be leaked.
*/
public void close() {
if (mLeakedException != null) {
getConnectionManager().shutdown();
mLeakedException = null;
}
}
public HttpParams getParams() {
return delegate.getParams();
}
public ClientConnectionManager getConnectionManager() {
return delegate.getConnectionManager();
}
public HttpResponse execute(HttpUriRequest request) throws IOException {
return delegate.execute(request);
}
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
return delegate.execute(request, context);
}
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
return delegate.execute(target, request);
}
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
return delegate.execute(target, request, context);
}
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
throws IOException, ClientProtocolException {
return delegate.execute(request, responseHandler);
}
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
throws IOException, ClientProtocolException {
return delegate.execute(request, responseHandler, context);
}
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {
return delegate.execute(target, request, responseHandler);
}
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException {
return delegate.execute(target, request, responseHandler, context);
}
/* cURL logging support. */
/**
* Logging tag and level.
*/
private static class LoggingConfiguration {
private final String tag;
private final int level;
private LoggingConfiguration(String tag, int level) {
this.tag = tag;
this.level = level;
}
/**
* Returns true if logging is turned on for this configuration.
*/
private boolean isLoggable() {
return Log.isLoggable(tag, level);
}
/**
* Returns true if auth logging is turned on for this configuration. Can only be set on
* insecure devices.
*/
private boolean isAuthLoggable() {
// String secure = SystemProperties.get("ro.secure");
// return "0".equals(secure) && Log.isLoggable(tag + "-auth", level);
return false;
}
/**
* Prints a message using this configuration.
*/
private void println(String message) {
Log.println(level, tag, message);
}
}
/** cURL logging configuration. */
private volatile LoggingConfiguration curlConfiguration;
/**
* Enables cURL request logging for this client.
*
* @param name to log messages with
* @param level at which to log messages (see {@link android.util.Log})
*/
public void enableCurlLogging(String name, int level) {
if (name == null) {
throw new NullPointerException("name");
}
if (level < Log.VERBOSE || level > Log.ASSERT) {
throw new IllegalArgumentException("Level is out of range ["
+ Log.VERBOSE + ".." + Log.ASSERT + "]");
}
curlConfiguration = new LoggingConfiguration(name, level);
}
/**
* Disables cURL logging for this client.
*/
public void disableCurlLogging() {
curlConfiguration = null;
}
/**
* Logs cURL commands equivalent to requests.
*/
private class CurlLogger implements HttpRequestInterceptor {
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
LoggingConfiguration configuration = curlConfiguration;
if (configuration != null && configuration.isLoggable() && request instanceof HttpUriRequest) {
configuration.println(toCurl((HttpUriRequest) request, configuration.isAuthLoggable()));
}
}
}
/**
* Generates a cURL command equivalent to the given request.
*/
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("curl ");
for (Header header: request.getAllHeaders()) {
if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
continue;
}
builder.append("--header \"");
builder.append(header.toString().trim());
builder.append("\" ");
}
URI uri = request.getURI();
// If this is a wrapped request, use the URI from the original
// request instead. getURI() on the wrapper seems to return a
// relative URI. We want an absolute URI.
if (request instanceof RequestWrapper) {
HttpRequest original = ((RequestWrapper) request).getOriginal();
if (original instanceof HttpUriRequest) {
uri = ((HttpUriRequest) original).getURI();
}
}
builder.append("\"");
builder.append(uri);
builder.append("\"");
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = entityRequest.getEntity();
if (entity != null && entity.isRepeatable()) {
if (entity.getContentLength() < 1024) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
entity.writeTo(stream);
String entityString = stream.toString();
// TODO: Check the content type, too.
builder.append(" --data-ascii \"").append(entityString).append("\"");
} else {
builder.append(" [TOO MUCH DATA TO INCLUDE]");
}
}
}
return builder.toString();
}
}
| Java |
package com.outsourcing.bottle.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import android.os.Environment;
import android.os.StatFs;
public class FileOperation {
private String filename = null;
private String rootName = null;
private String suffix = ".dat";
public static final String PATH = android.os.Environment.getExternalStorageDirectory().getPath()+ "/com.xuanwu.etion/";
// private final String PATH="/mnt/sdcard/com.xuanwu.etion/";
// private final String PATH = "/data/data/com.xuanwu.etion/";
public int startPosition;
public boolean insertdata = false;
private static String secondarydir = "";
private File file;
/**
* 二级目录名
*
* @param dir
*/
public FileOperation(String dir, String suffix) {
secondarydir = dir;
if (suffix != null)
this.suffix = suffix;
}
/**
* 创建打开文件
*
* @param name
*/
public boolean initFile(String name) {
filename = PATH + secondarydir + "/";
if (FileOperation.checkSDcard()) {
try {
if (name != null && name.length() > 1) {
file = new File(filename);
if (!file.exists()) {
file.mkdirs();
}
if (name != null && !"".equals(name)) {
filename = filename + name + suffix;
file = new File(filename);
if (!file.exists()) {
file.createNewFile();// 文件不存在则新建
}
}
} else {
file = new File(filename);
if (!file.exists()) {
file.mkdirs();
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建文件失败");
return false;
}
return true;
} else {
return false;
}
}
/**
* 创建打开文件
*
* @param name
*/
public boolean initFile(String path, String name) {
filename = path + secondarydir + "/";
if (FileOperation.checkSDcard()) {
try {
if (name != null && name.length() > 1) {
file = new File(filename);
if (!file.exists()) {
file.mkdirs();
}
if (name != null && !"".equals(name)) {
filename = filename + name + suffix;
file = new File(filename);
if (!file.exists()) {
file.createNewFile();// 文件不存在则新建
}
}
} else {
file = new File(filename);
if (!file.exists()) {
file.mkdirs();
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建文件失败");
return false;
}
return true;
} else {
return false;
}
}
public long getFileSize()
{
if (!file.exists()) {
return -1;
}
return file.length();
}
/**
* 检测是否支持存储卡
*
* @return
*/
public static String getRootName() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return "可用sdcrad";
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
/*
* 判断是否有SD卡
*/
public synchronized static boolean checkSDcard() {
String status = android.os.Environment.getExternalStorageState();
if (status.equals(android.os.Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
public synchronized static boolean lowSDcard() {
if (getAvailaleSize() <= 5 * 1024 * 1024) {
return true;
}
return false;
}
public static long getAvailaleSize() {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
/* 获取block的SIZE */
long blockSize = stat.getBlockSize();
/* 空闲的Block的数量 */
long availableBlocks = stat.getAvailableBlocks();
/* 返回bit大小值 */
return availableBlocks * blockSize;
}
/**
* 获取文件列表
*
* @param path
* @return
*/
public String[] getFileList() {
if (FileOperation.checkSDcard()) {
Vector<String> fileName = new Vector<String>();
if (file.exists() && file.isDirectory()) {
String[] str = file.list();
for (String s : str) {
if (new File(filename + s).isFile()) {
fileName.addElement(s.substring(0, s.lastIndexOf(".")));
}
}
return fileName.toArray(new String[] {});
}
}
return null;
}
/**
* 添加一行记录
*
* @param data
*/
public boolean addLine(byte[] data) {
/*
* try{ FileOutputStream fos = new FileOutputStream(file);
* ObjectOutputStream objOS = new ObjectOutputStream(fos);
* objOS.write(data); objOS.flush(); objOS.close();
*
* }catch(Exception e){ System.out.println("写存储卡错误");
* e.printStackTrace(); return false; }
*/
if (FileOperation.checkSDcard()) {
if (!file.exists()) {
return false;
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
System.out.println("写存储卡错误");
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println("写存储卡错误");
e.printStackTrace();
return false;
}
}
return true;
}
public void closeFile() {
try {
if (file != null) {
file = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 返回当前文件流
*
* @return
*/
public byte[] getData() {
if (FileOperation.checkSDcard()) {
if (file == null || !file.exists()) {
return null;
}
int length = (int) file.length();
byte[] b = new byte[length];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(b, 0, length);
fis.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return length != 0 ? b : null;
}
return null;
}
public boolean extraAddLine(byte[] data) {
if (FileOperation.checkSDcard()) {
if (file == null || !file.exists()) {
return false;
}
int length = (int) file.length();
byte[] b = new byte[length];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(b, 0, length);
fis.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
try {
FileOutputStream fos = new FileOutputStream(file);
if (b != null)
fos.write(b);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
System.out.println("写存储卡错误");
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println("写存储卡错误");
e.printStackTrace();
return false;
}
}
return true;
}
/**
* 删除文件
*/
public boolean deleteFile() {
try {
if (file != null)
file.delete();
} catch (Exception e) {
System.out.println("删除文件IO异常");
return false;
}
return true;
}
/**
* 判断文件是否存在
*
* @param name
* @return
*/
public boolean exist(String name) {
String mypath = PATH + secondarydir + "/";
File file = new File(mypath, name + suffix);
return file.exists();
}
/**
* 删除目录 如果目录下有子目录或文件,也全部删除
*
* @param pathName
*/
public static boolean deletDirectory(String pathName) {
boolean del = false;
if (FileOperation.checkSDcard()) {
File file = new File(pathName);
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
String[] f = file.list();
for (int i = 0; i < f.length; i++) {
deletDirectory(pathName + "/" + f[i]);
}
del = file.delete();
}
}
}
return del;
}
public static void deleteAllFile() {
delDir(PATH);
}
/**
* 删除目录 如果目录下有子目录或文件,也全部删除
*/
private static void delDir(String pathName) {
boolean del = false;
File file = new File(pathName);
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
String[] f = file.list();
for (int i = 0; i < f.length; i++) {
deletDirectory(pathName + "/" + f[i]);
}
del = file.delete();
}
}
}
/*--------------用于下载----------------------*/
/**
* 获得下载file
*
* @param fileName
* @param downloadSize
* 已下载的长度
* @return
*/
public File initDownloadFile(String fileName) {
if (null == fileName)
file = null;
filename = PATH + secondarydir;
file = new File(filename);
if (!file.exists())
file.mkdirs();
file = new File(filename, fileName + suffix);
return file;
}
public File getDownloadFile(String fileName) {
return new File(PATH + secondarydir + '/' + fileName);
}
public static String getDownloadedFilePath(String fileName) {
return PATH + secondarydir + '/' + fileName;
}
/**
* 获得下载 文件夹里的文件
*
* @return
*/
public File[] getDowloadFiles() {
filename = PATH + secondarydir;
file = new File(filename);
if (!file.exists())
return null;
else
return file.listFiles();
}
/**
* 遍历翼讯全文件
* @param name
*/
/**
* 删除目录
* 如果目录下有子目录或文件,也全部删除
*/
public boolean initAllFile(String name){
String fname = name+suffix;
File dir = new File(PATH);
if(dir.exists() && dir.isDirectory()){
File[] f = dir.listFiles();
for(int i=0;i<f.length;i++){
if(initAllFile(f[i],fname)){
return true;
}
}
}
return false;
}
private boolean initAllFile(File dir,String name){
if(FileOperation.checkSDcard() && name!=null && !"".equals(name.trim())){
//System.out.println(dir.getPath());
if(dir.exists()){
if(dir.isDirectory()){
File[] f = dir.listFiles();
for(int i=0;i<f.length;i++){
if(initAllFile(f[i],name)){
return true;
}
}
}else if(dir.isFile() && dir.exists() && dir.length()>0 && name.equals(dir.getName())){
file = dir;
filename = dir.getPath();
return true;
}
}
}
return false;
}
/*------------------------------------*/
public static File getFileFromBytes(byte[] b, String outputFile) {
BufferedOutputStream stream = null;
File file = null;
try {
file = new File("/ssdadad");
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return file;
}
public File getFile() {
return file;
}
}
| Java |
package com.android;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.util.Log;
/**
*
* @author 06peng
*
*/
public class ShellCommand {
private static final String TAG = "ShellCommand.java";
private Boolean can_su;
public SH sh;
public SH su;
public SH normal;
public ShellCommand() {
sh = new SH("sh");
su = new SH("su");
normal = new SH("");
}
public boolean canSU() {
return canSU(false);
}
public boolean canSU(boolean force_check) {
if (can_su == null || force_check) {
CommandResult r = su.runWaitFor("id");
StringBuilder out = new StringBuilder();
if (r.stdout != null)
out.append(r.stdout).append(" ; ");
if (r.stderr != null)
out.append(r.stderr);
Log.v(TAG, "canSU() su[" + r.exit_value + "]: " + out);
can_su = r.success();
}
return can_su;
}
/*
* public SH suOrSH() { return canSU() ? su : sh; }
*/
public class CommandResult {
public final String stdout;
public final String stderr;
public final Integer exit_value;
CommandResult(Integer exit_value_in, String stdout_in, String stderr_in) {
exit_value = exit_value_in;
stdout = stdout_in;
stderr = stderr_in;
}
CommandResult(Integer exit_value_in) {
this(exit_value_in, null, null);
}
public boolean success() {
return exit_value != null && exit_value == 0;
}
}
public class SH {
private String SHELL = "sh";
public SH(String SHELL_in) {
SHELL = SHELL_in;
}
private Process run(String s) {
Process process = null;
if (SHELL.equals("")) {
try {
process = Runtime.getRuntime().exec(s);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
process = Runtime.getRuntime().exec(SHELL);
DataOutputStream toProcess = new DataOutputStream(process.getOutputStream());
toProcess.writeBytes("exec " + s + "\n");
toProcess.flush();
} catch (Exception e) {
Log.e(TAG, "Exception while trying to run: '" + s + "' "
+ e.getMessage());
process = null;
}
}
return process;
}
private String getStreamLines(InputStream is) {
String out = null;
StringBuffer buffer = null;
DataInputStream dis = new DataInputStream(is);
try {
if (dis.available() > 0) {
buffer = new StringBuffer(dis.readLine());
while (dis.available() > 0)
buffer.append("!!").append(dis.readLine());
}
dis.close();
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
if (buffer != null)
out = buffer.toString();
return out;
}
public CommandResult runWaitFor(String s) {
Process process = run(s);
Integer exit_value = null;
String stdout = null;
String stderr = null;
if (process != null) {
try {
exit_value = process.waitFor();
stdout = getStreamLines(process.getInputStream());
stderr = getStreamLines(process.getErrorStream());
} catch (InterruptedException e) {
Log.e(TAG, "runWaitFor " + e.toString());
} catch (NullPointerException e) {
Log.e(TAG, "runWaitFor " + e.toString());
}
}
return new CommandResult(exit_value, stdout, stderr);
}
}
}
| Java |
/* Copyright (c) 2008 Google Inc.
*
* 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.google.gdata.util.common.base;
import static com.google.gdata.util.common.base.Preconditions.checkNotNull;
import java.io.IOException;
/**
* An {@link Escaper} that converts literal text into a format safe for
* inclusion in a particular context (such as an XML document). Typically (but
* not always), the inverse process of "unescaping" the text is performed
* automatically by the relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one
* very important difference. A CharEscaper can only process Java
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in
* isolation and may not cope when it encounters surrogate pairs. This class
* facilitates the correct escaping of all Unicode characters.
*
* <p>As there are important reasons, including potential security issues, to
* handle Unicode correctly if you are considering implementing a new escaper
* you should favor using UnicodeEscaper wherever possible.
*
* <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe
* when used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in the class {@link
* CharEscapers}. To create your own escapers extend this class and implement
* the {@link #escape(int)} method.
*
*
*/
public abstract class UnicodeEscaper implements Escaper {
/** The amount of padding (chars) to use when growing the escape buffer. */
private static final int DEST_PAD = 32;
/**
* Returns the escaped form of the given Unicode code point, or {@code null}
* if this code point does not need to be escaped. When called as part of an
* escaping operation, the given code point is guaranteed to be in the range
* {@code 0 <= cp <= Character#MAX_CODE_POINT}.
*
* <p>If an empty array is returned, this effectively strips the input
* character from the resulting text.
*
* <p>If the character does not need to be escaped, this method should return
* {@code null}, rather than an array containing the character representation
* of the code point. This enables the escaping algorithm to perform more
* efficiently.
*
* <p>If the implementation of this method cannot correctly handle a
* particular code point then it should either throw an appropriate runtime
* exception or return a suitable replacement character. It must never
* silently discard invalid input as this may constitute a security risk.
*
* @param cp the Unicode code point to escape if necessary
* @return the replacement characters, or {@code null} if no escaping was
* needed
*/
protected abstract char[] escape(int cp);
/**
* Scans a sub-sequence of characters from a given {@link CharSequence},
* returning the index of the next character that requires escaping.
*
* <p><b>Note:</b> When implementing an escaper, it is a good idea to override
* this method for efficiency. The base class implementation determines
* successive Unicode code points and invokes {@link #escape(int)} for each of
* them. If the semantics of your escaper are such that code points in the
* supplementary range are either all escaped or all unescaped, this method
* can be implemented more efficiently using {@link CharSequence#charAt(int)}.
*
* <p>Note however that if your escaper does not escape characters in the
* supplementary range, you should either continue to validate the correctness
* of any surrogate characters encountered or provide a clear warning to users
* that your escaper does not validate its input.
*
* <p>See {@link PercentEscaper} for an example.
*
* @param csq a sequence of characters
* @param start the index of the first character to be scanned
* @param end the index immediately after the last character to be scanned
* @throws IllegalArgumentException if the scanned sub-sequence of {@code csq}
* contains invalid surrogate pairs
*/
protected int nextEscapeIndex(CharSequence csq, int start, int end) {
int index = start;
while (index < end) {
int cp = codePointAt(csq, index, end);
if (cp < 0 || escape(cp) != null) {
break;
}
index += Character.isSupplementaryCodePoint(cp) ? 2 : 1;
}
return index;
}
/**
* Returns the escaped form of a given literal string.
*
* <p>If you are escaping input in arbitrary successive chunks, then it is not
* generally safe to use this method. If an input string ends with an
* unmatched high surrogate character, then this method will throw
* {@link IllegalArgumentException}. You should either ensure your input is
* valid <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before
* calling this method or use an escaped {@link Appendable} (as returned by
* {@link #escape(Appendable)}) which can cope with arbitrarily split input.
*
* <p><b>Note:</b> When implementing an escaper it is a good idea to override
* this method for efficiency by inlining the implementation of
* {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for
* {@link PercentEscaper} more than doubled the performance for unescaped
* strings (as measured by {@link CharEscapersBenchmark}).
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
public String escape(String string) {
int end = string.length();
int index = nextEscapeIndex(string, 0, end);
return index == end ? string : escapeSlow(string, index);
}
/**
* Returns the escaped form of a given literal string, starting at the given
* index. This method is called by the {@link #escape(String)} method when it
* discovers that escaping is required. It is protected to allow subclasses
* to override the fastpath escaping function to inline their escaping test.
* See {@link CharEscaperBuilder} for an example usage.
*
* <p>This method is not reentrant and may only be invoked by the top level
* {@link #escape(String)} method.
*
* @param s the literal string to be escaped
* @param index the index to start escaping from
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*/
protected final String escapeSlow(String s, int index) {
int end = s.length();
// Get a destination buffer and setup some loop variables.
char[] dest = DEST_TL.get();
int destIndex = 0;
int unescapedChunkStart = 0;
while (index < end) {
int cp = codePointAt(s, index, end);
if (cp < 0) {
throw new IllegalArgumentException(
"Trailing high surrogate at end of input");
}
char[] escaped = escape(cp);
if (escaped != null) {
int charsSkipped = index - unescapedChunkStart;
// This is the size needed to add the replacement, not the full
// size needed by the string. We only regrow when we absolutely must.
int sizeNeeded = destIndex + charsSkipped + escaped.length;
if (dest.length < sizeNeeded) {
int destLength = sizeNeeded + (end - index) + DEST_PAD;
dest = growBuffer(dest, destIndex, destLength);
}
// If we have skipped any characters, we need to copy them now.
if (charsSkipped > 0) {
s.getChars(unescapedChunkStart, index, dest, destIndex);
destIndex += charsSkipped;
}
if (escaped.length > 0) {
System.arraycopy(escaped, 0, dest, destIndex, escaped.length);
destIndex += escaped.length;
}
}
unescapedChunkStart
= index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
index = nextEscapeIndex(s, unescapedChunkStart, end);
}
// Process trailing unescaped characters - no need to account for escaped
// length or padding the allocation.
int charsSkipped = end - unescapedChunkStart;
if (charsSkipped > 0) {
int endIndex = destIndex + charsSkipped;
if (dest.length < endIndex) {
dest = growBuffer(dest, destIndex, endIndex);
}
s.getChars(unescapedChunkStart, end, dest, destIndex);
destIndex = endIndex;
}
return new String(dest, 0, destIndex);
}
/**
* Returns an {@code Appendable} instance which automatically escapes all
* text appended to it before passing the resulting text to an underlying
* {@code Appendable}.
*
* <p>Unlike {@link #escape(String)} it is permitted to append arbitrarily
* split input to this Appendable, including input that is split over a
* surrogate pair. In this case the pending high surrogate character will not
* be processed until the corresponding low surrogate is appended. This means
* that a trailing high surrogate character at the end of the input cannot be
* detected and will be silently ignored. This is unavoidable since the
* Appendable interface has no {@code close()} method, and it is impossible to
* determine when the last characters have been appended.
*
* <p>The methods of the returned object will propagate any exceptions thrown
* by the underlying {@code Appendable}.
*
* <p>For well formed <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>
* the escaping behavior is identical to that of {@link #escape(String)} and
* the following code is equivalent to (but much slower than)
* {@code escaper.escape(string)}: <pre>{@code
*
* StringBuilder sb = new StringBuilder();
* escaper.escape(sb).append(string);
* return sb.toString();}</pre>
*
* @param out the underlying {@code Appendable} to append escaped output to
* @return an {@code Appendable} which passes text to {@code out} after
* escaping it
* @throws NullPointerException if {@code out} is null
* @throws IllegalArgumentException if invalid surrogate characters are
* encountered
*
*/
public Appendable escape(final Appendable out) {
checkNotNull(out);
return new Appendable() {
int pendingHighSurrogate = -1;
char[] decodedChars = new char[2];
public Appendable append(CharSequence csq) throws IOException {
return append(csq, 0, csq.length());
}
public Appendable append(CharSequence csq, int start, int end)
throws IOException {
int index = start;
if (index < end) {
// This is a little subtle: index must never reference the middle of a
// surrogate pair but unescapedChunkStart can. The first time we enter
// the loop below it is possible that index != unescapedChunkStart.
int unescapedChunkStart = index;
if (pendingHighSurrogate != -1) {
// Our last append operation ended halfway through a surrogate pair
// so we have to do some extra work first.
char c = csq.charAt(index++);
if (!Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Expected low surrogate character but got " + c);
}
char[] escaped =
escape(Character.toCodePoint((char) pendingHighSurrogate, c));
if (escaped != null) {
// Emit the escaped character and adjust unescapedChunkStart to
// skip the low surrogate we have consumed.
outputChars(escaped, escaped.length);
unescapedChunkStart += 1;
} else {
// Emit pending high surrogate (unescaped) but do not modify
// unescapedChunkStart as we must still emit the low surrogate.
out.append((char) pendingHighSurrogate);
}
pendingHighSurrogate = -1;
}
while (true) {
// Find and append the next subsequence of unescaped characters.
index = nextEscapeIndex(csq, index, end);
if (index > unescapedChunkStart) {
out.append(csq, unescapedChunkStart, index);
}
if (index == end) {
break;
}
// If we are not finished, calculate the next code point.
int cp = codePointAt(csq, index, end);
if (cp < 0) {
// Our sequence ended half way through a surrogate pair so just
// record the state and exit.
pendingHighSurrogate = -cp;
break;
}
// Escape the code point and output the characters.
char[] escaped = escape(cp);
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
// This shouldn't really happen if nextEscapeIndex is correct but
// we should cope with false positives.
int len = Character.toChars(cp, decodedChars, 0);
outputChars(decodedChars, len);
}
// Update our index past the escaped character and continue.
index += (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
unescapedChunkStart = index;
}
}
return this;
}
public Appendable append(char c) throws IOException {
if (pendingHighSurrogate != -1) {
// Our last append operation ended halfway through a surrogate pair
// so we have to do some extra work first.
if (!Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Expected low surrogate character but got '" + c +
"' with value " + (int) c);
}
char[] escaped =
escape(Character.toCodePoint((char) pendingHighSurrogate, c));
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
out.append((char) pendingHighSurrogate);
out.append(c);
}
pendingHighSurrogate = -1;
} else if (Character.isHighSurrogate(c)) {
// This is the start of a (split) surrogate pair.
pendingHighSurrogate = c;
} else {
if (Character.isLowSurrogate(c)) {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c +
"' with value " + (int) c);
}
// This is a normal (non surrogate) char.
char[] escaped = escape(c);
if (escaped != null) {
outputChars(escaped, escaped.length);
} else {
out.append(c);
}
}
return this;
}
private void outputChars(char[] chars, int len) throws IOException {
for (int n = 0; n < len; n++) {
out.append(chars[n]);
}
}
};
}
/**
* Returns the Unicode code point of the character at the given index.
*
* <p>Unlike {@link Character#codePointAt(CharSequence, int)} or
* {@link String#codePointAt(int)} this method will never fail silently when
* encountering an invalid surrogate pair.
*
* <p>The behaviour of this method is as follows:
* <ol>
* <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.
* <li><b>If the character at the specified index is not a surrogate, it is
* returned.</b>
* <li>If the first character was a high surrogate value, then an attempt is
* made to read the next character.
* <ol>
* <li><b>If the end of the sequence was reached, the negated value of
* the trailing high surrogate is returned.</b>
* <li><b>If the next character was a valid low surrogate, the code point
* value of the high/low surrogate pair is returned.</b>
* <li>If the next character was not a low surrogate value, then
* {@link IllegalArgumentException} is thrown.
* </ol>
* <li>If the first character was a low surrogate value,
* {@link IllegalArgumentException} is thrown.
* </ol>
*
* @param seq the sequence of characters from which to decode the code point
* @param index the index of the first character to decode
* @param end the index beyond the last valid character to decode
* @return the Unicode code point for the given index or the negated value of
* the trailing high surrogate character at the end of the sequence
*/
protected static final int codePointAt(CharSequence seq, int index, int end) {
if (index < end) {
char c1 = seq.charAt(index++);
if (c1 < Character.MIN_HIGH_SURROGATE ||
c1 > Character.MAX_LOW_SURROGATE) {
// Fast path (first test is probably all we need to do)
return c1;
} else if (c1 <= Character.MAX_HIGH_SURROGATE) {
// If the high surrogate was the last character, return its inverse
if (index == end) {
return -c1;
}
// Otherwise look for the low surrogate following it
char c2 = seq.charAt(index);
if (Character.isLowSurrogate(c2)) {
return Character.toCodePoint(c1, c2);
}
throw new IllegalArgumentException(
"Expected low surrogate but got char '" + c2 +
"' with value " + (int) c2 + " at index " + index);
} else {
throw new IllegalArgumentException(
"Unexpected low surrogate character '" + c1 +
"' with value " + (int) c1 + " at index " + (index - 1));
}
}
throw new IndexOutOfBoundsException("Index exceeds specified range");
}
/**
* Helper method to grow the character buffer as needed, this only happens
* once in a while so it's ok if it's in a method call. If the index passed
* in is 0 then no copying will be done.
*/
private static final char[] growBuffer(char[] dest, int index, int size) {
char[] copy = new char[size];
if (index > 0) {
System.arraycopy(dest, 0, copy, 0, index);
}
return copy;
}
/**
* A thread-local destination buffer to keep us from creating new buffers.
* The starting size is 1024 characters. If we grow past this we don't
* put it back in the threadlocal, we just keep going and grow as needed.
*/
private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() {
@Override
protected char[] initialValue() {
return new char[1024];
}
};
}
| Java |
/*
* Copyright (C) 2007 Google Inc.
*
* 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.google.gdata.util.common.base;
import java.util.Collection;
import java.util.NoSuchElementException;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state. This allows constructs such as
* <pre>
* if (count <= 0) {
* throw new IllegalArgumentException("must be positive: " + count);
* }</pre>
*
* to be replaced with the more compact
* <pre>
* checkArgument(count > 0, "must be positive: %s", count);</pre>
*
* Note that the sense of the expression is inverted; with {@code Preconditions}
* you declare what you expect to be <i>true</i>, just as you do with an
* <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html">
* {@code assert}</a> or a JUnit {@code assertTrue()} call.
*
* <p>Take care not to confuse precondition checking with other similar types
* of checks! Precondition exceptions -- including those provided here, but also
* {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link
* UnsupportedOperationException} and others -- are used to signal that the
* <i>calling method</i> has made an error. This tells the caller that it should
* not have invoked the method when it did, with the arguments it did, or
* perhaps <i>ever</i>. Postcondition or other invariant failures should not
* throw these types of exceptions.
*
* <p><b>Note:</b> The methods of the {@code Preconditions} class are highly
* unusual in one way: they are <i>supposed to</i> throw exceptions, and promise
* in their specifications to do so even when given perfectly valid input. That
* is, {@code null} is a valid parameter to the method {@link
* #checkNotNull(Object)} -- and technically this parameter could be even marked
* as {@link Nullable} -- yet the method will still throw an exception anyway,
* because that's what its contract says to do.
*
* <p>This class may be used with the Google Web Toolkit (GWT).
*
*
*/
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkState(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(T iterable) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException();
}
return iterable;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(
T iterable, Object errorMessage) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return iterable;
}
/**
* Ensures that an {@code Iterable} object passed as a parameter to the
* calling method is not null and contains no null elements.
*
* @param iterable the iterable to check the contents of
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null {@code iterable} reference just validated
* @throws NullPointerException if {@code iterable} is null or contains at
* least one null element
*/
public static <T extends Iterable<?>> T checkContentsNotNull(T iterable,
String errorMessageTemplate, Object... errorMessageArgs) {
if (containsOrIsNull(iterable)) {
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return iterable;
}
private static boolean containsOrIsNull(Iterable<?> iterable) {
if (iterable == null) {
return true;
}
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
try {
return collection.contains(null);
} catch (NullPointerException e) {
// A NPE implies that the collection doesn't contain null.
return false;
}
} else {
for (Object element : iterable) {
if (element == null) {
return true;
}
}
return false;
}
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkElementIndex(int index, int size) {
checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkElementIndex(int index, int size, String desc) {
checkArgument(size >= 0, "negative size: %s", size);
if (index < 0) {
throw new IndexOutOfBoundsException(
format("%s (%s) must not be negative", desc, index));
}
if (index >= size) {
throw new IndexOutOfBoundsException(
format("%s (%s) must be less than size (%s)", desc, index, size));
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndex(int index, int size) {
checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndex(int index, int size, String desc) {
checkArgument(size >= 0, "negative size: %s", size);
if (index < 0) {
throw new IndexOutOfBoundsException(format(
"%s (%s) must not be negative", desc, index));
}
if (index > size) {
throw new IndexOutOfBoundsException(format(
"%s (%s) must not be greater than size (%s)", desc, index, size));
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i>
* in an array, list or string of size {@code size}, and are in order. A
* position index may range from zero to {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an
* array, list or string
* @param end a user-supplied index identifying a ending position in an array,
* list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is
* greater than {@code size}, or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
checkPositionIndex(start, size, "start index");
checkPositionIndex(end, size, "end index");
if (end < start) {
throw new IndexOutOfBoundsException(format(
"end index (%s) must not be less than start index (%s)", end, start));
}
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
*
* @param template a non-null string containing 0 or more {@code %s}
* placeholders.
* @param args the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}. Arguments can be null.
*/
// VisibleForTesting
static String format(String template, Object... args) {
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append("]");
}
return builder.toString();
}
}
| Java |
/* Copyright (c) 2008 Google Inc.
*
* 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.google.gdata.util.common.base;
/**
* An object that converts literal text into a format safe for inclusion in a
* particular context (such as an XML document). Typically (but not always), the
* inverse process of "unescaping" the text is performed automatically by the
* relevant parser.
*
* <p>For example, an XML escaper would convert the literal string {@code
* "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from
* being confused with an XML tag. When the resulting XML document is parsed,
* the parser API will return this text as the original literal string {@code
* "Foo<Bar>"}.
*
* <p>An {@code Escaper} instance is required to be stateless, and safe when
* used concurrently by multiple threads.
*
* <p>Several popular escapers are defined as constants in the class {@link
* CharEscapers}. To create your own escapers, use {@link
* CharEscaperBuilder}, or extend {@link CharEscaper} or {@code UnicodeEscaper}.
*
*
*/
public interface Escaper {
/**
* Returns the escaped form of a given literal string.
*
* <p>Note that this method may treat input characters differently depending on
* the specific escaper implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly,
* including surrogate character pairs. If the input is badly formed the
* escaper should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not
* verify the input for well formed characters. A CharEscaper should not be
* used in situations where input is not guaranteed to be restricted to the
* Basic Multilingual Plane (BMP).
* </ul>
*
* @param string the literal string to be escaped
* @return the escaped form of {@code string}
* @throws NullPointerException if {@code string} is null
* @throws IllegalArgumentException if {@code string} contains badly formed
* UTF-16 or cannot be escaped for any other reason
*/
public String escape(String string);
/**
* Returns an {@code Appendable} instance which automatically escapes all
* text appended to it before passing the resulting text to an underlying
* {@code Appendable}.
*
* <p>Note that this method may treat input characters differently depending on
* the specific escaper implementation.
* <ul>
* <li>{@link UnicodeEscaper} handles
* <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> correctly,
* including surrogate character pairs. If the input is badly formed the
* escaper should throw {@link IllegalArgumentException}.
* <li>{@link CharEscaper} handles Java characters independently and does not
* verify the input for well formed characters. A CharEscaper should not be
* used in situations where input is not guaranteed to be restricted to the
* Basic Multilingual Plane (BMP).
* </ul>
*
* @param out the underlying {@code Appendable} to append escaped output to
* @return an {@code Appendable} which passes text to {@code out} after
* escaping it.
*/
public Appendable escape(Appendable out);
}
| Java |
/* Copyright (c) 2008 Google Inc.
*
* 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.google.gdata.util.common.base;
/**
* A {@code UnicodeEscaper} that escapes some set of Java characters using
* the URI percent encoding scheme. The set of safe characters (those which
* remain unescaped) can be specified on construction.
*
* <p>For details on escaping URIs for use in web pages, see section 2.4 of
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>In most cases this class should not need to be used directly. If you
* have no special requirements for escaping your URIs, you should use either
* {@link CharEscapers#uriEscaper()} or
* {@link CharEscapers#uriEscaper(boolean)}.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>Any additionally specified safe characters remain the same.
* <li>If {@code plusForSpace} was specified, the space character " " is
* converted into a plus sign "+".
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal representation
* of the byte value.
* </ul>
*
* <p>RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!",
* "~", "*", "'", "(" and ")". It goes on to state:
*
* <p><i>Unreserved characters can be escaped without changing the semantics
* of the URI, but this should not be done unless the URI is being used
* in a context that does not allow the unescaped character to appear.</i>
*
* <p>For performance reasons the only currently supported character encoding of
* this class is UTF-8.
*
* <p><b>Note</b>: This escaper produces uppercase hexidecimal sequences. From
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
*
*/
public class PercentEscaper extends UnicodeEscaper {
/**
* A string of safe characters that mimics the behavior of
* {@link java.net.URLEncoder}.
*
*/
public static final String SAFECHARS_URLENCODER = "-_.*";
/**
* A string of characters that do not need to be encoded when used in URI
* path segments, as specified in RFC 3986. Note that some of these
* characters do need to be escaped when used in other parts of the URI.
*/
public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;=";
/**
* A string of characters that do not need to be encoded when used in URI
* query strings, as specified in RFC 3986. Note that some of these
* characters do need to be escaped when used in other parts of the URI.
*/
public static final String SAFEQUERYSTRINGCHARS_URLENCODER
= "-_.!~*'()@:$,;/?:";
// In some uri escapers spaces are escaped to '+'
private static final char[] URI_ESCAPED_SPACE = { '+' };
private static final char[] UPPER_HEX_DIGITS =
"0123456789ABCDEF".toCharArray();
/**
* If true we should convert space to the {@code +} character.
*/
private final boolean plusForSpace;
/**
* An array of flags where for any {@code char c} if {@code safeOctets[c]} is
* true then {@code c} should remain unmodified in the output. If
* {@code c > safeOctets.length} then it should be escaped.
*/
private final boolean[] safeOctets;
/**
* Constructs a URI escaper with the specified safe characters and optional
* handling of the space character.
*
* @param safeChars a non null string specifying additional safe characters
* for this escaper (the ranges 0..9, a..z and A..Z are always safe and
* should not be specified here)
* @param plusForSpace true if ASCII space should be escaped to {@code +}
* rather than {@code %20}
* @throws IllegalArgumentException if any of the parameters were invalid
*/
public PercentEscaper(String safeChars, boolean plusForSpace) {
// Avoid any misunderstandings about the behavior of this escaper
if (safeChars.matches(".*[0-9A-Za-z].*")) {
throw new IllegalArgumentException(
"Alphanumeric characters are always 'safe' and should not be " +
"explicitly specified");
}
// Avoid ambiguous parameters. Safe characters are never modified so if
// space is a safe character then setting plusForSpace is meaningless.
if (plusForSpace && safeChars.contains(" ")) {
throw new IllegalArgumentException(
"plusForSpace cannot be specified when space is a 'safe' character");
}
if (safeChars.contains("%")) {
throw new IllegalArgumentException(
"The '%' character cannot be specified as 'safe'");
}
this.plusForSpace = plusForSpace;
this.safeOctets = createSafeOctets(safeChars);
}
/**
* Creates a boolean[] with entries corresponding to the character values
* for 0-9, A-Z, a-z and those specified in safeChars set to true. The array
* is as small as is required to hold the given character information.
*/
private static boolean[] createSafeOctets(String safeChars) {
int maxChar = 'z';
char[] safeCharArray = safeChars.toCharArray();
for (char c : safeCharArray) {
maxChar = Math.max(c, maxChar);
}
boolean[] octets = new boolean[maxChar + 1];
for (int c = '0'; c <= '9'; c++) {
octets[c] = true;
}
for (int c = 'A'; c <= 'Z'; c++) {
octets[c] = true;
}
for (int c = 'a'; c <= 'z'; c++) {
octets[c] = true;
}
for (char c : safeCharArray) {
octets[c] = true;
}
return octets;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~760ns to ~400ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
protected int nextEscapeIndex(CharSequence csq, int index, int end) {
for (; index < end; index++) {
char c = csq.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
break;
}
}
return index;
}
/*
* Overridden for performance. For unescaped strings this improved the
* performance of the uri escaper from ~400ns to ~170ns as measured by
* {@link CharEscapersBenchmark}.
*/
@Override
public String escape(String s) {
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if (c >= safeOctets.length || !safeOctets[c]) {
return escapeSlow(s, index);
}
}
return s;
}
/**
* Escapes the given Unicode code point in UTF-8.
*/
@Override
protected char[] escape(int cp) {
// We should never get negative values here but if we do it will throw an
// IndexOutOfBoundsException, so at least it will get spotted.
if (cp < safeOctets.length && safeOctets[cp]) {
return null;
} else if (cp == ' ' && plusForSpace) {
return URI_ESCAPED_SPACE;
} else if (cp <= 0x7F) {
// Single byte UTF-8 characters
// Start with "%--" and fill in the blanks
char[] dest = new char[3];
dest[0] = '%';
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
dest[1] = UPPER_HEX_DIGITS[cp >>> 4];
return dest;
} else if (cp <= 0x7ff) {
// Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff]
// Start with "%--%--" and fill in the blanks
char[] dest = new char[6];
dest[0] = '%';
dest[3] = '%';
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[1] = UPPER_HEX_DIGITS[0xC | cp];
return dest;
} else if (cp <= 0xffff) {
// Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff]
// Start with "%E-%--%--" and fill in the blanks
char[] dest = new char[9];
dest[0] = '%';
dest[1] = 'E';
dest[3] = '%';
dest[6] = '%';
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp];
return dest;
} else if (cp <= 0x10ffff) {
char[] dest = new char[12];
// Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff]
// Start with "%F-%--%--%--" and fill in the blanks
dest[0] = '%';
dest[1] = 'F';
dest[3] = '%';
dest[6] = '%';
dest[9] = '%';
dest[11] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[8] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[5] = UPPER_HEX_DIGITS[cp & 0xF];
cp >>>= 4;
dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)];
cp >>>= 2;
dest[2] = UPPER_HEX_DIGITS[cp & 0x7];
return dest;
} else {
// If this ever happens it is due to bug in UnicodeEscaper, not bad input.
throw new IllegalArgumentException(
"Invalid unicode character value " + cp);
}
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (C) 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.viewpagerindicator;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.outsourcing.bottle.R;
/**
* This widget implements the dynamic action bar tab behavior that can change
* across different configurations or circumstances.
*/
public class TabPageIndicator extends HorizontalScrollView implements PageIndicator {
Runnable mTabSelector;
private OnClickListener mTabClickListener = new OnClickListener() {
public void onClick(View view) {
TabView tabView = (TabView)view;
mViewPager.setCurrentItem(tabView.getIndex());
}
};
private LinearLayout mTabLayout;
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mListener;
private LayoutInflater mInflater;
int mMaxTabWidth;
private int mSelectedTabIndex;
public TabPageIndicator(Context context) {
this(context, null);
}
public TabPageIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
setHorizontalScrollBarEnabled(false);
mInflater = LayoutInflater.from(context);
mTabLayout = new LinearLayout(getContext());
addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT));
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY;
setFillViewport(lockedExpanded);
final int childCount = mTabLayout.getChildCount();
if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) {
if (childCount > 2) {
mMaxTabWidth = (int)(MeasureSpec.getSize(widthMeasureSpec) * 0.4f);
} else {
mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2;
}
} else {
mMaxTabWidth = -1;
}
final int oldWidth = getMeasuredWidth();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int newWidth = getMeasuredWidth();
if (lockedExpanded && oldWidth != newWidth) {
// Recenter the tab display if we're at a new (scrollable) size.
setCurrentItem(mSelectedTabIndex);
}
}
private void animateToTab(final int position) {
final View tabView = mTabLayout.getChildAt(position);
if (mTabSelector != null) {
removeCallbacks(mTabSelector);
}
mTabSelector = new Runnable() {
public void run() {
final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2;
smoothScrollTo(scrollPos, 0);
mTabSelector = null;
}
};
post(mTabSelector);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
if (mTabSelector != null) {
// Re-post the selector we saved
post(mTabSelector);
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mTabSelector != null) {
removeCallbacks(mTabSelector);
}
}
private void addTab(String text, int index) {
//Workaround for not being able to pass a defStyle on pre-3.0
final TabView tabView = (TabView)mInflater.inflate(R.layout.vpi__tab, null);
tabView.init(this, text, index);
tabView.setFocusable(true);
tabView.setOnClickListener(mTabClickListener);
mTabLayout.addView(tabView, new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, 1));
}
@Override
public void onPageScrollStateChanged(int arg0) {
if (mListener != null) {
mListener.onPageScrollStateChanged(arg0);
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
if (mListener != null) {
mListener.onPageScrolled(arg0, arg1, arg2);
}
}
@Override
public void onPageSelected(int arg0) {
setCurrentItem(arg0);
if (mListener != null) {
mListener.onPageSelected(arg0);
}
}
@Override
public void setViewPager(ViewPager view) {
final PagerAdapter adapter = view.getAdapter();
if (adapter == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
if (!(adapter instanceof TitleProvider)) {
throw new IllegalStateException("ViewPager adapter must implement TitleProvider to be used with TitlePageIndicator.");
}
mViewPager = view;
view.setOnPageChangeListener(this);
notifyDataSetChanged();
}
public void notifyDataSetChanged() {
mTabLayout.removeAllViews();
TitleProvider adapter = (TitleProvider)mViewPager.getAdapter();
final int count = ((PagerAdapter)adapter).getCount();
for (int i = 0; i < count; i++) {
addTab(adapter.getTitle(i), i);
}
if (mSelectedTabIndex > count) {
mSelectedTabIndex = count - 1;
}
setCurrentItem(mSelectedTabIndex);
requestLayout();
}
@Override
public void setViewPager(ViewPager view, int initialPosition) {
setViewPager(view);
setCurrentItem(initialPosition);
}
@Override
public void setCurrentItem(int item) {
if (mViewPager == null) {
throw new IllegalStateException("ViewPager has not been bound.");
}
mSelectedTabIndex = item;
final int tabCount = mTabLayout.getChildCount();
for (int i = 0; i < tabCount; i++) {
final View child = mTabLayout.getChildAt(i);
final boolean isSelected = (i == item);
child.setSelected(isSelected);
if (isSelected) {
animateToTab(item);
}
}
}
@Override
public void setOnPageChangeListener(OnPageChangeListener listener) {
mListener = listener;
}
public static class TabView extends LinearLayout {
private TabPageIndicator mParent;
private int mIndex;
public TabView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void init(TabPageIndicator parent, String text, int index) {
mParent = parent;
mIndex = index;
TextView textView = (TextView)findViewById(android.R.id.text1);
textView.setText(text);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Re-measure if we went beyond our maximum size.
if (mParent.mMaxTabWidth > 0 && getMeasuredWidth() > mParent.mMaxTabWidth) {
super.onMeasure(MeasureSpec.makeMeasureSpec(mParent.mMaxTabWidth, MeasureSpec.EXACTLY),
heightMeasureSpec);
}
}
public int getIndex() {
return mIndex;
}
}
}
| Java |
/*
* Copyright (C) 2011 Patrik Akerfeldt
* Copyright (C) 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.viewpagerindicator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import com.outsourcing.bottle.R;
/**
* Draws circles (one for each view). The current view position is filled and
* others are only stroked.
*/
public class CirclePageIndicator extends View implements PageIndicator {
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
private float mRadius;
private final Paint mPaintPageFill;
private final Paint mPaintStroke;
private final Paint mPaintFill;
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mListener;
private int mCurrentPage;
private int mSnapPage;
private int mCurrentOffset;
private int mScrollState;
private int mPageSize;
private int mOrientation;
private boolean mCentered;
private boolean mSnap;
private static final int INVALID_POINTER = -1;
private int mTouchSlop;
private float mLastMotionX = -1;
private int mActivePointerId = INVALID_POINTER;
private boolean mIsDragging;
public CirclePageIndicator(Context context) {
this(context, null);
}
public CirclePageIndicator(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.vpiCirclePageIndicatorStyle);
}
public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//Load defaults from resources
final Resources res = getResources();
final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
final int defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color);
final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
final int defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color);
final float defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width);
final float defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius);
final boolean defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered);
final boolean defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap);
//Retrieve styles attributes
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, R.style.Widget_CirclePageIndicator);
mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered);
mOrientation = a.getInt(R.styleable.CirclePageIndicator_indicatorOrientation, defaultOrientation);
mPaintPageFill = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintPageFill.setStyle(Style.FILL);
mPaintPageFill.setColor(a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor));
mPaintStroke = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintStroke.setStyle(Style.STROKE);
mPaintStroke.setColor(a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor));
mPaintStroke.setStrokeWidth(a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth));
mPaintFill = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintFill.setStyle(Style.FILL);
mPaintFill.setColor(a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor));
mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius);
mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap);
a.recycle();
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
}
public void setCentered(boolean centered) {
mCentered = centered;
invalidate();
}
public boolean isCentered() {
return mCentered;
}
public void setPageColor(int pageColor) {
mPaintPageFill.setColor(pageColor);
invalidate();
}
public int getPageColor() {
return mPaintPageFill.getColor();
}
public void setFillColor(int fillColor) {
mPaintFill.setColor(fillColor);
invalidate();
}
public int getFillColor() {
return mPaintFill.getColor();
}
public void setOrientation(int orientation) {
switch (orientation) {
case HORIZONTAL:
case VERTICAL:
mOrientation = orientation;
updatePageSize();
requestLayout();
break;
default:
throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.");
}
}
public int getOrientation() {
return mOrientation;
}
public void setStrokeColor(int strokeColor) {
mPaintStroke.setColor(strokeColor);
invalidate();
}
public int getStrokeColor() {
return mPaintStroke.getColor();
}
public void setStrokeWidth(float strokeWidth) {
mPaintStroke.setStrokeWidth(strokeWidth);
invalidate();
}
public float getStrokeWidth() {
return mPaintStroke.getStrokeWidth();
}
public void setRadius(float radius) {
mRadius = radius;
invalidate();
}
public float getRadius() {
return mRadius;
}
public void setSnap(boolean snap) {
mSnap = snap;
invalidate();
}
public boolean isSnap() {
return mSnap;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mViewPager == null) {
return;
}
final int count = mViewPager.getAdapter().getCount();
if (count == 0) {
return;
}
if (mCurrentPage >= count) {
setCurrentItem(count - 1);
return;
}
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
if (mOrientation == HORIZONTAL) {
longSize = getWidth();
longPaddingBefore = getPaddingLeft();
longPaddingAfter = getPaddingRight();
shortPaddingBefore = getPaddingTop();
} else {
longSize = getHeight();
longPaddingBefore = getPaddingTop();
longPaddingAfter = getPaddingBottom();
shortPaddingBefore = getPaddingLeft();
}
final float threeRadius = mRadius * 3;
final float shortOffset = shortPaddingBefore + mRadius;
float longOffset = longPaddingBefore + mRadius;
if (mCentered) {
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f);
}
float dX;
float dY;
float pageFillRadius = mRadius;
if (mPaintStroke.getStrokeWidth() > 0) {
pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
}
//Draw stroked circles
for (int iLoop = 0; iLoop < count; iLoop++) {
float drawLong = longOffset + (iLoop * threeRadius);
if (mOrientation == HORIZONTAL) {
dX = drawLong;
dY = shortOffset;
} else {
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (mPaintPageFill.getAlpha() > 0) {
canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != mRadius) {
canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
}
}
//Draw the filled circle according to the current scroll
float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
if (!mSnap && (mPageSize != 0)) {
cx += (mCurrentOffset * 1.0f / mPageSize) * threeRadius;
}
if (mOrientation == HORIZONTAL) {
dX = longOffset + cx;
dY = shortOffset;
} else {
dX = shortOffset;
dY = longOffset + cx;
}
canvas.drawCircle(dX, dY, mRadius, mPaintFill);
}
public boolean onTouchEvent(android.view.MotionEvent ev) {
if (super.onTouchEvent(ev)) {
return true;
}
if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
return false;
}
final int action = ev.getAction();
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mLastMotionX = ev.getX();
break;
case MotionEvent.ACTION_MOVE: {
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = x - mLastMotionX;
if (!mIsDragging) {
if (Math.abs(deltaX) > mTouchSlop) {
mIsDragging = true;
}
}
if (mIsDragging) {
if (!mViewPager.isFakeDragging()) {
mViewPager.beginFakeDrag();
}
mLastMotionX = x;
mViewPager.fakeDragBy(deltaX);
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!mIsDragging) {
final int count = mViewPager.getAdapter().getCount();
final int width = getWidth();
final float halfWidth = width / 2f;
final float sixthWidth = width / 6f;
if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
mViewPager.setCurrentItem(mCurrentPage - 1);
return true;
} else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
mViewPager.setCurrentItem(mCurrentPage + 1);
return true;
}
}
mIsDragging = false;
mActivePointerId = INVALID_POINTER;
if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastMotionX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
return true;
};
@Override
public void setViewPager(ViewPager view) {
if (view.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
mViewPager = view;
mViewPager.setOnPageChangeListener(this);
updatePageSize();
invalidate();
}
private void updatePageSize() {
if (mViewPager != null) {
mPageSize = (mOrientation == HORIZONTAL) ? mViewPager.getWidth() : mViewPager.getHeight();
}
}
@Override
public void setViewPager(ViewPager view, int initialPosition) {
setViewPager(view);
setCurrentItem(initialPosition);
}
@Override
public void setCurrentItem(int item) {
if (mViewPager == null) {
throw new IllegalStateException("ViewPager has not been bound.");
}
mViewPager.setCurrentItem(item);
mCurrentPage = item;
invalidate();
}
@Override
public void notifyDataSetChanged() {
invalidate();
}
@Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mCurrentPage = position;
mCurrentOffset = positionOffsetPixels;
updatePageSize();
invalidate();
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageSelected(int position) {
if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position;
mSnapPage = position;
invalidate();
}
if (mListener != null) {
mListener.onPageSelected(position);
}
}
@Override
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mListener = listener;
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == HORIZONTAL) {
setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
} else {
setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
}
}
/**
* Determines the width of this view
*
* @param measureSpec
* A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int measureLong(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
//We were told how big to be
result = specSize;
} else {
//Calculate the width according the views count
final int count = mViewPager.getAdapter().getCount();
result = (int)(getPaddingLeft() + getPaddingRight()
+ (count * 2 * mRadius) + (count - 1) * mRadius + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/**
* Determines the height of this view
*
* @param measureSpec
* A measureSpec packed into an int
* @return The height of the view, honoring constraints from measureSpec
*/
private int measureShort(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
//We were told how big to be
result = specSize;
} else {
//Measure the height
result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState)state;
super.onRestoreInstanceState(savedState.getSuperState());
mCurrentPage = savedState.currentPage;
mSnapPage = savedState.currentPage;
requestLayout();
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPage = mCurrentPage;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPage;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPage = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPage);
}
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];
}
};
}
}
| Java |
/*
* Copyright (C) 2011 Patrik Akerfeldt
*
* 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.viewpagerindicator;
/**
* A TitleProvider provides the title to display according to a view.
*/
public interface TitleProvider {
/**
* Returns the title of the view at position
* @param position
* @return
*/
public String getTitle(int position);
}
| Java |
/*
* Copyright (C) 2011 Jake Wharton
* Copyright (C) 2011 Patrik Akerfeldt
* Copyright (C) 2011 Francisco Figueiredo Jr.
*
* 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.viewpagerindicator;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import com.outsourcing.bottle.R;
/**
* A TitlePageIndicator is a PageIndicator which displays the title of left view
* (if exist), the title of the current select view (centered) and the title of
* the right view (if exist). When the user scrolls the ViewPager then titles are
* also scrolled.
*/
public class TitlePageIndicator extends View implements PageIndicator {
/**
* Percentage indicating what percentage of the screen width away from
* center should the underline be fully faded. A value of 0.25 means that
* halfway between the center of the screen and an edge.
*/
private static final float SELECTION_FADE_PERCENTAGE = 0.25f;
/**
* Percentage indicating what percentage of the screen width away from
* center should the selected text bold turn off. A value of 0.05 means
* that 10% between the center and an edge.
*/
private static final float BOLD_FADE_PERCENTAGE = 0.05f;
/**
* Interface for a callback when the center item has been clicked.
*/
public static interface OnCenterItemClickListener {
/**
* Callback when the center item has been clicked.
*
* @param position Position of the current center item.
*/
public void onCenterItemClick(int position);
}
public enum IndicatorStyle {
None(0), Triangle(1), Underline(2);
public final int value;
private IndicatorStyle(int value) {
this.value = value;
}
public static IndicatorStyle fromValue(int value) {
for (IndicatorStyle style : IndicatorStyle.values()) {
if (style.value == value) {
return style;
}
}
return null;
}
}
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mListener;
private TitleProvider mTitleProvider;
private int mCurrentPage;
private int mCurrentOffset;
private int mScrollState;
private final Paint mPaintText = new Paint();
private boolean mBoldText;
private int mColorText;
private int mColorSelected;
private Path mPath;
private final Paint mPaintFooterLine = new Paint();
private IndicatorStyle mFooterIndicatorStyle;
private final Paint mPaintFooterIndicator = new Paint();
private float mFooterIndicatorHeight;
private float mFooterIndicatorUnderlinePadding;
private float mFooterPadding;
private float mTitlePadding;
private float mTopPadding;
/** Left and right side padding for not active view titles. */
private float mClipPadding;
private float mFooterLineHeight;
private static final int INVALID_POINTER = -1;
private int mTouchSlop;
private float mLastMotionX = -1;
private int mActivePointerId = INVALID_POINTER;
private boolean mIsDragging;
private OnCenterItemClickListener mCenterItemClickListener;
public TitlePageIndicator(Context context) {
this(context, null);
}
public TitlePageIndicator(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.vpiTitlePageIndicatorStyle);
}
public TitlePageIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//Load defaults from resources
final Resources res = getResources();
final int defaultFooterColor = res.getColor(R.color.default_title_indicator_footer_color);
final float defaultFooterLineHeight = res.getDimension(R.dimen.default_title_indicator_footer_line_height);
final int defaultFooterIndicatorStyle = res.getInteger(R.integer.default_title_indicator_footer_indicator_style);
final float defaultFooterIndicatorHeight = res.getDimension(R.dimen.default_title_indicator_footer_indicator_height);
final float defaultFooterIndicatorUnderlinePadding = res.getDimension(R.dimen.default_title_indicator_footer_indicator_underline_padding);
final float defaultFooterPadding = res.getDimension(R.dimen.default_title_indicator_footer_padding);
final int defaultSelectedColor = res.getColor(R.color.default_title_indicator_selected_color);
final boolean defaultSelectedBold = res.getBoolean(R.bool.default_title_indicator_selected_bold);
final int defaultTextColor = res.getColor(R.color.default_title_indicator_text_color);
final float defaultTextSize = res.getDimension(R.dimen.default_title_indicator_text_size);
final float defaultTitlePadding = res.getDimension(R.dimen.default_title_indicator_title_padding);
final float defaultClipPadding = res.getDimension(R.dimen.default_title_indicator_clip_padding);
final float defaultTopPadding = res.getDimension(R.dimen.default_title_indicator_top_padding);
//Retrieve styles attributes
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitlePageIndicator, defStyle, R.style.Widget_TitlePageIndicator);
//Retrieve the colors to be used for this view and apply them.
mFooterLineHeight = a.getDimension(R.styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight);
mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger(R.styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle));
mFooterIndicatorHeight = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight);
mFooterIndicatorUnderlinePadding = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding);
mFooterPadding = a.getDimension(R.styleable.TitlePageIndicator_footerPadding, defaultFooterPadding);
mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topToPadding, defaultTopPadding);
mTitlePadding = a.getDimension(R.styleable.TitlePageIndicator_titlePadding, defaultTitlePadding);
mClipPadding = a.getDimension(R.styleable.TitlePageIndicator_clipPadding, defaultClipPadding);
mColorSelected = a.getColor(R.styleable.TitlePageIndicator_selectedColor, defaultSelectedColor);
mColorText = a.getColor(R.styleable.TitlePageIndicator_textColor, defaultTextColor);
mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, defaultSelectedBold);
final float textSize = a.getDimension(R.styleable.TitlePageIndicator_textSize, defaultTextSize);
final int footerColor = a.getColor(R.styleable.TitlePageIndicator_footerColor, defaultFooterColor);
mPaintText.setTextSize(textSize);
mPaintText.setAntiAlias(true);
mPaintFooterLine.setStyle(Paint.Style.FILL_AND_STROKE);
mPaintFooterLine.setStrokeWidth(mFooterLineHeight);
mPaintFooterLine.setColor(footerColor);
mPaintFooterIndicator.setStyle(Paint.Style.FILL_AND_STROKE);
mPaintFooterIndicator.setColor(footerColor);
a.recycle();
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
}
public int getFooterColor() {
return mPaintFooterLine.getColor();
}
public void setFooterColor(int footerColor) {
mPaintFooterLine.setColor(footerColor);
mPaintFooterIndicator.setColor(footerColor);
invalidate();
}
public float getFooterLineHeight() {
return mFooterLineHeight;
}
public void setFooterLineHeight(float footerLineHeight) {
mFooterLineHeight = footerLineHeight;
mPaintFooterLine.setStrokeWidth(mFooterLineHeight);
invalidate();
}
public float getFooterIndicatorHeight() {
return mFooterIndicatorHeight;
}
public void setFooterIndicatorHeight(float footerTriangleHeight) {
mFooterIndicatorHeight = footerTriangleHeight;
invalidate();
}
public float getFooterIndicatorPadding() {
return mFooterPadding;
}
public void setFooterIndicatorPadding(float footerIndicatorPadding) {
mFooterPadding = footerIndicatorPadding;
invalidate();
}
public IndicatorStyle getFooterIndicatorStyle() {
return mFooterIndicatorStyle;
}
public void setFooterIndicatorStyle(IndicatorStyle indicatorStyle) {
mFooterIndicatorStyle = indicatorStyle;
invalidate();
}
public int getSelectedColor() {
return mColorSelected;
}
public void setSelectedColor(int selectedColor) {
mColorSelected = selectedColor;
invalidate();
}
public boolean isSelectedBold() {
return mBoldText;
}
public void setSelectedBold(boolean selectedBold) {
mBoldText = selectedBold;
invalidate();
}
public int getTextColor() {
return mColorText;
}
public void setTextColor(int textColor) {
mPaintText.setColor(textColor);
mColorText = textColor;
invalidate();
}
public float getTextSize() {
return mPaintText.getTextSize();
}
public void setTextSize(float textSize) {
mPaintText.setTextSize(textSize);
invalidate();
}
public float getTitlePadding() {
return this.mTitlePadding;
}
public void setTitlePadding(float titlePadding) {
mTitlePadding = titlePadding;
invalidate();
}
public float getTopPadding() {
return this.mTopPadding;
}
public void setTopPadding(float topPadding) {
mTopPadding = topPadding;
invalidate();
}
public float getClipPadding() {
return this.mClipPadding;
}
public void setClipPadding(float clipPadding) {
mClipPadding = clipPadding;
invalidate();
}
public void setTypeface(Typeface typeface) {
mPaintText.setTypeface(typeface);
invalidate();
}
public Typeface getTypeface() {
return mPaintText.getTypeface();
}
/*
* (non-Javadoc)
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mViewPager == null) {
return;
}
final int count = mViewPager.getAdapter().getCount();
if (count == 0) {
return;
}
//Calculate views bounds
ArrayList<RectF> bounds = calculateAllBounds(mPaintText);
final int boundsSize = bounds.size();
//Make sure we're on a page that still exists
if (mCurrentPage >= boundsSize) {
setCurrentItem(boundsSize - 1);
return;
}
final int countMinusOne = count - 1;
final float halfWidth = getWidth() / 2f;
final int left = getLeft();
final float leftClip = left + mClipPadding;
final int width = getWidth();
final int height = getHeight();
final int right = left + width;
final float rightClip = right - mClipPadding;
int page = mCurrentPage;
float offsetPercent;
if (mCurrentOffset <= halfWidth) {
offsetPercent = 1.0f * mCurrentOffset / width;
} else {
page += 1;
offsetPercent = 1.0f * (width - mCurrentOffset) / width;
}
final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE);
final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE);
final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE;
//Verify if the current view must be clipped to the screen
RectF curPageBound = bounds.get(mCurrentPage);
float curPageWidth = curPageBound.right - curPageBound.left;
if (curPageBound.left < leftClip) {
//Try to clip to the screen (left side)
clipViewOnTheLeft(curPageBound, curPageWidth, left);
}
if (curPageBound.right > rightClip) {
//Try to clip to the screen (right side)
clipViewOnTheRight(curPageBound, curPageWidth, right);
}
//Left views starting from the current position
if (mCurrentPage > 0) {
for (int i = mCurrentPage - 1; i >= 0; i--) {
RectF bound = bounds.get(i);
//Is left side is outside the screen
if (bound.left < leftClip) {
float w = bound.right - bound.left;
//Try to clip to the screen (left side)
clipViewOnTheLeft(bound, w, left);
//Except if there's an intersection with the right view
RectF rightBound = bounds.get(i + 1);
//Intersection
if (bound.right + mTitlePadding > rightBound.left) {
bound.left = rightBound.left - w - mTitlePadding;
bound.right = bound.left + w;
}
}
}
}
//Right views starting from the current position
if (mCurrentPage < countMinusOne) {
for (int i = mCurrentPage + 1 ; i < count; i++) {
RectF bound = bounds.get(i);
//If right side is outside the screen
if (bound.right > rightClip) {
float w = bound.right - bound.left;
//Try to clip to the screen (right side)
clipViewOnTheRight(bound, w, right);
//Except if there's an intersection with the left view
RectF leftBound = bounds.get(i - 1);
//Intersection
if (bound.left - mTitlePadding < leftBound.right) {
bound.left = leftBound.right + mTitlePadding;
bound.right = bound.left + w;
}
}
}
}
//Now draw views
int colorTextAlpha = mColorText >>> 24;
for (int i = 0; i < count; i++) {
//Get the title
RectF bound = bounds.get(i);
//Only if one side is visible
if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) {
final boolean currentPage = (i == page);
//Only set bold if we are within bounds
mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText);
//Draw text as unselected
mPaintText.setColor(mColorText);
if(currentPage && currentSelected) {
//Fade out/in unselected text as the selected text fades in/out
mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent));
}
canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText);
//If we are within the selected bounds draw the selected text
if (currentPage && currentSelected) {
mPaintText.setColor(mColorSelected);
mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent));
canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding, mPaintText);
}
}
}
//Draw the footer line
mPath = new Path();
mPath.moveTo(0, height - mFooterLineHeight / 2f);
mPath.lineTo(width, height - mFooterLineHeight / 2f);
mPath.close();
canvas.drawPath(mPath, mPaintFooterLine);
switch (mFooterIndicatorStyle) {
case Triangle:
mPath = new Path();
mPath.moveTo(halfWidth, height - mFooterLineHeight - mFooterIndicatorHeight);
mPath.lineTo(halfWidth + mFooterIndicatorHeight, height - mFooterLineHeight);
mPath.lineTo(halfWidth - mFooterIndicatorHeight, height - mFooterLineHeight);
mPath.close();
canvas.drawPath(mPath, mPaintFooterIndicator);
break;
case Underline:
if (!currentSelected || page >= boundsSize) {
break;
}
RectF underlineBounds = bounds.get(page);
mPath = new Path();
mPath.moveTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight);
mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight);
mPath.lineTo(underlineBounds.right + mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight);
mPath.lineTo(underlineBounds.left - mFooterIndicatorUnderlinePadding, height - mFooterLineHeight - mFooterIndicatorHeight);
mPath.close();
mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent));
canvas.drawPath(mPath, mPaintFooterIndicator);
mPaintFooterIndicator.setAlpha(0xFF);
break;
}
}
public boolean onTouchEvent(android.view.MotionEvent ev) {
if (super.onTouchEvent(ev)) {
return true;
}
if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
return false;
}
final int action = ev.getAction();
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mLastMotionX = ev.getX();
break;
case MotionEvent.ACTION_MOVE: {
final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = x - mLastMotionX;
if (!mIsDragging) {
if (Math.abs(deltaX) > mTouchSlop) {
mIsDragging = true;
}
}
if (mIsDragging) {
if (!mViewPager.isFakeDragging()) {
mViewPager.beginFakeDrag();
}
mLastMotionX = x;
mViewPager.fakeDragBy(deltaX);
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!mIsDragging) {
final int count = mViewPager.getAdapter().getCount();
final int width = getWidth();
final float halfWidth = width / 2f;
final float sixthWidth = width / 6f;
final float leftThird = halfWidth - sixthWidth;
final float rightThird = halfWidth + sixthWidth;
final float eventX = ev.getX();
if (eventX < leftThird) {
if (mCurrentPage > 0) {
mViewPager.setCurrentItem(mCurrentPage - 1);
return true;
}
} else if (eventX > rightThird) {
if (mCurrentPage < count - 1) {
mViewPager.setCurrentItem(mCurrentPage + 1);
return true;
}
} else {
//Middle third
if (mCenterItemClickListener != null) {
mCenterItemClickListener.onCenterItemClick(mCurrentPage);
}
}
}
mIsDragging = false;
mActivePointerId = INVALID_POINTER;
if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastMotionX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
return true;
};
/**
* Set bounds for the right textView including clip padding.
*
* @param curViewBound
* current bounds.
* @param curViewWidth
* width of the view.
*/
private void clipViewOnTheRight(RectF curViewBound, float curViewWidth, int right) {
curViewBound.right = right - mClipPadding;
curViewBound.left = curViewBound.right - curViewWidth;
}
/**
* Set bounds for the left textView including clip padding.
*
* @param curViewBound
* current bounds.
* @param curViewWidth
* width of the view.
*/
private void clipViewOnTheLeft(RectF curViewBound, float curViewWidth, int left) {
curViewBound.left = left + mClipPadding;
curViewBound.right = mClipPadding + curViewWidth;
}
/**
* Calculate views bounds and scroll them according to the current index
*
* @param paint
* @param currentIndex
* @return
*/
private ArrayList<RectF> calculateAllBounds(Paint paint) {
ArrayList<RectF> list = new ArrayList<RectF>();
//For each views (If no values then add a fake one)
final int count = mViewPager.getAdapter().getCount();
final int width = getWidth();
final int halfWidth = width / 2;
for (int i = 0; i < count; i++) {
RectF bounds = calcBounds(i, paint);
float w = (bounds.right - bounds.left);
float h = (bounds.bottom - bounds.top);
bounds.left = (halfWidth) - (w / 2) - mCurrentOffset + ((i - mCurrentPage) * width);
bounds.right = bounds.left + w;
bounds.top = 0;
bounds.bottom = h;
list.add(bounds);
}
return list;
}
/**
* Calculate the bounds for a view's title
*
* @param index
* @param paint
* @return
*/
private RectF calcBounds(int index, Paint paint) {
//Calculate the text bounds
RectF bounds = new RectF();
bounds.right = paint.measureText(mTitleProvider.getTitle(index));
bounds.bottom = paint.descent() - paint.ascent();
return bounds;
}
@Override
public void setViewPager(ViewPager view) {
final PagerAdapter adapter = view.getAdapter();
if (adapter == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
if (!(adapter instanceof TitleProvider)) {
throw new IllegalStateException("ViewPager adapter must implement TitleProvider to be used with TitlePageIndicator.");
}
mViewPager = view;
mViewPager.setOnPageChangeListener(this);
mTitleProvider = (TitleProvider)adapter;
invalidate();
}
@Override
public void setViewPager(ViewPager view, int initialPosition) {
setViewPager(view);
setCurrentItem(initialPosition);
}
@Override
public void notifyDataSetChanged() {
invalidate();
}
/**
* Set a callback listener for the center item click.
*
* @param listener Callback instance.
*/
public void setOnCenterItemClickListener(OnCenterItemClickListener listener) {
mCenterItemClickListener = listener;
}
@Override
public void setCurrentItem(int item) {
if (mViewPager == null) {
throw new IllegalStateException("ViewPager has not been bound.");
}
mViewPager.setCurrentItem(item);
mCurrentPage = item;
invalidate();
}
@Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mCurrentPage = position;
mCurrentOffset = positionOffsetPixels;
invalidate();
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position;
invalidate();
}
if (mListener != null) {
mListener.onPageSelected(position);
}
}
@Override
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mListener = listener;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Measure our width in whatever mode specified
final int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
//Determine our height
float height = 0;
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightSpecMode == MeasureSpec.EXACTLY) {
//We were told how big to be
height = MeasureSpec.getSize(heightMeasureSpec);
} else {
//Calculate the text bounds
RectF bounds = new RectF();
bounds.bottom = mPaintText.descent()-mPaintText.ascent();
height = bounds.bottom - bounds.top + mFooterLineHeight + mFooterPadding + mTopPadding;
if (mFooterIndicatorStyle != IndicatorStyle.None) {
height += mFooterIndicatorHeight;
}
}
final int measuredHeight = (int)height;
setMeasuredDimension(measuredWidth, measuredHeight);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState)state;
super.onRestoreInstanceState(savedState.getSuperState());
mCurrentPage = savedState.currentPage;
requestLayout();
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPage = mCurrentPage;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPage;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPage = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPage);
}
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];
}
};
}
}
| Java |
/*
* Copyright (C) 2011 Patrik Akerfeldt
* Copyright (C) 2011 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.viewpagerindicator;
import android.support.v4.view.ViewPager;
/**
* A PageIndicator is responsible to show an visual indicator on the total views
* number and the current visible view.
*/
public interface PageIndicator extends ViewPager.OnPageChangeListener {
/**
* Bind the indicator to a ViewPager.
*
* @param view
*/
public void setViewPager(ViewPager view);
/**
* Bind the indicator to a ViewPager.
*
* @param view
* @param initialPosition
*/
public void setViewPager(ViewPager view, int initialPosition);
/**
* <p>Set the current page of both the ViewPager and indicator.</p>
*
* <p>This <strong>must</strong> be used if you need to set the page before
* the views are drawn on screen (e.g., default start page).</p>
*
* @param item
*/
public void setCurrentItem(int item);
/**
* Set a page change listener which will receive forwarded events.
*
* @param listener
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener);
/**
* Notify the indicator that the fragment list has changed.
*/
public void notifyDataSetChanged();
}
| Java |
package com.aviary.android.feather.async_tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import com.aviary.android.feather.Constants;
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.DecodeUtils;
import com.aviary.android.feather.library.utils.ImageLoader;
import com.aviary.android.feather.library.utils.ImageLoader.ImageSizes;
// TODO: Auto-generated Javadoc
/**
* Load an Image bitmap asynchronous.
*
* @author alessandro
*/
public class DownloadImageAsyncTask extends AsyncTask<Context, Void, Bitmap> {
/**
* The listener interface for receiving onImageDownload events. The class that is interested in processing a onImageDownload
* event implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnImageDownloadListener<code> method. When
* the onImageDownload event occurs, that object's appropriate
* method is invoked.
*
* @see OnImageDownloadEvent
*/
public static interface OnImageDownloadListener {
/**
* On download start.
*/
void onDownloadStart();
/**
* On download complete.
*
* @param result
* the result
*/
void onDownloadComplete( Bitmap result, ImageSizes sizes );
/**
* On download error.
*
* @param error
* the error
*/
void onDownloadError( String error );
};
private OnImageDownloadListener mListener;
private Uri mUri;
private String error;
private ImageLoader.ImageSizes mImageSize;
/**
* Instantiates a new download image async task.
*
* @param uri
* the uri
*/
public DownloadImageAsyncTask( Uri uri ) {
super();
mUri = uri;
}
/**
* Sets the on load listener.
*
* @param listener
* the new on load listener
*/
public void setOnLoadListener( OnImageDownloadListener listener ) {
mListener = listener;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
if ( mListener != null ) mListener.onDownloadStart();
mImageSize = new ImageLoader.ImageSizes();
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Bitmap doInBackground( Context... params ) {
Context context = params[0];
try {
final int max_size = Constants.getManagedMaxImageSize();
return DecodeUtils.decode( context, mUri, max_size, max_size, mImageSize );
} catch ( Exception e ) {
Logger logger = LoggerFactory.getLogger( "DownloadImageTask", LoggerType.ConsoleLoggerType );
logger.error( "error", e.getMessage() );
error = e.getMessage();
}
return null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
if ( mListener != null ) {
if ( result != null ) {
mListener.onDownloadComplete( result, mImageSize );
} else {
mListener.onDownloadError( error );
}
}
if ( mImageSize.getOriginalSize() == null ) {
mImageSize.setOriginalSize( mImageSize.getNewSize() );
}
mListener = null;
mUri = null;
error = null;
}
}
| Java |
package com.aviary.android.feather.async_tasks;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
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.plugins.PluginManager.InternalPlugin;
import com.aviary.android.feather.library.services.PluginService.StickerType;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.IOUtils;
import com.aviary.android.feather.library.utils.BitmapUtils.FLIP_MODE;
import com.aviary.android.feather.library.utils.BitmapUtils.ROTATION;
import com.aviary.android.feather.library.utils.ImageLoader.ImageSizes;
import com.aviary.android.feather.library.utils.ImageLoader;
import com.aviary.android.feather.utils.SimpleBitmapCache;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.ServiceUtils;
/**
* Load an internal asset asynchronous.
*
* @author alessandro
*/
public class AssetsAsyncDownloadManager {
public static final int THUMBNAIL_LOADED = 1;
@SuppressWarnings("unused")
private Context mContext;
private int mThumbSize = -1;
private Handler mHandler;
private volatile Boolean mStopped = false;
private final int nThreads;
/** thread pool */
private final PoolWorker[] threads;
/** The current runnable queue. */
private final LinkedList<MyRunnable> mQueue;
private SimpleBitmapCache mBitmapCache;
private Logger logger = LoggerFactory.getLogger( "AssetAsyncDownloadManager", LoggerType.ConsoleLoggerType );
/**
* Instantiates a new assets async download manager.
*
* @param context
* the context
* @param handler
* the handler
*/
public AssetsAsyncDownloadManager( Context context, Handler handler ) {
mContext = context;
mHandler = handler;
mBitmapCache = new SimpleBitmapCache();
nThreads = 1;
mQueue = new LinkedList<MyRunnable>();
threads = new PoolWorker[nThreads];
for ( int i = 0; i < nThreads; i++ ) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
/**
* Gets the thumb size.
*
* @return the thumb size
*/
public int getThumbSize() {
return mThumbSize;
}
/**
* set the default thumbnail size when resizing a bitmap.
*
* @param size
* the new thumb size
*/
public void setThumbSize( int size ) {
mThumbSize = size;
}
/**
* Shut down now.
*/
public void shutDownNow() {
logger.info( "shutDownNow" );
mStopped = true;
synchronized ( mQueue ) {
mQueue.clear();
mQueue.notify();
}
clearCache();
mContext = null;
for ( int i = 0; i < nThreads; i++ ) {
threads[i] = null;
}
}
/**
* The Class MyRunnable.
*/
private abstract class MyRunnable implements Runnable {
/** The view. */
public WeakReference<ImageView> view;
/**
* Instantiates a new my runnable.
*
* @param image
* the image
*/
public MyRunnable( ImageView image ) {
this.view = new WeakReference<ImageView>( image );
}
};
/**
* Load asset.
*
* @param resource
* the resource
* @param srcFile
* the src file
* @param background
* the background
* @param view
* the view
*/
public void loadStickerAsset( final InternalPlugin plugin,final String paster_dir, final String srcFile, final Drawable background, final ImageView view ) {
if ( mStopped || mThumbSize < 1 ) return;
mBitmapCache.resetPurgeTimer();
runTask( new MyRunnable( view ) {
@Override
public void run() {
if ( mStopped ) return;
Message message = mHandler.obtainMessage();
Bitmap bitmap = mBitmapCache.getBitmapFromCache( srcFile );
if ( bitmap != null ) {
message.what = THUMBNAIL_LOADED;
message.obj = new Thumb( bitmap, view.get() );
} else {
// bitmap = downloadBitmap( plugin, srcFile, background, view.get() );
byte[] iconByte = ServiceUtils.getImageFile(srcFile,paster_dir, AppContext.PasterDir);
bitmap = BitmapUtils.resizeBitmap(ServiceUtils.bytesToBitmap(iconByte), mThumbSize, mThumbSize);
if ( bitmap != null ) mBitmapCache.addBitmapToCache( srcFile, bitmap );
ImageView imageView = view.get();
if ( imageView != null ) {
MyRunnable bitmapTask = getBitmapTask( imageView );
if ( this == bitmapTask ) {
imageView.setTag( null );
message.what = THUMBNAIL_LOADED;
message.obj = new Thumb( bitmap, imageView );
} else {
logger.error( "image tag is different than current task!" );
}
}
}
if ( message.what == THUMBNAIL_LOADED ) mHandler.sendMessage( message );
}
} );
}
/**
* Load asset icon.
*
* @param info
* the info
* @param pm
* the pm
* @param view
* the view
*/
public void loadAssetIcon( final ApplicationInfo info, final PackageManager pm, final ImageView view ) {
if ( mStopped || mThumbSize < 1 ) return;
mBitmapCache.resetPurgeTimer();
runTask( new MyRunnable( view ) {
@Override
public void run() {
if ( mStopped ) return;
Message message = mHandler.obtainMessage();
Bitmap bitmap = mBitmapCache.getBitmapFromCache( info.packageName );
if ( bitmap != null ) {
message.what = THUMBNAIL_LOADED;
message.obj = new Thumb( bitmap, view.get() );
} else {
bitmap = downloadIcon( info, pm, view.get() );
if ( bitmap != null ) mBitmapCache.addBitmapToCache( info.packageName, bitmap );
ImageView imageView = view.get();
if ( imageView != null ) {
MyRunnable bitmapTask = getBitmapTask( imageView );
if ( this == bitmapTask ) {
imageView.setTag( null );
message.what = THUMBNAIL_LOADED;
message.obj = new Thumb( bitmap, imageView );
} else {
logger.error( "image tag is different than current task!" );
}
}
}
if ( message.what == THUMBNAIL_LOADED ) mHandler.sendMessage( message );
}
} );
}
/**
* Run task.
*
* @param task
* the task
*/
private void runTask( MyRunnable task ) {
synchronized ( mQueue ) {
Iterator<MyRunnable> iterator = mQueue.iterator();
while ( iterator.hasNext() ) {
MyRunnable current = iterator.next();
ImageView image = current.view.get();
if ( image == null ) {
iterator.remove();
// mQueue.remove( current );
} else {
if ( image.equals( task.view.get() ) ) {
current.view.get().setTag( null );
iterator.remove();
// mQueue.remove( current );
break;
}
}
}
task.view.get().setTag( new CustomTag( task ) );
mQueue.add( task );
mQueue.notify();
}
}
/**
* Download bitmap.
*
* @param resource
* the resource
* @param url
* the url
* @param background
* the background
* @param view
* the view
* @return the bitmap
*/
Bitmap downloadBitmap( InternalPlugin plugin, String url, Drawable background, View view ) {
if ( view == null ) return null;
try {
Bitmap bitmap;
Bitmap result;
bitmap = ImageLoader.loadStickerBitmap( plugin, url, StickerType.Small, mThumbSize, mThumbSize );
if ( background != null ) {
result = BitmapUtils.createThumbnail( bitmap, mThumbSize, mThumbSize, ROTATION.ROTATE_NULL, FLIP_MODE.None, null, background, 20, 10 );
} else {
result = bitmap;
}
if( result != bitmap ){
bitmap.recycle();
}
return result;
} catch ( Exception e ) {
e.printStackTrace();
return null;
}
}
public static Bitmap loadStickerBitmap(String name, int maxW, int maxH)
throws IOException {
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = null;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
InputStream stream = null;
if (stream != null) {
options.inSampleSize = computeSampleSize(stream, maxW * 1.5D,
maxH * 1.5D, 0, null, new BitmapFactory.Options());
IOUtils.closeSilently(stream);
} else {
throw new IOException("Stream is null");
}
options.inDither = false;
options.inJustDecodeBounds = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16384];
bitmap = BitmapFactory.decodeStream(stream, null, options);
if (bitmap != null) {
Bitmap output = BitmapUtils.resizeBitmap(bitmap, maxW, maxH);
if (output != bitmap) {
bitmap.recycle();
bitmap = output;
}
} else {
}
IOUtils.closeSilently(stream);
return bitmap;
}
private static int computeSampleSize(InputStream stream, double d,
double e, int orientation, ImageSizes sizes,
BitmapFactory.Options options) {
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(stream, null, options);
double h;
double w;
if ((orientation == 0) || (orientation == 180)) {
w = options.outWidth;
h = options.outHeight;
} else {
w = options.outHeight;
h = options.outWidth;
}
if (sizes != null) {
sizes.setOriginalSize(options.outWidth + "x" + options.outHeight);
sizes.setRealSize((int) w, (int) h);
}
int sampleSize = (int) Math.ceil(Math.max(w / d, h / e));
return sampleSize;
}
/**
* Download icon.
*
* @param info
* the info
* @param pm
* the pm
* @param view
* the view
* @return the bitmap
*/
Bitmap downloadIcon( ApplicationInfo info, PackageManager pm, View view ) {
if ( view == null ) return null;
Drawable d = info.loadIcon( pm );
if ( d instanceof BitmapDrawable ) {
Bitmap bitmap = ( (BitmapDrawable) d ).getBitmap();
return bitmap;
}
return null;
}
/**
* The Class PoolWorker.
*/
private class PoolWorker extends Thread {
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Runnable r;
while ( mStopped != true ) {
synchronized ( mQueue ) {
while ( mQueue.isEmpty() ) {
if ( mStopped ) break;
try {
mQueue.wait();
} catch ( InterruptedException ignored ) {}
}
try {
r = (Runnable) mQueue.removeFirst();
} catch ( NoSuchElementException e ) {
// queue is empty
break;
}
}
try {
r.run();
} catch ( RuntimeException e ) {
logger.error( e.getMessage() );
}
}
}
}
/**
* The Class CustomTag.
*/
static class CustomTag {
/** The task reference. */
private final WeakReference<MyRunnable> taskReference;
/**
* Instantiates a new custom tag.
*
* @param task
* the task
*/
public CustomTag( MyRunnable task ) {
super();
taskReference = new WeakReference<MyRunnable>( task );
}
/**
* Gets the downloader task.
*
* @return the downloader task
*/
public MyRunnable getDownloaderTask() {
return taskReference.get();
}
}
/**
* Gets the bitmap task.
*
* @param imageView
* the image view
* @return the bitmap task
*/
private static MyRunnable getBitmapTask( ImageView imageView ) {
if ( imageView != null ) {
Object tag = imageView.getTag();
if ( tag instanceof CustomTag ) {
CustomTag runnableTag = (CustomTag) tag;
return runnableTag.getDownloaderTask();
}
}
return null;
}
/**
* Clears the image cache used internally to improve performance. Note that for memory efficiency reasons, the cache will
* automatically be cleared after a certain inactivity delay.
*/
public void clearCache() {
mBitmapCache.clearCache();
}
/**
* The Class Thumb.
*/
public static class Thumb {
/** The bitmap. */
public Bitmap bitmap;
/** The image. */
public ImageView image;
/**
* Instantiates a new thumb.
*
* @param bmp
* the bmp
* @param img
* the img
*/
public Thumb( Bitmap bmp, ImageView img ) {
image = img;
bitmap = bmp;
}
}
}
| Java |
package com.aviary.android.feather.async_tasks;
import android.content.Context;
import android.os.Bundle;
import com.aviary.android.feather.library.media.ExifInterfaceWrapper;
import com.aviary.android.feather.library.services.ThreadPoolService.BGCallable;
public class ExifTask extends BGCallable<String, Bundle> {
@Override
public Bundle call( Context context, String path ) {
if ( path == null ) {
return null;
}
Bundle result = new Bundle();
try {
ExifInterfaceWrapper exif = new ExifInterfaceWrapper( path );
exif.copyTo( result );
} catch ( Throwable t ) {
t.printStackTrace();
}
return result;
}
}
| Java |
package com.aviary.android.feather.async_tasks;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
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.utils.SimpleBitmapCache;
/**
* Load an internal asset asynchronous.
*
* @author alessandro
*/
public class AsyncImageManager {
public static interface OnImageLoadListener {
public void onLoadComplete( ImageView view, Bitmap bitmap );
}
private static final int THUMBNAIL_LOADED = 1;
private volatile Boolean mStopped = false;
private final int nThreads;
/** thread pool */
private final PoolWorker[] threads;
/** The current runnable queue. */
private final LinkedList<MyRunnable> mQueue;
private SimpleBitmapCache mBitmapCache;
private OnImageLoadListener mListener;
private static Handler mHandler;
private Logger logger = LoggerFactory.getLogger( "AsyncImageManager", LoggerType.ConsoleLoggerType );
/**
* Instantiates a new assets async download manager.
*
* @param context
* the context
* @param handler
* the handler
*/
public AsyncImageManager() {
mBitmapCache = new SimpleBitmapCache();
nThreads = 1;
mQueue = new LinkedList<MyRunnable>();
threads = new PoolWorker[nThreads];
mHandler = new MyHandler( this );
for ( int i = 0; i < nThreads; i++ ) {
threads[i] = new PoolWorker();
threads[i].start();
}
mListener = null;
}
public void setOnLoadCompleteListener( OnImageLoadListener listener ) {
mListener = listener;
}
private static class MyHandler extends Handler {
WeakReference<AsyncImageManager> mParent;
public MyHandler( AsyncImageManager parent ) {
mParent = new WeakReference<AsyncImageManager>( parent );
}
@Override
public void handleMessage( Message msg ) {
switch ( msg.what ) {
case AsyncImageManager.THUMBNAIL_LOADED:
Thumb thumb = (Thumb) msg.obj;
if ( thumb.image != null && thumb.bitmap != null ) {
if ( thumb.image.get() != null && thumb.bitmap.get() != null ) {
if ( mParent != null && mParent.get() != null ) {
AsyncImageManager parent = mParent.get();
if ( parent.mListener != null ) {
parent.mListener.onLoadComplete( thumb.image.get(), thumb.bitmap.get() );
} else {
thumb.image.get().setImageBitmap( thumb.bitmap.get() );
}
}
}
}
break;
}
}
}
/**
* Shut down now.
*/
public void shutDownNow() {
logger.info( "shutDownNow" );
mStopped = true;
mHandler = null;
synchronized ( mQueue ) {
mQueue.clear();
mQueue.notify();
}
clearCache();
for ( int i = 0; i < nThreads; i++ ) {
threads[i] = null;
}
}
/**
* The Class MyRunnable.
*/
private abstract class MyRunnable implements Runnable {
/** The view. */
public WeakReference<ImageView> view;
/**
* Instantiates a new my runnable.
*
* @param image
* the image
*/
public MyRunnable( ImageView image ) {
this.view = new WeakReference<ImageView>( image );
}
};
/**
* Load asset.
*
* @param resource
* the resource
* @param hash
* the src file
* @param background
* the background
* @param view
* the view
*/
public void execute( final MyCallable executor, final String hash, final ImageView view ) {
if ( mStopped ) return;
mBitmapCache.resetPurgeTimer();
runTask( new MyRunnable( view ) {
@Override
public void run() {
if ( mStopped ) return;
Message message = mHandler.obtainMessage();
Bitmap bitmap = mBitmapCache.getBitmapFromCache( hash );
if ( bitmap != null ) {
message.what = THUMBNAIL_LOADED;
message.obj = new Thumb( bitmap, view.get() );
} else {
try {
bitmap = executor.call();
} catch ( Exception e ) {
e.printStackTrace();
}
if ( bitmap != null ) mBitmapCache.addBitmapToCache( hash, bitmap );
ImageView imageView = view.get();
if ( imageView != null ) {
MyRunnable bitmapTask = getBitmapTask( imageView );
if ( this == bitmapTask ) {
imageView.setTag( null );
message.what = THUMBNAIL_LOADED;
message.obj = new Thumb( bitmap, imageView );
} else {
logger.error( "image tag is different than current task!" );
}
}
}
if ( message.what == THUMBNAIL_LOADED ) mHandler.sendMessage( message );
}
} );
}
/**
* Run task.
*
* @param task
* the task
*/
private void runTask( MyRunnable task ) {
synchronized ( mQueue ) {
Iterator<MyRunnable> iterator = mQueue.iterator();
while ( iterator.hasNext() ) {
MyRunnable current = iterator.next();
ImageView image = current.view.get();
if ( image == null ) {
iterator.remove();
} else {
if ( image.equals( task.view.get() ) ) {
current.view.get().setTag( null );
iterator.remove();
break;
}
}
}
task.view.get().setTag( new CustomTag( task ) );
mQueue.add( task );
mQueue.notify();
}
}
/**
* Download icon.
*
* @param info
* the info
* @param pm
* the pm
* @param view
* the view
* @return the bitmap
*/
Bitmap downloadIcon( ApplicationInfo info, PackageManager pm, View view ) {
if ( view == null ) return null;
Drawable d = info.loadIcon( pm );
if ( d instanceof BitmapDrawable ) {
Bitmap bitmap = ( (BitmapDrawable) d ).getBitmap();
return bitmap;
}
return null;
}
/**
* The Class PoolWorker.
*/
private class PoolWorker extends Thread {
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Runnable r;
while ( mStopped != true ) {
synchronized ( mQueue ) {
while ( mQueue.isEmpty() ) {
if ( mStopped ) break;
try {
mQueue.wait();
} catch ( InterruptedException ignored ) {}
}
try {
r = (Runnable) mQueue.removeFirst();
} catch ( NoSuchElementException e ) {
// queue is empty
break;
}
}
try {
r.run();
} catch ( RuntimeException e ) {
logger.error( e.getMessage() );
}
}
}
}
/**
* The Class CustomTag.
*/
static class CustomTag {
/** The task reference. */
private final WeakReference<MyRunnable> taskReference;
/**
* Instantiates a new custom tag.
*
* @param task
* the task
*/
public CustomTag( MyRunnable task ) {
super();
taskReference = new WeakReference<MyRunnable>( task );
}
/**
* Gets the downloader task.
*
* @return the downloader task
*/
public MyRunnable getDownloaderTask() {
return taskReference.get();
}
}
/**
* Gets the bitmap task.
*
* @param imageView
* the image view
* @return the bitmap task
*/
private static MyRunnable getBitmapTask( ImageView imageView ) {
if ( imageView != null ) {
Object tag = imageView.getTag();
if ( tag instanceof CustomTag ) {
CustomTag runnableTag = (CustomTag) tag;
return runnableTag.getDownloaderTask();
}
}
return null;
}
/**
* Clears the image cache used internally to improve performance. Note that for memory efficiency reasons, the cache will
* automatically be cleared after a certain inactivity delay.
*/
public void clearCache() {
mBitmapCache.clearCache();
}
/**
* The Class Thumb.
*/
static class Thumb {
public WeakReference<Bitmap> bitmap;
public WeakReference<ImageView> image;
public Thumb( Bitmap bmp, ImageView img ) {
image = new WeakReference<ImageView>( img );
bitmap = new WeakReference<Bitmap>( bmp );
}
}
public static class MyCallable implements Callable<Bitmap> {
@Override
public Bitmap call() throws Exception {
return null;
}
}
}
| Java |
package com.aviary.android.feather.receivers;
import java.util.Iterator;
import java.util.Set;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import com.aviary.android.feather.library.content.FeatherIntent;
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;
/**
* Main receiver used to listen for new packages installations. When a package, which is recognized as a feather plugin, has been
* installed/removed or updated this receiver will broadcast a notification.
*
* @author alessandro
*
*/
public class FeatherSystemReceiver extends BroadcastReceiver {
/** The logger. */
static Logger logger = LoggerFactory.getLogger( "FeatherSystemReceiver", LoggerType.ConsoleLoggerType );
/**
* A package in the system has been installed/replaced or removed. Check if the package is a valid feather plugin and send a
* broadcast notification of the newly package. A valid feather plugin must have a resource with the follwing integer
* identifiers: is_sticker indicates it's a sticker pack plugin is_filter indicates it's a filter pack plugin is_tool indicates
* it's a new tool plugin ( not used )
*
* @param context
* the context
* @param intent
* the intent
*/
@Override
public void onReceive( Context context, Intent intent ) {
final String action = intent.getAction();
if ( null != action ) {
logger.info( "onReceive", action );
if ( Intent.ACTION_PACKAGE_ADDED.equals( action ) ) {
handlePackageAdded( context, intent );
} else if ( Intent.ACTION_PACKAGE_REMOVED.equals( action ) ) {
handlePackageRemoved( context, intent );
} else if ( Intent.ACTION_PACKAGE_REPLACED.equals( action ) ) {
handlePackageReplaced( context, intent );
}
}
}
/**
* Handle package.
*
* @param context
* the context
* @param packageName
* the package name
* @param intent
* the intent
*/
private void handlePackage( Context context, String packageName, Intent intent ) {
Resources res = null;
int is_sticker = 0;
int is_filter = 0;
int is_tool = 0;
int is_border = 0;
try {
res = context.getPackageManager().getResourcesForApplication( packageName );
} catch ( NameNotFoundException e ) {
e.printStackTrace();
}
if ( null != res ) {
int resid = 0;
resid = res.getIdentifier( "is_sticker", "integer", packageName );
if ( resid != 0 ) is_sticker = res.getInteger( resid );
resid = res.getIdentifier( "is_filter", "integer", packageName );
if ( resid != 0 ) is_filter = res.getInteger( resid );
resid = res.getIdentifier( "is_tool", "integer", packageName );
if ( resid != 0 ) is_tool = res.getInteger( resid );
resid = res.getIdentifier( "is_border", "integer", packageName );
if ( resid != 0 ) is_border = res.getInteger( resid );
}
intent.putExtra( FeatherIntent.PACKAGE_NAME, packageName );
intent.putExtra( FeatherIntent.IS_STICKER, is_sticker );
intent.putExtra( FeatherIntent.IS_FILTER, is_filter );
intent.putExtra( FeatherIntent.IS_TOOL, is_tool );
intent.putExtra( FeatherIntent.IS_BORDER, is_border );
intent.putExtra( FeatherIntent.APPLICATION_CONTEXT, context.getApplicationContext().getPackageName() );
}
/**
* Handle package replaced.
*
* @param context
* the context
* @param intent
* the intent
*/
private void handlePackageReplaced( Context context, Intent intent ) {
logger.info( "handlePackageReplaced: " + intent );
Uri data = intent.getData();
String path = data.getSchemeSpecificPart();
if ( null != path ) {
if ( path.startsWith( FeatherIntent.PLUGIN_BASE_PACKAGE ) ) {
Intent newIntent = new Intent( FeatherIntent.ACTION_PLUGIN_REPLACED );
newIntent.setData( data );
handlePackage( context, path, newIntent );
newIntent.putExtra( FeatherIntent.ACTION, FeatherIntent.ACTION_PLUGIN_REPLACED );
context.sendBroadcast( newIntent );
}
}
}
/**
* Handle package removed.
*
* @param context
* the context
* @param intent
* the intent
*/
private void handlePackageRemoved( Context context, Intent intent ) {
logger.info( "handlePackageRemoved: " + intent );
Uri data = intent.getData();
String path = data.getSchemeSpecificPart();
Bundle extras = intent.getExtras();
boolean is_replacing = isReplacing( extras );
if ( null != path && !is_replacing ) {
if ( path.startsWith( FeatherIntent.PLUGIN_BASE_PACKAGE ) ) {
Intent newIntent = new Intent( FeatherIntent.ACTION_PLUGIN_REMOVED );
newIntent.setData( data );
handlePackage( context, path, newIntent );
newIntent.putExtra( FeatherIntent.ACTION, FeatherIntent.ACTION_PLUGIN_REMOVED );
context.sendBroadcast( newIntent );
}
}
}
/**
* Handle package added.
*
* @param context
* the context
* @param intent
* the intent
*/
private void handlePackageAdded( Context context, Intent intent ) {
logger.info( "handlePackageAdded: " + intent );
Uri data = intent.getData();
String path = data.getSchemeSpecificPart();
Bundle extras = intent.getExtras();
boolean is_replacing = isReplacing( extras );
if ( null != path && !is_replacing ) {
if ( path.startsWith( FeatherIntent.PLUGIN_BASE_PACKAGE ) ) {
Intent newIntent = new Intent( FeatherIntent.ACTION_PLUGIN_ADDED );
newIntent.setData( data );
handlePackage( context, path, newIntent );
newIntent.putExtra( FeatherIntent.ACTION, FeatherIntent.ACTION_PLUGIN_ADDED );
context.sendBroadcast( newIntent );
}
}
}
/**
* Prints the bundle.
*
* @param bundle
* the bundle
*/
@SuppressWarnings("unused")
private void printBundle( Bundle bundle ) {
if ( null != bundle ) {
Set<String> set = bundle.keySet();
Iterator<String> iterator = set.iterator();
while ( iterator.hasNext() ) {
String key = iterator.next();
Object value = bundle.get( key );
logger.log( " ", key, value );
}
}
}
/**
* The operation.
*
* @param bundle
* the bundle
* @return true, if is replacing
*/
private boolean isReplacing( Bundle bundle ) {
if ( bundle != null && bundle.containsKey( Intent.EXTRA_REPLACING ) ) return bundle.getBoolean( Intent.EXTRA_REPLACING );
return false;
}
}
| Java |
package com.aviary.android.feather;
import it.sephiroth.android.library.imagezoom.ImageViewTouchBase;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.concurrent.Future;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import com.aviary.android.feather.effects.AbstractEffectPanel;
import com.aviary.android.feather.effects.CropPanel;
import com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel;
import com.aviary.android.feather.effects.AbstractEffectPanel.OnApplyResultListener;
import com.aviary.android.feather.effects.AbstractEffectPanel.OnContentReadyListener;
import com.aviary.android.feather.effects.AbstractEffectPanel.OnErrorListener;
import com.aviary.android.feather.effects.AbstractEffectPanel.OnPreviewListener;
import com.aviary.android.feather.effects.AbstractEffectPanel.OnProgressListener;
import com.aviary.android.feather.effects.AbstractEffectPanel.OptionPanel;
import com.aviary.android.feather.effects.EffectLoaderService;
import com.aviary.android.feather.library.content.EffectEntry;
import com.aviary.android.feather.library.content.FeatherIntent;
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.plugins.ExternalPacksTask;
import com.aviary.android.feather.library.plugins.PluginFetchTask;
import com.aviary.android.feather.library.plugins.PluginUpdaterTask;
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.EffectContext;
import com.aviary.android.feather.library.services.EffectContextService;
import com.aviary.android.feather.library.services.FutureListener;
import com.aviary.android.feather.library.services.HiResService;
import com.aviary.android.feather.library.services.LocalDataService;
import com.aviary.android.feather.library.services.PluginService;
import com.aviary.android.feather.library.services.PreferenceService;
import com.aviary.android.feather.library.services.ServiceLoader;
import com.aviary.android.feather.library.services.ThreadPoolService;
import com.aviary.android.feather.library.services.ThreadPoolService.BGCallable;
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.receivers.FeatherSystemReceiver;
import com.aviary.android.feather.utils.UIUtils;
import com.aviary.android.feather.widget.BottombarViewFlipper;
import com.aviary.android.feather.widget.BottombarViewFlipper.OnPanelCloseListener;
import com.aviary.android.feather.widget.BottombarViewFlipper.OnPanelOpenListener;
import com.aviary.android.feather.widget.ToolbarView;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.util.AppContext;
// TODO: Auto-generated Javadoc
/**
* FilterManager is the core of feather. It manages all the tool panels, notifies about new plugins installed, etc
*
* @author alessandro
*
*/
public final class FilterManager implements OnPreviewListener, OnApplyResultListener, EffectContext, OnErrorListener,
OnContentReadyListener, OnProgressListener {
/**
* The Interface FeatherContext.<br />
* The activity caller must implement this interface
*/
public interface FeatherContext {
/**
* Gets the Activity main image view.
*
* @return the main image
*/
ImageViewTouchBase getMainImage();
/**
* Gets the Activity bottom bar view.
*
* @return the bottom bar
*/
BottombarViewFlipper getBottomBar();
/**
* Gets the Activity options panel container view.
*
* @return the options panel container
*/
ViewGroup getOptionsPanelContainer();
/**
* Gets the Activity drawing image container view.
*
* @return the drawing image container
*/
ViewGroup getDrawingImageContainer();
/**
* Show tool progress.
*/
void showToolProgress();
/**
* Hide tool progress.
*/
void hideToolProgress();
/**
* Show a modal progress
*/
void showModalProgress();
/**
* Hide the modal progress
*/
void hideModalProgress();
/**
* Gets the toolbar.
*
* @return the toolbar
*/
ToolbarView getToolbar();
}
public interface OnHiResListener {
void OnLoad( Uri uri );
void OnApplyActions( MoaActionList actionlist );
}
public interface OnBitmapChangeListener {
public void onPreviewChange( ColorFilter filter );
public void onBitmapChange( Bitmap bitmap, boolean update, Matrix matrix );
public void onPreviewChange( Bitmap bitmap );
public void onClearColorFilter();
}
/**
* The listener interface for receiving onTool events. The class that is interested in processing a onTool event implements this
* interface, and the object created with that class is registered with a component using the component's
* <code>addOnToolListener<code> method. When
* the onTool event occurs, that object's appropriate
* method is invoked.
*
* @see OnToolEvent
*/
public static interface OnToolListener {
/**
* On tool completed.
*/
void onToolCompleted();
}
/**
* All the possible states the filtermanager can use during the feather lifecycle.
*
* @author alessandro
*/
static enum STATE {
CLOSED_CANCEL, CLOSED_CONFIRMED, CLOSING, DISABLED, OPENED, OPENING,
}
/** The Constant STATE_OPENING. */
public static final int STATE_OPENING = 0;
/** The Constant STATE_OPENED. */
public static final int STATE_OPENED = 1;
/** The Constant STATE_CLOSING. */
public static final int STATE_CLOSING = 2;
/** The Constant STATE_CLOSED. */
public static final int STATE_CLOSED = 3;
/** The Constant STATE_DISABLED. */
public static final int STATE_DISABLED = 4;
public static final int STATE_CONTENT_READY = 5;
public static final int STATE_READY = 6;
public static final String LOG_TAG = "filter-manager";
/** The current bitmap. */
private Bitmap mBitmap;
/** The base context. This is the main activity */
private FeatherContext mContext;
/** The current active effect. */
private AbstractEffectPanel mCurrentEffect;
/** The current active effect entry. */
private EffectEntry mCurrentEntry;
/** The current panel state. */
private STATE mCurrentState;
/** The main tool listener. */
private OnToolListener mToolListener;
/** bitmap change listener */
private OnBitmapChangeListener mBitmapChangeListener;
private final Handler mHandler;
private final ServiceLoader<EffectContextService> mServiceLoader;
private EffectLoaderService mEffectLoader;
private Logger logger;
/** The changed state. If the original image has been modified. */
private boolean mChanged;
private Configuration mConfiguration;
private String mApiKey;
private String mSessionId;
private boolean mHiResEnabled = false;
private OnHiResListener mHiResListener;
private DragLayer mDragLayer;
private static Handler mPluingsHandler;
/**
* Instantiates a new filter manager.
*
* @param context
* the context
* @param handler
* the handler
*/
public FilterManager( final FeatherContext context, final Handler handler, final String apiKey ) {
logger = LoggerFactory.getLogger( "FilterManager", LoggerType.ConsoleLoggerType );
mContext = context;
mHandler = handler;
mApiKey = apiKey;
mPluingsHandler = new PluginHandler( this );
mServiceLoader = new ServiceLoader<EffectContextService>( this );
initServices( context );
mConfiguration = new Configuration( ((Context)context).getResources().getConfiguration() );
setCurrentState( STATE.DISABLED );
mChanged = false;
}
public void setDragLayer( DragLayer view ) {
mDragLayer = view;
}
private synchronized void initServices( final FeatherContext context ) {
logger.info( "initServices" );
mServiceLoader.register( ThreadPoolService.class );
mServiceLoader.register( ConfigService.class );
mServiceLoader.register( PluginService.class );
mServiceLoader.register( EffectLoaderService.class );
mServiceLoader.register( PreferenceService.class );
mServiceLoader.register( HiResService.class );
mServiceLoader.register( DragControllerService.class );
mServiceLoader.register( LocalDataService.class );
updateInstalledPlugins( null );
updateAvailablePlugins();
}
private void updateAvailablePlugins() {
logger.info( "updateAvailablePlugins" );
ThreadPoolService background = getService( ThreadPoolService.class );
if ( null != background ) {
if ( Constants.getExternalPacksEnabled() ) {
FutureListener<Bundle> listener = new FutureListener<Bundle>() {
@Override
public void onFutureDone( Future<Bundle> future ) {
logger.log( "updateAvailablePlugins::completed" );
Bundle result = null;
try {
result = future.get();
} catch ( Throwable t ) {
logger.error( t.getMessage() );
return;
}
mPluingsHandler.post( new ExternalPluginTaskCompletedRunnable( result ) );
}
};
background.submit( new ExternalPacksTask(), listener, null );
}
}
}
private void updateInstalledPlugins( Bundle extras ) {
logger.info( "updateInstalledPlugins" );
ThreadPoolService background = getService( ThreadPoolService.class );
if ( background != null ) {
final boolean externalItemsEnabled = Constants.getExternalPacksEnabled();
FutureListener<PluginFetchTask.Result> listener = new FutureListener<PluginFetchTask.Result>() {
@Override
public void onFutureDone( Future<PluginFetchTask.Result> future ) {
PluginFetchTask.Result result;
try {
result = future.get();
} catch ( Throwable t ) {
logger.error( t.getMessage() );
return;
}
mPluingsHandler.post( new PluginTaskCompletedRunnable( result ) );
}
};
BGCallable<Bundle, PluginFetchTask.Result> task;
if( null == extras ){
// first time
task = new PluginFetchTask();
} else {
// when a plugin is changed
task = new PluginUpdaterTask( externalItemsEnabled ? mPluingsHandler : null );
}
background.submit( task, listener, extras );
} else {
logger.error( "failed to retrieve ThreadPoolService" );
}
}
/**
* Register a default handler to receive hi-res messages
*
* @param basicHandler
*/
public void setOnHiResListener( OnHiResListener listener ) {
mHiResListener = listener;
}
private void initHiResService() {
logger.info( "initHiResService" );
LocalDataService dataService = getService( LocalDataService.class );
if ( Constants.containsValue( Constants.EXTRA_OUTPUT_HIRES_SESSION_ID ) ) {
mSessionId = Constants.getValueFromIntent( Constants.EXTRA_OUTPUT_HIRES_SESSION_ID, "" );
logger.info( "session-id: " + mSessionId + ", length: " + mSessionId.length() );
if ( mSessionId != null && mSessionId.length() == 64 ) {
mHiResEnabled = true;
HiResService service = getService( HiResService.class );
if ( !service.isRunning() ) {
service.start();
}
service.load( mSessionId, mApiKey, dataService.getSourceImageUri() );
} else {
logger.error( "session id is invalid" );
}
} else {
logger.warning( "missing session id" );
}
if ( null != mHiResListener ) {
mHiResListener.OnLoad( dataService.getSourceImageUri() );
}
}
/**
* This is the entry point of every feather tools. The main activity catches the tool onClick listener and notify the
* filtermanager.
*
* @param tag
* the tag
*/
public void activateEffect( final EffectEntry tag ) {
if ( !getEnabled() || !isClosed() || mBitmap == null ) return;
if ( mCurrentEffect != null ) throw new IllegalStateException( "There is already an active effect. Cannot activate new" );
if ( mEffectLoader == null ) mEffectLoader = (EffectLoaderService) getService( EffectLoaderService.class );
final AbstractEffectPanel effect = mEffectLoader.load( tag );
if ( effect != null ) {
mCurrentEffect = effect;
mCurrentEntry = tag;
setCurrentState( STATE.OPENING );
prepareEffectPanel( effect, tag );
Tracker.recordTag( mCurrentEntry.name.name().toLowerCase() + ": opened" );
if (mCurrentEffect instanceof CropPanel) {
mContext.getBottomBar().setOnPanelOpenListener( new OnPanelOpenListener() {
@Override
public void onOpened() {
setCurrentState( STATE.OPENED );
mContext.getBottomBar().setOnPanelOpenListener( null );
mContext.getBottomBar().setVisibility(View.INVISIBLE);
}
@Override
public void onOpening() {
mCurrentEffect.onOpening();
}
} );
mContext.getBottomBar().open();
}else {
mContext.getBottomBar().setOnPanelOpenListener( new OnPanelOpenListener() {
@Override
public void onOpened() {
setCurrentState( STATE.OPENED );
mContext.getBottomBar().setOnPanelOpenListener( null );
}
@Override
public void onOpening() {
mCurrentEffect.onOpening();
}
} );
mContext.getBottomBar().open();
}
}
}
/**
* Dispose.
*/
public void dispose() {
// TODO: if a panel is opened the deactivate an destroy it
if ( mCurrentEffect != null ) {
logger.log( "Deactivate and destroy current panel" );
mCurrentEffect.onDeactivate();
mCurrentEffect.onDestroy();
mCurrentEffect = null;
}
mServiceLoader.dispose();
mContext = null;
mToolListener = null;
mBitmapChangeListener = null;
System.gc();
}
@Override
public double getApplicationMaxMemory() {
return Constants.getApplicationMaxMemory();
}
@Override
public void getRuntimeMemoryInfo( double[] outValues ) {
Constants.getMemoryInfo( outValues );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContext#getBaseContext()
*/
@Override
public Context getBaseContext() {
return (Activity) mContext;
}
@Override
public Activity getBaseActivity() {
return (Activity) mContext;
}
/**
* Return the current bitmap.
*
* @return the bitmap
*/
public Bitmap getBitmap() {
return mBitmap;
}
/**
* Return true if the main image has been modified by any of the feather tools.
*
* @return the bitmap is changed
*/
public boolean getBitmapIsChanged() {
return mChanged;
}
/**
* Return the active tool, null if there is not active tool.
*
* @return the current effect
*/
@Override
public EffectEntry getCurrentEffect() {
return mCurrentEntry;
}
/**
* Return the current panel associated with the active tool. Null if there's no active tool
*
* @return the current panel
*/
public AbstractEffectPanel getCurrentPanel() {
return mCurrentEffect;
}
/**
* Return the current image transformation matrix. this is useful for those tools which implement ContentPanel and want to
* display the preview bitmap with the same zoom level of the main image
*
* @return the current image view matrix
* @see ContentPanel
*/
@Override
public Matrix getCurrentImageViewMatrix() {
return mContext.getMainImage().getDisplayMatrix();
}
/**
* Return true if enabled.
*
* @return the enabled
*/
public boolean getEnabled() {
return mCurrentState != STATE.DISABLED;
}
/**
* Return the service, if previously registered using ServiceLoader.
*
* @param <T>
* the generic type
* @param cls
* the cls
* @return the service
*/
@SuppressWarnings("unchecked")
@Override
public <T> T getService( Class<T> cls ) {
try {
return (T) mServiceLoader.getService( (Class<EffectContextService>) cls );
} catch ( IllegalAccessException e ) {
e.printStackTrace();
return null;
}
}
/**
* Return true if there's no active tool.
*
* @return true, if is closed
*/
public boolean isClosed() {
return ( mCurrentState == STATE.CLOSED_CANCEL ) || ( mCurrentState == STATE.CLOSED_CONFIRMED );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContext#isConnectedOrConnecting()
*/
@Override
public boolean isConnectedOrConnecting() {
try {
final ConnectivityManager conn = (ConnectivityManager) getBaseContext().getSystemService( Context.CONNECTIVITY_SERVICE );
if ( ( conn.getActiveNetworkInfo() == null ) || !conn.getActiveNetworkInfo().isConnectedOrConnecting() ) return false;
return true;
} catch ( final SecurityException e ) {
// the android.permission.ACCESS_NETWORK_STATE is not set, so we're assuming
// an internet connection is available
logger.error( "android.permission.ACCESS_NETWORK_STATE is not defined. Assuming network is fine" );
return true;
}
}
/**
* return true if there's one active tool.
*
* @return true, if is opened
*/
public boolean isOpened() {
return mCurrentState == STATE.OPENED;
}
/**
* On activate.
*
* @param bitmap
* the bitmap
*/
public void onActivate( final Bitmap bitmap, int[] originalSize ) {
if ( mCurrentState != STATE.DISABLED ) throw new IllegalStateException( "Cannot activate. Already active!" );
if ( ( mBitmap != null ) && !mBitmap.isRecycled() ) {
mBitmap = null;
}
mBitmap = bitmap;
LocalDataService dataService = getService( LocalDataService.class );
dataService.setSourceImageSize( originalSize );
mChanged = false;
setCurrentState( STATE.CLOSED_CONFIRMED );
initHiResService();
}
/**
* Current activity is asking to apply the current tool.
*/
public void onApply() {
logger.info( "FilterManager::onapply" );
if ( !getEnabled() || !isOpened() ) return;
if ( mCurrentEffect == null ) throw new IllegalStateException( "there is no current effect active in the context" );
if ( !mCurrentEffect.isEnabled() ) return;
if ( mCurrentEffect.getIsChanged() ) {
mCurrentEffect.onSave();
mChanged = true;
} else {
onCancel();
}
}
/**
* Parent activity just received a onBackPressed event. If there's one active tool, it will be asked to manage the onBackPressed
* event. If the active tool onBackPressed method return a false then try to close it.
*
* @return true, if successful
*/
public boolean onBackPressed() {
if ( isClosed() ) return false;
if ( mCurrentState != STATE.DISABLED ) {
if ( isOpened() ) {
if ( !mCurrentEffect.onBackPressed() ) onCancel();
}
return true;
}
return false;
}
/**
* Main activity asked to cancel the current operation.
*/
public void onCancel() {
if ( !getEnabled() || !isOpened() ) return;
if ( mCurrentEffect == null ) throw new IllegalStateException( "there is no current effect active in the context" );
if ( !mCurrentEffect.onCancel() ) {
cancel();
}
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContext#cancel()
*/
@Override
public void cancel() {
logger.info( "FilterManager::cancel" );
if ( !getEnabled() || !isOpened() ) return;
if ( mCurrentEffect == null ) throw new IllegalStateException( "there is no current effect active in the context" );
Tracker.recordTag( mCurrentEntry.name.name().toLowerCase() + ": cancelled" );
// send the cancel event to the effect
mCurrentEffect.onCancelled();
// check changed image
if ( mCurrentEffect.getIsChanged() ) {
// panel is changed, restore the original bitmap
if ( mCurrentEffect instanceof ContentPanel ) {
ContentPanel panel = (ContentPanel) mCurrentEffect;
setNextBitmap( mBitmap, true, panel.getContentDisplayMatrix() );
} else {
setNextBitmap( mBitmap, false );
}
} else {
// panel is not changed
if ( mCurrentEffect instanceof ContentPanel ) {
ContentPanel panel = (ContentPanel) mCurrentEffect;
setNextBitmap( mBitmap, true, panel.getContentDisplayMatrix() );
} else {
setNextBitmap( mBitmap, false );
}
}
onClose( false );
}
/**
* On close.
*
* @param isConfirmed
* the is confirmed
*/
private void onClose( final boolean isConfirmed ) {
logger.info( "onClose" );
setCurrentState( STATE.CLOSING );
mContext.getBottomBar().setVisibility(View.VISIBLE);
mContext.getBottomBar().setOnPanelCloseListener( new OnPanelCloseListener() {
@Override
public void onClosed() {
setCurrentState( isConfirmed ? STATE.CLOSED_CONFIRMED : STATE.CLOSED_CANCEL );
mContext.getBottomBar().setOnPanelCloseListener( null );
}
@Override
public void onClosing() {
mCurrentEffect.onClosing();
}
} );
mContext.getBottomBar().close();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnApplyResultListener#onComplete(android.graphics.Bitmap,
* java.util.HashMap)
*/
@Override
public void onComplete( final Bitmap result, MoaActionList actions, HashMap<String, String> trackingAttributes ) {
logger.info( "onComplete: " + android.os.Debug.getNativeHeapAllocatedSize() );
Tracker.recordTag( mCurrentEntry.name.name().toLowerCase() + ": applied", trackingAttributes );
if ( result != null ) {
if ( mCurrentEffect instanceof ContentPanel ) {
ContentPanel panel = (ContentPanel) mCurrentEffect;
final boolean changed = BitmapUtils.compareBySize( mBitmap, result );
setNextBitmap( result, true, changed ? null : panel.getContentDisplayMatrix() );
} else {
setNextBitmap( result, false );
}
} else {
logger.error( "Error: returned bitmap is null!" );
setNextBitmap( mBitmap, true );
}
onClose( true );
if ( mHiResEnabled ) {
// send the actions...
if ( null == actions ) logger.error( "WTF actionlist is null!!!!" );
HiResService service = getService( HiResService.class );
if ( service.isRunning() ) {
service.execute( mSessionId, mApiKey, actions );
}
}
if ( null != mHiResListener ) {
mHiResListener.OnApplyActions( actions );
}
}
/**
* Sets the next bitmap.
*
* @param bitmap
* the new next bitmap
*/
void setNextBitmap( Bitmap bitmap ) {
setNextBitmap( bitmap, true );
}
/**
* Sets the next bitmap.
*
* @param bitmap
* the bitmap
* @param update
* the update
*/
void setNextBitmap( Bitmap bitmap, boolean update ) {
setNextBitmap( bitmap, update, null );
}
/**
* Sets the next bitmap.
*
* @param bitmap
* the bitmap
* @param update
* the update
* @param matrix
* the matrix
*/
void setNextBitmap( Bitmap bitmap, boolean update, Matrix matrix ) {
logger.log( "setNextBitmap", bitmap, update, matrix );
if ( null != mBitmapChangeListener ) mBitmapChangeListener.onBitmapChange( bitmap, update, matrix );
if ( !mBitmap.equals( bitmap ) ) {
logger.warning( "[recycle] original Bitmap: " + mBitmap );
mBitmap.recycle();
mBitmap = null;
}
mBitmap = bitmap;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnErrorListener#onError(java.lang.String)
*/
@Override
public void onError( final String error ) {
new AlertDialog.Builder( (Activity) mContext ).setTitle( R.string.generic_error_title ).setMessage( error )
.setIcon( android.R.drawable.ic_dialog_alert ).show();
}
@Override
public void onError( final String error, int yesLabel, OnClickListener yesListener, int noLabel, OnClickListener noListener ) {
new AlertDialog.Builder( (Activity) mContext ).setTitle( R.string.generic_error_title ).setMessage( error )
.setPositiveButton( yesLabel, yesListener ).setNegativeButton( noLabel, noListener )
.setIcon( android.R.drawable.ic_dialog_alert ).show();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnPreviewListener#onPreviewChange(android.graphics.Bitmap)
*/
@Override
public void onPreviewChange( final Bitmap result ) {
if ( !getEnabled() || !isOpened() ) return;
if ( null != mBitmapChangeListener ) mBitmapChangeListener.onPreviewChange( result );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnPreviewListener#onPreviewChange(android.graphics.ColorFilter)
*/
@Override
public void onPreviewChange( ColorFilter colorFilter ) {
if ( !getEnabled() || !isOpened() ) return;
if ( null != mBitmapChangeListener ) mBitmapChangeListener.onPreviewChange( colorFilter );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnContentReadyListener#onReady(com.aviary.android.feather.effects.
* AbstractEffectPanel)
*/
@Override
public void onReady( final AbstractEffectPanel panel ) {
mHandler.sendEmptyMessage( STATE_CONTENT_READY );
mHandler.sendEmptyMessage( STATE_READY );
}
/**
* Replace the current bitmap.
*
* @param bitmap
* the bitmap
*/
public void onReplaceImage( final Bitmap bitmap, int[] originalSize ) {
if ( !getEnabled() || !isClosed() ) throw new IllegalStateException( "Cannot replace bitmap. Not active nor closed!" );
LocalDataService dataService = getService( LocalDataService.class );
if ( ( mBitmap != null ) && !mBitmap.isRecycled() ) {
logger.warning( "[recycle] original Bitmap: " + mBitmap );
mBitmap.recycle();
mBitmap = null;
}
mChanged = false;
mBitmap = bitmap;
dataService.setSourceImageSize( originalSize );
HiResService service = getService( HiResService.class );
if ( mHiResEnabled && service.isRunning() ) {
service.replace( mSessionId, mApiKey, dataService.getSourceImageUri() );
}
if ( null != mHiResListener ) {
mHiResListener.OnLoad( dataService.getSourceImageUri() );
}
}
/**
* On save.
*/
public void onSave() {
if ( !getEnabled() || !isClosed() ) return;
}
/**
* Prepare effect panel.
*
* @param effect
* the effect
* @param entry
* the entry
*/
private void prepareEffectPanel( final AbstractEffectPanel effect, final EffectEntry entry ) {
View option_child = null;
View drawing_child = null;
if ( effect instanceof OptionPanel ) {
option_child = ( (OptionPanel) effect ).getOptionView( UIUtils.getLayoutInflater(), mContext.getOptionsPanelContainer() );
mContext.getOptionsPanelContainer().addView( option_child );
}
if ( effect instanceof ContentPanel ) {
drawing_child = ( (ContentPanel) effect ).getContentView( UIUtils.getLayoutInflater() );
drawing_child.setLayoutParams( new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
mContext.getDrawingImageContainer().addView( drawing_child );
}
effect.onCreate( mBitmap );
}
/**
* Run a Runnable on the main UI thread.
*
* @param action
* the action
*/
@Override
public void runOnUiThread( final Runnable action ) {
if ( mContext != null ) ( (Activity) mContext ).runOnUiThread( action );
}
/**
* Sets the current state.
*
* @param newState
* the new current state
*/
private void setCurrentState( final STATE newState ) {
if ( newState != mCurrentState ) {
final STATE previousState = mCurrentState;
mCurrentState = newState;
switch ( newState ) {
case OPENING:
mCurrentEffect.setOnPreviewListener( this );
mCurrentEffect.setOnApplyResultListener( this );
mCurrentEffect.setOnErrorListener( this );
mCurrentEffect.setOnProgressListener( this );
if ( mCurrentEffect instanceof ContentPanel ) ( (ContentPanel) mCurrentEffect ).setOnReadyListener( this );
mHandler.sendEmptyMessage( FilterManager.STATE_OPENING );
break;
case OPENED:
mCurrentEffect.onActivate();
mHandler.sendEmptyMessage( FilterManager.STATE_OPENED );
if( !(mCurrentEffect instanceof ContentPanel) ){
mHandler.sendEmptyMessage( STATE_READY );
}
break;
case CLOSING:
mHandler.sendEmptyMessage( FilterManager.STATE_CLOSING );
mHandler.post( new Runnable() {
@Override
public void run() {
mCurrentEffect.onDeactivate();
if ( null != mBitmapChangeListener ) mBitmapChangeListener.onClearColorFilter();
if ( mCurrentEffect instanceof ContentPanel ) ( (ContentPanel) mCurrentEffect ).setOnReadyListener( null );
mContext.getDrawingImageContainer().removeAllViews();
}
} );
break;
case CLOSED_CANCEL:
case CLOSED_CONFIRMED:
if (null != mContext.getOptionsPanelContainer()) {
mContext.getOptionsPanelContainer().removeAllViews();
}
if ( previousState != STATE.DISABLED ) {
mCurrentEffect.onDestroy();
mCurrentEffect.setOnPreviewListener( null );
mCurrentEffect.setOnApplyResultListener( null );
mCurrentEffect.setOnErrorListener( null );
mCurrentEffect.setOnProgressListener( null );
mCurrentEffect = null;
mCurrentEntry = null;
}
mHandler.sendEmptyMessage( FilterManager.STATE_CLOSED );
if ( ( newState == STATE.CLOSED_CONFIRMED ) && ( previousState != STATE.DISABLED ) )
if ( mToolListener != null ) mToolListener.onToolCompleted();
System.gc();
break;
case DISABLED:
mHandler.sendEmptyMessage( FilterManager.STATE_DISABLED );
break;
}
}
}
/**
* Sets the enabled.
*
* @param value
* the new enabled
*/
public void setEnabled( final boolean value ) {
if ( !value ) {
if ( isClosed() ) {
setCurrentState( STATE.DISABLED );
} else {
logger.warning( "FilterManager must be closed to change state" );
}
}
}
/**
* Sets the on tool listener.
*
* @param listener
* the new on tool listener
*/
public void setOnToolListener( final OnToolListener listener ) {
mToolListener = listener;
}
public void setOnBitmapChangeListener( final OnBitmapChangeListener listener ) {
mBitmapChangeListener = listener;
}
/**
* Main Activity configuration changed We want to dispatch the configuration event also to the opened panel.
*
* @param newConfig
* the new config
* @return true if the event has been handled
*/
public boolean onConfigurationChanged( Configuration newConfig ) {
boolean result = false;
logger.info( "onConfigurationChanged: " + newConfig.orientation + ", " + mConfiguration.orientation );
if ( mCurrentEffect != null ) {
if ( mCurrentEffect.isCreated() ) {
logger.info( "onConfigurationChanged, sending event to ", mCurrentEffect );
mCurrentEffect.onConfigurationChanged( newConfig, mConfiguration );
result = true;
}
}
mConfiguration = new Configuration( newConfig );
return result;
}
/**
* A plugin or theme has been installed/removed or replaced Notify the internal pluginservice about the new plugin. All the
* classes which have a listener attached to the PluginService will be notified too.
*
* @param intent
* the intent
* @see FeatherSystemReceiver
*/
public void onPluginChanged( Intent intent ) {
logger.info( "onReceive", intent );
logger.info( "data", intent.getData() );
updateInstalledPlugins( intent.getExtras() );
}
private static class PluginHandler extends Handler {
WeakReference<EffectContext> mContext;
public PluginHandler( EffectContext context ) {
mContext = new WeakReference<EffectContext>( context );
}
@Override
public void handleMessage( Message msg ) {
EffectContext effectContext = mContext.get();
if ( null != effectContext ) {
Context context = effectContext.getBaseContext();
UpdateType update = (UpdateType) msg.obj;
PluginService service = effectContext.getService( PluginService.class );
final String packagename = update.getPackageName();
final int pluginType = update.getPluginType();
LoggerFactory.log( "PluginHandler::handleMessage. " + msg.what + ", update:" + update.toString() );
switch ( msg.what ) {
case PluginUpdaterTask.MSG_PLUING_ADD:
service.install( context, packagename, pluginType );
break;
case PluginUpdaterTask.MSG_PLUING_REMOVE:
if ( service.installed( packagename ) ) {
service.uninstall( context, packagename );
}
break;
case PluginUpdaterTask.MSG_PLUING_REPLACE:
if ( service.uninstall( context, packagename ) ) {
service.install( context, packagename, pluginType );
}
break;
}
}
};
};
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnProgressListener#onProgressStart()
*/
@Override
public void onProgressStart() {
mContext.showToolProgress();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel.OnProgressListener#onProgressEnd()
*/
@Override
public void onProgressEnd() {
mContext.hideToolProgress();
}
@Override
public void onProgressModalStart() {
mContext.showModalProgress();
}
@Override
public void onProgressModalEnd() {
mContext.hideModalProgress();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContext#setToolbarTitle(int)
*/
@Override
public void setToolbarTitle( int resId ) {
setToolbarTitle( getBaseContext().getString( resId ) );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContext#setToolbarTitle(java.lang.CharSequence)
*/
@Override
public void setToolbarTitle( CharSequence value ) {
mContext.getToolbar().setTitle( value );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.library.services.EffectContext#restoreToolbarTitle()
*/
@Override
public void restoreToolbarTitle() {
if ( mCurrentEntry != null ) mContext.getToolbar().setTitle( mCurrentEntry.labelResourceId );
}
@Override
public void downloadPlugin( final String packageName, final int type ) {
searchOrDownloadPlugin( packageName, type, false );
}
@Override
public void searchPlugin( final int type ) {
String name = FeatherIntent.PluginType.getName( type );
String packageName = FeatherIntent.PLUGIN_BASE_PACKAGE;
if ( null != name ) {
packageName = packageName + name + ".*";
} else {
packageName = packageName + "*";
}
searchOrDownloadPlugin( packageName, type, true );
}
public void searchOrDownloadPlugin( final String packageName, final int type, final boolean search ) {
logger.info( "searchOrDownloadPlugin: " + packageName + ", search: " + search );
Intent intent = new Intent( Intent.ACTION_VIEW );
if ( search )
intent.setData( Uri.parse( "market://search?q=" + packageName ) );
else
intent.setData( Uri.parse( "market://details?id=" + packageName ) );
try {
String name = FeatherIntent.PluginType.getName( type );
if ( null != name ) {
HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put( "assetType", name );
Tracker.recordTag( "content: addMoreClicked", attrs );
}
getBaseContext().startActivity( intent );
} catch ( ActivityNotFoundException e ) {
Toast.makeText( getBaseContext(), R.string.feather_activity_not_found, Toast.LENGTH_SHORT ).show();
e.printStackTrace();
}
}
@Override
public DragLayer getDragLayer() {
return mDragLayer;
}
private class PluginTaskCompletedRunnable implements Runnable {
PluginFetchTask.Result mResult;
public PluginTaskCompletedRunnable( final PluginFetchTask.Result result ) {
mResult = result;
}
@Override
public void run() {
PluginService pluginService = getService( PluginService.class );
if( null != pluginService )
pluginService.update( mResult.installed, mResult.delta );
}
}
private class ExternalPluginTaskCompletedRunnable implements Runnable {
Bundle mResult;
public ExternalPluginTaskCompletedRunnable( final Bundle result ) {
mResult = result;
}
@Override
public void run() {
PluginService pluginService = getService( PluginService.class );
if ( null != pluginService ) {
pluginService.updateExternalPackages( mResult );
}
}
}
}
| Java |
package com.aviary.android.feather.database;
import android.database.DataSetObserver;
public abstract class DataSetObserverExtended extends DataSetObserver {
public void onAdded() {
// Do Nothing
}
public void onRemoved() {
// Do Nothing
}
}
| Java |
package com.aviary.android.feather.database;
import android.database.Observable;
public class DataSetObservableExtended extends Observable<DataSetObserverExtended> {
/**
* Invokes onChanged on each observer. Called when the data set being observed has changed, and which when read contains the new
* state of the data.
*/
public void notifyChanged() {
synchronized ( mObservers ) {
for ( DataSetObserverExtended observer : mObservers ) {
observer.onChanged();
}
}
}
/**
* Invokes onChanged on each observer. Called when an item in the data set being observed has added, and which when read contains
* the new state of the data.
*/
public void notifyAdded() {
synchronized ( mObservers ) {
for ( DataSetObserverExtended observer : mObservers ) {
observer.onAdded();
}
}
}
/**
* Invokes onRemoved on each observer. Called when an item in the data set being observed has removed, and which when read
* contains the new state of the data.
*/
public void notifyRemoved() {
synchronized ( mObservers ) {
for ( DataSetObserverExtended observer : mObservers ) {
observer.onRemoved();
}
}
}
/**
* Invokes onInvalidated on each observer. Called when the data set being monitored has changed such that it is no longer valid.
*/
public void notifyInvalidated() {
synchronized ( mObservers ) {
for ( DataSetObserverExtended observer : mObservers ) {
observer.onInvalidated();
}
}
}
}
| Java |
package com.aviary.android.feather.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.outsourcing.bottle.R;
import com.aviary.android.feather.graphics.AnimatedRotateDrawable;
import com.aviary.android.feather.library.graphics.drawable.FastBitmapDrawable;
import com.aviary.android.feather.widget.IToast;
import com.aviary.android.feather.widget.wp.CellLayout;
/**
* Variuos UI utilities.
*
* @author alessandro
*/
public class UIUtils {
private static Context mContext;
private static LayoutInflater mLayoutInflater;
/**
* Inits the.
*
* @param context
* the context
*/
public static void init( Context context ) {
mContext = context;
}
public static LayoutInflater getLayoutInflater() {
if ( mLayoutInflater == null ) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
}
return mLayoutInflater;
}
/**
* Show custom toast.
*
* @param viewResId
* the view res id
*/
public static void showCustomToast( int viewResId ) {
showCustomToast( viewResId, Toast.LENGTH_SHORT );
}
/**
* Show custom toast.
*
* @param viewResId
* the view res id
* @param duration
* the duration
*/
public static void showCustomToast( int viewResId, int duration ) {
showCustomToast( viewResId, duration, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM );
}
public static IToast createModalLoaderToast() {
IToast mToastLoader = IToast.make( mContext, -1 );
View view = getLayoutInflater().inflate( R.layout.feather_progress_view, null );
AnimatedRotateDrawable d = new AnimatedRotateDrawable( mContext.getResources(), R.drawable.feather_spinner_white_76, 12, 100 );
ProgressBar progress = (ProgressBar) view.findViewById( R.id.progress );
progress.setIndeterminateDrawable( d );
mToastLoader.setView( view );
return mToastLoader;
}
/**
* Display a system Toast using a custom ui view.
*
* @param viewResId
* the view res id
* @param duration
* the duration
* @param gravity
* the gravity
*/
public static void showCustomToast( int viewResId, int duration, int gravity ) {
View layout = getLayoutInflater().inflate( viewResId, null );
Toast toast = new Toast( mContext.getApplicationContext() );
toast.setGravity( gravity, 0, 0 );
toast.setDuration( duration );
toast.setView( layout );
toast.show();
}
/**
* Draw folder icon.
*
* @param folder
* the folder
* @param icon
* the icon
* @param icon_new
* the icon_new
* @return the drawable
*/
public static Drawable drawFolderIcon( Drawable folder, Drawable icon, Drawable icon_new ) {
final int w = folder.getIntrinsicWidth();
final int h = folder.getIntrinsicHeight();
folder.setBounds( 0, 0, w, h );
Bitmap bitmap = Bitmap.createBitmap( w, h, Config.ARGB_8888 );
Canvas canvas = new Canvas( bitmap );
folder.draw( canvas );
float icon_w = (float) w / 1.5f;
float icon_h = (float) h / 1.5f;
float icon_left = ( w - icon_w ) / 2;
float icon_top = ( h - icon_h ) / 2;
icon.setBounds( (int) icon_left, (int) icon_top, (int) ( icon_left + icon_w ), (int) ( icon_top + icon_h ) );
icon.setColorFilter( new PorterDuffColorFilter( 0xFFFFFFFF, Mode.MULTIPLY ) );
icon.setFilterBitmap( true );
icon.draw( canvas );
if ( icon_new != null ) {
icon_new.setBounds( 0, 0, (int) ( w / 2.5 ), (int) ( h / 2.5 ) );
icon_new.draw( canvas );
}
return new FastBitmapDrawable( bitmap );
}
/**
* Try to calculate the optimal number of columns for the current screen.
*
* @return the screen optimal columns
* @see CellLayout#setNumCols(int)
*/
public static int getScreenOptimalColumns() {
return getScreenOptimalColumns( 0 );
}
/**
* Gets the screen optimal columns.
*
* @param drawable_width
* the drawable_width
* @return the screen optimal columns
*/
public static int getScreenOptimalColumns( int drawable_width ) {
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
double a = (double) metrics.widthPixels / (double) metrics.densityDpi; // 2.25
int b = (int) Math.ceil( a * 2.0 ); // 5
if ( ( b * drawable_width ) > metrics.widthPixels ) {
return metrics.widthPixels / drawable_width;
}
return Math.min( Math.max( b, 3 ), 10 );
}
public static int getScreenOptimalColumnsPixels( int cell_pixels ) {
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
double a = (double) metrics.widthPixels;
int columns = (int) ( a / cell_pixels );
return columns;
}
}
| Java |
package com.aviary.android.feather.utils;
import android.app.ProgressDialog;
import android.os.Handler;
import com.aviary.android.feather.MonitoredActivity;
/**
* Some thread related utilities.
*
* @author alessandro
*/
public class ThreadUtils {
/**
* Start background job.
*
* @param activity
* the activity
* @param title
* the title
* @param message
* the message
* @param job
* the job
* @param handler
* the handler
*/
public static void startBackgroundJob( MonitoredActivity activity, String title, String message, Runnable job, Handler handler ) {
ProgressDialog dialog = ProgressDialog.show( activity, title, message, true, false );
new Thread( new BackgroundJob( activity, job, dialog, handler ) ).start();
}
/**
* The Class BackgroundJob.
*/
private static class BackgroundJob extends MonitoredActivity.LifeCycleAdapter implements Runnable {
private final MonitoredActivity mActivity;
private final ProgressDialog mDialog;
private final Runnable mJob;
private final Handler mHandler;
private final Runnable mCleanupRunner = new Runnable() {
@Override
public void run() {
mActivity.removeLifeCycleListener( BackgroundJob.this );
if ( mDialog.getWindow() != null ) mDialog.dismiss();
}
};
/**
* Instantiates a new background job.
*
* @param activity
* the activity
* @param job
* the job
* @param dialog
* the dialog
* @param handler
* the handler
*/
public BackgroundJob( MonitoredActivity activity, Runnable job, ProgressDialog dialog, Handler handler ) {
mActivity = activity;
mDialog = dialog;
mJob = job;
mActivity.addLifeCycleListener( this );
mHandler = handler;
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try {
mJob.run();
} finally {
mHandler.post( mCleanupRunner );
}
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.MonitoredActivity.LifeCycleAdapter#onActivityDestroyed(com.aviary.android.feather.MonitoredActivity
* )
*/
@Override
public void onActivityDestroyed( MonitoredActivity activity ) {
mCleanupRunner.run();
mHandler.removeCallbacks( mCleanupRunner );
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.MonitoredActivity.LifeCycleAdapter#onActivityStopped(com.aviary.android.feather.MonitoredActivity
* )
*/
@Override
public void onActivityStopped( MonitoredActivity activity ) {
mDialog.hide();
}
/*
* (non-Javadoc)
*
* @see
* com.aviary.android.feather.MonitoredActivity.LifeCycleAdapter#onActivityStarted(com.aviary.android.feather.MonitoredActivity
* )
*/
@Override
public void onActivityStarted( MonitoredActivity activity ) {
mDialog.show();
}
}
}
| Java |
package com.aviary.android.feather.utils;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import android.content.res.AssetManager;
import android.graphics.Typeface;
public class TypefaceUtils {
private static final HashMap<String, SoftReference<Typeface>> sTypeCache = new HashMap<String, SoftReference<Typeface>>();
public static Typeface createFromAsset( final AssetManager assets, final String fontname ) {
Typeface result = null;
SoftReference<Typeface> cachedFont = getFromCache( fontname );
if( null != cachedFont && cachedFont.get() != null ){
result = cachedFont.get();
} else {
result = Typeface.createFromAsset( assets, fontname );
putIntoCache( fontname, result );
}
return result;
}
private static SoftReference<Typeface> getFromCache( final String fontname ) {
synchronized ( sTypeCache ) {
return sTypeCache.get( fontname );
}
}
private static void putIntoCache( final String fontname, final Typeface font ) {
synchronized ( sTypeCache ) {
sTypeCache.put( fontname, new SoftReference<Typeface>( font ) );
}
}
}
| Java |
package com.aviary.android.feather.utils;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;
import android.graphics.Bitmap;
import android.os.Handler;
public class SimpleBitmapCache {
private static final int DELAY_BEFORE_PURGE = 30 * 1000;
private static final int HARD_CACHE_CAPACITY = 4;
private final Handler purgeHandler = new Handler();
private final HashMap<String, Bitmap> sHardBitmapCache = new LinkedHashMap<String, Bitmap>( HARD_CACHE_CAPACITY / 2, 0.75f, true ) {
private static final long serialVersionUID = 7320831300767054723L;
@Override
protected boolean removeEldestEntry( LinkedHashMap.Entry<String, Bitmap> eldest ) {
if ( size() > HARD_CACHE_CAPACITY ) {
sSoftBitmapCache.put( eldest.getKey(), new SoftReference<Bitmap>( eldest.getValue() ) );
return true;
} else
return false;
}
};
private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>(
HARD_CACHE_CAPACITY / 2 );
public SimpleBitmapCache() {}
public Bitmap getBitmapFromCache( String url ) {
synchronized ( sHardBitmapCache ) {
final Bitmap bitmap = sHardBitmapCache.get( url );
if ( bitmap != null ) {
sHardBitmapCache.remove( url );
sHardBitmapCache.put( url, bitmap );
return bitmap;
}
}
SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get( url );
if ( bitmapReference != null ) {
final Bitmap bitmap = bitmapReference.get();
if ( bitmap != null ) {
return bitmap;
} else {
sSoftBitmapCache.remove( url );
}
}
return null;
}
public void addBitmapToCache( String url, Bitmap bitmap ) {
if ( bitmap != null ) {
synchronized ( sHardBitmapCache ) {
sHardBitmapCache.put( url, bitmap );
}
}
}
public void clearCache() {
sHardBitmapCache.clear();
sSoftBitmapCache.clear();
}
public void resetPurgeTimer() {
purgeHandler.removeCallbacks( mPurger );
purgeHandler.postDelayed( mPurger, DELAY_BEFORE_PURGE );
}
private final Runnable mPurger = new Runnable() {
@Override
public void run() {
clearCache();
}
};
}
| Java |
package com.aviary.android.feather.effects;
import org.json.JSONException;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import com.aviary.android.feather.Constants;
import com.outsourcing.bottle.R;
import com.aviary.android.feather.library.filters.FilterLoaderFactory;
import com.aviary.android.feather.library.filters.FilterLoaderFactory.Filters;
import com.aviary.android.feather.library.filters.INativeRangeFilter;
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.services.EffectContext;
import com.aviary.android.feather.library.utils.BitmapUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.aviary.android.feather.widget.Wheel;
// TODO: Auto-generated Javadoc
/**
* The Class NativeEffectRangePanel.
*/
public class NativeEffectRangePanel extends ColorMatrixEffectPanel {
View mDrawingPanel;
int mLastValue;
ApplyFilterTask mCurrentTask;
volatile boolean mIsRendering = false;
boolean enableFastPreview;
MoaActionList mActions = null;
/**
* Instantiates a new native effect range panel.
*
* @param context
* the context
* @param type
* the type
* @param resourcesBaseName
* the resources base name
*/
public NativeEffectRangePanel( EffectContext context, Filters type, String resourcesBaseName ) {
super( context, type, resourcesBaseName );
mFilter = FilterLoaderFactory.get( type );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onCreate(android.graphics.Bitmap)
*/
@Override
public void onCreate( Bitmap bitmap ) {
super.onCreate( bitmap );
mWheel.setWheelScaleFactor( 2 );
mWheelRadio.setTicksNumber( mWheel.getTicks() * 4, mWheel.getWheelScaleFactor() );
enableFastPreview = Constants.getFastPreviewEnabled();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onActivate()
*/
@Override
public void onActivate() {
super.onActivate();
disableHapticIsNecessary( mWheel );
int ticksCount = mWheel.getTicksCount();
mWheelRadio.setTicksNumber( ticksCount, mWheel.getWheelScaleFactor() );
mPreview = BitmapUtils.copy( mBitmap, Bitmap.Config.ARGB_8888 );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onScrollStarted(com.aviary.android.feather.widget.Wheel, float,
* int)
*/
@Override
public void onScrollStarted( Wheel view, float value, int roundValue ) {
mLogger.info( "onScrollStarted" );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onScroll(com.aviary.android.feather.widget.Wheel, float, int)
*/
@Override
public void onScroll( Wheel view, float value, int roundValue ) {
mWheelRadio.setValue( value );
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onScrollFinished(com.aviary.android.feather.widget.Wheel,
* float, int)
*/
@Override
public void onScrollFinished( Wheel view, float value, int roundValue ) {
mWheelRadio.setValue( value );
if ( mLastValue != roundValue ) {
float realValue = ( mWheelRadio.getValue() );
mLogger.info( "onScrollFinished: " + value + ", " + realValue );
applyFilter( realValue * 100 );
}
mLastValue = roundValue;
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onProgressEnd()
*/
@Override
protected void onProgressEnd() {
if ( !enableFastPreview )
onProgressModalEnd();
else
super.onProgressEnd();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onProgressStart()
*/
@Override
protected void onProgressStart() {
if ( !enableFastPreview )
onProgressModalStart();
else
super.onProgressStart();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.AbstractEffectPanel#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onDeactivate()
*/
@Override
public void onDeactivate() {
onProgressEnd();
super.onDeactivate();
}
/*
* (non-Javadoc)
*
* @see com.aviary.android.feather.effects.ColorMatrixEffectPanel#onGenerateResult()
*/
@Override
protected void onGenerateResult() {
mLogger.info( "onGenerateResult: " + mIsRendering );
if ( mIsRendering ) {
GenerateResultTask task = new GenerateResultTask();
task.execute();
} else {
onComplete( mPreview, mActions );
}
}
/*
* (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#getIsChanged()
*/
@Override
public boolean getIsChanged() {
return super.getIsChanged() || mIsRendering == true;
}
/**
* Kill current task.
*
* @return true, if successful
*/
boolean killCurrentTask() {
if ( mCurrentTask != null ) {
return mCurrentTask.cancel( true );
}
return false;
}
/**
* Apply a filter.
*
* @param value
* the value
*/
protected void applyFilter( float value ) {
killCurrentTask();
if ( value == 0 ) {
BitmapUtils.copy( mBitmap, mPreview );
onPreviewChanged( mPreview, true );
setIsChanged( false );
mActions = null;
} else {
mCurrentTask = new ApplyFilterTask( value );
mCurrentTask.execute( mBitmap );
}
}
/**
* Generate content view.
*
* @param inflater
* the inflater
* @return the view
*/
protected View generateContentView( LayoutInflater inflater ) {
return inflater.inflate( R.layout.feather_native_range_effects_content, null );
}
/**
* The Class ApplyFilterTask.
*/
class ApplyFilterTask extends AsyncTask<Bitmap, Void, Bitmap> {
/** The m result. */
MoaResult mResult;
/**
* Instantiates a new apply filter task.
*
* @param value
* the value
*/
public ApplyFilterTask( float value ) {
( (INativeRangeFilter) mFilter ).setValue( value );
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
mLogger.info( this, "onPreExecute" );
try {
mResult = ( (INativeRangeFilter) mFilter ).prepare( mBitmap, mPreview, 1, 1 );
} catch ( JSONException e ) {
e.printStackTrace();
}
onProgressStart();
}
@Override
protected void onCancelled() {
super.onCancelled();
mLogger.info( this, "onCancelled" );
if ( mResult != null ) {
mResult.cancel();
}
onProgressEnd();
mIsRendering = false;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Bitmap doInBackground( Bitmap... arg0 ) {
if ( isCancelled() ) return null;
mIsRendering = true;
long t1 = System.currentTimeMillis();
try {
mResult.execute();
mActions = ( (INativeRangeFilter) mFilter ).getActions();
} catch ( Exception exception ) {
exception.printStackTrace();
mLogger.error( exception.getMessage() );
return null;
}
long t2 = System.currentTimeMillis();
if ( null != mTrackingAttributes ) {
mTrackingAttributes.put( "renderTime", Long.toString( t2 - t1 ) );
}
if ( isCancelled() ) return null;
return mPreview;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
if ( !isActive() ) return;
mLogger.info( this, "onPostExecute" );
onProgressEnd();
if ( result != null ) {
if ( SystemUtils.isHoneyComb() ) {
Moa.notifyPixelsChanged( mPreview );
}
onPreviewChanged( mPreview, true );
} else {
BitmapUtils.copy( mBitmap, mPreview );
onPreviewChanged( mPreview, true );
setIsChanged( false );
}
mIsRendering = false;
mCurrentTask = null;
}
}
/**
* 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 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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.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.outsourcing.bottle.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()
*/
@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()
*/
@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.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
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.BitmapFactory;
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.Looper;
import android.os.Message;
import android.os.Process;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.aviary.android.feather.Constants;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.BottleTypeTable;
import com.outsourcing.bottle.db.StickersPackTable;
import com.outsourcing.bottle.db.StickersTable;
import com.outsourcing.bottle.domain.BottleTypeEntry;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.PasterDirConfigEntry;
import com.outsourcing.bottle.domain.PastersListInfo;
import com.outsourcing.bottle.domain.StickEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
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;
import com.google.gson.Gson;
/**
*贴纸ֽ
* @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;
private com.outsourcing.bottle.util.ImageLoader btConfigLoader;
/**
* 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( false );
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 = true;
// 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() ) );
}
btConfigLoader = new com.outsourcing.bottle.util.ImageLoader(getContext().getBaseContext(), AppContext.PasterDir);
}
@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
*/
int mCurrentPasterDir;
private void setCurrentPack( PasterDirConfigEntry info ) {
mCurrentPasterDir = info.getPasterdir_id();
if (info.getUnlocked() == 1) {
setStatus( Status.Stickers );
}else {
new AlertDialog.Builder(this.getContext().getBaseContext()).setTitle(TextUtil.R("system_info")).setMessage(info.getUseterm()).setPositiveButton(TextUtil.R("confirm_ok"), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new DownloadSticksTask().execute();
}
}).setNegativeButton(TextUtil.R("confirm_cancel"), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
class DownloadSticksTask extends AsyncTask<Void, Void, String[]> {
private ProgressDialog dialog = null;
@Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
dialog.dismiss();
if (null != result) {
Toast.makeText(getContext().getBaseContext(), result[0], Toast.LENGTH_LONG).show();
if (result[1].equals("1")) {
new SticksListTask().execute();
}
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getContext().getBaseContext());
dialog.setTitle(TextUtil.R("basic_txt_tip"));
dialog.setMessage(TextUtil.R("feather_txt_stick_buy"));
dialog.setCancelable(false);
dialog.setIndeterminate(true);
dialog.show();
}
@Override
protected String[] doInBackground(Void... params) {
return getPasterDirPay(mCurrentPasterDir);
}
}
/**下载贴纸列表线程*/
class SticksListTask extends AsyncTask<Void, Void, List<StickEntry>> {
private ProgressDialog dialog = null;
@Override
protected void onPostExecute(List<StickEntry> result) {
super.onPostExecute(result);
dialog.dismiss();
if (null != result) {
String[] listcopy = new String[result.size()];
for (int i = 0; i < listcopy.length; i++) {
listcopy[i] = result.get(i).getPaster_url();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
mViewFlipper.setDisplayedChild( 1 );
getOptionView().post( new LoadStickersRunner( listcopy ) );
// Toast.makeText(getContext().getBaseContext(), result, Toast.LENGTH_LONG).show();
// updateInstalledPacks(false);
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getContext().getBaseContext());
dialog.setTitle(TextUtil.R("basic_txt_tip"));
dialog.setMessage(TextUtil.R("feather_txt_download_stick"));
dialog.setCancelable(false);
dialog.setIndeterminate(true);
dialog.show();
}
@Override
protected List<StickEntry> doInBackground(Void... params) {
return getPastersList(mCurrentPasterDir);
}
}
/**
*购买贴纸目录接口
*/
private String[] getPasterDirPay(int pasterdir_id) {
StringBuffer url = new StringBuffer(UrlConfig.pasterdir_pay);
url.append("?clitype=2");
url.append("&language=" + AppContext.language);
url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
url.append("&login_token=" + AppContext.getInstance().getLogin_token());
url.append("&dirid=" + pasterdir_id);
ServiceUtils.dout("getPasterDirPay url:" + url.toString());
try {
String result = HttpUtils.doGet(url.toString());
ServiceUtils.dout("getPasterDirPay result:" + result);
if (null != result) {
JSONObject obj = new JSONObject(result);
JSONObject resultObj = obj.getJSONObject("results");
int success = resultObj.getInt("success");
String errmsg = resultObj.getString("errmsg");
String successmsg = resultObj.getString("successmsg");
Message message = null;
String[] strings = new String[2];
if (success == 1) {
strings[0] = successmsg;
strings[1] = "1";
getLoginUserStickers();
return strings;
} else {
// message = handler.obtainMessage(EXEU_LIKE_OPERATION_FAILED,
// errmsg);
// handler.sendMessage(message);
strings[0] = errmsg;
strings[1] = "0";
return strings;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取贴纸目录
*/
private void getLoginUserStickers() {
try {
StickersPackTable stickPackTable = new StickersPackTable();
StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
url.append("?clitype=2");
url.append("&language=" + AppContext.language);
url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
url.append("&login_token=" + AppContext.getInstance().getLogin_token());
ServiceUtils.dout("login url:" + url.toString());
String result = HttpUtils.doGet(url.toString());
Gson gson = new Gson();
LoginUserInfo loginUserInfo = gson.fromJson(result,
LoginUserInfo.class);
/*********** 保存贴纸目录路径 *********/
List<PasterDirConfigEntry> pasterdir_config = loginUserInfo
.getPasterdir_privs_list();
stickPackTable.clearTalbe();
for (PasterDirConfigEntry mPasterDirEntry : pasterdir_config) {
stickPackTable.saveStickDir(mPasterDirEntry);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取贴纸目录下贴纸列表接口
*/
private List<StickEntry> getPastersList(int dirid) {
StringBuffer url = new StringBuffer(UrlConfig.get_pasters_list);
url.append("?clitype=2");
url.append("&language=" + AppContext.language);
url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
url.append("&login_token=" + AppContext.getInstance().getLogin_token());
url.append("&dirid=" + dirid);
ServiceUtils.dout("getPastersList url:" + url.toString());
try {
String result = HttpUtils.doGet(url.toString());
ServiceUtils.dout("getPastersList result:" + result);
Gson gson = new Gson();
PastersListInfo pasterListInfo = gson.fromJson(result, PastersListInfo.class);
if (pasterListInfo.getResults().getAuthok() == 1) {
StickersTable stickersTable = new StickersTable();
List<StickEntry> mStickList = pasterListInfo.getPasters_list();
for (StickEntry stickEntry : mStickList) {
stickersTable.saveStickList(dirid,stickEntry);
}
return mStickList;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 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();
StickersTable btt = new StickersTable();
ArrayList<StickEntry> bottltTypes = btt.getStickList(mCurrentPasterDir);
if ( bottltTypes != null && bottltTypes.size()>0) {
String[] listcopy = new String[bottltTypes.size()];
for (int i = 0; i < listcopy.length; i++) {
listcopy[i] = bottltTypes.get(i).getPaster_url();
}
mViewFlipper.setDisplayedChild( 1 );
getOptionView().post( new LoadStickersRunner( listcopy ) );
}else {
new SticksListTask().execute();
}
}
/**
* 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 = null;
try {
bitmap = ImageLoader.loadStickerBitmap( mPlugin, dragInfo, StickerType.Small, size, size );
if (null != bitmap) {
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 );
}else {
return false;
}
} catch ( Exception e ) {
e.printStackTrace();
}
if (null != bitmap) {
return getDragController().startDrag( image, StickersPanel.this, dragInfo, DragControllerService.DRAG_ACTION_MOVE, nativeClick );
}else {
return false;
}
}
}
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;
// }
byte[] iconByte = ServiceUtils.getImageFileForSticker(drawable, AppContext.PasterDir);
if (null != iconByte) {
stream = new ByteArrayInputStream(iconByte);
}
try {
if (stream != null) {
StickerDrawable d = new StickerDrawable(null, stream, drawable,
drawable);
if (null != d) {
d.setAntiAlias(true);
mUsedStickers.add(drawable);
mUsedStickersPacks.add(drawable);
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 = drawable;
if (null != sourceDir) {
// mCurrentAction.setValue( "source", sourceDir );
mCurrentAction.setValue("source", drawable);
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);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// }
}
/**
* 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 BaseAdapter {
private final String TAG = StickersPacksAdapter.class.getSimpleName();
int screenId, cellId;
LayoutInflater mLayoutInflater;
long mCurrentDate;
boolean mInFirstLayout = true;
String mGetMoreLabel;
Drawable mFolderIcon, mGetMoreIcon, mGetMoreFreeIcon;
Typeface mPackTypeface;
List<PasterDirConfigEntry> stickDirEntries;
com.outsourcing.bottle.util.ImageLoader btLoader = null;
/**
* 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, List<PasterDirConfigEntry> objects ) {
stickDirEntries = 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 );
btLoader = new com.outsourcing.bottle.util.ImageLoader(getContext().getBaseContext(), AppContext.PasterDir);
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) ( getRealCount() ) / mWorkspaceItemsPerPage );
}
/**
* Gets the real count.
*
* @return the real count
*/
public int getRealCount() {
return stickDirEntries.size();
}
@Override
public View getView( int position, View convertView, ViewGroup parent ) {
ServiceUtils.dout(TAG+" getView:position"+position);
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 ) {
ServiceUtils.dout(TAG+" count:"+count+" i:"+i+" index:"+index);
final PasterDirConfigEntry appInfo = (PasterDirConfigEntry) getItem( index + i );
String label = null;
if (appInfo != null) {
if (AppContext.language == 1) {
label = appInfo.getPasterdir_name_cn();
} else {
label = appInfo.getPasterdir_name_en();
}
ImageView image_stick = (ImageView) itemView.findViewById( R.id.image_stick_pack );
btLoader.DisplayImage(appInfo.getPasterdir_coverurl(), image_stick, R.drawable.paster_frame);
TextView text = (TextView) itemView.findViewById( R.id.text );
ImageView image_dollar = (ImageView) itemView.findViewById( R.id.image_dollar);
// if ( null != mPackTypeface ) {
// text.setTypeface( mPackTypeface );
// }
if (appInfo.getUnlocked() == 1) {
image_dollar.setVisibility(View.INVISIBLE);
}else {
image_dollar.setVisibility(View.VISIBLE);
}
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;
}
@Override
public Object getItem(int position) {
return stickDirEntries == null ? null : stickDirEntries.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
// public class BottleTypeAdapter extends BaseAdapter {
//
// List<PasterDirConfigEntry> stickDirEntries;
//
// public BottleTypeAdapter(List<PasterDirConfigEntry> stickDirEntries){
// this.stickDirEntries = stickDirEntries;
// }
//
// @Override
// public int getCount() {
// return stickDirEntries == null ? 0 : stickDirEntries.size();
// }
//
// @Override
// public Object getItem(int position) {
// return stickDirEntries == null ? null : stickDirEntries.get(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// View view;
// ViewHolder holder;
// if (convertView != null) {
// view = convertView;
// holder = (ViewHolder) view.getTag();
// } else {
// holder = new ViewHolder();
// view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_griditem, null);
// holder.stick_icon = (ImageView) view.findViewById(R.id.choose_bottle_bottle_icon);
// holder.stick_name = (TextView) view.findViewById(R.id.choose_bottle_bottle_name);
// view.setTag(holder);
// }
// PasterDirConfigEntry entry = stickDirEntries.get(position);
// if (entry != null) {
// byte[] iconByte = ServiceUtils.getImageFile(entry.getPasterdir_coverurl(), AppContext.BottleTypeIcon);
// Bitmap bitmap = ServiceUtils.bytesToBitmap(iconByte);
// holder.stick_icon.setImageBitmap(bitmap);
// if (AppContext.language == 1) {
// holder.stick_name.setText(entry.getPasterdir_name_cn());
// } else {
// holder.stick_name.setText(entry.getPasterdir_name_en());
// }
// }
// return view;
// }
// }
public static class ViewHolder {
ImageView stick_icon;
TextView stick_name;
}
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 );
// }
// final String appInfo = (String) getItem(position);
// byte[] iconByte = ServiceUtils.getImageFile(appInfo, AppContext.PasterDir);
// Bitmap bitmap = ServiceUtils.bytesToBitmap(iconByte);
// image.setImageBitmap(bitmap);
btConfigLoader.DisplayImage(getItem(position), image, R.drawable.paster_frame, mFinalSize - 10);
// 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,mCurrentPasterDir+"", 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, List<PasterDirConfigEntry>> {
private boolean mPostAnimate;
UpdateInstalledPacksTask( boolean postAnimate ) {
mPostAnimate = postAnimate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mLayoutLoader.setVisibility( View.VISIBLE );
mWorkspace.setVisibility( View.INVISIBLE );
}
@Override
protected List<PasterDirConfigEntry> doInBackground( Void... params ) {
List<PasterDirConfigEntry> mpDirConfigEntries = null;
if ( getContext().getBaseContext() != null ) {
StickersPackTable tStickersPackTable = new StickersPackTable();
mpDirConfigEntries = tStickersPackTable.getStickDir();
return mpDirConfigEntries;
}
return null;
}
@Override
protected void onPostExecute(List<PasterDirConfigEntry> 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.outsourcing.bottle.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( 1, 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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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 final EffectEntry[] mAvatarEntries;
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.EFFECTS, R.drawable.feather_tool_icon_effects, R.string.effects ),
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.ADJUST, R.drawable.feather_tool_icon_adjust, R.string.adjust ),
new EffectEntry( FilterLoaderFactory.Filters.BRIGHTNESS, R.drawable.feather_tool_icon_brightness, R.string.brightness ),
};
}
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 ),
new EffectEntry( FilterLoaderFactory.Filters.TEXT, R.drawable.feather_tool_icon_text, R.string.text ),
new EffectEntry( FilterLoaderFactory.Filters.EFFECTS, R.drawable.feather_tool_icon_effects, R.string.effects ),
new EffectEntry( FilterLoaderFactory.Filters.BLEMISH, R.drawable.feather_tool_icon_blemish, R.string.blemish ),
};
}
static {
mAvatarEntries = new EffectEntry[] {
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.STICKERS, R.drawable.feather_tool_icon_stickers, R.string.stickers ),
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 ),
};
}
/**
* 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;
case Constants.ACTIVITY_AVATAR:
return mAvatarEntries;
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;
import com.outsourcing.bottle.R;
/**
* FeatherActivity is the main activity controller.
*
* @author alessandro
*/
public class FeatherActivity extends MonitoredActivity implements OnToolbarClickListener, OnImageDownloadListener, OnToolListener,
FeatherContext, OnPageChangeListener, OnBitmapChangeListener {
private int fromType;
/** 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 );
try {
setFromType(getIntent().getIntExtra("From_Type", 0));
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" );
} catch (Exception e) {
e.printStackTrace();
} catch (Error e) {
e.printStackTrace();
}
}
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 );
try {
NativeFilterProxy.init( this, null );
} catch (Exception e) {
e.printStackTrace();
} catch (Error e) {
e.printStackTrace();
}
}
/*
* (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;
}
List<EffectEntry> listEntries ;
/**
* Load the current tools list in a separate thread
*/
private void delayedInitializeTools() {
Thread t = new Thread( new Runnable() {
@Override
public void run() {
listEntries = loadTools(getFromType());
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();
// if (fromType == Constants.ACTIVITY_EDIT) {
//
// mUIHandler.postDelayed( new Runnable() {
//
// @Override
// public void run() {
// final EffectEntry entry= new EffectEntry( FilterLoaderFactory.Filters.CROP, R.drawable.feather_tool_icon_crop, R.string.crop);
// mFilterManager.activateEffect(entry);
// }
// }, 200);
// }
}
/*
* (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, 100 );
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();
}
}
}
}
public int getFromType() {
return fromType;
}
public void setFromType(int fromType) {
this.fromType = fromType;
}
}
| 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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.OverScroller;
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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.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.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
*/
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.outsourcing.bottle.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.outsourcing.bottle.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.outsourcing.bottle.R;
import com.outsourcing.bottle.util.ServiceUtils;
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 = HorizontalFixedListView.class.getSimpleName();
/** 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() );
ServiceUtils.dout(LOG_TAG+"layoutChildren right:"+right);
}
}
/**
* 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 );
ServiceUtils.dout(LOG_TAG +" fillListRight mMaxX:"+mMaxX);
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() );
ServiceUtils.dout(LOG_TAG+" child.layout r:"+rightEdge + mChildWidth);
rightEdge += mChildWidth;
mRightViewIndex++;
ServiceUtils.dout(LOG_TAG+" fillListRight mRightViewIndex:"+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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.