code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.ArrayList;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
public class NativeMethods {
private final static String TAG = "NativeMethods";
static {
System.loadLibrary("dslrdashboard");
}
public native Object loadRawImage(String imgPath);
public native boolean loadRawImageThumb(String imgPath, String thumbPath);
//public native String[] getExifInfo(String imgPath);
public native int getExifData(String path, int count, Object obj);
public native int setGPSExifData(String path, double latitude, double longitude, double altitude);
public native int copyExifData(String source, String target);
public native int getRGBHistogram(Bitmap lvImage, int[] rArray, int[] gArray, int[] bArray, int[] lumaArray);
private static NativeMethods _instance = null;
public static NativeMethods getInstance() {
if (_instance == null)
_instance = new NativeMethods();
return _instance;
}
private NativeMethods() {
mPaintBlack = new Paint();
mPaintBlack.setStyle(Paint.Style.FILL);
mPaintBlack.setColor(Color.BLACK);
mPaintBlack.setTextSize(25);
mPaintBlack.setAlpha(100);
mPaintWhite = new Paint();
mPaintWhite.setStyle(Paint.Style.STROKE);
mPaintWhite.setColor(Color.WHITE);
mPaintWhite.setTextSize(25);
mPaintYellow = new Paint();
mPaintYellow.setStyle(Paint.Style.FILL);
mPaintYellow.setColor(Color.YELLOW);
mPaintYellow.setTextSize(25);
mPaintRed = new Paint();
mPaintRed.setStyle(Paint.Style.FILL);
mPaintRed.setColor(Color.RED);
mPaintRed.setTextSize(25);
mPaintRed.setAlpha(180);
mPaintGreen = new Paint();
mPaintGreen.setStyle(Paint.Style.FILL);
mPaintGreen.setColor(Color.GREEN);
mPaintGreen.setTextSize(25);
mPaintGreen.setAlpha(180);
mPaintBlue = new Paint();
mPaintBlue.setStyle(Paint.Style.FILL);
mPaintBlue.setColor(Color.BLUE);
mPaintBlue.setTextSize(25);
mPaintBlue.setAlpha(180);
}
public ArrayList<ExifDataHelper> getImageExif(String[] exifNames, String path){
ArrayList<ExifDataHelper> helper = new ArrayList<ExifDataHelper>();
for(String name : exifNames) {
String[] tmp = name.split("@");
helper.add(new ExifDataHelper(tmp[0], tmp[1]));
}
getExifData(path, helper.size(), helper);
return helper;
}
public void exifValueCallback(String test, int index, Object obj) {
ArrayList<ExifDataHelper> helper = (ArrayList<ExifDataHelper>)obj;
//Log.d(TAG, "Exif value callback " + test + " index: " + index + " helper test: " + helper.size());
helper.get(index).mExifValue = test;
}
public String exifNameCallback(int index, Object obj) {
ArrayList<ExifDataHelper> helper = (ArrayList<ExifDataHelper>)obj;
//Log.d(TAG, "Name callback " + helper.get(index).mExifName + " index: " + index + " helper test: " + helper.size());
return helper.get(index).mExifName;
}
private Paint mPaintWhite;
private Paint mPaintBlack;
private Paint mPaintYellow;
private Paint mPaintRed;
private Paint mPaintGreen;
private Paint mPaintBlue;
private int[] mrArray = new int[257];
private int[] mgArray = new int[257];
private int[] mbArray = new int[257];
private int[] mlumaArray = new int[257];
private float mHistogramWidth = 450;
private float mHistogramHeight = 150;
private float dx = (float)mHistogramWidth / (float)256;
public Bitmap createHistogramBitmap(Bitmap source, boolean separate) {
getRGBHistogram(source, mrArray, mgArray, mbArray, mlumaArray);
if (source != null) {
Log.d(TAG, "drawHistogram");
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
int cHeight = separate ? (int)mHistogramHeight * 4 : (int)mHistogramHeight * 2;
Bitmap hist = Bitmap.createBitmap((int)mHistogramWidth, cHeight, conf);
Canvas canvas = new Canvas(hist);
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mPaintBlack);
//canvas.drawRect(1, 1, canvas.getWidth()-1, canvas.getHeight()-1, mPaintWhite);
int count = separate ? 4 : 2;
for (int i = 0; i < count ; i++) {
int hpos = (int)mHistogramHeight * i;
canvas.drawRect(1, hpos + 1, canvas.getWidth() - 1, hpos + (int)mHistogramHeight - 1, mPaintWhite);
}
int maxVal = Math.max(mrArray[256], mbArray[256]);
maxVal = Math.max(maxVal, mgArray[256]);
for (int i =0; i < 256; i++ ){
float left = (float)i * dx;// + canvas.getWidth() - mHistogramWidth;
if (!separate) {
canvas.drawRect(left, mHistogramHeight -1, left + dx, mHistogramHeight - (((float)mlumaArray[i] * mHistogramHeight)/ (float)mlumaArray[256]) +1, mPaintYellow);
canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mrArray[i] * mHistogramHeight)/ (float)mrArray[256]) +1, mPaintRed);
canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mbArray[i] * mHistogramHeight)/ (float)mbArray[256]) +1, mPaintBlue);
canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mgArray[i] * mHistogramHeight)/ (float)mgArray[256]) +1 , mPaintGreen);
} else {
canvas.drawRect(left, mHistogramHeight -1, left + dx, mHistogramHeight - (((float)mlumaArray[i] * mHistogramHeight)/ (float)mlumaArray[256]) +1, mPaintYellow);
canvas.drawRect(left, (mHistogramHeight * 2) -1, left + dx, (mHistogramHeight * 2) - (((float)mrArray[i] * mHistogramHeight)/ (float)mrArray[256]) +1, mPaintRed);
canvas.drawRect(left, (mHistogramHeight * 4) -1, left + dx, (mHistogramHeight * 4 ) - (((float)mbArray[i] * mHistogramHeight)/ (float)mbArray[256]) +1, mPaintBlue);
canvas.drawRect(left, (mHistogramHeight * 3) -1, left + dx, (mHistogramHeight * 3 )- (((float)mgArray[i] * mHistogramHeight)/ (float)mgArray[256]) +1 , mPaintGreen);
}
}
return hist;
}
else
return null;
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
public abstract class DslrFragmentBase extends DialogFragment {
private IDslrActivity mActivity = null;
private boolean mIsAttached = false;
private PtpDevice mPtpDevice = null;
protected IDslrActivity getDslrActivity() {
return mActivity;
}
protected PtpDevice getPtpDevice() {
return mPtpDevice;
}
protected boolean getIsAttached() {
return mIsAttached;
}
protected boolean getIsPtpDeviceInitialized() {
return mPtpDevice != null ? mPtpDevice.getIsPtpDeviceInitialized() : false;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
mActivity = (IDslrActivity)activity;
mPtpDevice = mActivity.getPtpDevice();
mIsAttached = true;
} catch (ClassCastException e) {
mActivity = null;
}
}
@Override
public void onDetach() {
mIsAttached = false;
mActivity = null;
super.onDetach();
}
public void initFragment(){
if (mIsAttached)
internalInitFragment();
}
public void ptpPropertyChanged(PtpProperty property) {
internalPtpPropertyChanged(property);
}
public void sharedPrefsChanged(SharedPreferences prefs, String key) {
internalSharedPrefsChanged(prefs, key);
}
@Override
public void onResume() {
super.onResume();
internalInitFragment();
}
protected void initializePtpPropertyView(View view, PtpProperty property) {
if (property == null)
view.setVisibility(View.GONE);
else {
view.setVisibility(View.VISIBLE);
internalPtpPropertyChanged(property);
}
}
protected abstract void internalInitFragment();
protected abstract void internalPtpPropertyChanged(PtpProperty property);
protected abstract void ptpDeviceEvent(PtpDeviceEvent event, Object data);
protected abstract void internalSharedPrefsChanged(SharedPreferences prefs, String key);
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
public abstract class PtpCommunicatorBase {
protected abstract void processCommand(PtpCommand cmd) throws Exception;
public abstract boolean getIsNetworkCommunicator();
public abstract int getWriteEpMaxPacketSize();
public abstract void closeCommunicator();
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AboutFragment extends DslrFragmentBase {
private final static String TAG = "AboutFragment";
private TextView mAbout, mNoCamera;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_about, container, false);
mAbout = (TextView)view.findViewById(R.id.txt_about);
mNoCamera = (TextView)view.findViewById(R.id.txt_nocamera);
mAbout.setText(Html.fromHtml(getActivity().getString(R.string.about)));
mNoCamera.setText(Html.fromHtml(getActivity().getString(R.string.nocamera)));
return view;
}
@Override
protected void internalInitFragment() {
// TODO Auto-generated method stub
}
@Override
protected void internalPtpPropertyChanged(PtpProperty property) {
// TODO Auto-generated method stub
}
@Override
protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) {
switch(event) {
case PtpDeviceInitialized:
mNoCamera.setVisibility(View.GONE);
break;
case PtpDeviceStoped:
mNoCamera.setVisibility(View.VISIBLE);
break;
}
}
@Override
protected void internalSharedPrefsChanged(SharedPreferences prefs,
String key) {
// TODO Auto-generated method stub
}
@Override
public void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
public void onResume() {
Log.d(TAG, "onResume");
mNoCamera.setVisibility(View.VISIBLE);
if (getPtpDevice() != null && getPtpDevice().getIsPtpDeviceInitialized())
mNoCamera.setVisibility(View.GONE);
super.onResume();
}
@Override
public void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
@Override
public void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class ExifAdapter extends BaseAdapter {
private ArrayList<ExifDataHelper> _items;
public ArrayList<ExifDataHelper> items(){
return _items;
}
public Context context;
public LayoutInflater inflater;
public ExifAdapter(Context context, ArrayList<ExifDataHelper> arrayList){
super();
this.context = context;
this._items = arrayList;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void changeItems(ArrayList<ExifDataHelper> arrayList){
_items = arrayList;
notifyDataSetChanged();
}
public int getCount() {
return _items.size();
}
public Object getItem(int position) {
return _items.get(position);
}
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getItemViewType(int position) {
return IGNORE_ITEM_VIEW_TYPE;
}
@Override
public int getViewTypeCount() {
return 1;
}
public static class ViewHolder
{
TextView txtExifName;
TextView txtExifValue;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.exif_list_item, null);
holder.txtExifName = (TextView) convertView.findViewById(R.id.txtexifdescription);
holder.txtExifValue = (TextView) convertView.findViewById(R.id.txtexifvalue);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
ExifDataHelper helper = _items.get(position);
holder.txtExifName.setText(helper.mExifDescription);
holder.txtExifValue.setText(helper.mExifValue);
return convertView;
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.ArrayList;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
public class FocusStackingDialog {
private final static String TAG = FocusStackingDialog.class.getSimpleName();
private Context mContext;
private DslrHelper mDslrHelper;
private PtpDevice mPtpDevice;
private View mView;
private CustomDialog mDialog;
private EditText mEditImageNumber, mEditFocusStep;
private RadioButton mFocusDown, mFocusUp;
private Button mStartFocusStacking;
private CheckBox mFocusFirst;
private int mFocusImages = 5;
private int mFocusStep = 10;
private boolean mFocusDirectionDown = true;
private boolean mFocusFocusFirst = false;
public FocusStackingDialog(Context context) {
mContext = context;
mDslrHelper = DslrHelper.getInstance();
mPtpDevice = mDslrHelper.getPtpDevice();
if (mPtpDevice != null) {
mFocusImages = mPtpDevice.getFocusImages();
mFocusStep = mPtpDevice.getFocusStep();
mFocusDirectionDown = mPtpDevice.getFocusDirectionDown();
mFocusFocusFirst = mPtpDevice.getFocusFocusFirst();
}
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(R.layout.focusstackingdialog, null);
mEditImageNumber = (EditText)mView.findViewById(R.id.focus_stacking_Number);
mEditFocusStep = (EditText)mView.findViewById(R.id.focus_stacking_Step);
mFocusDown = (RadioButton)mView.findViewById(R.id.focus_stacking_RadioDown);
mFocusUp = (RadioButton)mView.findViewById(R.id.focus_stacking_RadioUp);
mStartFocusStacking = (Button)mView.findViewById(R.id.focus_stacking_start);
mFocusFirst = (CheckBox)mView.findViewById(R.id.focus_stacking_focus_first);
mStartFocusStacking.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mFocusImages = Integer.valueOf(mEditImageNumber.getText().toString());
mFocusStep = Integer.valueOf(mEditFocusStep.getText().toString());
mFocusDirectionDown = mFocusDown.isChecked();
Log.d(TAG, "Focus direction down: " + mFocusDirectionDown);
Log.d(TAG, "Focus images: " + mFocusImages);
Log.d(TAG, "Focus step: " + mFocusStep);
mDialog.dismiss();
mPtpDevice.startFocusStacking(mFocusImages, mFocusStep, mFocusDirectionDown, mFocusFocusFirst);
}
});
// mFocusUp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Log.d(TAG, "Focus direction down: " + isChecked);
// mFocusDirectionDown = isChecked;
// }
// });
// mEditImageNumber.addTextChangedListener(new TextWatcher() {
//
// public void onTextChanged(CharSequence s, int start, int before, int count) {
// // TODO Auto-generated method stub
//
// }
//
// public void beforeTextChanged(CharSequence s, int start, int count,
// int after) {
// // TODO Auto-generated method stub
//
// }
//
// public void afterTextChanged(Editable s) {
// mFocusImages = Integer.valueOf(s.toString());
// Log.d(TAG, "Focus images changed: " + mFocusImages);
// }
// });
// mEditFocusStep.addTextChangedListener(new TextWatcher() {
//
// public void onTextChanged(CharSequence s, int start, int before, int count) {
// // TODO Auto-generated method stub
//
// }
//
// public void beforeTextChanged(CharSequence s, int start, int count,
// int after) {
// // TODO Auto-generated method stub
//
// }
//
// public void afterTextChanged(Editable s) {
// mFocusStep = Integer.valueOf(s.toString());
// Log.d(TAG, "Focus step changed: " + mFocusStep);
// }
// });
}
private void initDialog(){
mEditImageNumber.setText(Integer.toString(mFocusImages));
mEditFocusStep.setText(Integer.toString(mFocusStep));
mFocusDown.setChecked(mFocusDirectionDown);
mFocusFirst.setChecked(mFocusFocusFirst);
}
public void show() {
initDialog();
CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext);
customBuilder.setTitle("Focus Stacking settings")
.setContentView(mView);
mDialog = customBuilder
.create();
mDialog.show();
}
}
| Java |
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package com.dslr.dashboard;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.TimeZone;
import android.graphics.Bitmap;
import android.util.Log;
public class PtpObjectInfo {
private final static String TAG = "PtpObjectInfo";
public int objectId;
public int storageId; // 8.1
public int objectFormatCode; // 6.2
public int protectionStatus; // 0 r/w, 1 r/o
public int objectCompressedSize;
public int thumbFormat; // 6.2
public int thumbCompressedSize;
public int thumbPixWidth;
public int thumbPixHeight;
public int imagePixWidth;
public int imagePixHeight;
public int imageBitDepth;
public int parentObject;
public int associationType; // 6.4
public int associationDesc; // 6.4
public int sequenceNumber; // (ordered associations)
public String filename; // (sans path)
private String mCaptureDate; // DateTime string
private String mModificationDate; // DateTime string
public String keywords;
public Date captureDate = null;
public Date modificationDate = null;
public PtpObjectInfo(int objectIdentification, PtpBuffer buf){
objectId = objectIdentification;
if (buf != null)
parse(buf);
}
public Bitmap thumb = null;
public void parse (PtpBuffer buf)
{
buf.parse();
storageId = buf.nextS32 ();
objectFormatCode = buf.nextU16 ();
protectionStatus = buf.nextU16 ();
objectCompressedSize = /* unsigned */ buf.nextS32 ();
thumbFormat = buf.nextU16 ();
thumbCompressedSize = /* unsigned */ buf.nextS32 ();
thumbPixWidth = /* unsigned */ buf.nextS32 ();
thumbPixHeight = /* unsigned */ buf.nextS32 ();
imagePixWidth = /* unsigned */ buf.nextS32 ();
imagePixHeight = /* unsigned */ buf.nextS32 ();
imageBitDepth = /* unsigned */ buf.nextS32 ();
parentObject = buf.nextS32 ();
associationType = buf.nextU16 ();
associationDesc = buf.nextS32 ();
sequenceNumber = /* unsigned */ buf.nextS32 ();
filename = buf.nextString ();
mCaptureDate = buf.nextString ();
mModificationDate = buf.nextString ();
keywords = buf.nextString ();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
captureDate = sdf.parse(mCaptureDate, new ParsePosition(0));
modificationDate = sdf.parse(mModificationDate, new ParsePosition(0));
//Log.d(TAG, "CaptureDate: " + mCaptureDate + " Parsed: " + captureDate.toString());
}
// public PtpObjectInfo clone() {
// PtpObjectInfo obj = new PtpObjectInfo(objectId, null);
//
// obj.storageId = this.storageId;
// obj.objectFormatCode = this.objectFormatCode;
// obj.protectionStatus = this.protectionStatus;
// obj.objectCompressedSize = /* unsigned */ this.objectCompressedSize;
//
// obj.thumbFormat = this.thumbFormat;
// obj.thumbCompressedSize = /* unsigned */ this.thumbCompressedSize;
// obj.thumbPixWidth = /* unsigned */ this.thumbPixWidth;
// obj.thumbPixHeight = /* unsigned */ this.thumbPixHeight;
//
// obj.imagePixWidth = /* unsigned */ this.imagePixWidth;
// obj.imagePixHeight = /* unsigned */ this.imagePixHeight;
// obj.imageBitDepth = /* unsigned */ this.imageBitDepth;
// obj.parentObject = this.parentObject;
//
// obj.associationType = this.associationType;
// obj.associationDesc = this.associationDesc;
// obj.sequenceNumber = /* unsigned */ this.sequenceNumber;
// obj.filename = this.filename;
//
// obj.captureDate = this.captureDate;
// obj.modificationDate = this.modificationDate;
// obj.keywords = this.keywords;
//
// return obj;
// }
/** ObjectFormatCode: unrecognized non-image format */
public static final int Undefined = 0x3000;
/** ObjectFormatCode: associations include folders and panoramas */
public static final int Association = 0x3001;
/** ObjectFormatCode: */
public static final int Script = 0x3002;
/** ObjectFormatCode: */
public static final int Executable = 0x3003;
/** ObjectFormatCode: */
public static final int Text = 0x3004;
/** ObjectFormatCode: */
public static final int HTML = 0x3005;
/** ObjectFormatCode: */
public static final int DPOF = 0x3006;
/** ObjectFormatCode: */
public static final int AIFF = 0x3007;
/** ObjectFormatCode: */
public static final int WAV = 0x3008;
/** ObjectFormatCode: */
public static final int MP3 = 0x3009;
/** ObjectFormatCode: */
public static final int AVI = 0x300a;
/** ObjectFormatCode: */
public static final int MPEG = 0x300b;
/** ObjectFormatCode: */
public static final int ASF = 0x300c;
/** ObjectFormatCode: QuickTime video */
public static final int QuickTime = 0x300d;
/** ImageFormatCode: unknown image format */
public static final int UnknownImage = 0x3800;
/**
* ImageFormatCode: EXIF/JPEG version 2.1, the preferred format
* for thumbnails and for images.
*/
public static final int EXIF_JPEG = 0x3801;
/**
* ImageFormatCode: Uncompressed TIFF/EP, the alternate format
* for thumbnails.
*/
public static final int TIFF_EP = 0x3802;
/** ImageFormatCode: FlashPix image format */
public static final int FlashPix = 0x3803;
/** ImageFormatCode: MS-Windows bitmap image format */
public static final int BMP = 0x3804;
/** ImageFormatCode: Canon camera image file format */
public static final int CIFF = 0x3805;
// 3806 is reserved
/** ImageFormatCode: Graphics Interchange Format (deprecated) */
public static final int GIF = 0x3807;
/** ImageFormatCode: JPEG File Interchange Format */
public static final int JFIF = 0x3808;
/** ImageFormatCode: PhotoCD Image Pac*/
public static final int PCD = 0x3809;
/** ImageFormatCode: Quickdraw image format */
public static final int PICT = 0x380a;
/** ImageFormatCode: Portable Network Graphics */
public static final int PNG = 0x380b;
/** ImageFormatCode: Tag Image File Format */
public static final int TIFF = 0x380d;
/** ImageFormatCode: TIFF for Information Technology (graphic arts) */
public static final int TIFF_IT = 0x380e;
/** ImageFormatCode: JPEG 2000 baseline */
public static final int JP2 = 0x380f;
/** ImageFormatCode: JPEG 2000 extended */
public static final int JPX = 0x3810;
/**
* Returns true for format codes that have the image type bit set.
*/
public boolean isImage ()
{
return (objectFormatCode & 0xf800) == 0x3800;
}
/**
* Returns true for some recognized video format codes.
*/
public boolean isVideo ()
{
switch (objectFormatCode) {
case AVI:
case MPEG:
case ASF:
case QuickTime:
return true;
}
return false;
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.Hashtable;
public class DslrProperties {
private Hashtable<Integer, DslrProperty> mProperties;
private int mVendorId, mProductId;
public DslrProperties(int vendorId, int productId){
mVendorId = vendorId;
mProductId = productId;
mProperties = new Hashtable<Integer, DslrProperty>();
}
public Hashtable<Integer, DslrProperty> properties(){
return mProperties;
}
public DslrProperty addProperty(int propertyCode){
DslrProperty property = new DslrProperty(propertyCode);
mProperties.put(propertyCode, property);
return property;
}
public boolean containsProperty(int propertyCode){
return mProperties.containsKey(propertyCode);
}
public DslrProperty getProperty(int propertyCode){
return mProperties.get(propertyCode);
}
public int getVendorId(){
return mVendorId;
}
public int getProductId(){
return mProductId;
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.nio.channels.ClosedByInterruptException;
import android.util.Log;
public abstract class ThreadBase extends Thread {
private boolean mIsThreadPaused = false;
protected int mSleepTime = 10;
public boolean getIsThreadPaused() {
return mIsThreadPaused;
}
public void setIsThreadPaused(boolean value) {
mIsThreadPaused = value;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(mSleepTime);
} catch (InterruptedException e) {
Log.i("ThreadBase", "Thread interrupted");
break;
} catch (Exception e) {
Log.i("ThreadBase", "Thread exception " + e.getMessage());
break;
}
if (!mIsThreadPaused) {
codeToExecute();
}
}
Log.i("ThreadBase", "Thread ended");
}
public abstract void codeToExecute();
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import org.xmlpull.v1.XmlPullParserException;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class DslrHelper {
private static final String TAG = "DslrHelper";
private static DslrHelper mInstance = null;
public static DslrHelper getInstance() {
if (mInstance == null)
mInstance = new DslrHelper();
return mInstance;
}
private DslrHelper() {
}
private DslrProperties mDslrProperties;
private boolean mIsInitialized = false;
private int mVendorId = 0;
private int mProductId = 0;
private PtpDevice mPtpDevice = null;
public boolean getIsInitialized() {
return mIsInitialized;
}
public PtpDevice getPtpDevice() {
return mPtpDevice;
}
public int getVendorId() {
return mVendorId;
}
public int getProductId() {
return mProductId;
}
public void loadDslrProperties(Context context, PtpDevice ptpDevice,
int vendorId, int productId) {
if (context == null || ptpDevice == null)
return;
mPtpDevice = ptpDevice;
mVendorId = vendorId;
mProductId = productId;
mDslrProperties = new DslrProperties(vendorId, productId);
String deviceId = null;
int propertyTitle = 0;
String productName = String.format("%04X%04X", vendorId, productId)
.toLowerCase();
boolean addItems = true;
Log.d(TAG, "Loading DSLR properties for: " + productName);
Resources res = context.getResources();
XmlResourceParser devices = context.getResources().getXml(
R.xml.propertyvalues);
int eventType = -1;
DslrProperty dslrProperty = null;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_DOCUMENT) {
} else if (eventType == XmlResourceParser.START_TAG) {
String strName = devices.getName();
if (strName.equals("device")) {
} else if (strName.equals("ptpproperty")) {
int propertyCode = Integer.parseInt(
devices.getAttributeValue(null, "id"), 16);
deviceId = devices.getAttributeValue(null, "deviceId");
addItems = false;
if (deviceId != null) {
if (deviceId.toLowerCase().equals(productName)) {
addItems = true;
}
} else {
addItems = true;
}
if (addItems) {
dslrProperty = mDslrProperties
.addProperty(propertyCode);
dslrProperty.setPropertyTitle( devices.getAttributeResourceValue(null, "title", 0));
}
// if (deviceId != null
// && deviceId.toLowerCase().equals(productName)) {
// dslrProperty = mDslrProperties
// .addProperty(propertyCode);
// addItems = true;
// } else {
// dslrProperty = mDslrProperties
// .getProperty(propertyCode);
// if (dslrProperty == null) {
// dslrProperty = mDslrProperties
// .addProperty(propertyCode);
// addItems = true;
// } else
// addItems = false;
// }
} else if (strName.equals("item")) {
if (addItems) {
int valueId = devices.getAttributeResourceValue(null,
"value", 0);
int nameId = devices.getAttributeResourceValue(null,
"name", 0);
int resId = devices.getAttributeResourceValue(null,
"img", 0);
Object value = null;
String valueType = res.getResourceTypeName(valueId);
if (valueType.equals("string")) {
value = res.getString(valueId);
} else if (valueType.equals("integer")) {
value = res.getInteger(valueId);
}
dslrProperty.addPropertyValue(value, nameId, resId);
}
}
}
try {
eventType = devices.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
mIsInitialized = true;
Log.d(TAG, "Document End");
}
public void createDialog(Context context, final int propertyCode,
String dialogTitle, final ArrayList<PtpPropertyListItem> items,
int selectedItem, DialogInterface.OnClickListener listener) {
createDialog(context, propertyCode, dialogTitle, items, 0,
selectedItem, listener);
}
public void createDialog(Context context, final int propertyCode,
String dialogTitle, final ArrayList<PtpPropertyListItem> items,
final int offset, int selectedItem,
DialogInterface.OnClickListener listener) {
if (!mIsInitialized)
return;
DialogInterface.OnClickListener mListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, items.get(which).getValue().getClass().toString());
Integer value = null;
Object val = items.get(which).getValue();
if (val instanceof Long)
val = (Long) val - offset;
else if (val instanceof Integer)
val = (Integer) val - offset;
if (val != null) {
// value = value - offset;
mPtpDevice.setDevicePropValueCmd(propertyCode, val);
}
}
};
if (listener != null)
mListener = listener;
CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
customBuilder.setTitle(dialogTitle).setListItems(items, selectedItem)
.setListOnClickListener(mListener);
CustomDialog dialog = customBuilder.create();
dialog.show();
}
// public void createDialog(FragmentManager fragmentManager, final int
// propertyCode, String dialogTitle, final ArrayList<PtpPropertyListItem>
// items, int selectedItem, DialogInterface.OnClickListener listener) {
// Log.d(TAG, "CreateDialog");
// if (!mIsInitialized)
// return;
// DialogInterface.OnClickListener mListener = new
// DialogInterface.OnClickListener() {
//
// public void onClick(DialogInterface dialog, int which) {
// mPtpDevice.setDevicePropValueCmd(propertyCode,
// items.get(which).getValue());
// }
// };
// if (listener != null)
// mListener = listener;
// PtpPropertyDialog dialog = new PtpPropertyDialog(items, selectedItem,
// dialogTitle, mListener);
//
// dialog.show(fragmentManager.beginTransaction(), "dialog");
// }
public void createDslrDialog(Context context, final int propertyCode,
String dialogTitle, DialogInterface.OnClickListener listener) {
createDslrDialog(context, propertyCode, 0, dialogTitle, listener);
}
public void createDslrDialog(Context context, final int propertyCode,
final int offset, String dialogTitle,
DialogInterface.OnClickListener listener) {
if (!mIsInitialized)
return;
PtpProperty property = mPtpDevice.getPtpProperty(propertyCode);
if (property == null)
return;
DslrProperty dslrProperty = mDslrProperties.getProperty(property
.getPropertyCode());
if (dslrProperty == null)
return;
ArrayList<PtpPropertyListItem> items = null;
int selectedItem = -1;
Vector<?> propValues = property.getEnumeration();
if (propValues != null) {
items = new ArrayList<PtpPropertyListItem>();
selectedItem = propValues.indexOf(property.getValue());
for (int i = 0; i < propValues.size(); i++) {
PtpPropertyListItem item = dslrProperty
.getPropertyByValue(propValues.get(i + offset));
if (item != null)
items.add(item);
}
} else {
int vFrom = 0;
int vTo = 0;
int vStep = 1;
PtpProperty.PtpRange range = property.getRange();
if (range != null) {
try {
vFrom = (Integer) range.getMinimum();
vTo = (Integer) range.getMaximum();
vStep = (Integer) range.getIncrement();
items = new ArrayList<PtpPropertyListItem>();
for (int i = vFrom; i <= vTo; i += vStep) {
PtpPropertyListItem item = dslrProperty
.getPropertyByValue(i + offset);
if (item != null)
items.add(item);
}
} catch (Exception e) {
}
} else
items = dslrProperty.valueNames();
selectedItem = dslrProperty.indexOfValue(property.getValue());
}
String title = dialogTitle;
if (dslrProperty.propertyTitle() != 0)
title = (String)context.getText(dslrProperty.propertyTitle());
createDialog(context, propertyCode, title, items, selectedItem,
listener);
}
// public void createDslrDialog(FragmentManager fragmentManager, final int
// propertyCode, String dialogTitle, DialogInterface.OnClickListener
// listener){
// if (!mIsInitialized)
// return;
// PtpProperty property = mPtpDevice.getPtpProperty(propertyCode);
// if (property == null)
// return;
//
// DslrProperty dslrProperty =
// mDslrProperties.getProperty(property.getPropertyCode());
// if (dslrProperty == null)
// return;
// ArrayList<PtpPropertyListItem> items = null;
// int selectedItem = -1;
// Vector<?> propValues = property.getEnumeration();
// if (propValues != null){
//
// items = new ArrayList<PtpPropertyListItem>();
// selectedItem = propValues.indexOf(property.getValue());
//
//
// for(int i = 0; i < propValues.size(); i++){
// PtpPropertyListItem item =
// dslrProperty.getPropertyByValue(propValues.get(i));
// if (item != null)
// items.add(item);
// }
// }
// else {
// int vFrom = 0;
// int vTo = 0;
// int vStep = 1;
//
// PtpProperty.PtpRange range = property.getRange();
// if (range != null) {
// try {
// vFrom = (Integer)range.getMinimum();
// vTo = (Integer)range.getMaximum();
// vStep = (Integer)range.getIncrement();
//
// items = new ArrayList<PtpPropertyListItem>();
//
// for(int i = vFrom; i <= vTo; i += vStep){
// PtpPropertyListItem item = dslrProperty.getPropertyByValue(i);
// if (item != null)
// items.add(item);
// }
//
// } catch (Exception e) {
//
// }
// }
// else
// items = dslrProperty.valueNames();
// selectedItem = dslrProperty.indexOfValue(property.getValue());
// }
// createDialog(fragmentManager, propertyCode, dialogTitle, items,
// selectedItem, listener);
// }
public void setDslrImg(ImageView view, PtpProperty property) {
setDslrImg(view, 0, property);
}
public void setDslrImg(ImageView view, int offset, PtpProperty property) {
setDslrImg(view, offset, property, true);
}
public void setDslrImg(ImageView view, int propertyCode) {
setDslrImg(view, 0, propertyCode);
}
public void setDslrImg(ImageView view, int offset, int propertyCode) {
if (mIsInitialized && mPtpDevice != null) {
setDslrImg(view, offset, mPtpDevice.getPtpProperty(propertyCode),
true);
}
}
public void setDslrImg(ImageView view, PtpProperty property,
boolean setEnableStatus) {
setDslrImg(view, 0, property, setEnableStatus);
}
public void setDslrImg(ImageView view, int offset, PtpProperty property,
boolean setEnableStatus) {
if (property != null && view != null) {
DslrProperty prop = mDslrProperties.getProperty(property
.getPropertyCode());
if (prop == null)
return;
if (setEnableStatus)
view.setEnabled(property.getIsWritable());
if (property.getDataType() <= 0x000a) {
Integer value = (Integer) property.getValue();
view.setImageResource(prop.getImgResourceId(value + offset));
} else
view.setImageResource(prop.getImgResourceId(property.getValue()));
}
}
public void setDslrTxt(TextView view, PtpProperty property) {
try {
DslrProperty prop = mDslrProperties.getProperty(property
.getPropertyCode());
if (prop == null)
return;
view.setEnabled(property.getIsWritable());
int propRes = prop.getnameResourceId(property.getValue());
if (propRes != 0)
view.setText(propRes);
else
Log.d(TAG, String.format(
"setDslrTxt value not found for property: %#x",
property.getPropertyCode()));
} catch (Exception e) {
Log.d(TAG,
String.format(
"setDslrTxt exception, property: %#x exception: ",
property.getPropertyCode())
+ e.getMessage());
}
}
public void showApertureDialog(Context context) {
Log.d(TAG, "Show aperture dialog");
if (!mIsInitialized)
return;
final PtpProperty property = mPtpDevice
.getPtpProperty(PtpProperty.FStop);
if (property != null) {
final Vector<?> enums = property.getEnumeration();
int selectedItem = enums.indexOf(property.getValue());
if (enums != null) {
final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
for (int i = 0; i < enums.size(); i++) {
Integer value = (Integer) enums.get(i);
Double val = ((double) value / 100);
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setTitle(val.toString());
item.setValue(enums.get(i));
items.add(item);
}
createDialog(context, PtpProperty.FStop, "Select aperture",
items, selectedItem, null);
}
}
}
public void showExposureTimeDialog(Context context) {
if (!mIsInitialized)
return;
PtpProperty property = mPtpDevice
.getPtpProperty(PtpProperty.ExposureTime);
if (property != null) {
final Vector<?> enums = property.getEnumeration();
int selectedItem = enums.indexOf(property.getValue());
if (enums != null) {
ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
for (int i = 0; i < enums.size(); i++) {
String str;
Long nesto = (Long) enums.get(i);
if (nesto == 0xffffffffL)
str = "Bulb";
else {
if (nesto >= 10000)
str = String.format("%.1f \"",
(double) nesto / 10000);
else
str = String.format("1/%.1f",
10000 / (double) nesto);
}
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setTitle(str);
item.setValue(enums.get(i));
items.add(item);
}
createDialog(context, PtpProperty.ExposureTime,
"Select exposure time", items, selectedItem, null);
}
}
}
public void showExposureCompensationDialog(Context context) {
Log.d(TAG, "Show exposure compensation dialog");
if (!mIsInitialized)
return;
final PtpProperty property = mPtpDevice
.getPtpProperty(PtpProperty.ExposureBiasCompensation);
if (property != null) {
final Vector<?> enums = property.getEnumeration();
int selectedItem = enums.indexOf(property.getValue());
if (enums != null) {
final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
for (int i = 0; i < enums.size(); i++) {
Integer value = (Integer) enums.get(i);
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setTitle(String.format("%+.1f EV",
(double) value / 1000));
item.setValue(enums.get(i));
items.add(item);
}
createDialog(context, PtpProperty.ExposureBiasCompensation,
"Select EV compensation", items, selectedItem, null);
}
}
}
public void showInternalFlashCompensationDialog(Context context) {
Log.d(TAG, "Show exposure compensation dialog");
if (!mIsInitialized)
return;
final PtpProperty property = mPtpDevice
.getPtpProperty(PtpProperty.InternalFlashCompensation);
if (property != null) {
PtpProperty.PtpRange range = property.getRange();
if (range != null) {
int selectedItem = -1;
int i = 0;
ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
for (int r = (Integer) range.getMinimum(); r <= (Integer) range
.getMaximum(); r += (Integer) range.getIncrement()) {
if (r == (Integer) property.getValue())
selectedItem = i;
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setTitle(String.format("%+.1f EV", (double) r / 6));
item.setValue(r);
items.add(item);
i++;
}
createDialog(context, PtpProperty.InternalFlashCompensation,
"Select Internal Flash Compensation", items,
selectedItem, null);
}
}
}
// enable/disable controls in view group
public void enableDisableControls(ViewGroup viewGroup, boolean enable) {
enableDisableControls(viewGroup, enable, false);
}
public void enableDisableControls(ViewGroup viewGroup, boolean enable, boolean checkOnlyVisible) {
if (viewGroup != null) {
boolean change = true;
if (viewGroup.getTag() != null) {
Boolean old = (Boolean) viewGroup.getTag();
if (old == enable)
change = false;
}
if (change) {
viewGroup.setTag(enable);
for (int i = 0; i < viewGroup.getChildCount(); i++) {
boolean checkView = viewGroup.getChildAt(i).getVisibility() == View.VISIBLE;
if (!checkOnlyVisible)
checkView = true;
if (checkView) {
if (enable) {
if (viewGroup.getChildAt(i).getTag() != null) {
viewGroup.getChildAt(i).setEnabled(
(Boolean) viewGroup.getChildAt(i)
.getTag());
viewGroup.getChildAt(i).setTag(null);
}
} else {
viewGroup.getChildAt(i).setTag(
viewGroup.getChildAt(i).isEnabled());
viewGroup.getChildAt(i).setEnabled(false);
}
}
}
}
}
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.graphics.RectF;
public class PtpLiveViewObject {
public static final int FIXED_POINT = 16;
public static final int ONE = 1 << FIXED_POINT;
private int mVendorId, mProductId;
public LvSizeInfo jpegImageSize;
LvSizeInfo wholeSize;
LvSizeInfo displayAreaSize;
LvSizeInfo displayCenterCoordinates;
LvSizeInfo afFrameSize;
LvSizeInfo afFrameCenterCoordinates;
int noPersons = 0;
LvSizeInfo[] personAfFrameSize = null;//= new SizeInfo[5];
LvSizeInfo[] personAfFrameCenterCoordinates = null; // = new SizeInfo[5];
public RectF[] afRects = null; // = new RectF[6];
public int selectedFocusArea = 0;
public int rotationDirection = 0;
public int focusDrivingStatus = 0;
public int shutterSpeedUpper = 0;
public int shutterSpeedLower = 0;
public int apertureValue = 0;
public int countDownTime = 0;
public int focusingJudgementResult = 0;
public int afDrivingEnabledStatus = 0;
public int levelAngleInformation = 0;
public int faceDetectionAfModeStatus = 0;
public int faceDetectionPersonNo = 0;
public int afAreaIndex = 0;
public byte[] data;
// d7000 properties
public double rolling = 0;
public boolean hasRolling = false;
public double pitching = 0;
public boolean hasPitching = false;
public double yawing = 0;
public boolean hasYawing = false;
public int movieRecordingTime = 0;
public boolean movieRecording = false;
public boolean hasApertureAndShutter = true;
public float ox, oy, dLeft, dTop;
public int imgLen;
public int imgPos;
public PtpLiveViewObject(int vendorId, int productId){
mVendorId = vendorId;
mProductId = productId;
switch (mProductId){
case 0x0429: // d5100
case 0x0428: // d7000
case 0x042a: // d800
case 0x042e: // d800e
case 0x042d: // d600
noPersons = 35;
break;
case 0x0423: // d5000
case 0x0421: // d90
noPersons = 5;
break;
case 0x041a: // d300
case 0x041c: // d3
case 0x0420: // d3x
case 0x0422: // d700
case 0x0425: // d300s
case 0x0426: // d3s
noPersons = 0;
break;
}
personAfFrameSize = new LvSizeInfo[noPersons];
personAfFrameCenterCoordinates = new LvSizeInfo[noPersons];
afRects = new RectF[noPersons + 1];
for (int i = 0; i < noPersons; i++) {
personAfFrameSize[i] = new LvSizeInfo();
personAfFrameCenterCoordinates[i] = new LvSizeInfo();
}
jpegImageSize = new LvSizeInfo();
wholeSize = new LvSizeInfo();
displayAreaSize = new LvSizeInfo();
displayCenterCoordinates = new LvSizeInfo();
afFrameSize = new LvSizeInfo();
afFrameCenterCoordinates = new LvSizeInfo();
}
public float sDw, sDh;
private PtpBuffer buf = null;
public void setBuffer(PtpBuffer buffer){
buf = buffer;
}
public void parse(int sWidth, int sHeight){
if (buf != null){
buf.parse();
switch (mProductId){
case 0x042d: // d600
buf.nextS32(); // display information area size
buf.nextS32(); // live view image area size
break;
}
jpegImageSize.setSize(buf.nextU16(true), buf.nextU16(true));
sDw = (float)sWidth / (float)jpegImageSize.horizontal;
sDh = (float)sHeight / (float)jpegImageSize.vertical;
//Log.d(MainActivity.TAG, "++ Width: " + jpegImageSize.horizontal + " height: " + jpegImageSize.vertical);
wholeSize.setSize(buf.nextU16(true), buf.nextU16(true));
displayAreaSize.setSize(buf.nextU16(true), buf.nextU16(true));
displayCenterCoordinates.setSize(buf.nextU16(true), buf.nextU16(true));
afFrameSize.setSize(buf.nextU16(true), buf.nextU16(true));
afFrameCenterCoordinates.setSize(buf.nextU16(true), buf.nextU16(true));
buf.nextS32(); // reserved
selectedFocusArea = buf.nextU8();
rotationDirection = buf.nextU8();
focusDrivingStatus = buf.nextU8();
buf.nextU8(); // reserved
shutterSpeedUpper = buf.nextU16(true);
shutterSpeedLower = buf.nextU16(true);
apertureValue = buf.nextU16(true);
countDownTime = buf.nextU16(true);
focusingJudgementResult = buf.nextU8();
afDrivingEnabledStatus = buf.nextU8();
buf.nextU16(); // reserved
ox = (float)jpegImageSize.horizontal / (float)displayAreaSize.horizontal;
oy = (float)jpegImageSize.vertical / (float)displayAreaSize.vertical;
dLeft = ((float)displayCenterCoordinates.horizontal - ((float)displayAreaSize.horizontal / 2));
dTop = ((float)displayCenterCoordinates.vertical - ((float)displayAreaSize.vertical / 2));
switch (mProductId){
case 0x0426: // d3s
CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize);
hasApertureAndShutter = false;
hasRolling = true;
rolling = ((double)buf.nextS32(true)) / ONE;
imgPos = 128 + 12;
break;
case 0x0420: // d3x
CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize);
hasRolling = true;
rolling = ((double)buf.nextS32(true)) / ONE;
imgPos = 64 + 12;
break;
case 0x041a: // d300
case 0x041c: // d3
case 0x0422: // d700
case 0x0425: // d300s
CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize);
imgPos = 64 + 12;
break;
case 0x0429: // d5100
case 0x0428: // d7000 break;
case 0x042a: // d800
case 0x042e: // d800e
case 0x042d: // d600
// d800 don't have the aperture and shutter values
if (mProductId == 0x042a || mProductId == 0x042e)
hasApertureAndShutter = false;
hasRolling = true;
rolling = ((double)buf.nextS32(true)) / ONE;
hasPitching = true;
pitching = ((double)buf.nextS32(true)) / ONE;
hasYawing = true;
yawing = ((double)buf.nextS32(true)) / ONE;
movieRecordingTime = buf.nextS32();
movieRecording = buf.nextU8() == 1;
faceDetectionAfModeStatus = buf.nextU8();
faceDetectionPersonNo = buf.nextU8();
afAreaIndex = buf.nextU8();
CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize);
for(int i = 0; i < noPersons; i++){
personAfFrameSize[i].setSize(buf.nextU16(true), buf.nextU16(true));
personAfFrameCenterCoordinates[i].setSize(buf.nextU16(true), buf.nextU16(true));
if ((i+1) <= faceDetectionPersonNo)
CalcCoord(i + 1, dLeft, dTop, personAfFrameCenterCoordinates[i], personAfFrameSize[i]);
}
imgPos = 384 + 12;
break;
case 0x0423: // d5000
case 0x0421: // d90
levelAngleInformation = buf.nextS32(true);
faceDetectionAfModeStatus = buf.nextU8();
buf.nextU8(); // reserved
faceDetectionPersonNo = buf.nextU8();
afAreaIndex = buf.nextU8();
CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize);
for(int i = 0; i < noPersons; i++){
personAfFrameSize[i].setSize(buf.nextU16(true), buf.nextU16(true));
personAfFrameCenterCoordinates[i].setSize(buf.nextU16(true), buf.nextU16(true));
if ((i+1) <= faceDetectionPersonNo)
CalcCoord(i + 1, dLeft, dTop, personAfFrameCenterCoordinates[i], personAfFrameSize[i]);
}
imgPos = 128+12;
break;
}
imgLen = buf.data().length - imgPos;
data = buf.data();
}
//System.arraycopy(buf.data(), imgPos, imgData, 0, imgLen);
}
private void CalcCoord(int coord, float dLeft, float dTop, LvSizeInfo afCenter, LvSizeInfo afSize)
{
float left, top, right, bottom;
left = (((float)afCenter.horizontal - ((float)afSize.horizontal / 2)) - dLeft) * ox;
top = (((float)afCenter.vertical - ((float)afSize.vertical / 2)) - dTop) * ox;
if (left < 0)
left = 0;
if (top < 0)
top = 0;
right = left + ((float)afSize.horizontal * ox);
bottom = top + ((float)afSize.vertical * oy);
if (right > jpegImageSize.horizontal)
right = jpegImageSize.horizontal;
if (bottom > jpegImageSize.vertical)
bottom = jpegImageSize.vertical;
//Log.d(MainActivity.TAG, "++ Left: " + left + " top: " + top +" right: " + right + " bottom: " + bottom);
afRects[coord] = new RectF(left * sDw, top * sDh, right * sDw, bottom * sDh);
}
public class LvSizeInfo {
public int horizontal;
public int vertical;
public LvSizeInfo(){
horizontal = 0;
vertical = 0;
}
public LvSizeInfo(int horSize, int vertSize){
horizontal = horSize;
vertical = vertSize;
}
public void setSize(int hor, int vert){
horizontal = hor;
vertical = vert;
}
public void setSize(LvSizeInfo sizeInfo){
horizontal = sizeInfo.horizontal;
vertical = sizeInfo.vertical;
}
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
public class LvSurfaceHelper {
public PtpLiveViewObject mLvo;
public boolean mHistogramEnabled = true;
public boolean mHistogramSeparate = true;
public PtpProperty mLvZoom;
// public LayoutMain.TouchMode mTouchMode;
// public int mMfDriveStep;
// public int mFocusCurrent;
// public int mFocusMax;
public int mOsdDisplay;
public LvSurfaceHelper(PtpLiveViewObject lvo, PtpProperty lvZoom, int osdDisplay){
mLvo = lvo;
mLvZoom = lvZoom;
mOsdDisplay = osdDisplay;
}
// public LvSurfaceHelper(PtpLiveViewObject lvo, PtpProperty lvZoom, LayoutMain.TouchMode touchMode, int mfDriveStep, int focusCurrent, int focusMax, int osdDisplay) {
// mLvo = lvo;
// mLvZoom = lvZoom;
// mTouchMode = touchMode;
// mMfDriveStep = mfDriveStep;
// mFocusCurrent = focusCurrent;
// mFocusMax = focusMax;
// mOsdDisplay = osdDisplay;
// }
}
| Java |
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package com.dslr.dashboard;
public class PtpPropertyValue {
int mTypecode;
Object mValue;
PtpPropertyValue (int tc)
{ mTypecode = tc; }
private PtpPropertyValue (int tc, Object obj)
{
mTypecode = tc;
mValue = obj;
}
public Object getValue ()
{ return mValue; }
public int getTypeCode ()
{ return mTypecode; }
protected void parse (PtpBuffer data)
{
mValue = get(mTypecode, data);
}
public static void setNewPropertyValue(PtpBuffer data, int valueType, Object value){
switch(valueType){
case u8:
case s8:
data.put8((Integer) value);
break;
case s16:
case u16:
data.put16((Integer)value);
break;
case s32:
data.put32((Integer)value);
break;
case u32:
data.put32((Long)value);
break;
case s64:
case u64:
data.put64((Long)value);
break;
case string:
data.putString(value.toString());
break;
}
}
static Object get (int code, PtpBuffer buf)
{
switch (code) {
case s8:
return Integer.valueOf(buf.nextS8 ());
case u8:
return Integer.valueOf(buf.nextU8 ());
case s16:
return Integer.valueOf(buf.nextS16 ());
case u16:
return Integer.valueOf(buf.nextU16 ());
case s32:
return Integer.valueOf(buf.nextS32 ());
case u32:
return Long.valueOf(0xffffffffL & buf.nextS32 ());
//return buf.nextS32();
case s64:
return Long.valueOf(buf.nextS64 ());
case u64:
// FIXME: unsigned masquerading as signed ...
return Long.valueOf(buf.nextS64());
// case s128: case u128:
case s8array:
return buf.nextS8Array ();
case u8array:
return buf.nextU8Array ();
case s16array:
return buf.nextS16Array ();
case u16array:
return buf.nextU16Array ();
case u32array:
// FIXME: unsigned masquerading as signed ...
case s32array:
return buf.nextS32Array ();
case u64array:
// FIXME: unsigned masquerading as signed ...
case s64array:
return buf.nextS64Array ();
// case s128array: case u128array:
case string:
return buf.nextString ();
}
throw new IllegalArgumentException ();
}
// code values, per 5.3 table 3
public static final int s8 = 0x0001;
/** Unsigned eight bit integer */
public static final int u8 = 0x0002;
public static final int s16 = 0x0003;
/** Unsigned sixteen bit integer */
public static final int u16 = 0x0004;
public static final int s32 = 0x0005;
/** Unsigned thirty two bit integer */
public static final int u32 = 0x0006;
public static final int s64 = 0x0007;
/** Unsigned sixty four bit integer */
public static final int u64 = 0x0008;
public static final int s128 = 0x0009;
/** Unsigned one hundred twenty eight bit integer */
public static final int u128 = 0x000a;
public static final int s8array = 0x4001;
/** Array of unsigned eight bit integers */
public static final int u8array = 0x4002;
public static final int s16array = 0x4003;
/** Array of unsigned sixteen bit integers */
public static final int u16array = 0x4004;
public static final int s32array = 0x4005;
/** Array of unsigned thirty two bit integers */
public static final int u32array = 0x4006;
public static final int s64array = 0x4007;
/** Array of unsigned sixty four bit integers */
public static final int u64array = 0x4008;
public static final int s128array = 0x4009;
/** Array of unsigned one hundred twenty eight bit integers */
public static final int u128array = 0x400a;
/** Unicode string */
public static final int string = 0xffff;
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class UsbSerialAttachedActivity extends Activity {
private static final String TAG = "UsbSerialAttachedActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
protected void onNewIntent(Intent intent) {
Log.d(TAG, "onNewIntent");
super.onNewIntent(intent);
}
@Override
protected void onResume() {
Log.d(TAG, "onResume");
Intent intent = new Intent(this, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
Bundle extras = new Bundle();
extras.putBoolean("UsbSerialAttached", true);
intent.putExtras(extras);
startActivity(intent);
finish();
super.onResume();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.util.Log;
import com.dslr.dashboard.PtpPartialObjectProccessor.PtpPartialObjectProgressListener;
public class PtpGetPreviewImageProcessor implements IPtpCommandFinalProcessor {
private static String TAG = "GetPreviewImageProcessor";
private PtpPartialObjectProgressListener mProgressListener;
public void setProgressListener(PtpPartialObjectProgressListener listener){
mProgressListener = listener;
}
private PtpObjectInfo mObjectInfo;
private int mOffset = 0;
private int mMaxSize = 0x100000;
//private byte[] _objectData;
private File mFile;
private OutputStream mStream;
// public byte[] pictureData(){
// return _objectData;
// }
public PtpObjectInfo objectInfo(){
return mObjectInfo;
}
public int maxSize(){
return mMaxSize;
}
public PtpGetPreviewImageProcessor(PtpObjectInfo objectInfo, File file){
this(objectInfo, 0x100000, file);
}
public PtpGetPreviewImageProcessor(PtpObjectInfo objectInfo, int maxSize, File file){
mFile = file;
mObjectInfo = objectInfo;
mMaxSize = maxSize;
//_objectData = new byte[_objectInfo.objectCompressedSize];
try {
mStream = new BufferedOutputStream(new FileOutputStream(mFile));
} catch (FileNotFoundException e) {
}
}
public boolean doFinalProcessing(PtpCommand cmd) {
boolean result = false;
int count = cmd.incomingData().getPacketLength() - 12;
Log.d(TAG, "Size: " + count);
Log.d(TAG, "Response: " + cmd.getResponseCode());
if (cmd.isResponseOk())
{
try {
mStream.write(cmd.incomingData().data(), 12, count);
} catch (IOException e) {
}
Log.d(TAG, "Remaining: " + cmd.responseParam());
if (cmd.responseParam() != 0) {
mOffset += count;
Log.d(TAG, "offset: " + mOffset);
result = true;
}
else {
mOffset += count;
Log.d(TAG, "offset: " + mOffset);
try {
mStream.flush();
mStream.close();
} catch (IOException e) {
}
}
if (mProgressListener != null){
mProgressListener.onProgress(mOffset);
}
}
return result;
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
public class ExifDataHelper {
public String mExifName;
public String mExifDescription;
public String mExifValue;
public ExifDataHelper(String exifName, String exifDescription) {
mExifName = exifName;
mExifDescription = exifDescription;
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
public class PtpDevice {
private static final String TAG = "PtpDevice";
public final static String PREF_KEY_LV_AT_START = "pref_key_lv_at_start";
public final static String PREF_KEY_LV_RETURN = "pref_key_lv_return";
public final static String PREF_KEY_SHOOTING_AF = "pref_key_shooting_af";
public final static String PREF_KEY_GENERAL_SCREEN_ON = "pref_key_general_screen_on";
public final static String PREF_KEY_GENERAL_INTERNAL_VIEWER = "pref_key_general_internal_viewer";
public final static String PREF_KEY_SDRAM_LOCATION = "pref_key_sdram_saving_location";
public final static String PREF_KEY_SDRAM_PREFIX = "pref_key_sdram_prefix";
public final static String PREF_KEY_SDRAM_NUMBERING = "pref_key_sdram_numbering";
public final static String PREF_KEY_BKT_ENABLED = "pref_key_bkt_enabled";
public final static String PREF_KEY_BKT_COUNT = "pref_key_bkt_count";
public final static String PREF_KEY_BKT_DIRECTION = "pref_key_bkt_direction";
public final static String PREF_KEY_BKT_STEP = "pref_key_bkt_step";
public final static String PREF_KEY_BKT_FOCUS_FIRST = "pref_key_bkt_focus_first";
public final static String PREF_KEY_TIMELAPSE_INTERVAL = "pref_key_timelapse_interval";
public final static String PREF_KEY_TIMELAPSE_ITERATIONS = "pref_key_timelapse_iterations";
public final static String PREF_KEY_FOCUS_IMAGES = "pref_key_focus_images";
public final static String PREF_KEY_FOCUS_STEPS = "pref_key_focus_steps";
public final static String PREF_KEY_FOCUS_DIRECTION_DOWN = "pref_key_focus_direction_down";
public final static String PREF_KEY_FOCUS_FOCUS_FIRST = "pref_key_focus_focus_first";
public final static String PREF_KEY_GPS_ENABLED = "pref_key_gps_enabled";
public final static String PREF_KEY_GPS_SAMPLES = "pref_key_gps_samples";
public final static String PREF_KEY_GPS_INTERVAL = "pref_key_gps_interval";
public interface OnPtpDeviceEventListener {
public void sendEvent(PtpDeviceEvent event, Object data);
}
private OnPtpDeviceEventListener mOnPtpDeviceEventListener = null;
public void setOnPtpDeviceEventListener(OnPtpDeviceEventListener listener) {
mOnPtpDeviceEventListener = listener;
}
public void removeOnPtpDeviceEventListener() {
mOnPtpDeviceEventListener = null;
}
private void sendPtpDeviceEvent(PtpDeviceEvent event) {
sendPtpDeviceEvent(event, null);
}
private void sendPtpDeviceEvent(PtpDeviceEvent event, Object data) {
if (mOnPtpDeviceEventListener != null)
mOnPtpDeviceEventListener.sendEvent(event, data);
}
public interface OnPtpPropertyChangedListener {
public void sendPtpPropertyChanged(PtpProperty property);
}
private OnPtpPropertyChangedListener mPtpPropertyChangedListener = null;
public void setOnPtpPropertyChangedListener(
OnPtpPropertyChangedListener listener) {
mPtpPropertyChangedListener = listener;
}
public void removePtpPropertyChangedListener() {
mPtpPropertyChangedListener = null;
}
private void sendPtpPropertyChanged(PtpProperty property) {
if (mPtpPropertyChangedListener != null)
mPtpPropertyChangedListener.sendPtpPropertyChanged(property);
}
private SharedPreferences.OnSharedPreferenceChangeListener mPrefListener = null;
public void setOnSharedPreferenceChangeListener(
SharedPreferences.OnSharedPreferenceChangeListener listener) {
mPrefListener = listener;
}
public void removeSharedPreferenceChangeListener() {
mPrefListener = null;
}
public boolean getIsCommandSupported(int ptpCommand) {
if (!mIsPtpDeviceInitialized)
return false;
return mDeviceInfo.supportsOperation(ptpCommand);
}
public boolean getIsMovieRecordingStarted() {
return mIsMovieRecordingStarted;
}
public boolean getCaptureToSdram() {
return mCaptureToSdram;
}
public void setCaptureToSdram(boolean value) {
mCaptureToSdram = value;
sendPtpDeviceEvent(PtpDeviceEvent.RecordingDestinationChanged, mCaptureToSdram);
}
private int mVendorId = 0;
private int mProductId = 0;
private PtpService mPtpService = null;
private SharedPreferences mPrefs = null;
private PtpCommunicatorBase mCommunicator = null;
private boolean mIsInitialized = false;
private ExecutorService mExecutor;
private boolean mIsExecutorRunning = false;
private boolean mIsPtpDeviceInitialized = false;
private PtpDeviceInfo mDeviceInfo = null;
private Hashtable<Integer, PtpProperty> mPtpProperties;
private Hashtable<Integer, PtpStorageInfo> mPtpStorages;
private boolean mIsLiveViewEnabled = false;
private boolean mIsPtpObjectsLoaded = false;
private ThreadBase mEventThread = null;
// private LiveviewThread mLiveviewThread = null;
private boolean mIsMovieRecordingStarted = false;
private PtpLiveViewObject mLvo = null;
private boolean mCaptureToSdram = false;
// internal bracketing backup
private Object mInternalBracketingShootingMode = null;
private Object mInternalBracketingBurstNumber = null;
// preferences private
private boolean mLiveViewAtStart = false;
private boolean mLiveViewReturn = false;
private boolean mAFBeforeCapture = true;
private boolean mGeneralScreenOn = true;
private boolean mGeneralInternalViewer = true;
// custom bracketing preferences
private boolean mIsCustomBracketingEnabled = false;
private int mBktStep = 1;
private int mBktDirection = 2;
private int mBktCount = 3;
private boolean mBktFocusFirst = true;
// sdram image saving preferences
private String mSdramSavingLocation = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"DSLR").getAbsolutePath();
private String mSdramPrefix = "dslr";
private int mSdramPictureNumbering = 1;
// time lapse preferences
private long mTimelapseInterval = 10000; // interval in seconds
private int mTimelapseIterations = 10;
// gps location preferences
private boolean mGpsInfoEnabled = true;
private int mGpsSamples = 3;
private int mGpsInterval = 2;
// preferences public
public boolean getLiveViewAtStart() {
return mLiveViewAtStart;
}
public boolean getLiveViewReturn() {
return mLiveViewReturn;
}
public boolean getAFBeforeCapture() {
return mAFBeforeCapture;
}
public void setAFBeforeCapture(boolean value) {
if (value != mAFBeforeCapture) {
mAFBeforeCapture = value;
Editor editor = mPrefs.edit();
editor.putBoolean(PREF_KEY_SHOOTING_AF, value);
editor.commit();
}
}
public boolean getGeneralScreenOn() {
return mGeneralScreenOn;
}
public boolean getGeneralInternalViewer() {
return mGeneralInternalViewer;
}
// custom bracketing public properties
public boolean getIsCustomBracketingEnabled() {
return mIsCustomBracketingEnabled;
}
public void setIsCustomBracketingEnabled(boolean value) {
mIsCustomBracketingEnabled = value;
mPrefs
.edit()
.putBoolean(PREF_KEY_BKT_ENABLED, mIsCustomBracketingEnabled)
.commit();
}
public int getCustomBracketingCount() {
return mBktCount;
}
public void setCustomBracketingCount(int value) {
mBktCount = value;
mPrefs
.edit()
.putString(PREF_KEY_BKT_COUNT, Integer.toString(mBktCount))
.commit();
}
public int getCustomBracketingDirection() {
return mBktDirection;
}
public void setCustomBracketingDirection(int value) {
mBktDirection = value;
mPrefs
.edit()
.putString(PREF_KEY_BKT_DIRECTION, Integer.toString(mBktDirection))
.commit();
}
public int getCustomBracketingStep() {
return mBktStep;
}
public void setCustomBracketingStep(int value) {
mBktStep = value;
mPrefs
.edit()
.putString(PREF_KEY_BKT_STEP, Integer.toString(mBktStep))
.commit();
}
public boolean getCustomBracketingFocusFirst(){
return mBktFocusFirst;
}
public void setCustomBracketingFocusFirst(boolean value) {
mBktFocusFirst = value;
mPrefs
.edit()
.putBoolean(PREF_KEY_BKT_FOCUS_FIRST, mBktFocusFirst)
.commit();
}
// sdram image saving public preferences
public void setSdramPictureNumbering(int value) {
mSdramPictureNumbering = value;
mPrefs
.edit()
.putString(PREF_KEY_SDRAM_NUMBERING, Integer.toString(mSdramPictureNumbering))
.commit();
}
// timelapse public preferences
public long getTimelapseInterval(){
return mTimelapseInterval;
}
public void setTimelapseInterval(long value){
mTimelapseInterval = value;
mPrefs
.edit()
.putString(PREF_KEY_TIMELAPSE_INTERVAL, Long.toString(mTimelapseInterval))
.commit();
}
public int getTimelapseIterations(){
return mTimelapseIterations;
}
public void setTimelapseIterations(int value){
mTimelapseIterations = value;
mPrefs
.edit()
.putString(PREF_KEY_TIMELAPSE_ITERATIONS, Integer.toString(mTimelapseIterations))
.commit();
}
public PtpDevice(PtpService ptpService) {
mPtpService = ptpService;
mPrefs = mPtpService.getPreferences();
loadPreferences();
mDeviceInfo = new PtpDeviceInfo();
mPtpProperties = new Hashtable<Integer, PtpProperty>();
mPtpStorages = new Hashtable<Integer, PtpStorageInfo>();
}
private SharedPreferences.OnSharedPreferenceChangeListener mPrefChangedListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
Log.d(TAG, "Preference changed: " + key);
loadPreferences();
if (mPrefListener != null)
mPrefListener.onSharedPreferenceChanged(sharedPreferences, key);
}
};
private void loadPreferences() {
Log.d(TAG, "Loading preferences");
mLiveViewAtStart = mPrefs.getBoolean(PREF_KEY_LV_AT_START, false);
mLiveViewReturn = mPrefs.getBoolean(PREF_KEY_LV_RETURN, false);
mAFBeforeCapture = mPrefs.getBoolean(PREF_KEY_SHOOTING_AF, true);
mGeneralScreenOn = mPrefs.getBoolean(PREF_KEY_GENERAL_SCREEN_ON, true);
mGeneralInternalViewer = mPrefs.getBoolean(PREF_KEY_GENERAL_INTERNAL_VIEWER, true);
String tmp = mPrefs.getString(PREF_KEY_SDRAM_LOCATION, "");
if (tmp.equals("")) {
Editor editor = mPrefs.edit();
editor.putString(PREF_KEY_SDRAM_LOCATION, mSdramSavingLocation);
editor.commit();
} else
mSdramSavingLocation = tmp;
mSdramPrefix = mPrefs.getString(PREF_KEY_SDRAM_PREFIX, "dslr");
mSdramPictureNumbering = Integer.valueOf(mPrefs.getString(
PREF_KEY_SDRAM_NUMBERING, "1"));
mIsCustomBracketingEnabled = mPrefs.getBoolean(PREF_KEY_BKT_ENABLED, false);
mBktCount = Integer.valueOf(mPrefs.getString(PREF_KEY_BKT_COUNT, "3"));
mBktDirection = Integer.valueOf(mPrefs.getString(PREF_KEY_BKT_DIRECTION, "2"));
mBktStep = Integer.valueOf(mPrefs.getString(PREF_KEY_BKT_STEP, "1"));
mBktFocusFirst = mPrefs.getBoolean(PREF_KEY_BKT_FOCUS_FIRST, true);
mTimelapseInterval = Long.valueOf(mPrefs.getString(PREF_KEY_TIMELAPSE_INTERVAL, "10000"));
mTimelapseIterations = Integer.valueOf(mPrefs.getString(PREF_KEY_TIMELAPSE_ITERATIONS, "10"));
mFocusImages = Integer.valueOf(mPrefs.getString(PREF_KEY_FOCUS_IMAGES, "5"));
mFocusStep = Integer.valueOf(mPrefs.getString(PREF_KEY_FOCUS_STEPS, "10"));
mFocusDirectionDown = mPrefs.getBoolean(PREF_KEY_FOCUS_DIRECTION_DOWN, true);
mFocusFocusFirst = mPrefs.getBoolean(PREF_KEY_FOCUS_FOCUS_FIRST, false);
mGpsInfoEnabled = mPrefs.getBoolean(PREF_KEY_GPS_ENABLED, false);
mGpsSamples = Integer.valueOf(mPrefs.getString(PREF_KEY_GPS_SAMPLES, "3"));
mGpsInterval = Integer.valueOf(mPrefs.getString(PREF_KEY_GPS_INTERVAL, "2"));
mPtpService.getGpsLocationHelper().setGpsSampleCount(mGpsSamples);
mPtpService.getGpsLocationHelper().setGpsSampleInterval(mGpsInterval);
sendPtpDeviceEvent(PtpDeviceEvent.PrefsLoaded, null);
}
public void initialize(int vendorId, int productId,
PtpCommunicatorBase communicator) {
if (!mIsInitialized) {
mExecutor = Executors.newSingleThreadExecutor();
mIsExecutorRunning = true;
mCommunicator = communicator;
mIsInitialized = true;
mVendorId = vendorId;
mProductId = productId;
mLvo = new PtpLiveViewObject(vendorId, productId);
mPrefs.registerOnSharedPreferenceChangeListener(mPrefChangedListener);
initializePtpDevice();
}
}
public void stop(boolean isUsbUnpluged) {
Log.d(TAG, "stop PTP device");
if (!isUsbUnpluged)
normalStop();
else
usbUnplugedStop();
mPrefs.unregisterOnSharedPreferenceChangeListener(mPrefChangedListener);
}
private void normalStop() {
// stop live view if running
Log.i(TAG, "ending live view");
endLiveViewDisplay(true);
// return to camera mode
Log.i(TAG, "switching to camera mode");
changeCameraModeCmd(true);
// return to sdcard mode
Log.i(TAG, "switching to sdcard mode");
setDevicePropValue(PtpProperty.RecordingMedia, 0x0000, true);
Log.d(TAG, "stoping PTPDevice threads");
usbUnplugedStop();
}
private void usbUnplugedStop() {
stopTimelapseExecutor();
mCommunicator.closeCommunicator();
if (mIsExecutorRunning) {
Log.d(TAG, "stoping communicator thread");
stopExecutor(mExecutor);
mIsExecutorRunning = false;
}
// if (mLiveviewThread != null)
// mLiveviewThread.interrupt();
if (mEventThread != null)
mEventThread.interrupt();
sendPtpDeviceEvent(PtpDeviceEvent.PtpDeviceStoped);
mIsInitialized = false;
mIsPtpDeviceInitialized = false;
mIsLiveViewEnabled = false;
mIsPtpObjectsLoaded = false;
mPtpProperties.clear();
mPtpStorages.clear();
}
public boolean getIsInitialized() {
return mIsInitialized;
}
public boolean getIsPtpDeviceInitialized() {
return mIsPtpDeviceInitialized;
}
public PtpService getPtpService() {
return mPtpService;
}
public int getVendorId() {
return mVendorId;
}
public int getProductId() {
return mProductId;
}
public PtpDeviceInfo getPtpDeviceInfo() {
return mDeviceInfo;
}
public boolean getIsLiveViewEnabled() {
return mIsLiveViewEnabled;
}
public boolean getIsPtpObjectsLoaded() {
return mIsPtpObjectsLoaded;
}
public Hashtable<Integer, PtpStorageInfo> getPtpStorages() {
return mPtpStorages;
}
public synchronized PtpProperty getPtpProperty(final int propertyCode) {
PtpProperty property = (PtpProperty) mPtpProperties.get(propertyCode);
return property;
}
private void stopExecutor(ExecutorService executor) {
if (executor != null) {
Log.d(TAG, "Shuting down executor");
executor.shutdown();
try {
// Wait a while for existing tasks to terminate
if (!executor.awaitTermination(500, TimeUnit.MICROSECONDS)) {
executor.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!executor.awaitTermination(500, TimeUnit.MILLISECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
protected synchronized PtpCommand sendCommand(PtpCommand cmd) {
try {
if (cmd.getCommandCode() != PtpCommand.GetDeviceInfo
&& cmd.getCommandCode() != PtpCommand.OpenSession) {
if (!mDeviceInfo.supportsOperation(cmd.getCommandCode()))
return null;
}
// Log.d(MainActivity.TAG, "Before get task");
FutureTask<PtpCommand> fCmd = cmd.getTask(mCommunicator);
// Log.d(MainActivity.TAG, "Before executing");
mExecutor.execute(fCmd);
// Log.d(MainActivity.TAG, "After executing");
PtpCommand result = fCmd.get();
return result;
} catch (Exception e) {
Log.e(TAG, "SendPtpCommand: ");// + e.getMessage());
return null;
}
}
private void initializePtpDevice() {
new Thread(new Runnable() {
public void run() {
// get the device info
PtpCommand cmd = sendCommand(getDeviceInfoCmd());
if ((cmd == null) || (cmd != null && !cmd.isDataOk()))
return;
mDeviceInfo.parse(cmd.incomingData());
// open the session
cmd = sendCommand(openSessionCmd());
if (cmd == null)
return;
if (cmd.isResponseOk()
|| (cmd.hasResponse() && cmd.incomingResponse()
.getPacketCode() == PtpResponse.SessionAlreadyOpen)) {
// we have a session
// load the supported properties
for (int i = 0; i < mDeviceInfo.getPropertiesSupported().length; i++) {
updateDevicePropDescCmd(mDeviceInfo
.getPropertiesSupported()[i]);
}
loadVendorProperties();
getStorageIds();
mIsPtpDeviceInitialized = true;
startEventListener();
sendPtpDeviceEvent(PtpDeviceEvent.PtpDeviceInitialized);
if (mIsLiveViewEnabled) {
sendPtpDeviceEvent(PtpDeviceEvent.LiveviewStart);
} else if (mLiveViewAtStart)
enterLiveViewAtStart();
}
}
}).start();
}
private void loadVendorProperties() {
Log.i(TAG, "Load vendor properties");
// try to get the vendor properties
PtpCommand cmd = sendCommand(getVendorPropCodesCmd());
// process the vendor properties
if (cmd != null && cmd.isDataOk()) {
cmd.incomingData().parse();
int[] vendorProps = cmd.incomingData().nextU16Array();
for (int i = 0; i < vendorProps.length; i++) {
PtpCommand pCmd = sendCommand(getDevicePropDescCmd(vendorProps[i]));
processLoadedProperty(pCmd);
}
}
}
private PtpCommand getDeviceInfoCmd() {
return new PtpCommand(PtpCommand.GetDeviceInfo);
}
private PtpCommand openSessionCmd() {
return new PtpCommand(PtpCommand.OpenSession).addParam(1);
}
private PtpCommand getDevicePropDescCmd(int propertyCode) {
return new PtpCommand(PtpCommand.GetDevicePropDesc)
.addParam(propertyCode);
}
private void updateDevicePropDescCmd(int propertyCode) {
processLoadedProperty(sendCommand(getDevicePropDescCmd(propertyCode)));
}
private void processLoadedProperty(PtpCommand cmd) {
if (cmd != null && cmd.isDataOk()) {
cmd.incomingData().parse();
PtpProperty property;
int propCode = cmd.incomingData().nextU16();
if (!mPtpProperties.containsKey(propCode)) {
// Log.i(TAG, String.format("+++ Creating new property %#04x",
// propCode));
property = new PtpProperty();
mPtpProperties.put(Integer.valueOf(propCode), property);
} else {
property = mPtpProperties.get(propCode);
// Log.i(TAG,
// String.format("+++ Property already in list %#04x",
// propCode));
}
property.parse(cmd.incomingData());
sendPtpPropertyChanged(property);
switch (property.getPropertyCode()) {
case PtpProperty.LiveViewStatus:
mIsLiveViewEnabled = (Integer) property.getValue() == 1;
break;
}
}
}
private PtpCommand getVendorPropCodesCmd() {
return new PtpCommand(PtpCommand.GetVendorPropCodes);
}
private PtpCommand getEventCmd() {
return new PtpCommand(PtpCommand.GetEvent);
}
private PtpCommand setDevicePropValueCommand(int propertyCode, Object value) {
// Log.i(TAG, "setDevicePropValueCommand");
PtpProperty property = mPtpProperties.get(propertyCode);
if (property != null) {
PtpBuffer buf = new PtpBuffer(
new byte[mCommunicator.getWriteEpMaxPacketSize()]);
PtpPropertyValue.setNewPropertyValue(buf, property.getDataType(),
value);
return new PtpCommand(PtpCommand.SetDevicePropValue).addParam(
propertyCode).setCommandData(buf.getOfssetArray());
} else
return null;
}
protected void setDevicePropValue(int propertyCode, Object value,
boolean updateProperty) {
final PtpCommand cmd = setDevicePropValueCommand(propertyCode, value);
if (cmd != null) {
PtpCommand fCmd = sendCommand(cmd);
if (fCmd != null && fCmd.isResponseOk()) {
// Log.d(TAG, "setDevicePropValue finished");
if (updateProperty)
updateDevicePropDescCmd(propertyCode);
}
}
// else
// Log.i(TAG, "property not found");
}
public void setDevicePropValueCmd(final int propertyCode, final Object value) {
setDevicePropValueCmd(propertyCode, value, true);
}
public void setDevicePropValueCmd(final int propertyCode,
final Object value, final boolean updateProperty) {
if (mIsPtpDeviceInitialized) {
new Thread(new Runnable() {
public void run() {
setDevicePropValue(propertyCode, value, updateProperty);
}
}).start();
}
}
protected PtpCommand getThumbCmd(int objectId) {
return new PtpCommand(PtpCommand.GetThumb).addParam(objectId);
}
protected PtpCommand getObjectInfoCmd(int objectId) {
return new PtpCommand(PtpCommand.GetObjectInfo).addParam(objectId);
}
private PtpCommand getStorageIdsCommand() {
return new PtpCommand(PtpCommand.GetStorageIDs);
}
private PtpCommand getStorageInfoCommand(int storageId) {
return new PtpCommand(PtpCommand.GetStorageInfo).addParam(storageId);
}
private PtpCommand getObjectHandlesCommand(int storageId) {
return new PtpCommand(PtpCommand.GetObjectHandles).addParam(storageId);
}
private int mSlot2Mode = 0;
private int mActiveSlot = 1;
public int getSlot2Mode() {
return mSlot2Mode;
}
public int getActiveSlot() {
return mActiveSlot;
}
private void getStorageIds() {
PtpCommand cmd = sendCommand(getStorageIdsCommand());
if ((cmd == null) || (cmd != null && !cmd.isDataOk()))
return;
cmd.incomingData().parse();
int count = cmd.incomingData().nextS32();
Log.d(TAG, "Storage id count: " + count);
PtpProperty prop = getPtpProperty(PtpProperty.Slot2ImageSaveMode);
if (prop != null) {
mSlot2Mode = (Integer) prop.getValue();
Log.d(TAG, "Slot2 mode: " + mSlot2Mode);
}
prop = getPtpProperty(PtpProperty.ActiveSlot);
if (prop != null) {
mActiveSlot = (Integer) prop.getValue();
Log.d(TAG, "Active slot: " + mActiveSlot);
}
for (int i = 1; i <= count; i++) {
int storeId = cmd.incomingData().nextS32();
int storeNo = storeId >> 16;
Log.d(TAG, "StoreID: " + storeId);
Log.d(TAG, "Getting info for slot: " + storeNo);
if ((storeId & 1) == 1) {
Log.d(TAG, "Slot has card");
sendPtpDeviceEvent(PtpDeviceEvent.SdCardInserted, storeId >> 16);
getStorageInfo(storeId);
// getObjectHandles(storeId);
} else {
Log.d(TAG, "Slot is empty");
sendPtpDeviceEvent(PtpDeviceEvent.SdCardRemoved, storeId >> 16);
}
}
}
private void getStorageIdsCmd() {
new Thread(new Runnable() {
public void run() {
getStorageIds();
}
}).start();
}
private void getStorageInfo(final int storageId) {
Log.d(TAG, String.format("Get storage info: %#04x", storageId));
PtpCommand cmd = sendCommand(getStorageInfoCommand(storageId));
if ((cmd == null) || (cmd != null && !cmd.isDataOk()))
return;
PtpStorageInfo storage;
if (mPtpStorages.containsKey(storageId)) {
storage = mPtpStorages.get(storageId);
storage.updateInfo(cmd.incomingData());
} else {
storage = new PtpStorageInfo(storageId, cmd.incomingData());
mPtpStorages.put(storageId, storage);
}
sendPtpDeviceEvent(PtpDeviceEvent.SdCardInfoUpdated, storage);
}
private void getObjectHandles(final int storageId) {
Log.d(TAG, String.format("load object handles: %#04x", storageId));
PtpCommand cmd = sendCommand(getObjectHandlesCommand(storageId));
if ((cmd == null) || (cmd != null && !cmd.isDataOk()))
return;
cmd.incomingData().parse();
int count = cmd.incomingData().nextS32();
for (int i = 1; i <= count; i++) {
getObjectInfo(cmd.incomingData().nextS32());
}
}
private PtpObjectInfo getObjectInfo(final int objectId) {
Log.d(TAG, String.format("Get object info: %#04x", objectId));
PtpObjectInfo obj = null;
PtpCommand cmd = sendCommand(getObjectInfoCmd(objectId));
if ((cmd == null) || (cmd != null && !cmd.isDataOk()))
return null;
cmd.incomingData().parse();
int storageId = cmd.incomingData().nextS32();
PtpStorageInfo storage = mPtpStorages.get(storageId);
if (storage.objects.containsKey(objectId)) {
obj = storage.objects.get(objectId);
obj.parse(cmd.incomingData());
} else {
obj = new PtpObjectInfo(objectId, cmd.incomingData());
storage.objects.put(objectId, obj);
}
loadObjectThumb(obj);
// sendPtpServiceEvent(PtpServiceEventType.ObjectAdded, obj);
return obj;
}
private void loadObjectThumb(PtpObjectInfo obj) {
switch (obj.objectFormatCode) {
case 0x3000:
case 0x3801:
File file = new File(mSdramSavingLocation + "/.dslrthumbs");
if (!file.exists())
file.mkdir();
file = new File(file, obj.filename + ".jpg");
if (!file.exists()) {
PtpCommand cmd = sendCommand(getThumbCmd(obj.objectId));
if ((cmd == null) || (cmd != null && !cmd.isDataOk()))
return;
obj.thumb = BitmapFactory.decodeByteArray(cmd.incomingData()
.data(), 12, cmd.incomingData().data().length - 12);
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
obj.thumb.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
obj.thumb.recycle();
} catch (Exception e) {
}
}
break;
}
}
private PtpCommand getLargeThumbCommand(int objectId) {
return new PtpCommand(PtpCommand.GetLargeThumb).addParam(objectId);
}
public byte[] getLargeThumb(int objectId) {
PtpCommand cmd = sendCommand(getLargeThumbCommand(objectId));
if (cmd != null && cmd.isResponseOk())
return cmd.incomingData().data();
else
return null;
}
public void loadObjectInfos() {
Log.d(TAG, "load object infos");
if (!mIsPtpObjectsLoaded) {
for (PtpStorageInfo info : mPtpStorages.values()) {
getObjectHandles(info.storageId);
}
mIsPtpObjectsLoaded = true;
// sendPtpServiceEvent(PtpServiceEventType.ObjectInfosLoaded, null);
}
}
protected PtpCommand getPartialObjectCmd(PtpObjectInfo objectInfo,
int maxSize, File file) {
return getPartialObjectCmd(objectInfo, maxSize, file, null);
}
protected PtpCommand getPartialObjectCmd(
PtpObjectInfo objectInfo,
int maxSize,
File file,
PtpPartialObjectProccessor.PtpPartialObjectProgressListener progressListener) {
PtpPartialObjectProccessor processor = new PtpPartialObjectProccessor(
objectInfo, file);
processor.setProgressListener(progressListener);
return new PtpCommand(PtpCommand.GetPartialObject)
.addParam(objectInfo.objectId)
.addParam(0)
.addParam(maxSize)
.setFinalProcessor(processor);
}
public PtpCommand getPreviewImageCmd(
PtpObjectInfo objectInfo,
int maxSize,
File file,
PtpPartialObjectProccessor.PtpPartialObjectProgressListener progressListener) {
return sendCommand(getPreviewImage(objectInfo, maxSize, file, progressListener));
}
private PtpCommand getPreviewImage(
PtpObjectInfo objectInfo,
int maxSize,
File file,
PtpPartialObjectProccessor.PtpPartialObjectProgressListener progressListener) {
PtpGetPreviewImageProcessor processor = new PtpGetPreviewImageProcessor(objectInfo, file);
processor.setProgressListener(progressListener);
return new PtpCommand(PtpCommand.GetPreviewImage)
.addParam(objectInfo.objectId)
.addParam(1)
.addParam(maxSize)
.setFinalProcessor(processor);
}
private PtpCommand deleteObject(int objectId) {
return new PtpCommand(PtpCommand.DeleteObject)
.addParam(objectId);
}
public void deleteObjectCmd(ImageObjectHelper obj) {
if (obj != null && obj.objectInfo != null) {
PtpCommand cmd = sendCommand(deleteObject(obj.objectInfo.objectId));
if (cmd != null && cmd.isResponseOk()) {
PtpStorageInfo storage = mPtpStorages.get(obj.objectInfo.storageId);
if (storage != null)
storage.deleteObject(obj.objectInfo.objectId);
}
}
}
public void changeCameraMode() {
if (mIsPtpDeviceInitialized) {
PtpProperty property = getPtpProperty(PtpProperty.ExposureProgramMode);
if (property != null)
changeCameraMode(property.getIsWritable());
}
}
private void changeCameraModeCmd(boolean cameraMode) {
if (mIsPtpDeviceInitialized) {
int mode = cameraMode ? 0 : 1;
PtpCommand cmd = sendCommand(new PtpCommand(
PtpCommand.ChangeCameraMode).addParam(mode));
if (cmd != null && cmd.isResponseOk())
updateDevicePropDescCmd(PtpProperty.ExposureProgramMode);
}
}
public void changeCameraMode(final boolean cameraMode) {
new Thread(new Runnable() {
public void run() {
changeCameraModeCmd(cameraMode);
}
}).start();
}
private boolean mNeedReturnToLiveview = false;
private void checkReturnToLiveView() {
Log.i(TAG, "Check return to live view: " + mNeedReturnToLiveview);
if (mNeedReturnToLiveview) {
Log.i(TAG, "Need return to live view");
startLiveViewDisplay(true);
mNeedReturnToLiveview = false;
}
}
private void checkNeedReturnToLiveView(boolean captureToSdram) {
mNeedReturnToLiveview = false;
Log.i(TAG, "Check if we need to return to live view after capture");
PtpProperty property = getPtpProperty(PtpProperty.LiveViewStatus);
if (property != null) {
mNeedReturnToLiveview = (Integer) property.getValue() != 0;
Log.i(TAG, "Need to return to live view: " + mNeedReturnToLiveview);
if (mNeedReturnToLiveview) {
endLiveViewDisplay(true);
// only return to live view if it is set in preferences
mNeedReturnToLiveview = mLiveViewReturn;
}
}
}
public void changeAfAreaCmd(final int x, final int y) {
new Thread(new Runnable() {
public void run() {
PtpCommand cmd = sendCommand(new PtpCommand(
PtpCommand.ChangeAfArea).addParam(x).addParam(y));
if (cmd != null && cmd.isDataOk()) {
}
}
}).start();
}
public PtpLiveViewObject getLiveViewImage() {
PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.GetLiveViewImage));
if (cmd != null && cmd.isDataOk()) {
mLvo.setBuffer(cmd.incomingData());
return mLvo;
}
return null;
}
public void toggleInternalBracketing() {
PtpProperty property = getPtpProperty(PtpProperty.EnableBracketing);
if (property != null) {
if ((Integer)property.getValue() == 0) {
setDevicePropValueCmd(PtpProperty.EnableBracketing, 1);
property = getPtpProperty(PtpProperty.StillCaptureMode);
if (property != null) {
mInternalBracketingShootingMode = property.getValue();
setDevicePropValueCmd(PtpProperty.StillCaptureMode, 1);
}
property = getPtpProperty(PtpProperty.BurstNumber);
if (property != null) {
mInternalBracketingBurstNumber = property.getValue();
setDevicePropValueCmd(PtpProperty.BurstNumber, 3);
}
}
else {
setDevicePropValueCmd(PtpProperty.EnableBracketing, 0);
if (mInternalBracketingShootingMode != null) {
setDevicePropValueCmd(PtpProperty.StillCaptureMode, mInternalBracketingShootingMode);
mInternalBracketingShootingMode = null;
}
if (mInternalBracketingBurstNumber != null) {
setDevicePropValueCmd(PtpProperty.BurstNumber, mInternalBracketingBurstNumber);
mInternalBracketingBurstNumber = null;
}
}
}
}
private int mOldAFMode = 0;
private boolean mAfModeChanged = false;
private PtpCommand initiateCaptureCommand(boolean captureToSdram) {
return initiateCaptureCommand(captureToSdram, mAFBeforeCapture);
}
private PtpCommand initiateCaptureCommand(boolean captureToSdram, boolean performAf) {
PtpCommand cmd = null;
if (getIsCommandSupported(PtpCommand.InitiateCaptureRecInMedia)) {
cmd = new PtpCommand(PtpCommand.InitiateCaptureRecInMedia);
if (performAf)
cmd.addParam(0xfffffffe); // perform AF before capture
else
cmd.addParam(0xffffffff); // no AF before capture
if (captureToSdram)
cmd.addParam(0x0001);
else
cmd.addParam(0x0000);
} else {
// check if need AF before capture
cmd = new PtpCommand(PtpCommand.InitiateCapture);
if (captureToSdram) {
if (performAf) {
if (getIsCommandSupported(PtpCommand.AfAndCaptureRecInSdram))
cmd = new PtpCommand(PtpCommand.AfAndCaptureRecInSdram);
} else
if (getIsCommandSupported(PtpCommand.InitiateCaptureRecInSdram))
cmd = new PtpCommand(PtpCommand.InitiateCaptureRecInSdram)
.addParam(0xffffffff);
}
if (!performAf) {
PtpProperty property = getPtpProperty(PtpProperty.AfModeSelect);
if (property != null) {
Integer oldAfMode = (Integer) property.getValue();
if (oldAfMode != 4) {
setDevicePropValue(PtpProperty.AfModeSelect, 4, true);
mOldAFMode = oldAfMode;
mAfModeChanged = true;
}
}
}
}
return cmd;
}
public void initiateCaptureCmd() {
initiateCaptureCmd(true);
}
private boolean mIsInCapture = false;
private void initiateCapture(boolean checkNeedReturnToLV,
boolean captureToSdram, boolean performAf) {
if (checkNeedReturnToLV)
checkNeedReturnToLiveView(captureToSdram);
Log.d(TAG, "Initiate capture");
sendPtpDeviceEvent(PtpDeviceEvent.CaptureInitiated, null);
PtpCommand cmd = sendCommand(initiateCaptureCommand(captureToSdram, performAf));
if (cmd != null && cmd.isResponseOk()) {
boolean again = false;
do {
again = false;
cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady));
if (cmd != null) {
switch (cmd.getResponseCode()) {
case PtpResponse.OK:
Log.i(TAG, "Initiate capture ok");
break;
case PtpResponse.DeviceBusy:
Log.i(TAG, "Initiate capture busy");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
again = true;
break;
default:
Log.i(TAG,
"Initiate capture error: "
+ String.format("%04X",
cmd.getResponseCode()));
break;
}
}
} while (again);
mIsInCapture = true;
sendPtpDeviceEvent(PtpDeviceEvent.CaptureStart, null);
if (mAfModeChanged) {
setDevicePropValue(PtpProperty.AfModeSelect, mOldAFMode, true);
mAfModeChanged = false;
}
} else
sendPtpDeviceEvent(PtpDeviceEvent.BusyEnd, null);
}
public void initiateCaptureCmd(final boolean checkNeedReturnToLV) {
initiateCaptureCmd(checkNeedReturnToLV, mCaptureToSdram);
}
public void initiateCaptureCmd(final boolean checkNeedReturnToLV,
final boolean captureToSdram) {
sendPtpDeviceEvent(PtpDeviceEvent.BusyBegin, null);
new Thread(new Runnable() {
public void run() {
if (mIsCustomBracketingEnabled)
initCustomBracketing();
else
initiateCapture(checkNeedReturnToLV, captureToSdram, mAFBeforeCapture);
}
}).start();
}
private void captureComplete() {
if (mNeedBracketing)
nextBracketingImage();
if (mIsInFocusStacking)
nextFocusStackingImage();
if (!mNeedBracketing && !mTimelapseRunning && !mIsInFocusStacking) {
sendPtpDeviceEvent(PtpDeviceEvent.BusyEnd, null);
checkReturnToLiveView();
}
}
public void startAfDriveCmd() {
new Thread(new Runnable() {
public void run() {
sendCommand(new PtpCommand(PtpCommand.AfDrive));
}
}).start();
}
private void startEventListener() {
if (!mCommunicator.getIsNetworkCommunicator()) {
if (!mDeviceInfo.supportsOperation(PtpCommand.GetEvent)) {
PtpUsbCommunicator communicator = (PtpUsbCommunicator) mCommunicator;
if (communicator != null) {
Log.d(TAG, "----- Using interrupt endpoint for events");
mEventThread = new InterruptEventThread(
communicator.getUsbDeviceConnection(),
communicator.getInterrupEp());
mEventThread.start();
}
} else {
Log.d(TAG, "----- Using the GetEvent command for events");
mEventThread = new EventThread();
mEventThread.start();
}
}
}
private synchronized void processEvent(int eventCode, int eventParam) {
// Log.d(MainActivity.TAG, "+*+*+*+* event code: " +
// Integer.toHexString(eventCode) + " param: " +
// Integer.toHexString(eventParam));
switch (eventCode) {
case PtpEvent.CancelTransaction:
Log.d(TAG, "CancelTransaction: " + String.format("%#x", eventParam));
break;
case PtpEvent.ObjectAdded:
Log.d(TAG, "ObjectAdded: " + String.format("%#x", eventParam));
PtpObjectInfo info = getObjectInfo(eventParam);
sendPtpDeviceEvent(PtpDeviceEvent.ObjectAdded, info);
break;
case PtpEvent.StoreAdded:
Log.d(TAG, "StoreAdded: " + String.format("%#x", eventParam));
getStorageInfo(eventParam);
sendPtpDeviceEvent(PtpDeviceEvent.SdCardInserted, eventParam >> 16);
break;
case PtpEvent.StoreRemoved:
Log.d(TAG, "StoreRemoved: " + String.format("%#x", eventParam));
// remove the store
mPtpStorages.remove(eventParam);
sendPtpDeviceEvent(PtpDeviceEvent.SdCardRemoved, eventParam >> 16);
break;
case PtpEvent.DevicePropChanged:
Log.d(TAG, "DevicePropChanged: " + String.format("%#x", eventParam));
updateDevicePropDescCmd(eventParam);
// getDevicePropDescCommand(eventParam);
break;
case PtpEvent.DeviceInfoChanged:
Log.d(TAG, "DeviceInfoChanged: " + String.format("%#x", eventParam));
break;
case PtpEvent.RequestObjectTransfer:
Log.d(TAG,
"RequestObjectTransfer: "
+ String.format("%#x", eventParam));
break;
case PtpEvent.StoreFull:
Log.d(TAG, "StoreFull: " + String.format("%#x", eventParam));
break;
case PtpEvent.StorageInfoChanged:
Log.d(TAG,
"StorageInfoChanged: " + String.format("%#x", eventParam));
getStorageInfo(eventParam);
// execute when the capture was executed on camera
// mIsInImageAqusition = false;
// sendPtpServiceEvent(PtpServiceEventType.CaptureCompleteInSdcard,
// null);
break;
case PtpEvent.CaptureComplete:
Log.d(TAG, "CaptureComplete: " + String.format("%#x", eventParam));
mIsInCapture = false;
sendPtpDeviceEvent(PtpDeviceEvent.CaptureComplete, null);
captureComplete();
break;
case PtpEvent.ObjectAddedInSdram:
Log.d(TAG,
"ObjectAddedInSdram: " + String.format("%#x", eventParam));
sendPtpDeviceEvent(PtpDeviceEvent.ObjectAddedInSdram, null);
// mIsInImageAqusition = true;
// if (mEventThread != null)
// mEventThread.setPauseEventListener(true);
// sendPtpServiceEvent(PtpServiceEventType.GetObjectFromSdramStart,
// null);
if (mProductId == 0x0412)
getPictureFromSdram(0xFFFF0001, true);
else
getPictureFromSdram(eventParam, true);
break;
case PtpEvent.CaptureCompleteRecInSdram:
Log.d(TAG,
"CaptureCompleteRecInSdram: "
+ String.format("%#x", eventParam));
mIsInCapture = false;
sendPtpDeviceEvent(PtpDeviceEvent.CaptureCompleteInSdram, null);
captureComplete();
break;
case PtpEvent.PreviewImageAdded:
Log.d(TAG, "PreviewImageAdded: " + String.format("%#x", eventParam));
break;
}
}
private class EventThread extends ThreadBase {
public EventThread() {
mSleepTime = 100;
}
@Override
public void codeToExecute() {
// Log.d(TAG, "get DSLR events");
PtpCommand cmd = sendCommand(getEventCmd());
if (cmd != null) {
if (cmd.isDataOk()) {
cmd.incomingData().parse();
int numEvents = cmd.incomingData().nextU16();
int eventCode, eventParam;
for (int i = 1; i <= numEvents; i++) {
eventCode = cmd.incomingData().nextU16();
eventParam = cmd.incomingData().nextS32();
processEvent(eventCode, eventParam);
}
}
}
else
this.interrupt();
}
}
private class InterruptEventThread extends ThreadBase {
private UsbDeviceConnection mUsbDeviceConnection = null;
private UsbEndpoint mInterruptEp = null;
public InterruptEventThread(UsbDeviceConnection usbDeviceConnection,
UsbEndpoint interruptEp) {
mUsbDeviceConnection = usbDeviceConnection;
mInterruptEp = interruptEp;
mSleepTime = 400;
}
private void processInterrupPacket(byte[] data)
throws ExecutionException {
PtpBuffer buf = new PtpBuffer(data);
int eventCode = buf.getPacketCode();
buf.parse();
int eventParam = buf.nextS32();
Log.d(TAG,
"++=====++ New interrupt packet: " + buf.getPacketLength()
+ " type: " + buf.getPacketType() + " code:"
+ String.format("%#x", buf.getPacketCode()));
processEvent(eventCode, eventParam);
}
@Override
public void codeToExecute() {
PtpBuffer buf = new PtpBuffer();
byte[] tmpData = new byte[4096];
byte[] data = null;
boolean needMore = false;
int counter = 0, size = 0, bytesRead = 0;
try {
if (needMore) {
bytesRead = mUsbDeviceConnection.bulkTransfer(mInterruptEp,
tmpData, tmpData.length, 200);
if (bytesRead > 0) {
Log.d(TAG, "bytes read: " + bytesRead);
System.arraycopy(tmpData, 0, data, counter, bytesRead);
counter += bytesRead;
if (counter >= size) {
needMore = false;
processInterrupPacket(data);
}
}
} else {
bytesRead = mUsbDeviceConnection.bulkTransfer(mInterruptEp,
tmpData, tmpData.length, 200);
if (bytesRead > 0) {
Log.d(TAG, "bytes read: " + bytesRead);
buf.wrap(tmpData);
size = buf.getPacketLength();
Log.d(TAG, "packet size " + size);
data = new byte[size];
System.arraycopy(tmpData, 0, data, 0, bytesRead);
if (buf.getPacketLength() > bytesRead) {
needMore = true;
counter = bytesRead;
} else
processInterrupPacket(data);
}
}
} catch (ExecutionException e) {
this.interrupt();
}
}
}
public void enterLiveViewAtStart() {
new Thread(new Runnable() {
public void run() {
Log.i(TAG, "Entering live view at start");
Log.i(TAG, "Setting recording media to sdram");
setDevicePropValue(PtpProperty.RecordingMedia, 0x0001, true);
Log.i(TAG, "Starting live view");
startLiveViewDisplay(true);
}
}).start();
}
protected int startLiveView() {
setDevicePropValue(PtpProperty.RecordingMedia, 0x0001, true);
PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.StartLiveView));
if (cmd != null) {
boolean again = false;
do {
cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady));
if (cmd != null) {
switch (cmd.getResponseCode()) {
case PtpResponse.OK:
Log.i(TAG, "Live view start ok");
return PtpResponse.OK;
case PtpResponse.DeviceBusy:
Log.i(TAG, "Live view start busy");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
again = true;
break;
default:
Log.i(TAG, "Live view start error");
return 0;
}
}
} while (again);
} else
Log.i(TAG, "Live view start error");
return 0;
}
protected void startLiveViewDisplay(boolean notiftyUI) {
switch (startLiveView()) {
case PtpResponse.OK:
if (notiftyUI)
sendPtpDeviceEvent(PtpDeviceEvent.LiveviewStart);
break;
}
}
public void startLiveViewCmd() {
if (mIsPtpDeviceInitialized) {
new Thread(new Runnable() {
public void run() {
startLiveViewDisplay(true);
}
}).start();
}
}
protected int endLiveView() {
// it's a bit hard to stop so try it 3 times
Log.d(TAG, "Stop live view");
PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.EndLiveView));
if (cmd != null) {
Log.d(TAG, "Stop live view response " + cmd.isResponseOk());
if (cmd.isResponseOk())
return PtpResponse.OK;
boolean again = false;
do {
Log.d(TAG, "Stop live view deviceready");
cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady));
if (cmd != null) {
switch (cmd.getResponseCode()) {
case PtpResponse.OK:
Log.i(TAG, "Live view end ok");
setDevicePropValue(PtpProperty.RecordingMedia, 0x0000, true);
return PtpResponse.OK;
case PtpResponse.DeviceBusy:
Log.i(TAG, "Live view end busy");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
again = true;
break;
default:
Log.i(TAG, "Live view end error");
return 0;
}
}
} while (again);
} else {
Log.i(TAG, "Live view end error ");
}
return 0;
}
protected void endLiveViewDisplay(boolean notifyUI) {
// if (mLiveviewThread != null)
// mLiveviewThread.setIsLiveviewEnabled(false);
switch (endLiveView()) {
case PtpResponse.OK:
if (notifyUI) {
sendPtpDeviceEvent(PtpDeviceEvent.LiveviewStop);
sendPtpDeviceEvent(PtpDeviceEvent.MovieRecordingEnd);
mIsMovieRecordingStarted = false;
}
break;
}
}
public void endLiveViewCmd(final boolean notifyUI) {
if (mIsPtpDeviceInitialized) {
new Thread(new Runnable() {
public void run() {
endLiveViewDisplay(notifyUI);
}
}).start();
}
}
public void startMovieRecCmd() {
if (!mIsMovieRecordingStarted) {
PtpCommand cmd = sendCommand(new PtpCommand(
PtpCommand.StartMovieRecInCard));
if (cmd != null && cmd.isResponseOk()) {
mIsMovieRecordingStarted = true;
sendPtpDeviceEvent(PtpDeviceEvent.MovieRecordingStart, null);
}
}
}
public void stopMovieRecCmd() {
PtpCommand cmd = sendCommand(new PtpCommand(PtpCommand.EndMovieRec));
if (cmd != null && cmd.isResponseOk()) {
mIsMovieRecordingStarted = false;
sendPtpDeviceEvent(PtpDeviceEvent.MovieRecordingEnd, null);
}
}
public File getObjectSaveFile(String objectName, boolean copyFileName) {
File folder = new File(mSdramSavingLocation);
if (!folder.exists()) {
Log.d(TAG, "Make dir: " + folder.mkdir());
}
File f;
if (!copyFileName) {
int dotposition = objectName.lastIndexOf(".");
String ext = objectName.substring(dotposition + 1, objectName.length());
f = new File(folder, String.format("%s%04d.%s", mSdramPrefix,
mSdramPictureNumbering, ext));
setSdramPictureNumbering(mSdramPictureNumbering + 1);
}
else
f = new File(folder,objectName);
Log.d(TAG, "File name: " + f);
return f;
}
private void runMediaScanner(File file) {
Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(
"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
mediaScanIntent.setData(contentUri);
mPtpService.sendBroadcast(mediaScanIntent);
}
public void getObjectFromCamera(final ImageObjectHelper obj, PtpPartialObjectProccessor.PtpPartialObjectProgressListener listener) {
PtpPartialObjectProccessor.PtpPartialObjectProgressListener mListener = new PtpPartialObjectProccessor.PtpPartialObjectProgressListener() {
public void onProgress(int offset) {
Log.d(TAG, "Progress");
obj.progress = offset;
sendPtpDeviceEvent(
PtpDeviceEvent.GetObjectFromCameraProgress,
obj);
}
};
if (listener != null)
mListener = listener;
if (obj != null && obj.objectInfo != null) {
sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromCamera, obj);
obj.file = getObjectSaveFile(obj.objectInfo.filename, true);
int maxSize = 0x200000;
if (obj.objectInfo.objectCompressedSize < maxSize)
maxSize = (int) (obj.objectInfo.objectCompressedSize / 2);
PtpCommand cmd = sendCommand(getPartialObjectCmd(
obj.objectInfo,
maxSize,
obj.file,
mListener
));
if (cmd != null && cmd.isDataOk()) {
runMediaScanner(obj.file);
sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromCameraFinished,
obj);
}
}
}
private void getPictureFromSdram(int objectId, boolean fromSdram) {
if (mEventThread != null)
mEventThread.setIsThreadPaused(true);
try {
final ImageObjectHelper helper = new ImageObjectHelper();
helper.galleryItemType = ImageObjectHelper.PHONE_PICTURE;
PtpCommand cmd = sendCommand(getObjectInfoCmd(objectId));
if (cmd != null && cmd.isDataOk()) {
helper.objectInfo = new PtpObjectInfo(objectId,
cmd.incomingData());
helper.file = getObjectSaveFile(helper.objectInfo.filename, false);
sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromSdramInfo,
helper);
cmd = sendCommand(getThumbCmd(objectId));
if (cmd != null && cmd.isDataOk()) {
helper.saveThumb(cmd.incomingData(), fromSdram);
sendPtpDeviceEvent(PtpDeviceEvent.GetObjectFromSdramThumb,
helper);
int maxSize = 0x200000;
if (helper.objectInfo.objectCompressedSize < maxSize)
maxSize = (int) (helper.objectInfo.objectCompressedSize / 2);
cmd = sendCommand(getPartialObjectCmd(
helper.objectInfo,
maxSize,
helper.file,
new PtpPartialObjectProccessor.PtpPartialObjectProgressListener() {
public void onProgress(int offset) {
Log.d(TAG, "Progress");
helper.progress = offset;
sendPtpDeviceEvent(
PtpDeviceEvent.GetObjectFromSdramProgress,
helper);
}
}));
if (cmd != null && cmd.isDataOk()) {
// TODO : gps
// if (mPreferencesHelper.mAddGpsLocation) {
// addGpsLocation(helper.file);
// }
// else
if (mGpsInfoEnabled) {
GpsLocationHelper gpsHelper = mPtpService.getGpsLocationHelper();
gpsHelper.addGpsLocation(helper.file);
}
else {
runMediaScanner(helper.file);
sendPtpDeviceEvent(
PtpDeviceEvent.GetObjectFromSdramFinished,
helper);
}
}
}
}
} finally {
if (mEventThread != null) {
mEventThread.setIsThreadPaused(false);
}
}
}
private Object mCurrentEv = null;
private Object[] mEvValues;
public int mBracketingCount = 0;
public int mCurrentBracketing = 0;
public boolean mNeedBracketing = false;
public boolean getNeedBracketing() {
return mNeedBracketing;
}
public int getBracketingCount() {
return mBracketingCount;
}
public int getCurrentBracketing() {
return mCurrentBracketing;
}
private void initCustomBracketing() {
PtpProperty prop = getPtpProperty(PtpProperty.ExposureBiasCompensation);
// PtpProperty afProp = getPtpProperty(PtpProperty.AfModeSelect);
// if (afProp != null){
// mAfValue = afProp.getValue();
// }
// else
// mAfValue = null;
mCurrentBracketing = 0;
mBracketingCount = 0;
if (prop != null){
mCurrentEv = prop.getValue();
mEvValues = new Object[mBktCount];
final Vector<?> enums = prop.getEnumeration();
int currentEv = enums.indexOf(prop.getValue());
int evIndex = currentEv;
int evCounter = 0;
switch(mBktDirection) {
case 0: // negative
do {
mEvValues[evCounter] = enums.get(evIndex);
evCounter++;
evIndex -= mBktStep;
mBracketingCount++;
} while (evIndex >= 0 && evCounter < mBktCount);
break;
case 1: // positive
do {
mEvValues[evCounter] = enums.get(evIndex);
evCounter++;
evIndex += mBktStep;
mBracketingCount++;
} while (evIndex < enums.size() && evCounter < mBktCount);
break;
case 2: // both
mEvValues[evCounter] = enums.get(evIndex);
mBracketingCount = 1;
evCounter++;
int counter = 1;
do {
evIndex = counter * mBktStep;
if ((currentEv - evIndex) >= 0 && (currentEv + evIndex) <= enums.size()){
mEvValues[evCounter] = enums.get(currentEv + evIndex);
mEvValues[evCounter + 1] = enums.get(currentEv - evIndex);
mBracketingCount += 2;
}
counter++;
evCounter += 2;
} while (evCounter < mBktCount);
break;
}
mNeedBracketing = mBracketingCount > 0;
// set focus to manual
// mService.setDevicePropValue(PtpProperty.AfModeSelect, 0x0004, true);
nextBracketingImage();
}
}
private void nextBracketingImage() {
Log.d(TAG, "Custom bracketing image: " + mCurrentBracketing);
Log.d(TAG, "Custom bracketing focus first: " + mBktFocusFirst);
if (mCurrentBracketing < mBracketingCount) {
setDevicePropValue(PtpProperty.ExposureBiasCompensation, mEvValues[mCurrentBracketing], true);
if (mCurrentBracketing == 0)
initiateCapture(true, mCaptureToSdram, mBktFocusFirst);
else
initiateCapture(false, mCaptureToSdram, false);
//mService.sendCommandNew(mService.getShootCommand(mToSdram));
mCurrentBracketing++;
} else {
mNeedBracketing = false;
// if (mAfValue != null)
// mService.setDevicePropValue(PtpProperty.AfModeSelect, mAfValue, true);
if (mCurrentEv != null)
setDevicePropValue(PtpProperty.ExposureBiasCompensation, mCurrentEv, true);
}
}
private boolean mTimelapseRunning = false;
private int mTimelapseRemainingIterations = 10;
public boolean getIsTimelapseRunning(){
return mTimelapseRunning;
}
public int getTimelapseRemainingIterations(){
return mTimelapseRemainingIterations;
}
private Runnable timelapseTask = new Runnable() {
public void run() {
if (!mIsInCapture) {
Log.d(TAG, "Timelapse image capture");
if (mTimelapseRemainingIterations == mTimelapseIterations)
initiateCaptureCmd(true);
else
initiateCaptureCmd(false);
}
mTimelapseRemainingIterations -= 1;
sendPtpDeviceEvent(PtpDeviceEvent.TimelapseEvent, mTimelapseRemainingIterations);
if (mTimelapseRemainingIterations == 0){
stopTimelapseExecutor();
return;
}
Log.d(TAG, "----- Timelapse event ----- iterations remain: " + mTimelapseRemainingIterations);
}
};
ScheduledExecutorService mTimelapseScheduler;
public void startTimelapse(long interval, int frameCount){
Log.d(TAG, "---- Timelapse started ----");
mTimelapseRunning = true;
setTimelapseIterations(frameCount);
setTimelapseInterval(interval);
mTimelapseRemainingIterations = frameCount;
mTimelapseScheduler = Executors.newSingleThreadScheduledExecutor();
mTimelapseScheduler.scheduleAtFixedRate(timelapseTask, 100, mTimelapseInterval, TimeUnit.MILLISECONDS);
sendPtpDeviceEvent(PtpDeviceEvent.TimelapseStarted, null);
}
public void stopTimelapse() {
stopTimelapseExecutor();
if (!mIsInCapture && mNeedBracketing)
captureComplete();
}
private void stopTimelapseExecutor(){
Log.d(TAG, "---- Timelapse stoped ----");
stopExecutor(mTimelapseScheduler);
mTimelapseScheduler = null;
mTimelapseRunning = false;
sendPtpDeviceEvent(PtpDeviceEvent.TimelapseStoped, null);
}
private int mFocusImages = 5;
private int mFocusStep = 10;
private boolean mFocusDirectionDown = true;
private boolean mFocusFocusFirst = false;
private boolean mIsInFocusStacking = false;
private int mFocusStackingCurrentImage = 1;
private boolean mStopFocusStacking = false;
public int getFocusImages() {
return mFocusImages;
}
public void setFocusImages(int value) {
mFocusImages = value;
mPrefs
.edit()
.putString(PREF_KEY_FOCUS_IMAGES, Integer.toString(mFocusImages))
.commit();
}
public int getFocusStep(){
return mFocusStep;
}
public void setFocusStep(int value) {
mFocusStep = value;
mPrefs
.edit()
.putString(PREF_KEY_FOCUS_STEPS, Integer.toString(mFocusStep))
.commit();
}
public boolean getFocusDirectionDown(){
return mFocusDirectionDown;
}
public void setFocusDirectionDown(boolean value){
mFocusDirectionDown = value;
mPrefs
.edit()
.putBoolean(PREF_KEY_FOCUS_DIRECTION_DOWN, mFocusDirectionDown)
.commit();
}
public boolean getFocusFocusFirst(){
return mFocusFocusFirst;
}
public void setFocusFocusFirst(boolean value) {
mFocusFocusFirst = value;
mPrefs
.edit()
.putBoolean(PREF_KEY_FOCUS_FOCUS_FIRST, mFocusFocusFirst)
.commit();
}
public int getCurrentFocusStackingImage() {
return mFocusStackingCurrentImage;
}
public boolean getIsInFocusStacking() {
return mIsInFocusStacking;
}
public void stopFocusStacking() {
mStopFocusStacking = true;
}
public boolean getStopFocusStacking() {
return mStopFocusStacking;
}
public void startFocusStacking(int imagesToTake, int focusSteps, boolean directionDown, boolean focusFirst) {
setFocusImages(imagesToTake);
setFocusStep(focusSteps);
setFocusDirectionDown(directionDown);
setFocusFocusFirst(focusFirst);
mStopFocusStacking = false;
mIsInFocusStacking = true;
mFocusStackingCurrentImage = 1;
new Thread(new Runnable() {
public void run() {
sendPtpDeviceEvent(PtpDeviceEvent.BusyBegin, null);
nextFocusStackingImage();
}
}).start();
//nextFocusStackingImage();
}
private void nextFocusStackingImage() {
Log.d(TAG, "Focus stacking image: " + mFocusStackingCurrentImage);
if (mStopFocusStacking) {
mIsInFocusStacking = false;
mStopFocusStacking = false;
captureComplete();
return;
}
if (mFocusStackingCurrentImage == 1) {
initiateCapture(true, mCaptureToSdram, mFocusFocusFirst);
mFocusStackingCurrentImage++;
}
else {
if (mFocusStackingCurrentImage <= mFocusImages) {
// start live
startLiveView();
// get the afmode
Object afMode = null;
PtpProperty property = getPtpProperty(PtpProperty.AfModeSelect);
if (property != null)
afMode = property.getValue();
// set afmode to af-s
setDevicePropValue(PtpProperty.AfModeSelect, 0, true);
// move the focus
seekFocus(mFocusDirectionDown ? 1 : 2, mFocusStep);
// set back the afmode
setDevicePropValue(PtpProperty.AfModeSelect, afMode, true);
// stop live view
endLiveView();
initiateCapture(false, mCaptureToSdram, false);
mFocusStackingCurrentImage++;
} else
mIsInFocusStacking = false;
}
}
public void seekFocusMin() {
boolean repeat = true;
while(repeat) {
repeat = seekFocus(1, 32767) == PtpResponse.OK;
}
}
public void seekFocusMax() {
boolean repeat = true;
while(repeat) {
repeat = seekFocus(2, 32767) == PtpResponse.OK;
}
}
public int seekFocus(int direction, int amount) {
Log.i(TAG, "Seek focus direction: " + direction + " step: " + amount);
boolean again = false;
int retry = 0;
int res = 0;
do {
res = driveFocusToEnd(direction, amount);
switch(res) {
case PtpResponse.OK:
Log.i(TAG, "Seek focus OK");
again = false;
break;
case PtpResponse.MfDriveStepEnd:
retry += 1;
Log.i(TAG, "Seek focus MfDriveStepEnd retry: " + retry);
if (retry < 5)
again = true;
else
again = false;
break;
case PtpResponse.MfDriveStepInsufficiency:
Log.i(TAG, "Seek focus MfDriveStepInsufficiency retry: " + retry);
if (retry > 0) {
again = false;
}
else {
retry += 1;
again = true;
}
break;
default:
Log.i(TAG, "Seek focus other: " + res);
again = false;
break;
}
} while (again) ;
return res;
}
private int driveFocusToEnd(int direction, int step) {
boolean again = true;
PtpCommand cmd;
cmd = sendCommand(getMfDriveCommand(direction, step));
if (cmd != null) {
switch(cmd.getResponseCode()) {
case PtpResponse.OK:
// do a deviceready command
again = true;
while(again) {
cmd = sendCommand(new PtpCommand(PtpCommand.DeviceReady));
if (cmd != null) {
switch (cmd.getResponseCode()){
case PtpResponse.DeviceBusy:
// we do another deviceready
// do some pause
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
default:
// for all other cases assume there is an error
return cmd.getResponseCode();
}
}
else
return 0;
}
break;
default:
return cmd.getResponseCode();
}
}
else return 0;
return 0;
}
private PtpCommand getMfDriveCommand(int direction, int amount) {
return new PtpCommand(PtpCommand.MfDrive)
.addParam(direction)
.addParam(amount);
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
public class MainActivity extends ActivityBase implements IDslrActivity {
private static final String TAG = "MainActivity";
private boolean mCheckForUsb = false;
private List<WeakReference<Fragment>> mFragments = new ArrayList<WeakReference<Fragment>>();
private MenuItem mMainMenuItem;
private MainMenuProvider mMainMenuProvider;
private BottomFragment mBottomFragment;
private RightFragment mRightFragment;
private LeftFragment mLeftFragment;
private LiveViewFragment mLiveViewFragment;
private RightFragmentLv mRightFragmentLv;
private AboutFragment mAboutFragment;
private ProgressFragment mProgressFragment;
private DslrFragmentBase mLeft, mRight, mBottom, mCenter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_main);
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (mPrefs.getBoolean(PtpDevice.PREF_KEY_GENERAL_SCREEN_ON, true))
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mMainMenuProvider = new MainMenuProvider(this);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayUseLogoEnabled(true);
mBottomFragment = new BottomFragment();
mRightFragment = new RightFragment();
mLeftFragment = new LeftFragment();
mLiveViewFragment = new LiveViewFragment();
mRightFragmentLv = new RightFragmentLv();
mAboutFragment = new AboutFragment();
mProgressFragment = new ProgressFragment();
mBottom = mBottomFragment;
mLeft = mLeftFragment;
mRight = mRightFragment;
mCenter = mAboutFragment;
getFragmentManager().beginTransaction()
.replace(R.id.center_layout, mCenter)
.commit();
}
private void toggleKeepScreenOn(){
if (getPtpDevice().getGeneralScreenOn())
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "onCreateOptionsMenu");
getMenuInflater().inflate(R.menu.activity_main, menu);
mMainMenuItem = menu.findItem(R.id.menu_action_test);
mMainMenuItem.setActionProvider(mMainMenuProvider);
if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized())
mMainMenuItem.setVisible(true);
else
mMainMenuItem.setVisible(false);
return true;
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
protected void onResume() {
Log.d(TAG, "onResume");
checkUsbIntent(getIntent());
doBindService(PtpService.class);
super.onResume();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause");
unbindPtpService(true, true);
setPtpDevice(null);
super.onPause();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
protected void onNewIntent(Intent intent) {
Log.d(TAG, "onNewIntent");
checkUsbIntent(intent);
super.onNewIntent(intent);
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
Log.d(TAG, "onAttachFragment");
try {
if (fragment instanceof DslrFragmentBase)
Log.d(TAG, "This is DslrFramentBase");
DslrFragmentBase dslrFragment = (DslrFragmentBase)fragment;
if (dslrFragment != null) {
if (!mFragments.contains(fragment)) {
Log.d(TAG, "attach new fragment");
mFragments.add(new WeakReference<Fragment>(fragment));
}
}
} catch (ClassCastException e) {
Log.d(TAG, "Not DSLR fragment");
}
}
private void checkUsbIntent(Intent intent) {
if (intent != null ) {
Bundle extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("UsbAttached"))
mCheckForUsb = true;
}
}
}
PtpDevice.OnPtpDeviceEventListener mPtpDeviceEventListener = new PtpDevice.OnPtpDeviceEventListener() {
public void sendEvent(final PtpDeviceEvent event, final Object data) {
Log.d(TAG, "OnPtpDeviceEventListener");
runOnUiThread(new Runnable() {
public void run() {
switch(event) {
case PtpDeviceInitialized:
initDisplay();
break;
case PtpDeviceStoped:
removeDisplay();
break;
case PrefsLoaded:
toggleKeepScreenOn();
break;
case LiveviewStart:
//if (!mLiveViewFragment.getIsAttached())
getFragmentManager().beginTransaction()
//.remove(mCenter)
.replace(R.id.center_layout, mLiveViewFragment)
.commit();
mCenter = mLiveViewFragment;
break;
case LiveviewStop:
if (!mProgressFragment.getIsAttached()) {
getFragmentManager().beginTransaction()
//.remove(mCenter)
.replace(R.id.center_layout, mAboutFragment)
.commit();
mCenter = mAboutFragment;
}
toggleFullscreen(false);
toggleLvLayout(false);
break;
case SdCardInfoUpdated:
case SdCardInserted:
case SdCardRemoved:
break;
case CaptureStart:
break;
case CaptureComplete:
break;
case BusyBegin:
if (!mProgressFragment.getIsAttached()) {
getFragmentManager()
.beginTransaction()
.replace(R.id.center_layout, mProgressFragment)
.commit();
mCenter = mProgressFragment;
}
break;
case BusyEnd:
getFragmentManager()
.beginTransaction()
.replace(R.id.center_layout, mAboutFragment)
.commit();
mCenter = mAboutFragment;
break;
case ObjectAdded:
break;
case GetObjectFromSdramInfo:
break;
case GetObjectFromSdramThumb:
break;
case GetObjectFromSdramProgress:
break;
case GetObjectFromCameraProgress:
break;
case GetObjectFromSdramFinished:
break;
case GetObjectFromCameraFinished:
break;
}
ptpDeviceEvent(event, data);
}
});
}
};
PtpDevice.OnPtpPropertyChangedListener mPtpPropertyChangedListener = new PtpDevice.OnPtpPropertyChangedListener() {
public void sendPtpPropertyChanged(final PtpProperty property) {
runOnUiThread(new Runnable() {
public void run() {
ptpPropertyChanged(property);
}
});
}
};
SharedPreferences.OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences,
final String key) {
runOnUiThread(new Runnable() {
public void run() {
ptpDeviceSharedPrefs(sharedPreferences, key);
if (key.equals(PtpDevice.PREF_KEY_GENERAL_SCREEN_ON))
toggleKeepScreenOn();
}
});
}
};
private void removeDisplay() {
runOnUiThread(new Runnable() {
public void run() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (mBottom != null)
ft.remove(mBottom);
if (mRight != null)
ft.remove(mRight);
if (mLeft != null)
ft.remove(mLeft);
if (mCenter != null && mCenter != mAboutFragment)
ft.remove(mCenter);
ft.commit();
mMainMenuItem.setVisible(false);
}
});
}
private void initDisplay() {
Log.d(TAG, "initDisplay");
DslrHelper.getInstance().loadDslrProperties(this, mPtpDevice, mPtpDevice.getVendorId() , mPtpDevice.getProductId());
if (mPtpDevice.getIsLiveViewEnabled())
mCenter = mLiveViewFragment;
else
mCenter = mAboutFragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (mBottom != null && !mBottom.getIsAttached()) //!mBottom.isAdded())
ft.replace(R.id.bottom_layout, mBottom);
if (!mIsFullScreen) {
if (mRight != null && !mRight.getIsAttached()) // !mRight.isAdded())
ft.replace(R.id.right_layout, mRight);
if (mLeft != null && !mLeft.isAdded())
ft.replace(R.id.left_layout, mLeft);
}
if (mCenter != null && !mCenter.getIsAttached()) // !mCenter.isAdded())
ft.replace(R.id.center_layout, mCenter);
ft.commit();
runOnUiThread(new Runnable() {
public void run() {
if (mMainMenuItem != null) {
mMainMenuItem.setVisible(true);
mMainMenuProvider.initDisplay();
}
}
});
}
private void ptpDeviceEvent(PtpDeviceEvent event, Object data) {
for (WeakReference<Fragment> wr : mFragments) {
Fragment fragment = wr.get();
if (fragment != null) {
try{
DslrFragmentBase fr = (DslrFragmentBase)fragment;
if (fr.getIsAttached())
fr.ptpDeviceEvent(event, data);
}
catch (ClassCastException e) {
}
}
}
mMainMenuProvider.ptpDeviceEvent(event, data);
}
private void ptpPropertyChanged(PtpProperty property) {
for (WeakReference<Fragment> wr : mFragments) {
Fragment fragment = wr.get();
if (fragment != null) {
try{
DslrFragmentBase fr = (DslrFragmentBase)fragment;
if (fr.getIsAttached())
fr.ptpPropertyChanged(property);
}
catch (ClassCastException e) {
}
}
}
mMainMenuProvider.ptpPropertyChanged(property);
}
private void ptpDeviceSharedPrefs(SharedPreferences prefs, String key) {
for (WeakReference<Fragment> wr : mFragments) {
Fragment fragment = wr.get();
if (fragment != null) {
try{
DslrFragmentBase fr = (DslrFragmentBase)fragment;
if (fr.getIsAttached())
fr.sharedPrefsChanged(prefs, key);
}
catch (ClassCastException e) {
}
}
}
}
private void setPtpDevice(PtpDevice ptpDevice) {
Log.d(TAG, "setPtpDevice");
// remove listener of the old PtpDevice
if (mPtpDevice != null) {
mPtpDevice.removeOnPtpDeviceEventListener();
mPtpDevice.removePtpPropertyChangedListener();
mPtpDevice.removeSharedPreferenceChangeListener();
// mPtpDevice.removeLiveViewObjectListener();
}
mPtpDevice = ptpDevice;
if (mPtpDevice != null) {
// if (mPtpDevice.getIsPtpDeviceInitialized()) {
// initDisplay();
// }
mPtpDevice.setOnPtpDeviceEventListener(mPtpDeviceEventListener);
mPtpDevice.setOnPtpPropertyChangedListener(mPtpPropertyChangedListener);
mPtpDevice.setOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);
// mPtpDevice.setLiveviewObjectListener(mLiveViewListener);
}
}
// private boolean mIsBound = false;
private PtpService mPtpService = null;
private PtpDevice mPtpDevice = null;
public PtpDevice getPtpDevice() {
return mPtpDevice;
}
private void unbindPtpService(boolean stopService, boolean keepAliveIfUsbConnected) {
if (stopService && mPtpService != null)
mPtpService.stopPtpService(keepAliveIfUsbConnected);
doUnbindService(PtpService.class);
}
@Override
protected void serviceConnected(Class<?> serviceClass, ComponentName name, ServiceBase service) {
Log.d(TAG, "onServiceConnected");
if (serviceClass.equals(PtpService.class)) {
Log.d(TAG, "PtpService connected");
mPtpService = (PtpService) service;
setPtpDevice(mPtpService.getPtpDevice());
startService(new Intent(MainActivity.this, PtpService.class));
if (mCheckForUsb)
mPtpService.searchForUsbCamera();
if (mPtpService.getIsUsbDeviceInitialized() && mPtpDevice.getIsPtpDeviceInitialized())
initDisplay();
}
}
@Override
protected void serviceDisconnected(Class<?> serviceClass, ComponentName name) {
Log.d(TAG, "onServiceDisconnected " + name.getClassName());
if (serviceClass.equals(PtpService.class)) {
Log.d(TAG, "PtpService disconnected");
mPtpService = null;
}
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId()) {
case R.id.menu_settings:
getFragmentManager().beginTransaction()
.replace(R.id.center_layout, new SettingsFragment())
.addToBackStack("prefs")
.commit();
return true;
case R.id.menu_search_usb:
if (!mPtpService.getIsUsbDeviceInitialized())
mPtpService.searchForUsbCamera();
return true;
case R.id.menu_close_usb:
if (mPtpService.getIsUsbDeviceInitialized())
mPtpService.closeUsbConnection();
return true;
case R.id.menu_action_image_browse:
Intent ipIntent = new Intent(this, DslrImageBrowserActivity.class);
ipIntent.setAction(Intent.ACTION_VIEW);
ipIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(ipIntent);
return true;
default:
return true;
}
}
private boolean mIsFullScreen = false;
public void toggleFullscreen(boolean enable) {
if (enable != mIsFullScreen) {
if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()) {
if (!enable) {
getActionBar().show();
getFragmentManager().beginTransaction()
.replace(R.id.right_layout, mRight)
.replace(R.id.left_layout, mLeft)
.commit();
} else {
getActionBar().hide();
getFragmentManager().beginTransaction()
.remove(mRight)
.remove(mLeft)
.commit();
}
mIsFullScreen = enable;
}
}
}
public void toggleFullScreen() {
toggleFullscreen(!mIsFullScreen);
}
public boolean getIsFullScreen() {
return mIsFullScreen;
}
private boolean mIsLvLayoutEnabled = false;
public boolean getIsLvLayoutEnabled() {
return mIsLvLayoutEnabled;
}
public void toggleLvLayout() {
toggleLvLayout(!mIsLvLayoutEnabled);
}
public void toggleLvLayout(boolean showLvLayout) {
if (showLvLayout) {
if (mRight != mRightFragmentLv) {
mRight = mRightFragmentLv;
getFragmentManager().beginTransaction()
.replace(R.id.right_layout, mRight)
.commit();
}
mIsLvLayoutEnabled = true;
} else {
if (mRight != mRightFragment) {
mRight = mRightFragment;
getFragmentManager().beginTransaction()
.replace(R.id.right_layout, mRight)
.commit();
}
mIsLvLayoutEnabled = false;
}
}
public void zoomLiveView(boolean up){
if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()){
// check if liveview is enabled
PtpProperty lvStatus = mPtpDevice.getPtpProperty(PtpProperty.LiveViewStatus);
if (lvStatus != null && (Integer)lvStatus.getValue() == 1){
// get the zoom factor
PtpProperty zoom = mPtpDevice.getPtpProperty(PtpProperty.LiveViewImageZoomRatio);
if (zoom != null){
int zValue = (Integer)zoom.getValue();
if (up){
if (zValue < 5)
mPtpDevice.setDevicePropValueCmd(PtpProperty.LiveViewImageZoomRatio, zValue + 1);
}
else {
if (zValue > 0)
mPtpDevice.setDevicePropValueCmd(PtpProperty.LiveViewImageZoomRatio, zValue - 1);
}
}
}
}
}
@Override
protected void processArduinoButtons(EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons) {
for (ArduinoButtonEnum button : releasedButtons) {
switch (button) {
case Button0:
if (!button.getIsLongPress())
mPtpDevice.initiateCaptureCmd();
else
mPtpDevice.setCaptureToSdram(!mPtpDevice.getCaptureToSdram());
break;
case Button4:
generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK,0));
break;
case Button5:
generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER,0));
break;
case Button6:
generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT,0));
break;
case Button7:
generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT,0));
break;
case Button8:
generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP,0));
break;
case Button9:
generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN,0));
break;
}
Log.d(TAG, "Released button: " + button.toString() + " is long press: " + button.getIsLongPress());
}
for (ArduinoButtonEnum button : pressedButtons) {
switch(button){
case Button4:
generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
break;
case Button5:
generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
break;
case Button6:
generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
break;
case Button7:
generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
break;
case Button8:
generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP));
break;
case Button9:
generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN));
break;
}
Log.d(TAG, "Pressed button: " + button.toString());
}
}
}
| Java |
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package com.dslr.dashboard;
public class PtpDeviceInfo {
private int mStandardVersion;
private int mVendorExtensionId;
private int mVendorExtensionVersion;
private String mVendorExtensionDesc;
private int mFunctionalMode; // may change;
private int mOperationsSupported []; // 10.2
private int mEventsSupported []; // 12.5
private int mPropertiesSupported []; // 13.3.5
private int mCaptureFormats []; // 6
private int mImageFormats []; // 6
private String mManufacturer;
private String mModel;
private String mDeviceVersion;
private String mSerialNumber;
private boolean mIsInitialized = false;
public PtpDeviceInfo () {
mIsInitialized = false;
}
public PtpDeviceInfo(PtpBuffer data) {
parse(data);
}
public int getStandardVersion() {
return mStandardVersion;
}
public int getVendorExtensionId() {
return mVendorExtensionId;
}
public int getVendorExtensionVersion() {
return mVendorExtensionVersion;
}
public String getVendorExtensionDesc() {
return mVendorExtensionDesc;
}
public int getFunctionalMode() {
return mFunctionalMode;
}
public int[] getOperationsSupported() {
return mOperationsSupported;
}
public int[] getEventsSupported() {
return mEventsSupported;
}
public int[] getPropertiesSupported() {
return mPropertiesSupported;
}
public int[] getCaptureFormats() {
return mCaptureFormats;
}
public int[] getImageFormats() {
return mImageFormats;
}
public String getManufacturer(){
return mManufacturer;
}
public String getModel() {
return mModel;
}
public String getDeviceVersion(){
return mDeviceVersion;
}
public String getSerialNumber(){
return mSerialNumber;
}
public boolean getIsInitialized() {
return mIsInitialized;
}
private boolean supports (int supported [], int code) {
for (int i = 0; i < supported.length; i++) {
if (code == supported [i])
return true;
}
return false;
}
/** Returns true iff the device supports this operation */
public boolean supportsOperation (int opCode) {
return supports (mOperationsSupported, opCode);
}
/** Returns true iff the device supports this event */
public boolean supportsEvent (int eventCode) {
return supports (mEventsSupported, eventCode);
}
/** Returns true iff the device supports this property */
public boolean supportsProperty (int propCode) {
return supports (mPropertiesSupported, propCode);
}
/** Returns true iff the device supports this capture format */
public boolean supportsCaptureFormat (int formatCode) {
return supports (mCaptureFormats, formatCode);
}
/** Returns true iff the device supports this image format */
public boolean supportsImageFormat (int formatCode) {
return supports (mImageFormats, formatCode);
}
public void parse (PtpBuffer data) {
data.parse();
mStandardVersion = data.nextU16 ();
mVendorExtensionId = /* unsigned */ data.nextS32 ();
mVendorExtensionVersion = data.nextU16 ();
mVendorExtensionDesc = data.nextString ();
mFunctionalMode = data.nextU16 ();
mOperationsSupported = data.nextU16Array ();
mEventsSupported = data.nextU16Array ();
mPropertiesSupported = data.nextU16Array ();
mCaptureFormats = data. nextU16Array ();
mImageFormats = data.nextU16Array ();
mManufacturer = data.nextString ();
mModel = data.nextString ();
mDeviceVersion = data.nextString ();
mSerialNumber = data.nextString ();
mIsInitialized = true;
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
public enum BitmapManager {
INSTANCE;
private final String TAG = "ThumbLoader";
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void clearCach(){
cache.clear();
imageViews.clear();
}
public void queueJob(final String url, final ImageView imageView) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
Bitmap bmp = (Bitmap)msg.obj;
if (bmp != null) {
imageView.setImageBitmap(bmp);
cache.put(url, new SoftReference<Bitmap>(bmp));
} else {
imageView.setImageBitmap(placeholder);
}
}
}
};
pool.submit(new Runnable() {
public void run() {
final Bitmap bmp = downloadBitmap(url);
Message message = Message.obtain();
message.obj = bmp;
//Log.d(TAG, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView) {
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageViews.put(imageView, url);
imageView.setImageBitmap(placeholder);
queueJob(url, imageView);
}
}
private File getThumbFilePath( String fileName, String ext){
File file = new File(fileName);
File f = new File(file.getParent() + "/.thumb");
if (!f.exists())
f.mkdir();
String fname = file.getName();
if (!ext.isEmpty())
return new File(f, fname + "." + ext);
else
return new File(f, fname);
}
private Bitmap downloadBitmap(String url) {
Log.d(TAG, "downloadBitmap: " + url);
String thumbPath = "";
Bitmap bitmap = null;
if (url.contains(".dslrthumbs"))
thumbPath = url;
else {
File thumbFile = getThumbFilePath(url, "png");
if (thumbFile.exists())
thumbPath = thumbFile.getAbsolutePath();
else{
thumbFile = getThumbFilePath(url, "jpg");
if (thumbFile.exists())
thumbPath = thumbFile.getAbsolutePath();
}
}
if (!thumbPath.equals(""))
{
final int IMAGE_MAX_SIZE = 30000; // 1.2MP
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap tmp = BitmapFactory.decodeFile(thumbPath, options);
int scale = 1;
while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
scale++;
}
tmp = null;
if (scale > 1) {
scale--;
options = new BitmapFactory.Options();
options.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(thumbPath, options);
}
else
bitmap = BitmapFactory.decodeFile(thumbPath);
}
return bitmap;
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ProgressFragment extends DslrFragmentBase {
private static final String TAG = "ProgressFragment";
private TextView mProgressStatusMessage, mProgressFilename, mProgressBracketing, mProgressTimelapse, mProgressFocusStacking;
private ProgressBar mProgressDownload;
private Button mProgressStopTimelapse, mProgressStopFocusStacking;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_progress, container, false);
mProgressStatusMessage = (TextView)view.findViewById(R.id.progress_status_msg);
mProgressFilename = (TextView)view.findViewById(R.id.progress_filename);
mProgressDownload = (ProgressBar)view.findViewById(R.id.progress_download);
mProgressBracketing = (TextView)view.findViewById(R.id.progress_custombracketing);
mProgressTimelapse = (TextView)view.findViewById(R.id.progress_timelapse);
mProgressStopTimelapse = (Button)view.findViewById(R.id.progress_stop_timelapse);
mProgressFocusStacking = (TextView)view.findViewById(R.id.progress_focusstacking);
mProgressStopFocusStacking = (Button)view.findViewById(R.id.progress_stop_focusstacking);
mProgressStopTimelapse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getPtpDevice().stopTimelapse();
mProgressStopTimelapse.setVisibility(View.GONE);
}
});
mProgressStopFocusStacking.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getPtpDevice().stopFocusStacking();
mProgressStopFocusStacking.setVisibility(View.GONE);
}
});
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "onAttach");
}
@Override
public void onStart() {
Log.d(TAG, "onStart");
super.onStart();
}
@Override
public void onResume() {
Log.d(TAG, "onResume");
super.onResume();
}
@Override
public void onPause() {
Log.d(TAG, "onPause");
super.onPause();
}
@Override
public void onStop() {
Log.d(TAG, "onStop");
super.onStop();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
@Override
public void onDetach() {
Log.d(TAG, "onDetach");
super.onDetach();
}
@Override
protected void internalInitFragment() {
// TODO Auto-generated method stub
}
@Override
protected void internalPtpPropertyChanged(PtpProperty property) {
// TODO Auto-generated method stub
}
@Override
protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) {
switch (event) {
case BusyBegin:
mProgressStatusMessage.setText("Camera operation start");
break;
case BusyEnd:
mProgressBracketing.setVisibility(View.GONE);
mProgressTimelapse.setVisibility(View.GONE);
mProgressStopTimelapse.setVisibility(View.GONE);
mProgressFocusStacking.setVisibility(View.GONE);
mProgressStopFocusStacking.setVisibility(View.GONE);
mProgressDownload.setVisibility(View.GONE);
break;
case CaptureStart:
case CaptureInitiated:
mProgressStatusMessage.setText("Capture start");
if (getPtpDevice().getNeedBracketing()) {
mProgressBracketing.setVisibility(View.VISIBLE);
mProgressBracketing.setText(String.format("Custom bracketing image %d of %d", getPtpDevice().getCurrentBracketing() + 1, getPtpDevice().getBracketingCount()));
}
else
mProgressBracketing.setVisibility(View.GONE);
if (getPtpDevice().getIsTimelapseRunning()) {
mProgressTimelapse.setVisibility(View.VISIBLE);
mProgressTimelapse.setText(String.format("Timelapse image %d of %d", getPtpDevice().getTimelapseIterations() - getPtpDevice().getTimelapseRemainingIterations() , getPtpDevice().getTimelapseIterations()));
mProgressStopTimelapse.setVisibility(View.VISIBLE);
}
else {
mProgressTimelapse.setVisibility(View.GONE);
mProgressStopTimelapse.setVisibility(View.GONE);
}
if (getPtpDevice().getIsInFocusStacking()) {
mProgressFocusStacking.setVisibility(View.VISIBLE);
mProgressFocusStacking.setText(String.format("Focus stacking image %d of %d", getPtpDevice().getCurrentFocusStackingImage(), getPtpDevice().getFocusImages()));
if (!getPtpDevice().getStopFocusStacking())
mProgressStopFocusStacking.setVisibility(View.VISIBLE);
}
else {
mProgressFocusStacking.setVisibility(View.GONE);
mProgressStopFocusStacking.setVisibility(View.GONE);
}
// mProgressMessage1.setText("Image capture started");
break;
case CaptureComplete:
mProgressStatusMessage.setText("Capture complete");
// mProgressMessage1.setText("Image capture finished");
break;
case ObjectAdded:
mProgressStatusMessage.setText("Object added");
mProgressDownload.setVisibility(View.GONE);
if (data != null) {
PtpObjectInfo obj = (PtpObjectInfo)data;
mProgressFilename.setText(obj.filename);
}
break;
case GetObjectFromSdramInfo:
mProgressStatusMessage.setText("Got image info");
if (data != null) {
ImageObjectHelper obj = (ImageObjectHelper)data;
if (obj.galleryItemType == ImageObjectHelper.PHONE_PICTURE) {
mProgressFilename.setText(obj.file.getName());
mProgressDownload.setVisibility(View.VISIBLE);
mProgressDownload.setProgress(0);
mProgressDownload.setMax(obj.objectInfo.objectCompressedSize);
}
else {
mProgressFilename.setText(obj.objectInfo.filename);
}
}
break;
case GetObjectFromSdramThumb:
mProgressStatusMessage.setText("Got image thumb");
// mProgressMessage1.setText("Got image thumb");
break;
case GetObjectFromSdramProgress:
mProgressStatusMessage.setText("Downloading image");
if (data != null) {
ImageObjectHelper obj = (ImageObjectHelper)data;
mProgressDownload.setProgress(obj.progress);
}
break;
case GetObjectFromSdramFinished:
mProgressStatusMessage.setText("Image transfered from Camera SDRAM");
mProgressDownload.setVisibility(View.GONE);
break;
}
}
@Override
protected void internalSharedPrefsChanged(SharedPreferences prefs,
String key) {
// TODO Auto-generated method stub
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
public interface IPtpCommandFinalProcessor {
public boolean doFinalProcessing(PtpCommand cmd);
}
| Java |
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
package com.dslr.dashboard;
import java.util.Vector;
public class PtpProperty {
int mPropertyCode;
int mDataType;
boolean mWritable;
Object mFactoryDefault;
Object mCurrentValue;
int mFormType;
Object mConstraints;
public PtpProperty () { }
public void parse (PtpBuffer data)
{
data.parse ();
// per 13.3.3, tables 23, 24, 25
mPropertyCode = data.nextU16 ();
mDataType = data.nextU16 ();
mWritable = data.nextU8 () != 0;
// FIXME use factories, as vendor hooks
mFactoryDefault = PtpPropertyValue.get (mDataType, data);
mCurrentValue = PtpPropertyValue.get (mDataType, data);
mFormType = data.nextU8 ();
switch (mFormType) {
case 0: // no more
break;
case 1: // range: min, max, step
mConstraints = new PtpRange (mDataType, data);
break;
case 2: // enumeration: n, value1, ... valueN
mConstraints = parseEnumeration (data);
break;
default:
System.err.println ("ILLEGAL prop desc form, " + mFormType);
mFormType = 0;
break;
}
}
public int getPropertyCode(){
return mPropertyCode;
}
public int getDataType(){
return mDataType;
}
/** Returns true if the property is writable */
public boolean getIsWritable ()
{ return mWritable; }
/** Returns the current value (treat as immutable!) */
public Object getValue ()
{ return mCurrentValue; }
/** Returns the factory default value (treat as immutable!) */
public Object getDefault ()
{ return mFactoryDefault; }
public int getFormType() {
return mFormType;
}
// code values, per 13.3.5 table 26
public static final int BatteryLevel = 0x5001;
public static final int FunctionalMode = 0x5002;
public static final int ImageSize = 0x5003;
public static final int CompressionSetting = 0x5004;
public static final int WhiteBalance = 0x5005;
public static final int RGBGain = 0x5006;
public static final int FStop = 0x5007;
public static final int FocalLength = 0x5008;
public static final int FocusDistance = 0x5009;
public static final int FocusMode = 0x500a;
public static final int ExposureMeteringMode = 0x500b;
public static final int FlashMode = 0x500c;
public static final int ExposureTime = 0x500d;
public static final int ExposureProgramMode = 0x500e;
public static final int ExposureIndex = 0x500f;
public static final int ExposureBiasCompensation = 0x5010;
public static final int DateTime = 0x5011;
public static final int CaptureDelay = 0x5012;
public static final int StillCaptureMode = 0x5013;
public static final int Contrast = 0x5014;
public static final int Sharpness = 0x5015;
public static final int DigitalZoom = 0x5016;
public static final int EffectMode = 0x5017;
public static final int BurstNumber = 0x5018;
public static final int BurstInterval = 0x5019;
public static final int TimelapseNumber = 0x501a;
public static final int TimelapseInterval = 0x501b;
public static final int FocusMeteringMode = 0x501c;
public static final int UploadURL = 0x501d;
public static final int Artist = 0x501e;
public static final int CopyrightInfo = 0x501f;
public static final int WbTuneAuto = 0xd017;
public static final int WbTuneIncandescent = 0xd018;
public static final int WbTuneFluorescent = 0xd019;
public static final int WbTuneSunny = 0xd01a;
public static final int WbTuneFlash = 0xd01b;
public static final int WbTuneCloudy = 0xd01c;
public static final int WbTuneShade = 0xd01d;
public static final int WbPresetDataNo = 0xd01f;
public static final int WbPresetDataValue0 = 0xd025;
public static final int WbPresetDataValue1 = 0xd026;
public static final int ColorSpace = 0xd032;
public static final int VideoMode = 0xd036;
public static final int ResetCustomSetting = 0xd045;
public static final int IsoAutocontrol = 0xd054;
public static final int ExposureEvStep = 0xd056;
public static final int AfAtLiveView = 0xd05d;
public static final int AeLockRelease = 0xd05e;
public static final int AeAfLockSetting = 0xd05f;
public static final int AfModeAtLiveView = 0xd061;
public static final int AutoMeterOffDelay = 0xd062;
public static final int SelfTimerDelay = 0xd063;
public static final int LcdPowerOff = 0xd064;
public static final int ImageConfirmTimeAfterPhoto = 0xd065;
public static final int AutoOffTime = 0xd066;
public static final int ExposureDelay = 0xd06a;
public static final int NoiseReduction = 0xd06b;
public static final int NumberingMode = 0xd06c;
public static final int NoiseReductionHiIso = 0xd070;
public static final int FlashSyncSpeed = 0xd074;
public static final int FlashSlowSpeedLimit = 0xd075;
public static final int BracketingType = 0xd078;
public static final int FunctionButton = 0xd084;
public static final int CommandDialRotation = 0xd085;
public static final int EnableShutter = 0xd08a;
public static final int CommentString = 0xd090;
public static final int Enablecomment = 0xd091;
public static final int OrientationSensorMode = 0xd092;
public static final int MovieRecordScreenSize = 0xd0a0;
public static final int MovieRecordWithVoice = 0xd0a1;
public static final int MovieRecordMicrophoneLevel = 0xd0a2;
public static final int MovieRecProhibitionCondition = 0xd0a4;
public static final int LiveViewScreenDisplaySetting = 0xd0b2;
public static final int EnableBracketing = 0xd0c0;
public static final int AeBracketingStep = 0xd0c1;
public static final int AeBracketingCount = 0xd0c3;
public static final int WbBracketingStep = 0xd0c4;
public static final int LensId = 0xd0e0;
public static final int LensSort = 0xd0e1;
public static final int LensType = 0xd0e2;
public static final int LensfocalMin = 0xd0e3;
public static final int LensFocalMax = 0xd0e4;
public static final int LensApatureMin = 0xd0e5;
public static final int LensApatureMax = 0xd0e6;
public static final int FinderIsoDisplay = 0xd0f0;
public static final int SelfTimerShootExpose = 0xd0f5;
public static final int AutoDistortion = 0xd0f8;
public static final int SceneMode = 0xd0f9;
public static final int ShutterSpeed = 0xd100;
public static final int ExternalDcIn = 0xd101;
public static final int WarningStatus = 0xd102;
public static final int RemainingExposure = 0xd103;
public static final int AfLockStatus = 0xd104;
public static final int AeLockStatus = 0xd105;
public static final int FocusArea = 0xd108;
public static final int FlexibleProgram = 0xd109;
public static final int RecordingMedia = 0xd10b;
public static final int UsbSpeed = 0xd10c;
public static final int CcdNumber = 0xd10d;
public static final int Orientation = 0xd10e;
public static final int ExternalSpeedLightExist = 0xd120;
public static final int ExternalSpeedLightStatus = 0xd121;
public static final int ExternalSpeedLightSort = 0xd122;
public static final int FlashCompensation = 0xd124;
public static final int NewExternalSpeedLightMode = 0xd125;
public static final int InternalFlashCompensation = 0xd126;
public static final int Slot2ImageSaveMode = 0xd148;
public static final int ActiveDLighting = 0xd14e;
public static final int WbTuneFluorescentType = 0xd14f;
public static final int Beep = 0xd160;
public static final int AfModeSelect = 0xd161;
public static final int AfSubLight = 0xd163;
public static final int IsoAutoShutterTimer = 0xd164;
public static final int InternalFlashMode = 0xd167;
public static final int IsoAutoSetting = 0xd16a;
public static final int RemoteControlDelay = 0xd16b;
public static final int GridDisplay = 0xd16c;
public static final int InternalFlashManual = 0xd16d;
public static final int DateImprintSetting = 0xd170;
public static final int DateCounterSelect = 0xd171;
public static final int DateCountData = 0xd172;
public static final int DateCountDisplaySetting = 0xd173;
public static final int RangeFinderSetting = 0xd174;
public static final int IsoautoHighLimit = 0xd183;
public static final int IndicatorDisplay = 0xd18d;
public static final int LiveViewStatus = 0xd1a2;
public static final int LiveViewImageZoomRatio = 0xd1a3;
public static final int LiveViewProhibitionCondition = 0xd1a4;
public static final int ExposureDisplayStatus = 0xd1b0;
public static final int ExposureIndicateStatus = 0xd1b1;
public static final int InfoDisplayErrorStatus = 0xd1b2;
public static final int ExposureIndicateLightup = 0xd1b3;
public static final int InternalFlashPopup = 0xd1c0;
public static final int InternalFlashStatus = 0xd1c1;
public static final int InternalFlashManualRPTIntense = 0xd1d0;
public static final int InternalFlashManualRPTCount = 0xd1d1;
public static final int InternalFlashManualRPTInterval = 0xd1d2;
public static final int InternalFlashCommanderChannel = 0xd1d3;
public static final int InternalFlashCommanderSelfMode = 0xd1d4;
public static final int InternalFlashCommanderSelfComp = 0xd1d5;
public static final int InternalFlashCommanderSelfIntense = 0xd1d6;
public static final int InternalFlashCommanderGroupAMode = 0xd1d7;
public static final int InternalFlashCommanderGroupAComp = 0xd1d8;
public static final int InternalFlashCommanderGroupAIntense = 0xd1d9;
public static final int InternalFlashCommanderGroupBMode = 0xd1da;
public static final int InternalFlashCommanderGroupBComp = 0xd1db;
public static final int InternalFlashCommanderGroupBIntense = 0xd1dc;
public static final int ActiveSlot = 0xd1f2;
public static final int ActivePicCtrlItem = 0xd200;
public static final int ChangePicCtrlItem = 0xd201;
public static final int SessionInitiatorVersionInfo = 0xd406;
public static final int PerceivedDeviceType = 0xd407;
/**
* This class describes value ranges by minima, maxima,
* and permissible increments.
*/
public static final class PtpRange
{
private Object min, max, step;
PtpRange (int dataType, PtpBuffer data)
{
min = PtpPropertyValue.get (dataType, data);
max = PtpPropertyValue.get (dataType, data);
step = PtpPropertyValue.get (dataType, data);
}
/** Returns the maximum value of this range */
public Object getMaximum () { return max; }
/** Returns the minimum value of this range */
public Object getMinimum () { return min; }
/** Returns the increment of values in this range */
public Object getIncrement () { return step; }
}
/** Returns any range constraints for this property's value, or null */
public PtpRange getRange ()
{
if (mFormType == 1)
return (PtpRange) mConstraints;
return null;
}
private Vector<Object> parseEnumeration (PtpBuffer data)
{
int len = data.nextU16 ();
Vector<Object> retval = new Vector<Object> (len);
while (len-- > 0)
retval.addElement (PtpPropertyValue.get (mDataType, data));
return retval;
}
/** Returns any enumerated options for this property's value, or null */
public Vector<?> getEnumeration ()
{
if (mFormType == 2)
return (Vector<?>) mConstraints;
return null;
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.ActionProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
public class MainMenuProvider extends ActionProvider {
private static final String TAG = "MainMenuProvider";
private Context mContext;
private LinearLayout mMenuLayout;
private CheckableImageView mShootingMode, mSceneMode, mCameraMode, mLiveView, mCustomBracketing, mTimelapse, mFlashCommander, mFocusBracketing;
public MainMenuProvider(Context context) {
super(context);
mContext = context;
}
@Override
public View onCreateActionView() {
Log.d(TAG, "onCreateActionView");
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.main_menu_provider,null);
mMenuLayout = (LinearLayout)view.findViewById(R.id.menu_layout);
mShootingMode = (CheckableImageView)view.findViewById(R.id.shootingmode);
mSceneMode = (CheckableImageView)view.findViewById(R.id.scenemode);
mCameraMode = (CheckableImageView)view.findViewById(R.id.cameramode);
mLiveView = (CheckableImageView)view.findViewById(R.id.liveview);
mCustomBracketing = (CheckableImageView)view.findViewById(R.id.custom_bracketing);
mFlashCommander = (CheckableImageView)view.findViewById(R.id.flash_commander);
mTimelapse = (CheckableImageView)view.findViewById(R.id.timelapse);
mFocusBracketing = (CheckableImageView)view.findViewById(R.id.focus_bracketing);
mShootingMode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DslrHelper.getInstance().createDslrDialog(mContext, PtpProperty.ExposureProgramMode, "Select exposure program mode", null);
}
});
mSceneMode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DslrHelper.getInstance().createDslrDialog(mContext, PtpProperty.SceneMode, "Select Scene mode", null);
}
});
mCameraMode.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DslrHelper.getInstance().getPtpDevice().changeCameraMode();
}
});
mLiveView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mLiveView.isChecked())
DslrHelper.getInstance().getPtpDevice().endLiveViewCmd(true);
else
DslrHelper.getInstance().getPtpDevice().startLiveViewCmd();
}
});
mCustomBracketing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BracketingDialog dialog = new BracketingDialog(mContext);
dialog.show();
}
});
mCustomBracketing.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
PtpDevice ptpDevice = DslrHelper.getInstance().getPtpDevice();
ptpDevice.setIsCustomBracketingEnabled(!ptpDevice.getIsCustomBracketingEnabled());
mCustomBracketing.setChecked(ptpDevice.getIsCustomBracketingEnabled());
return true;
}
});
mTimelapse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TimelapseDialog dialog = new TimelapseDialog(mContext);
dialog.show();
}
});
mFlashCommander.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FlashCommanderFragment dialog = new FlashCommanderFragment();
dialog.show(((Activity)mContext).getFragmentManager().beginTransaction() , "flash_commnder");
// FlashDialog dialog = new FlashDialog(mContext);
// dialog.show();
}
});
mFocusBracketing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FocusStackingDialog dialog = new FocusStackingDialog(mContext);
dialog.show();
}
});
if (DslrHelper.getInstance().getIsInitialized() && DslrHelper.getInstance().getPtpDevice().getIsInitialized())
updateDisplay();
return view;
}
public void initDisplay(){
updateDisplay();
}
private void updateDisplay() {
DslrHelper dslrHelper = DslrHelper.getInstance();
if (dslrHelper != null && dslrHelper.getIsInitialized()) {
if (dslrHelper.getPtpDevice().getIsCommandSupported(PtpCommand.ChangeCameraMode))
mCameraMode.setVisibility(View.VISIBLE);
else
mCameraMode.setVisibility(View.GONE);
PtpProperty property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.ExposureProgramMode);
if (property != null) {
dslrHelper.setDslrImg(mShootingMode, property);
mShootingMode.setEnabled(property.getIsWritable());
if (mCameraMode.getVisibility() == View.VISIBLE) {
mCameraMode.setChecked(property.getIsWritable());
mCameraMode.setImageResource(mCameraMode.isChecked() ? R.drawable.hostmode : R.drawable.cameramode);
}
}
else
mShootingMode.setVisibility(View.GONE);
property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.SceneMode);
if (property != null) {
dslrHelper.setDslrImg(mSceneMode, property);
}
else
mSceneMode.setVisibility(View.GONE);
property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.LiveViewStatus);
if (property != null) {
boolean lvEnabled = (Integer)property.getValue() != 0;
mLiveView.setVisibility(View.VISIBLE);
mLiveView.setChecked(lvEnabled);
}
else
mLiveView.setVisibility(View.GONE);
mCustomBracketing.setChecked(dslrHelper.getPtpDevice().getIsCustomBracketingEnabled());
property = dslrHelper.getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfComp);
if (property != null)
mFlashCommander.setVisibility(View.VISIBLE);
else
mFlashCommander.setVisibility(View.GONE);
}
}
public void ptpPropertyChanged(PtpProperty property) {
DslrHelper dslrHelper = DslrHelper.getInstance();
if (property != null && dslrHelper.getIsInitialized() && mCameraMode != null && mShootingMode != null && mLiveView != null) {
switch(property.getPropertyCode()) {
case PtpProperty.ExposureProgramMode:
dslrHelper.setDslrImg(mShootingMode, property);
mShootingMode.setEnabled(property.getIsWritable());
if (mCameraMode.getVisibility() == View.VISIBLE) {
mCameraMode.setChecked(property.getIsWritable());
mCameraMode.setImageResource(mCameraMode.isChecked() ? R.drawable.hostmode : R.drawable.cameramode);
}
break;
case PtpProperty.SceneMode:
dslrHelper.setDslrImg(mSceneMode, property);
break;
case PtpProperty.LiveViewStatus:
boolean lvEnabled = (Integer)property.getValue() != 0;
mLiveView.setVisibility(View.VISIBLE);
mLiveView.setChecked(lvEnabled);
break;
}
}
}
public void ptpDeviceEvent(PtpDeviceEvent event, Object eventData) {
switch(event) {
case BusyBegin:
Log.d(TAG, "BusyBegin");
DslrHelper.getInstance().enableDisableControls(mMenuLayout, false);
break;
case BusyEnd:
Log.d(TAG, "BusyEnd");
DslrHelper.getInstance().enableDisableControls(mMenuLayout, true);
break;
}
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.RelativeLayout;
/**
* A special variation of RelativeLayout that can be used as a checkable object.
* This allows it to be used as the top-level view of a list view item, which
* also supports checking. Otherwise, it works identically to a RelativeLayout.
*/
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked
};
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
public void toggle() {
setChecked(!mChecked);
}
public boolean isChecked() {
return mChecked;
}
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
} | Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
import java.util.Currency;
import android.content.Context;
import android.os.Vibrator;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
/**
* Listener for controlling zoom state through touch events
*/
public class LongPressZoomListener implements View.OnTouchListener {
private static String TAG = "LongPressZoomListener";
/**
* Enum defining listener modes. Before the view is touched the listener is
* in the UNDEFINED mode. Once touch starts it can enter either one of the
* other two modes: If the user scrolls over the view the listener will
* enter PAN mode, if the user lets his finger rest and makes a longpress
* the listener will enter ZOOM mode.
*/
private enum Mode {
UNDEFINED, PAN, ZOOM, PINCH
}
/** Time of tactile feedback vibration when entering zoom mode */
private static final long VIBRATE_TIME = 50;
/** Current listener mode */
private Mode mMode = Mode.UNDEFINED;
/** Zoom control to manipulate */
private DynamicZoomControl mZoomControl;
/** X-coordinate of previously handled touch event */
private float mX;
/** Y-coordinate of previously handled touch event */
private float mY;
/** X-coordinate of latest down event */
private float mDownX;
/** Y-coordinate of latest down event */
private float mDownY;
/** Velocity tracker for touch events */
private VelocityTracker mVelocityTracker;
/** Distance touch can wander before we think it's scrolling */
private final int mScaledTouchSlop;
/** Duration in ms before a press turns into a long press */
private final int mLongPressTimeout;
/** Vibrator for tactile feedback */
private final Vibrator mVibrator;
/** Maximum velocity for fling */
private final int mScaledMaximumFlingVelocity;
float dist0, distCurrent;
/**
* Creates a new instance
*
* @param context Application context
*/
public LongPressZoomListener(Context context) {
mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mScaledMaximumFlingVelocity = ViewConfiguration.get(context)
.getScaledMaximumFlingVelocity();
mVibrator = (Vibrator)context.getSystemService("vibrator");
}
/**
* Sets the zoom control to manipulate
*
* @param control Zoom control
*/
public void setZoomControl(DynamicZoomControl control) {
mZoomControl = control;
}
/**
* Runnable that enters zoom mode
*/
private final Runnable mLongPressRunnable = new Runnable() {
public void run() {
// mMode = Mode.ZOOM;
// mVibrator.vibrate(VIBRATE_TIME);
}
};
// implements View.OnTouchListener
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction() & MotionEvent.ACTION_MASK;
final float x = event.getX();
final float y = event.getY();
float distx, disty;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
mZoomControl.stopFling();
v.postDelayed(mLongPressRunnable, mLongPressTimeout);
mDownX = x;
mDownY = y;
mX = x;
mY = y;
break;
case MotionEvent.ACTION_POINTER_DOWN:
//Get the distance when the second pointer touch
mMode = Mode.PINCH;
distx = Math.abs(event.getX(0) - event.getX(1));
disty = Math.abs(event.getY(0) - event.getY(1));
dist0 = FloatMath.sqrt((distx * distx) + (disty * disty));
Log.d(TAG, "Pinch mode");
break;
case MotionEvent.ACTION_POINTER_UP:
mMode = Mode.PAN;
break;
case MotionEvent.ACTION_MOVE: {
final float dx = (x - mX) / v.getWidth();
final float dy = (y - mY) / v.getHeight();
if (mMode == Mode.ZOOM) {
//Log.d(TAG, "dy: " + dy + "zoom: " + (float)Math.pow(20, -dy));
mZoomControl.zoom((float)Math.pow(20, -dy), mDownX / v.getWidth(), mDownY
/ v.getHeight());
} else if (mMode == Mode.PAN) {
mZoomControl.pan(-dx, -dy);
} else if (mMode == Mode.PINCH) {
//Get the current distance
distx = Math.abs(event.getX(0) - event.getX(1));
disty = Math.abs(event.getY(0) - event.getY(1));
distCurrent = FloatMath.sqrt((distx * distx) + (disty * disty));
float factor = (distCurrent / dist0) * 2f;
//Log.d(TAG, "Pinch distance: "+ distCurrent + "rate: " + (distCurrent/dist0));
mZoomControl.zoom(factor, mDownX / v.getWidth(), mDownY / v.getHeight());
// mZoomControl.zoom((float)Math.pow(1.5, (distCurrent - dist0)/v.getWidth()), mDownX / v.getWidth(), mDownY
// / v.getHeight());
} else {
final float scrollX = mDownX - x;
final float scrollY = mDownY - y;
final float dist = (float)Math.sqrt(scrollX * scrollX + scrollY * scrollY);
if (dist >= mScaledTouchSlop) {
v.removeCallbacks(mLongPressRunnable);
mMode = Mode.PAN;
}
}
mX = x;
mY = y;
break;
}
case MotionEvent.ACTION_UP:
if (mMode == Mode.PAN) {
mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity);
mZoomControl.startFling(-mVelocityTracker.getXVelocity() / v.getWidth(),
-mVelocityTracker.getYVelocity() / v.getHeight());
} else if (mMode == Mode.PINCH) {
} else {
mZoomControl.startFling(0, 0);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
v.removeCallbacks(mLongPressRunnable);
mMode = Mode.UNDEFINED;
break;
default:
mVelocityTracker.recycle();
mVelocityTracker = null;
v.removeCallbacks(mLongPressRunnable);
mMode = Mode.UNDEFINED;
break;
}
return true;
}
}
| Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
import android.os.Handler;
import android.os.SystemClock;
import java.util.Observable;
import java.util.Observer;
/**
* The DynamicZoomControl is responsible for controlling a ZoomState. It makes
* sure that pan movement follows the finger, that limits are satisfied and that
* we can zoom into specific positions.
*
* In order to implement these control mechanisms access to certain content and
* view state data is required which is made possible through the
* ZoomContentViewState.
*/
public class DynamicZoomControl implements Observer {
/** Minimum zoom level limit */
private static final float MIN_ZOOM = 1;
/** Maximum zoom level limit */
private static final float MAX_ZOOM = 16;
/** Velocity tolerance for calculating if dynamic state is resting */
private static final float REST_VELOCITY_TOLERANCE = 0.004f;
/** Position tolerance for calculating if dynamic state is resting */
private static final float REST_POSITION_TOLERANCE = 0.01f;
/** Target FPS when animating behavior such as fling and snap to */
private static final int FPS = 50;
/** Factor applied to pan motion outside of pan snap limits. */
private static final float PAN_OUTSIDE_SNAP_FACTOR = .4f;
/** Zoom state under control */
private final ZoomState mState = new ZoomState();
/** Object holding aspect quotient of view and content */
private AspectQuotient mAspectQuotient;
/**
* Dynamics object for creating dynamic fling and snap to behavior for pan
* in x-dimension.
*/
private final SpringDynamics mPanDynamicsX = new SpringDynamics();
/**
* Dynamics object for creating dynamic fling and snap to behavior for pan
* in y-dimension.
*/
private final SpringDynamics mPanDynamicsY = new SpringDynamics();
/** Minimum snap to position for pan in x-dimension */
private float mPanMinX;
/** Maximum snap to position for pan in x-dimension */
private float mPanMaxX;
/** Minimum snap to position for pan in y-dimension */
private float mPanMinY;
/** Maximum snap to position for pan in y-dimension */
private float mPanMaxY;
/** Handler for posting runnables */
private final Handler mHandler = new Handler();
/** Creates new zoom control */
public DynamicZoomControl() {
mPanDynamicsX.setFriction(2f);
mPanDynamicsY.setFriction(2f);
mPanDynamicsX.setSpring(50f, 1f);
mPanDynamicsY.setSpring(50f, 1f);
}
/**
* Set reference object holding aspect quotient
*
* @param aspectQuotient Object holding aspect quotient
*/
public void setAspectQuotient(AspectQuotient aspectQuotient) {
if (mAspectQuotient != null) {
mAspectQuotient.deleteObserver(this);
}
mAspectQuotient = aspectQuotient;
mAspectQuotient.addObserver(this);
}
/**
* Get zoom state being controlled
*
* @return The zoom state
*/
public ZoomState getZoomState() {
return mState;
}
/**
* Zoom
*
* @param f Factor of zoom to apply
* @param x X-coordinate of invariant position
* @param y Y-coordinate of invariant position
*/
public void zoom(float f, float x, float y) {
final float aspectQuotient = mAspectQuotient.get();
final float prevZoomX = mState.getZoomX(aspectQuotient);
final float prevZoomY = mState.getZoomY(aspectQuotient);
mState.setZoom(mState.getZoom() * f);
limitZoom();
final float newZoomX = mState.getZoomX(aspectQuotient);
final float newZoomY = mState.getZoomY(aspectQuotient);
// Pan to keep x and y coordinate invariant
mState.setPanX(mState.getPanX() + (x - .5f) * (1f / prevZoomX - 1f / newZoomX));
mState.setPanY(mState.getPanY() + (y - .5f) * (1f / prevZoomY - 1f / newZoomY));
updatePanLimits();
mState.notifyObservers();
}
/**
* Pan
*
* @param dx Amount to pan in x-dimension
* @param dy Amount to pan in y-dimension
*/
public void pan(float dx, float dy) {
final float aspectQuotient = mAspectQuotient.get();
dx /= mState.getZoomX(aspectQuotient);
dy /= mState.getZoomY(aspectQuotient);
if (mState.getPanX() > mPanMaxX && dx > 0 || mState.getPanX() < mPanMinX && dx < 0) {
dx *= PAN_OUTSIDE_SNAP_FACTOR;
}
if (mState.getPanY() > mPanMaxY && dy > 0 || mState.getPanY() < mPanMinY && dy < 0) {
dy *= PAN_OUTSIDE_SNAP_FACTOR;
}
final float newPanX = mState.getPanX() + dx;
final float newPanY = mState.getPanY() + dy;
mState.setPanX(newPanX);
mState.setPanY(newPanY);
mState.notifyObservers();
}
/**
* Runnable that updates dynamics state
*/
private final Runnable mUpdateRunnable = new Runnable() {
public void run() {
final long startTime = SystemClock.uptimeMillis();
mPanDynamicsX.update(startTime);
mPanDynamicsY.update(startTime);
final boolean isAtRest = mPanDynamicsX.isAtRest(REST_VELOCITY_TOLERANCE,
REST_POSITION_TOLERANCE)
&& mPanDynamicsY.isAtRest(REST_VELOCITY_TOLERANCE, REST_POSITION_TOLERANCE);
mState.setPanX(mPanDynamicsX.getPosition());
mState.setPanY(mPanDynamicsY.getPosition());
if (!isAtRest) {
final long stopTime = SystemClock.uptimeMillis();
mHandler.postDelayed(mUpdateRunnable, 1000 / FPS - (stopTime - startTime));
}
mState.notifyObservers();
}
};
/**
* Release control and start pan fling animation
*
* @param vx Velocity in x-dimension
* @param vy Velocity in y-dimension
*/
public void startFling(float vx, float vy) {
final float aspectQuotient = mAspectQuotient.get();
final long now = SystemClock.uptimeMillis();
mPanDynamicsX.setState(mState.getPanX(), vx / mState.getZoomX(aspectQuotient), now);
mPanDynamicsY.setState(mState.getPanY(), vy / mState.getZoomY(aspectQuotient), now);
mPanDynamicsX.setMinPosition(mPanMinX);
mPanDynamicsX.setMaxPosition(mPanMaxX);
mPanDynamicsY.setMinPosition(mPanMinY);
mPanDynamicsY.setMaxPosition(mPanMaxY);
mHandler.post(mUpdateRunnable);
}
/**
* Stop fling animation
*/
public void stopFling() {
mHandler.removeCallbacks(mUpdateRunnable);
}
/**
* Help function to figure out max delta of pan from center position.
*
* @param zoom Zoom value
* @return Max delta of pan
*/
private float getMaxPanDelta(float zoom) {
return Math.max(0f, .5f * ((zoom - 1) / zoom));
}
/**
* Force zoom to stay within limits
*/
private void limitZoom() {
if (mState.getZoom() < MIN_ZOOM) {
mState.setZoom(MIN_ZOOM);
} else if (mState.getZoom() > MAX_ZOOM) {
mState.setZoom(MAX_ZOOM);
}
}
/**
* Update limit values for pan
*/
private void updatePanLimits() {
final float aspectQuotient = mAspectQuotient.get();
final float zoomX = mState.getZoomX(aspectQuotient);
final float zoomY = mState.getZoomY(aspectQuotient);
mPanMinX = .5f - getMaxPanDelta(zoomX);
mPanMaxX = .5f + getMaxPanDelta(zoomX);
mPanMinY = .5f - getMaxPanDelta(zoomY);
mPanMaxY = .5f + getMaxPanDelta(zoomY);
}
// Observable interface implementation
public void update(Observable observable, Object data) {
limitZoom();
updatePanLimits();
}
}
| Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import java.util.Observable;
import java.util.Observer;
/**
* View capable of drawing an image at different zoom state levels
*/
public class ImageZoomView extends View implements Observer {
/** Paint object used when drawing bitmap. */
private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
/** Rectangle used (and re-used) for cropping source image. */
private final Rect mRectSrc = new Rect();
/** Rectangle used (and re-used) for specifying drawing area on canvas. */
private final Rect mRectDst = new Rect();
/** Object holding aspect quotient */
private final AspectQuotient mAspectQuotient = new AspectQuotient();
/** The bitmap that we're zooming in, and drawing on the screen. */
private Bitmap mBitmap;
/** State of the zoom. */
private ZoomState mState;
// Public methods
/**
* Constructor
*/
public ImageZoomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Set image bitmap
*
* @param bitmap The bitmap to view and zoom into
*/
public void setImage(Bitmap bitmap) {
mBitmap = bitmap;
if (mBitmap != null) {
mAspectQuotient.updateAspectQuotient(getWidth(), getHeight(), mBitmap.getWidth(), mBitmap.getHeight());
mAspectQuotient.notifyObservers();
invalidate();
}
}
/**
* Set object holding the zoom state that should be used
*
* @param state The zoom state
*/
public void setZoomState(ZoomState state) {
if (mState != null) {
mState.deleteObserver(this);
}
mState = state;
mState.addObserver(this);
invalidate();
}
/**
* Gets reference to object holding aspect quotient
*
* @return Object holding aspect quotient
*/
public AspectQuotient getAspectQuotient() {
return mAspectQuotient;
}
// Superclass overrides
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null && mState != null && !mBitmap.isRecycled()) {
final float aspectQuotient = mAspectQuotient.get();
final int viewWidth = getWidth();
final int viewHeight = getHeight();
final int bitmapWidth = mBitmap.getWidth();
final int bitmapHeight = mBitmap.getHeight();
final float panX = mState.getPanX();
final float panY = mState.getPanY();
final float zoomX = mState.getZoomX(aspectQuotient) * viewWidth / bitmapWidth;
final float zoomY = mState.getZoomY(aspectQuotient) * viewHeight / bitmapHeight;
// Setup source and destination rectangles
mRectSrc.left = (int)(panX * bitmapWidth - viewWidth / (zoomX * 2));
mRectSrc.top = (int)(panY * bitmapHeight - viewHeight / (zoomY * 2));
mRectSrc.right = (int)(mRectSrc.left + viewWidth / zoomX);
mRectSrc.bottom = (int)(mRectSrc.top + viewHeight / zoomY);
mRectDst.left = getLeft();
mRectDst.top = getTop();
mRectDst.right = getRight();
mRectDst.bottom = getBottom();
// Adjust source rectangle so that it fits within the source image.
if (mRectSrc.left < 0) {
mRectDst.left += -mRectSrc.left * zoomX;
mRectSrc.left = 0;
}
if (mRectSrc.right > bitmapWidth) {
mRectDst.right -= (mRectSrc.right - bitmapWidth) * zoomX;
mRectSrc.right = bitmapWidth;
}
if (mRectSrc.top < 0) {
mRectDst.top += -mRectSrc.top * zoomY;
mRectSrc.top = 0;
}
if (mRectSrc.bottom > bitmapHeight) {
mRectDst.bottom -= (mRectSrc.bottom - bitmapHeight) * zoomY;
mRectSrc.bottom = bitmapHeight;
}
canvas.drawBitmap(mBitmap, mRectSrc, mRectDst, mPaint);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mAspectQuotient.updateAspectQuotient(right - left, bottom - top, mBitmap.getWidth(),
mBitmap.getHeight());
mAspectQuotient.notifyObservers();
}
// implements Observer
public void update(Observable observable, Object data) {
invalidate();
}
}
| Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
/**
* SpringDynamics is a Dynamics object that uses friction and spring physics to
* snap to boundaries and give a natural and organic dynamic.
*/
public class SpringDynamics extends Dynamics {
/** Friction factor */
private float mFriction;
/** Spring stiffness factor */
private float mStiffness;
/** Spring damping */
private float mDamping;
/**
* Set friction parameter, friction physics are applied when inside of snap
* bounds.
*
* @param friction Friction factor
*/
public void setFriction(float friction) {
mFriction = friction;
}
/**
* Set spring parameters, spring physics are applied when outside of snap
* bounds.
*
* @param stiffness Spring stiffness
* @param dampingRatio Damping ratio, < 1 underdamped, > 1 overdamped
*/
public void setSpring(float stiffness, float dampingRatio) {
mStiffness = stiffness;
mDamping = dampingRatio * 2 * (float)Math.sqrt(stiffness);
}
/**
* Calculate acceleration at the current state
*
* @return Current acceleration
*/
private float calculateAcceleration() {
float acceleration;
final float distanceFromLimit = getDistanceToLimit();
if (distanceFromLimit != 0) {
acceleration = distanceFromLimit * mStiffness - mDamping * mVelocity;
} else {
acceleration = -mFriction * mVelocity;
}
return acceleration;
}
@Override
protected void onUpdate(int dt) {
// Calculate dt in seconds as float
final float fdt = dt / 1000f;
// Calculate current acceleration
final float a = calculateAcceleration();
// Calculate next position based on current velocity and acceleration
mPosition += mVelocity * fdt + .5f * a * fdt * fdt;
// Update velocity
mVelocity += a * fdt;
}
}
| Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
import java.util.Observable;
/**
* Class that holds the aspect quotient, defined as content aspect ratio divided
* by view aspect ratio.
*/
public class AspectQuotient extends Observable {
/**
* Aspect quotient
*/
private float mAspectQuotient;
// Public methods
/**
* Gets aspect quotient
*
* @return The aspect quotient
*/
public float get() {
return mAspectQuotient;
}
/**
* Updates and recalculates aspect quotient based on supplied view and
* content dimensions.
*
* @param viewWidth Width of view
* @param viewHeight Height of view
* @param contentWidth Width of content
* @param contentHeight Height of content
*/
public void updateAspectQuotient(float viewWidth, float viewHeight, float contentWidth,
float contentHeight) {
final float aspectQuotient = (contentWidth / contentHeight) / (viewWidth / viewHeight);
if (aspectQuotient != mAspectQuotient) {
mAspectQuotient = aspectQuotient;
setChanged();
}
}
}
| Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
import java.util.Observable;
/**
* A ZoomState holds zoom and pan values and allows the user to read and listen
* to changes. Clients that modify ZoomState should call notifyObservers()
*/
public class ZoomState extends Observable {
/**
* Zoom level A value of 1.0 means the content fits the view.
*/
private float mZoom;
/**
* Pan position x-coordinate X-coordinate of zoom window center position,
* relative to the width of the content.
*/
private float mPanX;
/**
* Pan position y-coordinate Y-coordinate of zoom window center position,
* relative to the height of the content.
*/
private float mPanY;
// Public methods
/**
* Get current x-pan
*
* @return current x-pan
*/
public float getPanX() {
return mPanX;
}
/**
* Get current y-pan
*
* @return Current y-pan
*/
public float getPanY() {
return mPanY;
}
/**
* Get current zoom value
*
* @return Current zoom value
*/
public float getZoom() {
return mZoom;
}
/**
* Help function for calculating current zoom value in x-dimension
*
* @param aspectQuotient (Aspect ratio content) / (Aspect ratio view)
* @return Current zoom value in x-dimension
*/
public float getZoomX(float aspectQuotient) {
return Math.min(mZoom, mZoom * aspectQuotient);
}
/**
* Help function for calculating current zoom value in y-dimension
*
* @param aspectQuotient (Aspect ratio content) / (Aspect ratio view)
* @return Current zoom value in y-dimension
*/
public float getZoomY(float aspectQuotient) {
return Math.min(mZoom, mZoom / aspectQuotient);
}
/**
* Set pan-x
*
* @param panX Pan-x value to set
*/
public void setPanX(float panX) {
if (panX != mPanX) {
mPanX = panX;
setChanged();
}
}
/**
* Set pan-y
*
* @param panY Pan-y value to set
*/
public void setPanY(float panY) {
if (panY != mPanY) {
mPanY = panY;
setChanged();
}
}
/**
* Set zoom
*
* @param zoom Zoom value to set
*/
public void setZoom(float zoom) {
if (zoom != mZoom) {
mZoom = zoom;
setChanged();
}
}
}
| Java |
/*
* Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the Sony Ericsson Mobile Communication AB nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.dslr.dashboard.imgzoom;
/**
* Utility class used to handle flinging within a specified limit.
*/
public abstract class Dynamics {
/**
* The maximum delta time, in milliseconds, between two updates
*/
private static final int MAX_TIMESTEP = 50;
/** The current position */
protected float mPosition;
/** The current velocity */
protected float mVelocity;
/** The current maximum position */
protected float mMaxPosition = Float.MAX_VALUE;
/** The current minimum position */
protected float mMinPosition = -Float.MAX_VALUE;
/** The time of the last update */
protected long mLastTime = 0;
/**
* Sets the state of the dynamics object. Should be called before starting
* to call update.
*
* @param position The current position.
* @param velocity The current velocity in pixels per second.
* @param now The current time
*/
public void setState(final float position, final float velocity, final long now) {
mVelocity = velocity;
mPosition = position;
mLastTime = now;
}
/**
* Returns the current position. Normally used after a call to update() in
* order to get the updated position.
*
* @return The current position
*/
public float getPosition() {
return mPosition;
}
/**
* Gets the velocity. Unit is in pixels per second.
*
* @return The velocity in pixels per second
*/
public float getVelocity() {
return mVelocity;
}
/**
* Used to find out if the list is at rest, that is, has no velocity and is
* inside the the limits. Normally used to know if more calls to update are
* needed.
*
* @param velocityTolerance Velocity is regarded as 0 if less than
* velocityTolerance
* @param positionTolerance Position is regarded as inside the limits even
* if positionTolerance above or below
*
* @return true if list is at rest, false otherwise
*/
public boolean isAtRest(final float velocityTolerance, final float positionTolerance) {
final boolean standingStill = Math.abs(mVelocity) < velocityTolerance;
final boolean withinLimits = mPosition - positionTolerance < mMaxPosition
&& mPosition + positionTolerance > mMinPosition;
return standingStill && withinLimits;
}
/**
* Sets the maximum position.
*
* @param maxPosition The maximum value of the position
*/
public void setMaxPosition(final float maxPosition) {
mMaxPosition = maxPosition;
}
/**
* Sets the minimum position.
*
* @param minPosition The minimum value of the position
*/
public void setMinPosition(final float minPosition) {
mMinPosition = minPosition;
}
/**
* Updates the position and velocity.
*
* @param now The current time
*/
public void update(final long now) {
int dt = (int)(now - mLastTime);
if (dt > MAX_TIMESTEP) {
dt = MAX_TIMESTEP;
}
onUpdate(dt);
mLastTime = now;
}
/**
* Gets the distance to the closest limit (max and min position).
*
* @return If position is more than max position: distance to max position. If
* position is less than min position: distance to min position. If
* within limits: 0
*/
protected float getDistanceToLimit() {
float distanceToLimit = 0;
if (mPosition > mMaxPosition) {
distanceToLimit = mMaxPosition - mPosition;
} else if (mPosition < mMinPosition) {
distanceToLimit = mMinPosition - mPosition;
}
return distanceToLimit;
}
/**
* Updates the position and velocity.
*
* @param dt The delta time since last time
*/
abstract protected void onUpdate(int dt);
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ImageGalleryAdapter extends BaseAdapter {
private final static String TAG = "ImageGalleryAdapter";
public interface SelectionChangedListener {
public void onSelectionChanged(
ArrayList<ImageObjectHelper> selectedItems);
}
public interface ImageItemClickedListener {
public void onImageItemClicked(ImageObjectHelper obj);
}
private SelectionChangedListener _selectionChangedListener;
public void setOnSelectionChanged(SelectionChangedListener listener) {
_selectionChangedListener = listener;
}
private ImageItemClickedListener _imageItemClickedListener;
public void setOnImageItemClicked(ImageItemClickedListener listener) {
_imageItemClickedListener = listener;
}
private ArrayList<ImageObjectHelper> _items;
public ArrayList<ImageObjectHelper> items() {
return _items;
}
public Context context;
public LayoutInflater inflater;
public ImageGalleryAdapter(Context context,
ArrayList<ImageObjectHelper> arrayList) {
super();
// Log.d(TAG, "Costructor");
this.context = context;
this._items = arrayList;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
BitmapManager.INSTANCE.setPlaceholder(BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_launcher));
}
public void changeItems(ArrayList<ImageObjectHelper> arrayList) {
// Log.d(TAG, "changeItems");
_items = arrayList;
notifyDataSetChanged();
}
public void addImgItem(ImageObjectHelper item) {
// Log.d(TAG, "addImgItem");
_items.add(item);
this.notifyDataSetChanged();
}
public void selectAll() {
// Log.d(TAG, "selectAll");
for (ImageObjectHelper item : _items) {
item.isChecked = true;
}
notifyDataSetChanged();
}
public void invert() {
Log.d(TAG, "invert");
for (ImageObjectHelper item : _items) {
item.isChecked = !item.isChecked;
}
notifyDataSetChanged();
}
public int getCount() {
// Log.d(TAG, "getCount: " + _items.size());
return _items.size();
}
public Object getItem(int position) {
// Log.d(TAG, "getItem: " + position);
return _items.get(position);
}
public long getItemId(int position) {
// Log.d(TAG, "getItemId: " + position);
return position;
}
@Override
public boolean hasStableIds() {
// Log.d(TAG, "hasSTableIds");
return true;
}
@Override
public int getItemViewType(int position) {
return IGNORE_ITEM_VIEW_TYPE;
}
@Override
public int getViewTypeCount() {
// Log.d(TAG, "getViewTypeCount");
return 1;
}
public static class ViewHolder {
CheckableLinearLayout itemLayout;
ImageView thumbImage;
TextView imgName;
//CheckBox checkBox;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Log.d(TAG, "getView");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.img_preview_item, null);
holder.itemLayout = (CheckableLinearLayout) convertView.findViewById(R.id.img_item_layout);
holder.imgName = (TextView) convertView.findViewById(R.id.imgName);
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
ImageObjectHelper helper = _items.get(position);
holder.thumbImage.setId(position);
holder.itemLayout.setChecked(helper.isChecked);
switch (helper.galleryItemType) {
case ImageObjectHelper.DSLR_PICTURE:
holder.imgName.setText(helper.objectInfo.filename);
break;
case ImageObjectHelper.PHONE_PICTURE:
holder.imgName.setText(helper.file.getName());
break;
}
BitmapManager.INSTANCE.loadBitmap(helper.file.getAbsolutePath(),
holder.thumbImage);
return convertView;
}
} | Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.HashMap;
import java.util.Iterator;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
public class PtpService extends ServiceBase {
public interface OnPtpServiceEventListener {
public void ServiceEvent(PtpServiceEvent event);
}
private OnPtpServiceEventListener mOnPtpServiceEventListener = null;
public void setOnPtpServiceEventListener(OnPtpServiceEventListener listener) {
mOnPtpServiceEventListener = listener;
}
private static final String TAG = "PtpService";
private void sendPtpServiceEvent(PtpServiceEvent event) {
if (mOnPtpServiceEventListener != null && mIsBind) {
mOnPtpServiceEventListener.ServiceEvent(event);
}
}
private UsbManager mUsbManager;
private UsbDevice mUsbDevice;
private UsbDeviceConnection mUsbConnection = null;
private UsbInterface mUsbIntf = null;
private UsbEndpoint mUsbWriteEp = null;
private UsbEndpoint mUsbReadEp = null;
private UsbEndpoint mUsbInterruptEp = null;
private boolean mIsUsbDevicePresent = false;
private boolean mIsUsbDeviceInitialized = false;
private boolean mIsUsbInterfaceClaimed = false;
private PtpDevice mPtpDevice = null;
private GpsLocationHelper mGpsHelper = null;
// preferences
private SharedPreferences mPrefs = null;
public boolean getIsUsbDevicePresent() {
return mIsUsbDevicePresent;
}
public boolean getIsUsbDeviceInitialized() {
return mIsUsbDeviceInitialized;
}
public PtpDevice getPtpDevice() {
return mPtpDevice;
}
public GpsLocationHelper getGpsLocationHelper() {
return mGpsHelper;
}
@Override
public IBinder onBind(Intent intent) {
cancelNotification();
return super.onBind(intent);
}
@Override
public void onRebind(Intent intent) {
Log.d(TAG, "onRebind");
super.onRebind(intent);
}
private static final String ACTION_USB_PERMISSION = "com.dslr.dashboard.USB_PERMISSION";
PendingIntent mPermissionIntent;
private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "Intent received " + action);
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
Log.d(TAG, "USB device permission granted");
mUsbDevice = usbDevice;
mIsUsbDevicePresent = true;
initUsbConnection();
}
}
}
}
};
private final BroadcastReceiver mUsbDeviceDetached = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (mUsbDevice == usbDevice) {
Log.d(PtpService.TAG, "DSLR USB device detached");
usbDeviceDetached();
}
}
}
};
private void usbDeviceDetached()
{
Log.d(TAG, "Usb device removed, stoping the service");
sendPtpServiceEvent(PtpServiceEvent.UsbDeviceRemoved);
closeUsbConnection(true);
mIsUsbDevicePresent = false;
if (!mIsBind)
stopSelf();
}
public void closeUsbConnection() {
closeUsbConnection(false);
}
public void closeUsbConnection(boolean isUsbUnpluged){
Log.d(TAG, "closeUsbConnection");
mPtpDevice.stop(isUsbUnpluged);
if (mUsbConnection != null) {
if (mIsUsbInterfaceClaimed) {
Log.d(TAG, "Releasing USB interface");
mUsbConnection.releaseInterface(mUsbIntf);
}
Log.d(TAG, "USB connection present, closing");
mUsbConnection.close();
}
mIsUsbDevicePresent = false;
mUsbIntf = null;
mUsbReadEp = null;
mUsbWriteEp = null;
mUsbInterruptEp = null;
mUsbConnection = null;
mUsbDevice = null;
mIsUsbInterfaceClaimed = false;
mIsUsbDeviceInitialized = false;
sendPtpServiceEvent(PtpServiceEvent.UsbDeviceRemoved);
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
super.onCreate();
mGpsHelper = new GpsLocationHelper(this);
IntentFilter usbDetachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbDeviceDetached, usbDetachedFilter);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbPermissionReceiver, filter);
// get the shared preferences
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// create the ptpdevice
mPtpDevice = new PtpDevice(this);
try {
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
}
catch(Exception e) {
Log.d(TAG, "UsbManager not available: " + e.getMessage());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
return START_STICKY; //super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
if (mGpsHelper != null) {
mGpsHelper.stopGpsLocator();
mGpsHelper = null;
}
unregisterReceiver(mUsbDeviceDetached);
unregisterReceiver(mUsbPermissionReceiver);
super.onDestroy();
}
@Override
public void onLowMemory() {
Log.d(TAG, "onLowMemory");
super.onLowMemory();
}
public void stopPtpService(boolean keepAliveIfUsbConnected){
Log.d(TAG, "stopPtpService");
cancelNotification();
if (mIsUsbDeviceInitialized){
if (!keepAliveIfUsbConnected) {
closeUsbConnection();
stopSelf();
}
else {
createNotification();
}
}
else {
stopSelf();
}
}
private static int mId = 0x0001;
private void cancelNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(mId);
}
private void createNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.dslrlauncher)
.setContentTitle("DslrDashboard")
.setContentText("Running in background");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build()); }
public void searchForUsbCamera() {
boolean deviceFound = false;
try
{
if (mUsbDevice == null) {
Log.d(TAG, "Ptp service usb device not initialized, search for one");
if (mUsbManager != null)
{
HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList();
Log.d(TAG, "Found USB devices count: " + devices.size());
Iterator<UsbDevice> iterator = devices.values().iterator();
while(iterator.hasNext())
{
UsbDevice usbDevice = iterator.next();
Log.d(TAG, "USB Device: " + usbDevice.getDeviceName() + " Product ID: " + usbDevice.getProductId() + " Vendor ID: " + usbDevice.getVendorId() + " Interface count: " + usbDevice.getInterfaceCount());
for(int i = 0; i < usbDevice.getInterfaceCount(); i++){
UsbInterface intf = usbDevice.getInterface(i);
Log.d(TAG, "Interface class: " + intf.getInterfaceClass() );
if (intf.getInterfaceClass() == android.hardware.usb.UsbConstants.USB_CLASS_STILL_IMAGE)
{
//mUsbDevice = usbDevice;
Log.d(TAG, "Ptp Service imaging usb device found requesting permission");
mUsbManager.requestPermission(usbDevice, mPermissionIntent);
deviceFound = true;
break;
}
}
if (deviceFound)
break;
}
}
else
Log.d(TAG, "USB Manager is unavailable");
}
else {
Log.d(TAG, "Ptp service usb imaging device already present");
//_usbManager.requestPermission(_usbDevice, mPermissionIntent);
}
} catch (Exception e) {
Log.d(TAG, "PtpService search for USB camrea exception: " + e.getMessage());
}
}
private void initUsbConnection()
{
try {
if (mUsbDevice != null) {
if (mUsbIntf == null) {
for(int i = 0; i < mUsbDevice.getInterfaceCount(); i++) {
UsbInterface uintf = mUsbDevice.getInterface(i);
if (uintf.getInterfaceClass() == UsbConstants.USB_CLASS_STILL_IMAGE){
// we have a still image interface
// Log.d(MainActivity.TAG, "Imaging USB interface found");
mUsbIntf = uintf;
break;
}
}
if (mUsbIntf != null) {
// get the endpoints
for(int i =0; i< mUsbIntf.getEndpointCount(); i++) {
UsbEndpoint ep = mUsbIntf.getEndpoint(i);
if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
mUsbWriteEp = ep;
// Log.d(MainActivity.TAG, "write endpoint found");
}
}
else {
switch(ep.getType()) {
case UsbConstants.USB_ENDPOINT_XFER_BULK:
mUsbReadEp = ep;
// Log.d(MainActivity.TAG, "read endpoint found");
break;
case UsbConstants.USB_ENDPOINT_XFER_INT:
mUsbInterruptEp = ep;
// Log.d(MainActivity.TAG, "interrupt endpoint found");
break;
}
}
}
}
else
Log.d(TAG, "No compatible USB interface found");
}
else
Log.d(TAG, "USB interface found");
// if we have read and write endpoints then we good to go
if (mUsbReadEp != null && mUsbWriteEp != null) {
if (!mIsUsbDeviceInitialized) {
mUsbConnection = mUsbManager.openDevice(mUsbDevice);
mIsUsbDeviceInitialized = mUsbConnection != null;
}
if (mIsUsbDeviceInitialized) {
// Log.d(TAG, "USB Device Initialized");
if (!mIsUsbInterfaceClaimed) {
mIsUsbInterfaceClaimed = mUsbConnection.claimInterface(mUsbIntf, true);
// Log.d(TAG, "USB Interface claimed: " + isInterfaceClaimed);
}
sendPtpServiceEvent(PtpServiceEvent.UsbDeviceInitialized);
// create the USB communicator
PtpUsbCommunicator communicator = new PtpUsbCommunicator(new PtpSession());
// initialize the USB communicator
communicator.initCommunicator(mUsbConnection, mUsbWriteEp, mUsbReadEp, mUsbInterruptEp);
// initialize the PTP device
mPtpDevice.initialize(mUsbDevice.getVendorId(), mUsbDevice.getProductId(), communicator);
}
}
}
else
Log.d(TAG, "No USB device present");
} catch (Exception e){
Log.d(TAG, "InitUsb exception: " + e.getMessage());
}
}
// preferences properties
public SharedPreferences getPreferences() {
return mPrefs;
}
}
| Java |
/*
<DslrDashboard - controling DSLR camera with Android phone/tablet>
Copyright (C) <2012> <Zoltan Hubai>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dslr.dashboard;
import java.util.ArrayList;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.TextView;
public class BracketingDialog{
private static String TAG = "BracketingDialog";
private Context mContext;
private DslrHelper mDslrHelper;
private PtpDevice mPtpDevice;
private View mView;
private TextView txtCustomBktStep, txtCustomBktDirection, txtCustomBktCount;
private CheckBox mBktFocusFirst;
public BracketingDialog(Context context) {
mContext = context;
mDslrHelper = DslrHelper.getInstance();
mPtpDevice = mDslrHelper.getPtpDevice();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(R.layout.bracketingdialog, null);
// addContentView(layout, new LayoutParams(
// LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//((TextView) layout.findViewById(R.id.title)).setText("Custom Bracketing settings");
txtCustomBktStep = (TextView)mView.findViewById(R.id.txt_custombktstep);
txtCustomBktDirection = (TextView)mView.findViewById(R.id.txt_custombktdirection);
txtCustomBktCount = (TextView)mView.findViewById(R.id.txt_custombktcount);
mBktFocusFirst = (CheckBox)mView.findViewById(R.id.bkt_focus_first);
setCustomValues();
txtCustomBktStep.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
customBktStepDialog();
}
});
txtCustomBktDirection.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
customBktDirektionDialog();
}
});
txtCustomBktCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
customBktCountDialog();
}
});
mBktFocusFirst.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mPtpDevice.setCustomBracketingFocusFirst(mBktFocusFirst.isChecked());
}
});
}
public void show() {
CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext);
customBuilder.setTitle("Custom Bracketing settings")
.setContentView(mView);
customBuilder
.create()
.show();
}
private void setCustomValues(){
if (mPtpDevice != null && mPtpDevice.getIsPtpDeviceInitialized()){
txtCustomBktDirection.setText(getCustomBktDirection(mPtpDevice.getCustomBracketingDirection()));
txtCustomBktCount.setText((String.format("%d", mPtpDevice.getCustomBracketingCount())));
PtpProperty property = mPtpDevice.getPtpProperty(PtpProperty.ExposureEvStep);
if (property != null) {
if ((Integer)property.getValue() == 0)
txtCustomBktStep.setText(String.format("%.1f EV", mPtpDevice.getCustomBracketingStep() * (1f / 3f)));
else
txtCustomBktStep.setText(String.format("%.1f EV", mPtpDevice.getCustomBracketingStep() * (1f / 2f)));
}
mBktFocusFirst.setChecked(mPtpDevice.getCustomBracketingFocusFirst());
//txtCustomBktStep.setText((String.format("%d", _dslrHelper.getPtpService().getBktStep())));
}
}
private String getCustomBktDirection(int direktion){
switch(direktion){
case 0:
return "Negative";
case 1:
return "Positive";
case 2:
return "Both";
default:
return "Both";
}
}
private void customBktCountDialog(){
final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
int selectedItem = -1;
for(int i = 0; i <= 3; i++){
int current = 3 + (i * 2);
if (current == mPtpDevice.getCustomBracketingCount())
selectedItem = i;
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setValue(current);
item.setTitle(String.format("%d images", current));
items.add(item);
}
CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext);
customBuilder.setTitle("Custom bracketing count")
.setListItems(items, selectedItem)
.setListOnClickListener(new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which >= 0 && which < items.size()){
mPtpDevice.setCustomBracketingCount((Integer) items.get(which).getValue());
txtCustomBktCount.setText(items.get(which).getTitle());
}
}
});
CustomDialog dialog = customBuilder.create();
dialog.show();
}
private void customBktDirektionDialog(){
final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
for(int i = 0; i <= 2; i++){
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setValue(i);
item.setTitle(getCustomBktDirection(i));
items.add(item);
}
CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext);
customBuilder.setTitle("Custom bracketing direktion")
.setListItems(items, mPtpDevice.getCustomBracketingDirection())
.setListOnClickListener(new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which >= 0 && which < items.size()){
mPtpDevice.setCustomBracketingDirection((Integer) items.get(which).getValue());
txtCustomBktDirection.setText(items.get(which).getTitle());
}
}
});
CustomDialog dialog = customBuilder.create();
dialog.show();
}
private void customBktStepDialog(){
PtpProperty prop = mPtpDevice.getPtpProperty(PtpProperty.ExposureEvStep);
if (prop != null){
int evStep = (Integer) prop.getValue();
final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>();
switch(evStep)
{
case 0: // 1/3
for(int i = 1; i <= 6; i++){
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setTitle(String.format("%.1f EV", i * (1f / 3f)));
item.setValue(i);
items.add(item);
}
break;
case 1: // 1/2
if (mPtpDevice.getCustomBracketingStep() > 4)
mPtpDevice.setCustomBracketingStep(1);
for(int i = 1; i <= 4; i++){
PtpPropertyListItem item = new PtpPropertyListItem();
item.setImage(-1);
item.setTitle(String.format("%.1f EV", i * (1f / 2f)));
item.setValue(i);
items.add(item);
}
break;
}
CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext);
customBuilder.setTitle("Custom bracketing EV step")
.setListItems(items, mPtpDevice.getCustomBracketingStep() - 1)
.setListOnClickListener(new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which >= 0 && which < items.size()){
mPtpDevice.setCustomBracketingStep((Integer) items.get(which).getValue());
txtCustomBktStep.setText(items.get(which).getTitle());
}
}
});
CustomDialog dialog = customBuilder.create();
dialog.show();
}
}
}
| Java |
/*
** 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.
*/
/*
* maps.jar doesn't include all its dependencies; fake them out here for testing.
*/
package android.widget;
public class ZoomButtonsController {
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import android.text.Editable;
import android.text.InputFilter;
class StubEditable implements Editable {
private final String mString;
public StubEditable(String s) {
mString = s;
}
public Editable append(char arg0) {
return null;
}
public Editable append(CharSequence arg0) {
return null;
}
public Editable append(CharSequence arg0, int arg1, int arg2) {
return null;
}
public char charAt(int index) {
return mString.charAt(index);
}
public void clear() {
}
public void clearSpans() {
}
public Editable delete(int arg0, int arg1) {
return null;
}
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
mString.getChars(srcBegin, srcEnd, dst, dstBegin);
}
public InputFilter[] getFilters() {
return null;
}
public int getSpanEnd(Object arg0) {
return 0;
}
public int getSpanFlags(Object arg0) {
return 0;
}
public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) {
return null;
}
public int getSpanStart(Object arg0) {
return 0;
}
public Editable insert(int arg0, CharSequence arg1) {
return null;
}
public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) {
return null;
}
public int length() {
return mString.length();
}
@SuppressWarnings("unchecked")
public int nextSpanTransition(int arg0, int arg1, Class arg2) {
return 0;
}
public void removeSpan(Object arg0) {
}
public Editable replace(int arg0, int arg1, CharSequence arg2) {
return null;
}
public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) {
return null;
}
public void setFilters(InputFilter[] arg0) {
}
public void setSpan(Object arg0, int arg1, int arg2, int arg3) {
}
public CharSequence subSequence(int start, int end) {
return mString.subSequence(start, end);
}
@Override
public String toString() {
return mString;
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.CachePersisterFacadeFactory;
import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import com.google.code.geobeagle.xmlimport.ImportThreadDelegate.ImportThreadHelper;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.xmlimport.gpx.GpxFileIterAndZipFileIterFactory;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxAndZipFilenameFilter;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.widget.Toast;
import java.io.FilenameFilter;
public class GpxImporterDI {
// Can't test this due to final methods in base.
public static class ImportThread extends Thread {
static ImportThread create(MessageHandler messageHandler, GpxLoader gpxLoader,
EventHandlers eventHandlers, XmlPullParserWrapper xmlPullParserWrapper,
ErrorDisplayer errorDisplayer, Aborter aborter) {
final GpxFilenameFilter gpxFilenameFilter = new GpxFilenameFilter();
final FilenameFilter filenameFilter = new GpxAndZipFilenameFilter(gpxFilenameFilter);
final ZipInputFileTester zipInputFileTester = new ZipInputFileTester(gpxFilenameFilter);
final GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory = new GpxFileIterAndZipFileIterFactory(
zipInputFileTester, aborter);
final GpxAndZipFiles gpxAndZipFiles = new GpxAndZipFiles(filenameFilter,
gpxFileIterAndZipFileIterFactory);
final EventHelperFactory eventHelperFactory = new EventHelperFactory(
xmlPullParserWrapper);
final ImportThreadHelper importThreadHelper = new ImportThreadHelper(gpxLoader,
messageHandler, eventHelperFactory, eventHandlers, errorDisplayer);
return new ImportThread(gpxAndZipFiles, importThreadHelper, errorDisplayer);
}
private final ImportThreadDelegate mImportThreadDelegate;
public ImportThread(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper,
ErrorDisplayer errorDisplayer) {
mImportThreadDelegate = new ImportThreadDelegate(gpxAndZipFiles, importThreadHelper,
errorDisplayer);
}
@Override
public void run() {
mImportThreadDelegate.run();
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ImportThreadWrapper {
private final Aborter mAborter;
private ImportThread mImportThread;
private final MessageHandler mMessageHandler;
private final XmlPullParserWrapper mXmlPullParserWrapper;
public ImportThreadWrapper(MessageHandler messageHandler,
XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) {
mMessageHandler = messageHandler;
mXmlPullParserWrapper = xmlPullParserWrapper;
mAborter = aborter;
}
public boolean isAlive() {
if (mImportThread != null)
return mImportThread.isAlive();
return false;
}
public void join() {
if (mImportThread != null)
try {
mImportThread.join();
} catch (InterruptedException e) {
// Ignore; we are aborting anyway.
}
}
public void open(CacheListRefresh cacheListRefresh, GpxLoader gpxLoader,
EventHandlers eventHandlers, ErrorDisplayer mErrorDisplayer) {
mMessageHandler.start(cacheListRefresh);
mImportThread = ImportThread.create(mMessageHandler, gpxLoader, eventHandlers,
mXmlPullParserWrapper, mErrorDisplayer, mAborter);
}
public void start() {
if (mImportThread != null)
mImportThread.start();
}
}
// Too hard to test this class due to final methods in base.
public static class MessageHandler extends Handler {
public static final String GEOBEAGLE = "GeoBeagle";
static final int MSG_DONE = 1;
static final int MSG_PROGRESS = 0;
public static MessageHandler create(ListActivity listActivity) {
final ProgressDialogWrapper progressDialogWrapper = new ProgressDialogWrapper(
listActivity);
return new MessageHandler(progressDialogWrapper);
}
private int mCacheCount;
private boolean mLoadAborted;
private CacheListRefresh mMenuActionRefresh;
private final ProgressDialogWrapper mProgressDialogWrapper;
private String mSource;
private String mStatus;
private String mWaypointId;
public MessageHandler(ProgressDialogWrapper progressDialogWrapper) {
mProgressDialogWrapper = progressDialogWrapper;
}
public void abortLoad() {
mLoadAborted = true;
mProgressDialogWrapper.dismiss();
}
@Override
public void handleMessage(Message msg) {
// Log.d(GEOBEAGLE, "received msg: " + msg.what);
switch (msg.what) {
case MessageHandler.MSG_PROGRESS:
mProgressDialogWrapper.setMessage(mStatus);
break;
case MessageHandler.MSG_DONE:
if (!mLoadAborted) {
mProgressDialogWrapper.dismiss();
mMenuActionRefresh.forceRefresh();
}
break;
default:
break;
}
}
public void loadComplete() {
sendEmptyMessage(MessageHandler.MSG_DONE);
}
public void start(CacheListRefresh cacheListRefresh) {
mCacheCount = 0;
mLoadAborted = false;
mMenuActionRefresh = cacheListRefresh;
// TODO: move text into resource.
mProgressDialogWrapper.show("Syncing caches", "Please wait...");
}
public void updateName(String name) {
mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name;
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateSource(String text) {
mSource = text;
mStatus = "Opening: " + mSource + "...";
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateWaypointId(String wpt) {
mWaypointId = wpt;
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ProgressDialogWrapper {
private final Context mContext;
private ProgressDialog mProgressDialog;
public ProgressDialogWrapper(Context context) {
mContext = context;
}
public void dismiss() {
if (mProgressDialog != null)
mProgressDialog.dismiss();
}
public void setMessage(CharSequence message) {
mProgressDialog.setMessage(message);
}
public void show(String title, String msg) {
mProgressDialog = ProgressDialog.show(mContext, title, msg);
}
}
public static class ToastFactory {
public void showToast(Context context, int resId, int duration) {
Toast.makeText(context, resId, duration).show();
}
}
public static class Toaster {
private final Context mContext;
private final int mResId;
private final int mDuration;
public Toaster(Context context, int resId, int duration) {
mContext = context;
mResId = resId;
mDuration = duration;
}
public void showToast() {
Toast.makeText(mContext, mResId, mDuration).show();
}
}
public static GpxImporter create(ListActivity listActivity,
XmlPullParserWrapper xmlPullParserWrapper, ErrorDisplayer errorDisplayer,
GeocacheListPresenter geocacheListPresenter, Aborter aborter,
MessageHandler messageHandler, CachePersisterFacadeFactory cachePersisterFacadeFactory,
CacheWriter cacheWriter) {
final PowerManager powerManager = (PowerManager)listActivity
.getSystemService(Context.POWER_SERVICE);
final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"Importing");
final CachePersisterFacade cachePersisterFacade = cachePersisterFacadeFactory.create(
cacheWriter, wakeLock);
final GpxLoader gpxLoader = GpxLoaderDI.create(cachePersisterFacade, xmlPullParserWrapper,
aborter, errorDisplayer, wakeLock);
final ToastFactory toastFactory = new ToastFactory();
final ImportThreadWrapper importThreadWrapper = new ImportThreadWrapper(messageHandler,
xmlPullParserWrapper, aborter);
final EventHandlerGpx eventHandlerGpx = new EventHandlerGpx(cachePersisterFacade);
final EventHandlerLoc eventHandlerLoc = new EventHandlerLoc(cachePersisterFacade);
final EventHandlers eventHandlers = new EventHandlers();
eventHandlers.add(".gpx", eventHandlerGpx);
eventHandlers.add(".loc", eventHandlerLoc);
return new GpxImporter(geocacheListPresenter, gpxLoader, listActivity, importThreadWrapper,
messageHandler, toastFactory, eventHandlers, errorDisplayer);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.cachedetails.CacheDetailsWriter;
import com.google.code.geobeagle.cachedetails.HtmlWriter;
import com.google.code.geobeagle.cachedetails.WriterWrapper;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import android.os.PowerManager.WakeLock;
import java.io.File;
public class CachePersisterFacadeDI {
//TODO: Remove class CachePersisterFacadeFactory
public static class CachePersisterFacadeFactory {
private final CacheDetailsWriter mCacheDetailsWriter;
private final CacheTypeFactory mCacheTypeFactory;
private final FileFactory mFileFactory;
private final HtmlWriter mHtmlWriter;
private final MessageHandler mMessageHandler;
private final WriterWrapper mWriterWrapper;
public CachePersisterFacadeFactory(MessageHandler messageHandler,
CacheTypeFactory cacheTypeFactory) {
mMessageHandler = messageHandler;
mFileFactory = new FileFactory();
mWriterWrapper = new WriterWrapper();
mHtmlWriter = new HtmlWriter(mWriterWrapper);
mCacheDetailsWriter = new CacheDetailsWriter(mHtmlWriter);
mCacheTypeFactory = cacheTypeFactory;
}
public CachePersisterFacade create(CacheWriter cacheWriter, WakeLock wakeLock) {
final CacheTagSqlWriter cacheTagSqlWriter = new CacheTagSqlWriter(cacheWriter, mCacheTypeFactory);
return new CachePersisterFacade(cacheTagSqlWriter, mFileFactory, mCacheDetailsWriter,
mMessageHandler, wakeLock);
}
}
public static class FileFactory {
public File createFile(String path) {
return new File(path);
}
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.EventHandler;
import com.google.code.geobeagle.xmlimport.EventHelper;
import com.google.code.geobeagle.xmlimport.EventHelper.XmlPathBuilder;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
public class EventHelperDI {
public static class EventHelperFactory {
private final XmlPullParserWrapper mXmlPullParser;
public EventHelperFactory(XmlPullParserWrapper xmlPullParser) {
mXmlPullParser = xmlPullParser;
}
public EventHelper create(EventHandler eventHandler) {
final XmlPathBuilder xmlPathBuilder = new XmlPathBuilder();
return new EventHelper(xmlPathBuilder, eventHandler, mXmlPullParser);
}
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.xmlimport.CachePersisterFacade;
import com.google.code.geobeagle.xmlimport.GpxLoader;
import com.google.code.geobeagle.xmlimport.GpxToCache;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.os.PowerManager.WakeLock;
public class GpxLoaderDI {
public static GpxLoader create(CachePersisterFacade cachePersisterFacade,
XmlPullParserWrapper xmlPullParserFactory, Aborter aborter, ErrorDisplayer errorDisplayer, WakeLock wakeLock) {
final GpxToCache gpxToCache = new GpxToCache(xmlPullParserFactory, aborter);
return new GpxLoader(cachePersisterFacade, errorDisplayer, gpxToCache, wakeLock);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GpxToCacheDI {
public static class XmlPullParserWrapper {
private String mSource;
private XmlPullParser mXmlPullParser;
public String getAttributeValue(String namespace, String name) {
return mXmlPullParser.getAttributeValue(namespace, name);
}
public int getEventType() throws XmlPullParserException {
return mXmlPullParser.getEventType();
}
public String getName() {
return mXmlPullParser.getName();
}
public String getSource() {
return mSource;
}
public String getText() {
return mXmlPullParser.getText();
}
public int next() throws XmlPullParserException, IOException {
return mXmlPullParser.next();
}
public void open(String path, Reader reader) throws XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
newPullParser.setInput(reader);
mSource = path;
mXmlPullParser = newPullParser;
}
}
public static XmlPullParser createPullParser(String path) throws FileNotFoundException,
XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
final Reader reader = new BufferedReader(new FileReader(path));
newPullParser.setInput(reader);
return newPullParser;
}
}
| Java |
/*
** 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.code.geobeagle.cachedetails;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class WriterWrapper {
Writer mWriter;
public void close() throws IOException {
mWriter.close();
}
public void open(String path) throws IOException {
mWriter = new BufferedWriter(new FileWriter(path), 4000);
}
public void write(String str) throws IOException {
try {
mWriter.write(str);
} catch (IOException e) {
throw new IOException("Error writing line '" + str + "'");
}
}
} | Java |
package com.google.code.geobeagle;
import java.util.Hashtable;
public class CacheTypeFactory {
private final Hashtable<Integer, CacheType> mCacheTypes =
new Hashtable<Integer, CacheType>(CacheType.values().length);
public CacheTypeFactory() {
for (CacheType cacheType : CacheType.values())
mCacheTypes.put(cacheType.toInt(), cacheType);
}
public CacheType fromInt(int i) {
return mCacheTypes.get(i);
}
public CacheType fromTag(String tag) {
for (CacheType cacheType : mCacheTypes.values()) {
if (tag.equals(cacheType.getTag()))
return cacheType;
}
//Quick-n-dirty way of implementing additional names for certain cache types
if (tag.equals("Traditional Cache"))
return CacheType.TRADITIONAL;
if (tag.equals("Multi-cache"))
return CacheType.MULTI;
if (tag.equals("Virtual"))
return CacheType.VIRTUAL;
if (tag.equals("Event"))
return CacheType.EVENT;
if (tag.equals("Webcam"))
return CacheType.WEBCAM;
if (tag.equals("Earth"))
return CacheType.EARTHCACHE;
return CacheType.NULL;
}
public int container(String container) {
if (container.equals("Micro")) {
return 1;
} else if (container.equals("Small")) {
return 2;
} else if (container.equals("Regular")) {
return 3;
} else if (container.equals("Large")) {
return 4;
}
return 0;
}
public int stars(String stars) {
try {
return Math.round(Float.parseFloat(stars) * 2);
} catch (Exception ex) {
return 0;
}
}
} | Java |
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.Time;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.content.Context;
import android.os.Handler;
import android.view.View;
public class GpsWidgetAndUpdater {
private final GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
private final UpdateGpsWidgetRunnable mUpdateGpsRunnable;
public GpsWidgetAndUpdater(Context context, View gpsWidgetView,
LocationControlBuffered mLocationControlBuffered,
CombinedLocationManager combinedLocationManager,
DistanceFormatter distanceFormatterMetric) {
final Time time = new Time();
final Handler handler = new Handler();
final MeterBars meterBars = GpsStatusWidget.create(context, gpsWidgetView);
final Meter meter = GpsStatusWidget.createMeterWrapper(gpsWidgetView, meterBars);
final TextLagUpdater textLagUpdater = GpsStatusWidget.createTextLagUpdater(gpsWidgetView,
combinedLocationManager, time);
mUpdateGpsRunnable = new UpdateGpsWidgetRunnable(handler, mLocationControlBuffered, meter,
textLagUpdater);
mGpsStatusWidgetDelegate = GpsStatusWidget.createGpsStatusWidgetDelegate(gpsWidgetView,
time, combinedLocationManager, meter, distanceFormatterMetric, meterBars,
textLagUpdater, context);
}
public GpsStatusWidgetDelegate getGpsStatusWidgetDelegate() {
return mGpsStatusWidgetDelegate;
}
public UpdateGpsWidgetRunnable getUpdateGpsWidgetRunnable() {
return mUpdateGpsRunnable;
}
}
| Java |
/*
** 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.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Time;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.gpsstatuswidget.TextLagUpdater.LagNull;
import com.google.code.geobeagle.gpsstatuswidget.TextLagUpdater.LastKnownLocationUnavailable;
import com.google.code.geobeagle.gpsstatuswidget.TextLagUpdater.LastLocationUnknown;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* @author sng Displays the GPS status (mAccuracy, availability, etc).
*/
public class GpsStatusWidget extends LinearLayout {
static GpsStatusWidgetDelegate createGpsStatusWidgetDelegate(View gpsStatusWidget, Time time,
CombinedLocationManager combinedLocationManager, Meter meter,
DistanceFormatter distanceFormatter, MeterBars meterBars,
TextLagUpdater textLagUpdater, Context parent) {
final TextView status = (TextView)gpsStatusWidget.findViewById(R.id.status);
final TextView provider = (TextView)gpsStatusWidget.findViewById(R.id.provider);
final MeterFader meterFader = new MeterFader(gpsStatusWidget, meterBars, time);
return new GpsStatusWidgetDelegate(combinedLocationManager, distanceFormatter, meter,
meterFader, provider, parent, status, textLagUpdater);
}
public static class InflatedGpsStatusWidget extends LinearLayout {
private GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
public InflatedGpsStatusWidget(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
public InflatedGpsStatusWidget(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
mGpsStatusWidgetDelegate.paint();
}
public void setDelegate(GpsStatusWidgetDelegate gpsStatusWidgetDelegate) {
mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate;
}
}
public GpsStatusWidget(Context context) {
super(context);
}
public static MeterBars create(Context context, View gpsWidget) {
final MeterFormatter meterFormatter = new MeterFormatter(context);
final TextView locationViewer = (TextView)gpsWidget.findViewById(R.id.location_viewer);
return new MeterBars(locationViewer, meterFormatter);
}
public static Meter createMeterWrapper(View gpsStatusWidget, MeterBars meterBars) {
final TextView accuracyView = (TextView)gpsStatusWidget.findViewById(R.id.accuracy);
return new Meter(meterBars, accuracyView);
}
public static TextLagUpdater createTextLagUpdater(View gpsStatusWidget,
CombinedLocationManager combinedLocationManager, Time time) {
final TextView lag = (TextView)gpsStatusWidget.findViewById(R.id.lag);
final LagNull lagNull = new LagNull();
final LastKnownLocationUnavailable lastKnownLocationUnavailable = new LastKnownLocationUnavailable(
lagNull);
final LastLocationUnknown lastLocationUnknown = new LastLocationUnknown(
combinedLocationManager, lastKnownLocationUnavailable);
return new TextLagUpdater(lastLocationUnknown, lag, time);
}
}
| Java |
package com.google.code.geobeagle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class ErrorDisplayerDi {
static public ErrorDisplayer createErrorDisplayer(Activity activity) {
final OnClickListener mOnClickListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
return new ErrorDisplayer(activity, mOnClickListener);
}
}
| Java |
/*
** 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.code.geobeagle.database;
public class Database {
public static final String DATABASE_NAME = "GeoBeagle.db";
public static final int DATABASE_VERSION = 11;
public static final String S0_COLUMN_CACHE_TYPE = "CacheType INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_CONTAINER = "Container INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1";
public static final String S0_COLUMN_DIFFICULTY = "Difficulty INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_TERRAIN = "Terrain INTEGER NOT NULL Default 0";
public static final String S0_INTENT = "intent";
public static final String SQL_CACHES_DONT_DELETE_ME = "UPDATE CACHES SET DeleteMe = 0 WHERE Source = ?";
public static final String SQL_CLEAR_CACHES = "DELETE FROM CACHES WHERE Source=?";
public static final String SQL_CREATE_CACHE_TABLE_V08 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR);";
public static final String SQL_CREATE_CACHE_TABLE_V10 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ");";
public static final String SQL_CREATE_CACHE_TABLE_V11 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", "
+ S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY
+ ", " + S0_COLUMN_TERRAIN + ");";
public static final String SQL_CREATE_GPX_TABLE_V10 = "CREATE TABLE GPX ("
+ "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL);";
public static final String SQL_CREATE_IDX_LATITUDE = "CREATE INDEX IDX_LATITUDE on CACHES (Latitude);";
public static final String SQL_CREATE_IDX_LONGITUDE = "CREATE INDEX IDX_LONGITUDE on CACHES (Longitude);";
public static final String SQL_CREATE_IDX_SOURCE = "CREATE INDEX IDX_SOURCE on CACHES (Source);";
public static final String SQL_DELETE_CACHE = "DELETE FROM CACHES WHERE Id=?";
public static final String SQL_DELETE_OLD_CACHES = "DELETE FROM CACHES WHERE DeleteMe = 1";
public static final String SQL_DELETE_OLD_GPX = "DELETE FROM GPX WHERE DeleteMe = 1";
public static final String SQL_DROP_CACHE_TABLE = "DROP TABLE IF EXISTS CACHES";
public static final String SQL_GPX_DONT_DELETE_ME = "UPDATE GPX SET DeleteMe = 0 WHERE Name = ?";
public static final String SQL_MATCH_NAME_AND_EXPORTED_LATER = "Name = ? AND ExportTime >= ?";
public static final String SQL_REPLACE_CACHE = "REPLACE INTO CACHES "
+ "(Id, Description, Latitude, Longitude, Source, DeleteMe, CacheType, Difficulty, Terrain, Container) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)";
public static final String SQL_REPLACE_GPX = "REPLACE INTO GPX (Name, ExportTime, DeleteMe) VALUES (?, ?, 0)";
public static final String SQL_RESET_DELETE_ME_CACHES = "UPDATE CACHES SET DeleteMe = 1 WHERE Source != '"
+ S0_INTENT + "'";
public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1";
public static final String TBL_CACHES = "CACHES";
public static final String TBL_GPX = "GPX";
}
| Java |
/*
** 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.code.geobeagle.database;
public class CacheWriterFactory {
public CacheWriter create(ISQLiteDatabase writableDatabase) {
return DatabaseDI.createCacheWriter(writableDatabase);
}
}
| Java |
/*
** 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.code.geobeagle.database;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.BoundingBox;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.Search;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.SearchDown;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.SearchUp;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.WhereStringFactory;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Arrays;
public class DatabaseDI {
public static class CacheReaderCursorFactory {
public CacheReaderCursor create(Cursor cursor) {
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheReaderCursor(cursor, geocacheFactory, dbToGeocacheAdapter);
}
}
public static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper {
private final OpenHelperDelegate mOpenHelperDelegate;
public GeoBeagleSqliteOpenHelper(Context context) {
super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
mOpenHelperDelegate = new OpenHelperDelegate();
}
public SQLiteWrapper getWritableSqliteWrapper() {
return new SQLiteWrapper(this.getWritableDatabase());
}
@Override
public void onCreate(SQLiteDatabase db) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onCreate(sqliteWrapper);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onUpgrade(sqliteWrapper, oldVersion);
}
}
public static class SQLiteWrapper implements ISQLiteDatabase {
private final SQLiteDatabase mSQLiteDatabase;
public SQLiteWrapper(SQLiteDatabase writableDatabase) {
mSQLiteDatabase = writableDatabase;
}
public void beginTransaction() {
mSQLiteDatabase.beginTransaction();
}
public int countResults(String table, String selection, String... selectionArgs) {
Log.d("GeoBeagle", "SQL count results: " + selection + ", "
+ Arrays.toString(selectionArgs));
Cursor cursor = mSQLiteDatabase.query(table, null, selection, selectionArgs, null,
null, null, null);
int count = cursor.getCount();
cursor.close();
return count;
}
public void endTransaction() {
mSQLiteDatabase.endTransaction();
}
public void execSQL(String sql) {
Log.d("GeoBeagle", "SQL: " + sql);
mSQLiteDatabase.execSQL(sql);
}
public void execSQL(String sql, Object... bindArgs) {
Log.d("GeoBeagle", "SQL: " + sql + ", " + Arrays.toString(bindArgs));
mSQLiteDatabase.execSQL(sql, bindArgs);
}
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
final Cursor query = mSQLiteDatabase.query(table, columns, selection, selectionArgs,
groupBy, orderBy, having, limit);
// Log.d("GeoBeagle", "limit: " + limit + ", count: " +
// query.getCount() + ", query: "
// + selection);
Log.d("GeoBeagle", "limit: " + limit + ", query: " + selection);
return query;
}
public Cursor rawQuery(String sql, String[] selectionArgs) {
return mSQLiteDatabase.rawQuery(sql, selectionArgs);
}
public void setTransactionSuccessful() {
mSQLiteDatabase.setTransactionSuccessful();
}
public void close() {
Log.d("GeoBeagle", "----------closing sqlite------");
mSQLiteDatabase.close();
}
public boolean isOpen() {
return mSQLiteDatabase.isOpen();
}
}
static public class SearchFactory {
public Search createSearch(double latitude, double longitude, float min, float max,
ISQLiteDatabase sqliteWrapper) {
WhereStringFactory whereStringFactory = new WhereStringFactory();
BoundingBox boundingBox = new BoundingBox(latitude, longitude, sqliteWrapper,
whereStringFactory);
SearchDown searchDown = new SearchDown(boundingBox, min);
SearchUp searchUp = new SearchUp(boundingBox, max);
return new WhereFactoryNearestCaches.Search(boundingBox, searchDown, searchUp);
}
}
public static CacheReader createCacheReader(ISQLiteDatabase sqliteWrapper) {
final CacheReaderCursorFactory cacheReaderCursorFactory = new CacheReaderCursorFactory();
return new CacheReader(sqliteWrapper, cacheReaderCursorFactory);
}
public static CacheWriter createCacheWriter(ISQLiteDatabase writableDatabase) {
// final SQLiteWrapper sqliteWrapper = new
// DatabaseDI.SQLiteWrapper(sqliteDatabaseWritable);
final DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheWriter(writableDatabase, dbToGeocacheAdapter);
}
}
| Java |
/*
** 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.code.geobeagle;
public enum CacheType {
NULL(0, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "null"),
MULTI(2, R.drawable.cache_multi, R.drawable.cache_multi_big,
R.drawable.map_pin2_multi, "Multi"),
TRADITIONAL(1, R.drawable.cache_tradi, R.drawable.cache_tradi_big,
R.drawable.map_pin2_tradi, "Traditional"),
UNKNOWN(3, R.drawable.cache_mystery, R.drawable.cache_mystery_big,
R.drawable.map_pin2_mystery, "Unknown Cache"),
MY_LOCATION(4, R.drawable.blue_dot, R.drawable.blue_dot,
R.drawable.map_pin2_empty, "My location"),
//Caches without unique icons
EARTHCACHE(5, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Earthcache"),
VIRTUAL(6, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Virtual Cache"),
LETTERBOX_HYBRID(7, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Letterbox Hybrid"),
EVENT(8, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Event Cache"),
WEBCAM(9, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Webcam Cache"),
CITO(10, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Cache In Trash Out Event"),
LOCATIONLESS(11, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Locationless (Reverse) Cache"),
APE(12, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Project APE Cache"),
MEGA(13, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Mega-Event Cache"),
//Waypoint types
WAYPOINT(20, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Waypoint"), //Not actually seen in GPX...
WAYPOINT_PARKING(21, R.drawable.cache_waypoint_p, R.drawable.cache_waypoint_p_big,
R.drawable.map_pin2_wp_p, "Waypoint|Parking Area"),
WAYPOINT_REFERENCE(22, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "Waypoint|Reference Point"),
WAYPOINT_STAGES(23, R.drawable.cache_waypoint_s, R.drawable.cache_waypoint_s_big,
R.drawable.map_pin2_wp_s, "Waypoint|Stages of a Multicache"),
WAYPOINT_TRAILHEAD(24, R.drawable.cache_waypoint_t, R.drawable.cache_waypoint_t_big,
R.drawable.map_pin2_wp_t, "Waypoint|Trailhead"),
WAYPOINT_FINAL(25, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "Waypoint|Final Location"); //TODO: Doesn't have unique graphics yet
private final int mIconId;
private final int mIconIdBig;
private final int mIx;
private final int mIconIdMap;
private final String mTag;
CacheType(int ix, int drawableId, int drawableIdBig, int drawableIdMap,
String tag) {
mIx = ix;
mIconId = drawableId;
mIconIdBig = drawableIdBig;
mIconIdMap = drawableIdMap;
mTag = tag;
}
public int icon() {
return mIconId;
}
public int iconBig() {
return mIconIdBig;
}
public int toInt() {
return mIx;
}
public int iconMap() {
return mIconIdMap;
}
public String getTag() {
return mTag;
}
}
| Java |
/*
** 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.code.geobeagle.gpx.zip;
import com.google.code.geobeagle.xmlimport.gpx.zip.GpxZipInputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipInputStream;
public class ZipInputStreamFactory {
public GpxZipInputStream create(String filename) throws IOException {
return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream(
new FileInputStream(filename))));
}
}
| Java |
/*
** 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.code.geobeagle;
public class Time {
public long getCurrentTime() {
return System.currentTimeMillis();
}
} | Java |
/*
** 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.code.geobeagle;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.Geocache.AttributeFormatter;
import com.google.code.geobeagle.Geocache.AttributeFormatterImpl;
import com.google.code.geobeagle.Geocache.AttributeFormatterNull;
import com.google.code.geobeagle.GeocacheFactory.Source.SourceFactory;
import com.google.code.geobeagle.activity.main.GeocacheFromParcelFactory;
import android.os.Parcel;
import android.os.Parcelable;
public class GeocacheFactory {
public static class CreateGeocacheFromParcel implements Parcelable.Creator<Geocache> {
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory = new GeocacheFromParcelFactory(
new GeocacheFactory());
public Geocache createFromParcel(Parcel in) {
return mGeocacheFromParcelFactory.create(in);
}
public Geocache[] newArray(int size) {
return new Geocache[size];
}
}
public static enum Provider {
ATLAS_QUEST(0, "LB"), GROUNDSPEAK(1, "GC"), MY_LOCATION(-1, "ML"), OPENCACHING(2, "OC");
private final int mIx;
private final String mPrefix;
Provider(int ix, String prefix) {
mIx = ix;
mPrefix = prefix;
}
public int toInt() {
return mIx;
}
public String getPrefix() {
return mPrefix;
}
}
public static Provider ALL_PROVIDERS[] = {
Provider.ATLAS_QUEST, Provider.GROUNDSPEAK, Provider.MY_LOCATION, Provider.OPENCACHING
};
public static enum Source {
GPX(0), LOC(3), MY_LOCATION(1), WEB_URL(2);
public static class SourceFactory {
private final Source mSources[] = new Source[values().length];
public SourceFactory() {
for (Source source : values())
mSources[source.mIx] = source;
}
public Source fromInt(int i) {
return mSources[i];
}
}
private final int mIx;
Source(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
static class AttributeFormatterFactory {
private AttributeFormatterImpl mAttributeFormatterImpl;
private AttributeFormatterNull mAttributeFormatterNull;
public AttributeFormatterFactory(AttributeFormatterImpl attributeFormatterImpl,
AttributeFormatterNull attributeFormatterNull) {
mAttributeFormatterImpl = attributeFormatterImpl;
mAttributeFormatterNull = attributeFormatterNull;
}
AttributeFormatter getAttributeFormatter(Source sourceType) {
if (sourceType == Source.GPX)
return mAttributeFormatterImpl;
return mAttributeFormatterNull;
}
}
private static CacheTypeFactory mCacheTypeFactory;
private static SourceFactory mSourceFactory;
private AttributeFormatterFactory mAttributeFormatterFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
mCacheTypeFactory = new CacheTypeFactory();
mAttributeFormatterFactory = new AttributeFormatterFactory(new AttributeFormatterImpl(),
new AttributeFormatterNull());
}
public CacheType cacheTypeFromInt(int cacheTypeIx) {
return mCacheTypeFactory.fromInt(cacheTypeIx);
}
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
if (name == null)
name = "";
final AttributeFormatter attributeFormatter = mAttributeFormatterFactory
.getAttributeFormatter(sourceType);
return new Geocache(id, name, latitude, longitude, sourceType, sourceName, cacheType,
difficulty, terrain, container, attributeFormatter);
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
}
| Java |
/*
** 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.code.geobeagle;
import com.google.code.geobeagle.LocationControlBuffered.GpsDisabledLocation;
import com.google.code.geobeagle.LocationControlBuffered.GpsEnabledLocation;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector.LocationComparator;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceSortStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.NullSortStrategy;
import com.google.code.geobeagle.location.LocationControl;
import com.google.code.geobeagle.location.LocationControl.LocationChooser;
import android.location.Location;
import android.location.LocationManager;
public class LocationControlDi {
public static LocationControlBuffered create(LocationManager locationManager) {
final LocationChooser locationChooser = new LocationChooser();
final LocationControl locationControl = new LocationControl(locationManager,
locationChooser);
final NullSortStrategy nullSortStrategy = new NullSortStrategy();
final LocationComparator locationComparator = new LocationComparator();
final DistanceSortStrategy distanceSortStrategy = new DistanceSortStrategy(
locationComparator);
final GpsDisabledLocation gpsDisabledLocation = new GpsDisabledLocation();
IGpsLocation lastGpsLocation;
final Location lastKnownLocation = locationManager.getLastKnownLocation("gps");
if (lastKnownLocation == null)
lastGpsLocation = gpsDisabledLocation;
else
lastGpsLocation = new GpsEnabledLocation((float)lastKnownLocation.getLatitude(),
(float)lastKnownLocation.getLongitude());
return new LocationControlBuffered(locationControl, distanceSortStrategy, nullSortStrategy,
gpsDisabledLocation, lastGpsLocation, lastKnownLocation);
}
}
| Java |
/*
** 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.code.geobeagle.activity;
import android.content.Context;
public class ActivityDI {
public static class ActivityTypeFactory {
private final ActivityType mActivityTypes[] = new ActivityType[ActivityType.values().length];
public ActivityTypeFactory() {
for (ActivityType activityType : ActivityType.values())
mActivityTypes[activityType.toInt()] = activityType;
}
public ActivityType fromInt(int i) {
return mActivityTypes[i];
}
}
public static ActivitySaver createActivitySaver(Context context) {
return new ActivitySaver(context.getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE)
.edit());
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.MapView;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
public class GeoMapView extends MapView {
private OverlayManager mOverlayManager;
public GeoMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Log.d("GeoBeagle", "~~~~~~~~~~onLayout " + changed + ", " + left + ", " + top + ", "
+ right + ", " + bottom);
if (mOverlayManager != null) {
mOverlayManager.selectOverlay();
}
}
public void setScrollListener(OverlayManager overlayManager) {
mOverlayManager = overlayManager;
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
import com.google.code.geobeagle.Geocache;
class CacheItem extends OverlayItem {
private final Geocache mGeocache;
CacheItem(GeoPoint geoPoint, String id, Geocache geocache) {
super(geoPoint, id, "");
mGeocache = geocache;
}
Geocache getGeocache() {
return mGeocache;
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionCacheList;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch;
import com.google.code.geobeagle.activity.map.QueryManager.CachedNeedsLoading;
import com.google.code.geobeagle.activity.map.QueryManager.PeggedLoader;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.Toaster;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class GeoMapActivity extends MapActivity {
private static class NullOverlay extends Overlay {
}
private static final int DEFAULT_ZOOM_LEVEL = 14;
private static boolean fZoomed = false;
private DbFrontend mDbFrontend;
private GeoMapActivityDelegate mGeoMapActivityDelegate;
private GeoMapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
@Override
protected boolean isRouteDisplayed() {
// This application doesn't use routes
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
// Set member variables first, in case anyone after this needs them.
mMapView = (GeoMapView)findViewById(R.id.mapview);
mDbFrontend = new DbFrontend(this);
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.setBuiltInZoomControls(true);
mMapView.setSatellite(false);
final Resources resources = getResources();
final Drawable defaultMarker = resources.getDrawable(R.drawable.map_pin2_others);
final CacheDrawables cacheDrawables = new CacheDrawables(resources);
final CacheItemFactory cacheItemFactory = new CacheItemFactory(cacheDrawables);
final List<Overlay> mapOverlays = mMapView.getOverlays();
final MenuActions menuActions = new MenuActions(getResources());
menuActions.add(new GeoMapActivityDelegate.MenuActionToggleSatellite(mMapView));
menuActions.add(new MenuActionCacheList(this));
final Intent intent = getIntent();
final MapController mapController = mMapView.getController();
final double latitude = intent.getFloatExtra("latitude", 0);
final double longitude = intent.getFloatExtra("longitude", 0);
final Overlay nullOverlay = new GeoMapActivity.NullOverlay();
final GeoPoint nullGeoPoint = new GeoPoint(0, 0);
mapOverlays.add(nullOverlay);
mapOverlays.add(mMyLocationOverlay);
final ArrayList<Geocache> nullList = new ArrayList<Geocache>();
final List<DensityPatch> densityPatches = new ArrayList<DensityPatch>();
final Toaster toaster = new Toaster(this, R.string.too_many_caches, Toast.LENGTH_SHORT);
final PeggedLoader peggedLoader = new QueryManager.PeggedLoader(mDbFrontend, nullList,
toaster);
final int[] initialLatLonMinMax = {
0, 0, 0, 0
};
CachedNeedsLoading cachedNeedsLoading = new CachedNeedsLoading(nullGeoPoint, nullGeoPoint);
final QueryManager queryManager = new QueryManager(peggedLoader, cachedNeedsLoading,
initialLatLonMinMax);
final DensityOverlayDelegate densityOverlayDelegate = DensityOverlay.createDelegate(
densityPatches, nullGeoPoint, queryManager);
final DensityOverlay densityOverlay = new DensityOverlay(densityOverlayDelegate);
final ArrayList<Geocache> geocacheList = new ArrayList<Geocache>();
final CachePinsOverlay cachePinsOverlay = new CachePinsOverlay(cacheItemFactory, this,
defaultMarker, geocacheList);
final CachePinsOverlayFactory cachePinsOverlayFactory = new CachePinsOverlayFactory(
mMapView, this, defaultMarker, cacheItemFactory, cachePinsOverlay, queryManager);
mGeoMapActivityDelegate = new GeoMapActivityDelegate(mMapView, menuActions);
final GeoPoint center = new GeoPoint((int)(latitude * GeoUtils.MILLION),
(int)(longitude * GeoUtils.MILLION));
mapController.setCenter(center);
final OverlayManager overlayManager = new OverlayManager(mMapView, mapOverlays,
densityOverlay, cachePinsOverlayFactory, false);
mMapView.setScrollListener(overlayManager);
if (!fZoomed) {
mapController.setZoom(DEFAULT_ZOOM_LEVEL);
fZoomed = true;
}
overlayManager.selectOverlay();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return mGeoMapActivityDelegate.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return mGeoMapActivityDelegate.onMenuOpened(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mGeoMapActivityDelegate.onOptionsItemSelected(item);
}
@Override
public void onPause() {
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
mDbFrontend.closeDatabase();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.enableCompass();
mDbFrontend.openDatabase();
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.List;
public class DensityOverlay extends Overlay {
// Create delegate because it's not possible to test classes that extend
// Android classes.
public static DensityOverlayDelegate createDelegate(List<DensityMatrix.DensityPatch> patches,
GeoPoint nullGeoPoint, QueryManager queryManager) {
final Rect patchRect = new Rect();
final Paint paint = new Paint();
paint.setARGB(128, 255, 0, 0);
final Point screenLow = new Point();
final Point screenHigh = new Point();
final DensityPatchManager densityPatchManager = new DensityPatchManager(patches,
queryManager);
return new DensityOverlayDelegate(patchRect, paint, screenLow, screenHigh,
densityPatchManager);
}
private DensityOverlayDelegate mDelegate;
public DensityOverlay(DensityOverlayDelegate densityOverlayDelegate) {
mDelegate = densityOverlayDelegate;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
mDelegate.draw(canvas, mapView, shadow);
}
}
| Java |
/*
** 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.code.geobeagle.activity.map;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
public class CachePinsOverlay extends ItemizedOverlay<CacheItem> {
private final CacheItemFactory mCacheItemFactory;
private final Context mContext;
private final ArrayList<Geocache> mCacheList;
public CachePinsOverlay(CacheItemFactory cacheItemFactory, Context context,
Drawable defaultMarker, ArrayList<Geocache> list) {
super(boundCenterBottom(defaultMarker));
mContext = context;
mCacheItemFactory = cacheItemFactory;
mCacheList = list;
populate();
}
/* (non-Javadoc)
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean, long)
*/
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
return super.draw(canvas, mapView, shadow, when);
}
@Override
protected boolean onTap(int i) {
Geocache geocache = getItem(i).getGeocache();
if (geocache == null)
return false;
final Intent intent = new Intent(mContext, GeoBeagle.class);
intent.setAction(GeocacheListController.SELECT_CACHE);
intent.putExtra("geocache", geocache);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
return true;
}
@Override
protected CacheItem createItem(int i) {
return mCacheItemFactory.createCacheItem(mCacheList.get(i));
}
@Override
public int size() {
return mCacheList.size();
}
}
| Java |
/*
** 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.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivityRestorer;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi;
import com.google.code.geobeagle.activity.main.GeocacheFromPreferencesFactory;
import com.google.code.geobeagle.activity.searchonline.JsInterface.JsInterfaceHelper;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidget.InflatedGpsStatusWidget;
import com.google.code.geobeagle.location.CombinedLocationListener;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import java.util.ArrayList;
public class SearchOnlineActivity extends Activity {
private SearchOnlineActivityDelegate mSearchOnlineActivityDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "SearchOnlineActivity onCreate");
setContentView(R.layout.search);
final LocationManager locationManager = (LocationManager)this
.getSystemService(Context.LOCATION_SERVICE);
final LocationControlBuffered mLocationControlBuffered = LocationControlDi
.create(locationManager);
final ArrayList<LocationListener> locationListeners = new ArrayList<LocationListener>(3);
final CombinedLocationManager mCombinedLocationManager = new CombinedLocationManager(
locationManager, locationListeners);
final InflatedGpsStatusWidget mGpsStatusWidget = (InflatedGpsStatusWidget)this
.findViewById(R.id.gps_widget_view);
final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi
.create(this);
final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(this,
mGpsStatusWidget, mLocationControlBuffered, mCombinedLocationManager,
distanceFormatterManager.getFormatter());
final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater
.getGpsStatusWidgetDelegate();
gpsWidgetAndUpdater.getUpdateGpsWidgetRunnable().run();
mGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate);
mGpsStatusWidget.setBackgroundColor(Color.BLACK);
final Refresher refresher = new NullRefresher();
final CompassListener mCompassListener = new CompassListener(refresher,
mLocationControlBuffered, 720);
final SensorManager mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
final CombinedLocationListener mCombinedLocationListener = new CombinedLocationListener(
mLocationControlBuffered, gpsStatusWidgetDelegate);
distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final GeocacheFromPreferencesFactory geocacheFromPreferencesFactory = new GeocacheFromPreferencesFactory(
geocacheFactory);
final ActivityTypeFactory activityTypeFactory = new ActivityTypeFactory();
final ActivityRestorer activityRestorer = new ActivityRestorer(this,
geocacheFromPreferencesFactory, activityTypeFactory, getSharedPreferences(
"GeoBeagle", Context.MODE_PRIVATE));
mSearchOnlineActivityDelegate = new SearchOnlineActivityDelegate(
((WebView)findViewById(R.id.help_contents)), mSensorManager, mCompassListener,
mCombinedLocationManager, mCombinedLocationListener, mLocationControlBuffered,
distanceFormatterManager, activitySaver);
final JsInterfaceHelper jsInterfaceHelper = new JsInterfaceHelper(this);
final JsInterface jsInterface = new JsInterface(mLocationControlBuffered, jsInterfaceHelper);
mSearchOnlineActivityDelegate.configureWebView(jsInterface);
activityRestorer.restore(getIntent().getFlags());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_online_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
startActivity(new Intent(this, CacheListActivity.class));
return true;
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "SearchOnlineActivity onResume");
mSearchOnlineActivityDelegate.onResume();
}
@Override
protected void onPause() {
super.onPause();
Log.d("GeoBeagle", "SearchOnlineActivity onPause");
mSearchOnlineActivityDelegate.onPause();
}
}
| Java |
/*
** 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.code.geobeagle.activity;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.activity.main.view.EditCacheActivityDelegate;
import com.google.code.geobeagle.activity.main.view.EditCacheActivityDelegate.CancelButtonOnClickListener;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.LocationSaver;
import android.app.Activity;
import android.os.Bundle;
public class EditCacheActivity extends Activity {
private EditCacheActivityDelegate mEditCacheActivityDelegate;
private DbFrontend mDbFrontend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final CancelButtonOnClickListener cancelButtonOnClickListener = new CancelButtonOnClickListener(
this);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
mDbFrontend = new DbFrontend(this);
LocationSaver locationSaver = new LocationSaver(mDbFrontend);
mEditCacheActivityDelegate = new EditCacheActivityDelegate(this,
cancelButtonOnClickListener, geocacheFactory, locationSaver);
mEditCacheActivityDelegate.onCreate();
}
@Override
protected void onPause() {
super.onPause();
mDbFrontend.closeDatabase();
}
@Override
protected void onResume() {
super.onResume();
mEditCacheActivityDelegate.onResume();
}
}
| Java |
/*
** 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.code.geobeagle.activity;
public enum ActivityType {
// These constants are persisted to the database. They are also used as
// indices in ActivityRestorer.
CACHE_LIST(1), NONE(0), SEARCH_ONLINE(2), VIEW_CACHE(3);
private final int mIx;
ActivityType(int i) {
mIx = i;
}
int toInt() {
return mIx;
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButton;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButtons;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckDetailsButton;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckWebPageButton;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader.DetailsOpener;
import android.app.AlertDialog.Builder;
import android.view.LayoutInflater;
import android.view.View;
public class Misc {
public static CacheDetailsOnClickListener createCacheDetailsOnClickListener(
GeoBeagle geoBeagle, Builder alertDialogBuilder, LayoutInflater layoutInflater) {
final DetailsOpener detailsOpener = new DetailsOpener(geoBeagle);
final CacheDetailsLoader cacheDetailsLoader = new CacheDetailsLoader(detailsOpener);
return new CacheDetailsOnClickListener(geoBeagle, alertDialogBuilder, layoutInflater,
cacheDetailsLoader);
}
public static WebPageAndDetailsButtonEnabler create(GeoBeagle geoBeagle, View webPageButton,
View detailsButton) {
final CheckWebPageButton checkWebPageButton = new CheckWebPageButton(webPageButton);
final CheckDetailsButton checkDetailsButton = new CheckDetailsButton(detailsButton);
final CheckButtons checkButtons = new CheckButtons(new CheckButton[] {
checkWebPageButton, checkDetailsButton
});
return new WebPageAndDetailsButtonEnabler(geoBeagle, checkButtons);
}
}
| Java |
/*
** 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.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.app.AlertDialog;
import android.view.LayoutInflater;
public class FieldNoteSenderDI {
public static FieldNoteSender build(GeoBeagle parent, LayoutInflater layoutInflater) {
final AlertDialog.Builder builder = new AlertDialog.Builder(parent);
final FieldNoteSender.DialogHelper dialogHelper = new FieldNoteSender.DialogHelper();
return new FieldNoteSender(layoutInflater, builder, dialogHelper);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.LocationControlBuffered.GpsDisabledLocation;
import com.google.code.geobeagle.actions.MenuActionSearchOnline;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegate.ImportIntentManager;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextAction;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionEdit;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionView;
import com.google.code.geobeagle.activity.cachelist.actions.menu.Abortable;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionMyLocation;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionToggleFilter;
import com.google.code.geobeagle.activity.cachelist.model.CacheListData;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.presenter.ActionAndTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.AdapterCachesSorter;
import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListAdapter;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.activity.cachelist.presenter.ListTitleFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.LocationAndAzimuthTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.LocationTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.SensorManagerWrapper;
import com.google.code.geobeagle.activity.cachelist.presenter.SqlCacheLoader;
import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.ToleranceStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag;
import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.FilterNearestCaches;
import com.google.code.geobeagle.database.LocationSaver;
import com.google.code.geobeagle.database.WhereFactoryAllCaches;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches;
import com.google.code.geobeagle.database.DatabaseDI.SearchFactory;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.WhereStringFactory;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidget;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater;
import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidget.InflatedGpsStatusWidget;
import com.google.code.geobeagle.location.CombinedLocationListener;
import com.google.code.geobeagle.location.CombinedLocationManager;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.CachePersisterFacadeFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.hardware.SensorManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout.LayoutParams;
import java.util.ArrayList;
import java.util.Calendar;
public class CacheListDelegateDI {
public static class Timing {
private long mStartTime;
public void lap(CharSequence msg) {
long finishTime = Calendar.getInstance().getTimeInMillis();
Log.d("GeoBeagle", "****** " + msg + ": " + (finishTime - mStartTime));
mStartTime = finishTime;
}
public void start() {
mStartTime = Calendar.getInstance().getTimeInMillis();
}
public long getTime() {
return Calendar.getInstance().getTimeInMillis();
}
}
public static CacheListDelegate create(ListActivity listActivity, LayoutInflater layoutInflater) {
final OnClickListener mOnClickListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
final ErrorDisplayer errorDisplayer = new ErrorDisplayer(listActivity, mOnClickListener);
final LocationManager locationManager = (LocationManager)listActivity
.getSystemService(Context.LOCATION_SERVICE);
ArrayList<LocationListener> locationListeners = new ArrayList<LocationListener>(3);
final CombinedLocationManager combinedLocationManager = new CombinedLocationManager(
locationManager, locationListeners);
final LocationControlBuffered locationControlBuffered = LocationControlDi
.create(locationManager);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final GeocacheFromMyLocationFactory geocacheFromMyLocationFactory = new GeocacheFromMyLocationFactory(
geocacheFactory, locationControlBuffered);
final BearingFormatter relativeBearingFormatter = new RelativeBearingFormatter();
final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi
.create(listActivity);
final ArrayList<GeocacheVector> geocacheVectorsList = new ArrayList<GeocacheVector>(10);
final GeocacheVectors geocacheVectors = new GeocacheVectors(geocacheVectorsList);
final CacheListData cacheListData = new CacheListData(geocacheVectors);
final XmlPullParserWrapper xmlPullParserWrapper = new XmlPullParserWrapper();
final GeocacheSummaryRowInflater geocacheSummaryRowInflater = new GeocacheSummaryRowInflater(
distanceFormatterManager.getFormatter(), geocacheVectors, layoutInflater,
relativeBearingFormatter);
final UpdateFlag updateFlag = new UpdateFlag();
final GeocacheListAdapter geocacheListAdapter = new GeocacheListAdapter(geocacheVectors,
geocacheSummaryRowInflater);
final InflatedGpsStatusWidget inflatedGpsStatusWidget = new InflatedGpsStatusWidget(
listActivity);
final GpsStatusWidget gpsStatusWidget = new GpsStatusWidget(listActivity);
gpsStatusWidget.addView(inflatedGpsStatusWidget, LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(listActivity,
gpsStatusWidget, locationControlBuffered, combinedLocationManager,
distanceFormatterManager.getFormatter());
final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater
.getGpsStatusWidgetDelegate();
inflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate);
final CombinedLocationListener combinedLocationListener = new CombinedLocationListener(
locationControlBuffered, gpsStatusWidgetDelegate);
final UpdateGpsWidgetRunnable updateGpsWidgetRunnable = gpsWidgetAndUpdater
.getUpdateGpsWidgetRunnable();
updateGpsWidgetRunnable.run();
final WhereFactoryAllCaches whereFactoryAllCaches = new WhereFactoryAllCaches();
final SearchFactory searchFactory = new SearchFactory();
final WhereStringFactory whereStringFactory = new WhereStringFactory();
final WhereFactoryNearestCaches whereFactoryNearestCaches = new WhereFactoryNearestCaches(
searchFactory, whereStringFactory);
final FilterNearestCaches filterNearestCaches = new FilterNearestCaches(
whereFactoryAllCaches, whereFactoryNearestCaches);
final ListTitleFormatter listTitleFormatter = new ListTitleFormatter();
final CacheListDelegateDI.Timing timing = new CacheListDelegateDI.Timing();
final AdapterCachesSorter adapterCachesSorter = new AdapterCachesSorter(cacheListData,
timing, locationControlBuffered);
final GpsDisabledLocation gpsDisabledLocation = new GpsDisabledLocation();
final DistanceUpdater distanceUpdater = new DistanceUpdater(geocacheListAdapter);
final ToleranceStrategy sqlCacheLoaderTolerance = new LocationTolerance(500,
gpsDisabledLocation, 1000);
final ToleranceStrategy adapterCachesSorterTolerance = new LocationTolerance(6,
gpsDisabledLocation, 1000);
final LocationTolerance distanceUpdaterLocationTolerance = new LocationTolerance(1,
gpsDisabledLocation, 1000);
final ToleranceStrategy distanceUpdaterTolerance = new LocationAndAzimuthTolerance(
distanceUpdaterLocationTolerance, 720);
final ActionAndTolerance[] actionAndTolerances = new ActionAndTolerance[] {
null, new ActionAndTolerance(adapterCachesSorter, adapterCachesSorterTolerance),
new ActionAndTolerance(distanceUpdater, distanceUpdaterTolerance)
};
final ActionManagerFactory actionManagerFactory = new ActionManagerFactory(
actionAndTolerances, sqlCacheLoaderTolerance);
final DbFrontend dbFrontend = new DbFrontend(listActivity);
final TitleUpdater titleUpdater = new TitleUpdater(listActivity, filterNearestCaches,
listTitleFormatter, timing);
final SqlCacheLoader sqlCacheLoader = new SqlCacheLoader(dbFrontend, filterNearestCaches,
cacheListData, locationControlBuffered, titleUpdater, timing);
final ActionManager actionManager = actionManagerFactory.create(sqlCacheLoader);
final CacheListRefresh cacheListRefresh = new CacheListRefresh(actionManager, timing,
locationControlBuffered, updateFlag);
final SensorManager sensorManager = (SensorManager)listActivity
.getSystemService(Context.SENSOR_SERVICE);
final CompassListenerFactory compassListenerFactory = new CompassListenerFactory(
locationControlBuffered);
distanceFormatterManager.addHasDistanceFormatter(geocacheSummaryRowInflater);
distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate);
final CacheListView.ScrollListener scrollListener = new CacheListView.ScrollListener(
updateFlag);
final SensorManagerWrapper sensorManagerWrapper = new SensorManagerWrapper(sensorManager);
final GeocacheListPresenter geocacheListPresenter = new GeocacheListPresenter(
combinedLocationListener, combinedLocationManager, compassListenerFactory,
distanceFormatterManager, geocacheListAdapter, geocacheSummaryRowInflater,
geocacheVectors, gpsStatusWidget, listActivity, locationControlBuffered,
sensorManagerWrapper, updateGpsWidgetRunnable, scrollListener);
final CacheTypeFactory cacheTypeFactory = new CacheTypeFactory();
final Aborter aborter = new Aborter();
final MessageHandler messageHandler = MessageHandler.create(listActivity);
final CachePersisterFacadeFactory cachePersisterFacadeFactory = new CachePersisterFacadeFactory(
messageHandler, cacheTypeFactory);
final GpxImporterFactory gpxImporterFactory = new GpxImporterFactory(aborter,
cachePersisterFacadeFactory, errorDisplayer, geocacheListPresenter, listActivity,
messageHandler, xmlPullParserWrapper);
final Abortable nullAbortable = new Abortable() {
public void abort() {
}
};
final MenuActionSyncGpx menuActionSyncGpx = new MenuActionSyncGpx(nullAbortable,
cacheListRefresh, gpxImporterFactory, dbFrontend);
final MenuActions menuActions = new MenuActions(listActivity.getResources());
menuActions.add(menuActionSyncGpx);
menuActions.add(new MenuActionToggleFilter(filterNearestCaches, cacheListRefresh));
menuActions.add(new MenuActionMyLocation(cacheListRefresh, errorDisplayer,
geocacheFromMyLocationFactory, new LocationSaver(dbFrontend)));
menuActions.add(new MenuActionSearchOnline(listActivity));
// menuActions.add(new MenuActionChooseFilter(listActivity));
final Intent geoBeagleMainIntent = new Intent(listActivity, GeoBeagle.class);
final ContextActionView contextActionView = new ContextActionView(geocacheVectors,
listActivity, geoBeagleMainIntent);
final ContextActionEdit contextActionEdit = new ContextActionEdit(geocacheVectors,
listActivity);
final ContextActionDelete contextActionDelete = new ContextActionDelete(
geocacheListAdapter, geocacheVectors, titleUpdater, dbFrontend);
final ContextAction[] contextActions = new ContextAction[] {
contextActionDelete, contextActionView, contextActionEdit
};
final GeocacheListController geocacheListController = new GeocacheListController(
cacheListRefresh, contextActions, filterNearestCaches, menuActionSyncGpx,
menuActions);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(listActivity);
final ImportIntentManager importIntentManager = new ImportIntentManager(listActivity);
return new CacheListDelegate(importIntentManager, activitySaver, cacheListRefresh,
geocacheListController, geocacheListPresenter, dbFrontend);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheListActivity extends ListActivity {
private CacheListDelegate mCacheListDelegate;
// This is the ctor that Android will use.
public CacheListActivity() {
}
// This is the ctor for testing.
public CacheListActivity(CacheListDelegate cacheListDelegate) {
mCacheListDelegate = cacheListDelegate;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return mCacheListDelegate.onContextItemSelected(item) || super.onContextItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "CacheListActivity onCreate");
mCacheListDelegate = CacheListDelegateDI.create(this, getLayoutInflater());
mCacheListDelegate.onCreate();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return mCacheListDelegate.onCreateOptionsMenu(menu);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mCacheListDelegate.onListItemClick(l, v, position, id);
}
/*
* (non-Javadoc)
* @see android.app.Activity#onMenuOpened(int, android.view.Menu)
*/
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
super.onMenuOpened(featureId, menu);
return mCacheListDelegate.onMenuOpened(featureId, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mCacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
Log.d("GeoBeagle", "CacheListActivity onPause");
super.onPause();
mCacheListDelegate.onPause();
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "CacheListActivity onResume");
mCacheListDelegate.onResume();
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class DistanceFormatterManagerDi {
public static DistanceFormatterManager create(Context context) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final DistanceFormatterMetric distanceFormatterMetric = new DistanceFormatterMetric();
final DistanceFormatterImperial distanceFormatterImperial = new DistanceFormatterImperial();
return new DistanceFormatterManager(sharedPreferences, distanceFormatterImperial,
distanceFormatterMetric);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
public class CompassListenerFactory {
private final LocationControlBuffered mLocationControlBuffered;
public CompassListenerFactory(LocationControlBuffered locationControlBuffered) {
mLocationControlBuffered = locationControlBuffered;
}
public CompassListener create(CacheListRefresh cacheListRefresh) {
return new CompassListener(cacheListRefresh, mLocationControlBuffered, 720);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.activity.cachelist.presenter.ActionAndTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.SqlCacheLoader;
import com.google.code.geobeagle.activity.cachelist.presenter.ToleranceStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager;
public class ActionManagerFactory {
private final ActionAndTolerance[] mActionAndTolerances;
private final ToleranceStrategy mSqlCacheLoaderTolerance;
public ActionManagerFactory(ActionAndTolerance[] actionAndTolerances,
ToleranceStrategy sqlCacheLoaderTolerance) {
mActionAndTolerances = actionAndTolerances;
mSqlCacheLoaderTolerance = sqlCacheLoaderTolerance;
}
public ActionManager create(SqlCacheLoader sqlCacheLoader) {
mActionAndTolerances[0] = new ActionAndTolerance(
sqlCacheLoader, mSqlCacheLoaderTolerance);
return new ActionManager(mActionAndTolerances);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.GpxImporter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.CachePersisterFacadeFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.app.ListActivity;
public class GpxImporterFactory {
private final Aborter mAborter;
private final CachePersisterFacadeFactory mCachePersisterFacadeFactory;
private final ErrorDisplayer mErrorDisplayer;
private final GeocacheListPresenter mGeocacheListPresenter;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final XmlPullParserWrapper mXmlPullParserWrapper;
public GpxImporterFactory(Aborter aborter,
CachePersisterFacadeFactory cachePersisterFacadeFactory, ErrorDisplayer errorDisplayer,
GeocacheListPresenter geocacheListPresenter, ListActivity listActivity,
MessageHandler messageHandler, XmlPullParserWrapper xmlPullParserWrapper) {
mAborter = aborter;
mCachePersisterFacadeFactory = cachePersisterFacadeFactory;
mErrorDisplayer = errorDisplayer;
mGeocacheListPresenter = geocacheListPresenter;
mListActivity = listActivity;
mMessageHandler = messageHandler;
mXmlPullParserWrapper = xmlPullParserWrapper;
}
public GpxImporter create(CacheWriter cacheWriter) {
return GpxImporterDI.create(mListActivity, mXmlPullParserWrapper, mErrorDisplayer,
mGeocacheListPresenter, mAborter, mMessageHandler, mCachePersisterFacadeFactory,
cacheWriter);
}
}
| Java |
/*
** 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.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
public class CacheListView extends ListView {
public static class ScrollListener implements OnScrollListener {
private final UpdateFlag mUpdateFlag;
public ScrollListener(UpdateFlag updateFlag) {
mUpdateFlag = updateFlag;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mUpdateFlag.setUpdatesEnabled(scrollState == SCROLL_STATE_IDLE);
}
}
// If these constructors aren't here, Android throws
// java.lang.NoSuchMethodException: CacheListView(Context,AttributeSet)
public CacheListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CacheListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CacheListView(Context context) {
super(context);
}
/*
* (non-Javadoc)
* @see android.widget.ListView#setAdapter(android.widget.ListAdapter)
*/
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
}
| Java |
/*
** 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.code.geobeagle.activity.preferences;
import com.google.code.geobeagle.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class EditPreferences extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.actions.menu.Abortable;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.ImportThreadWrapper;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.ToastFactory;
import android.app.ListActivity;
import android.widget.Toast;
public class GpxImporter implements Abortable {
private final ErrorDisplayer mErrorDisplayer;
private final EventHandlers mEventHandlers;
private final GpxLoader mGpxLoader;
private final ImportThreadWrapper mImportThreadWrapper;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final ToastFactory mToastFactory;
private final GeocacheListPresenter mGeocacheListPresenter;
GpxImporter(GeocacheListPresenter geocacheListPresenter, GpxLoader gpxLoader,
ListActivity listActivity, ImportThreadWrapper importThreadWrapper,
MessageHandler messageHandler, ToastFactory toastFactory, EventHandlers eventHandlers,
ErrorDisplayer errorDisplayer) {
mListActivity = listActivity;
mGpxLoader = gpxLoader;
mEventHandlers = eventHandlers;
mImportThreadWrapper = importThreadWrapper;
mMessageHandler = messageHandler;
mErrorDisplayer = errorDisplayer;
mToastFactory = toastFactory;
mGeocacheListPresenter = geocacheListPresenter;
}
public void abort() {
mMessageHandler.abortLoad();
mGpxLoader.abort();
if (mImportThreadWrapper.isAlive()) {
mImportThreadWrapper.join();
mToastFactory.showToast(mListActivity, R.string.import_canceled, Toast.LENGTH_SHORT);
}
}
public void importGpxs(CacheListRefresh cacheListRefresh) {
mGeocacheListPresenter.onPause();
mImportThreadWrapper.open(cacheListRefresh, mGpxLoader, mEventHandlers, mErrorDisplayer);
mImportThreadWrapper.start();
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import java.io.IOException;
class EventHandlerLoc implements EventHandler {
static final String XPATH_COORD = "/loc/waypoint/coord";
static final String XPATH_GROUNDSPEAKNAME = "/loc/waypoint/name";
static final String XPATH_LOC = "/loc";
static final String XPATH_WPT = "/loc/waypoint";
static final String XPATH_WPTNAME = "/loc/waypoint/name";
private final CachePersisterFacade mCachePersisterFacade;
EventHandlerLoc(CachePersisterFacade cachePersisterFacade) {
mCachePersisterFacade = cachePersisterFacade;
}
public void endTag(String previousFullPath) throws IOException {
if (previousFullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.endCache(Source.LOC);
}
}
public void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException {
if (mFullPath.equals(XPATH_COORD)) {
mCachePersisterFacade.wpt(mXmlPullParser.getAttributeValue(null, "lat"), mXmlPullParser
.getAttributeValue(null, "lon"));
} else if (mFullPath.equals(XPATH_WPTNAME)) {
mCachePersisterFacade.startCache();
mCachePersisterFacade.wptName(mXmlPullParser.getAttributeValue(null, "id"));
}
}
public boolean text(String mFullPath, String text) throws IOException {
if (mFullPath.equals(XPATH_WPTNAME))
mCachePersisterFacade.groundspeakName(text.trim());
return true;
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilesAndZipFilesIter;
import org.xmlpull.v1.XmlPullParserException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ImportThreadDelegate {
public static class ImportThreadHelper {
private final ErrorDisplayer mErrorDisplayer;
private final EventHandlers mEventHandlers;
private final EventHelperFactory mEventHelperFactory;
private final GpxLoader mGpxLoader;
private boolean mHasFiles;
private final MessageHandler mMessageHandler;
public ImportThreadHelper(GpxLoader gpxLoader, MessageHandler messageHandler,
EventHelperFactory eventHelperFactory, EventHandlers eventHandlers,
ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mGpxLoader = gpxLoader;
mMessageHandler = messageHandler;
mEventHelperFactory = eventHelperFactory;
mEventHandlers = eventHandlers;
mHasFiles = false;
}
public void cleanup() {
mMessageHandler.loadComplete();
}
public void end() {
mGpxLoader.end();
if (!mHasFiles)
mErrorDisplayer.displayError(R.string.error_no_gpx_files);
}
public boolean processFile(IGpxReader gpxReader) throws XmlPullParserException, IOException {
String filename = gpxReader.getFilename();
mHasFiles = true;
mGpxLoader.open(filename, gpxReader.open());
return mGpxLoader.load(mEventHelperFactory.create(mEventHandlers.get(filename)));
}
public void start() {
mGpxLoader.start();
}
}
private final ErrorDisplayer mErrorDisplayer;
private final GpxAndZipFiles mGpxAndZipFiles;
private final ImportThreadHelper mImportThreadHelper;
public ImportThreadDelegate(GpxAndZipFiles gpxAndZipFiles,
ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) {
mGpxAndZipFiles = gpxAndZipFiles;
mImportThreadHelper = importThreadHelper;
mErrorDisplayer = errorDisplayer;
}
public void run() {
try {
tryRun();
} catch (final FileNotFoundException e) {
mErrorDisplayer.displayError(R.string.error_opening_file, e.getMessage());
} catch (IOException e) {
mErrorDisplayer.displayError(R.string.error_reading_file, e.getMessage());
} catch (XmlPullParserException e) {
mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage());
} finally {
mImportThreadHelper.cleanup();
}
}
protected void tryRun() throws IOException, XmlPullParserException {
GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = mGpxAndZipFiles.iterator();
if (gpxFilesAndZipFilesIter == null) {
mErrorDisplayer.displayError(R.string.error_cant_read_sd);
return;
}
mImportThreadHelper.start();
while (gpxFilesAndZipFilesIter.hasNext()) {
if (!mImportThreadHelper.processFile(gpxFilesAndZipFilesIter.next()))
return;
}
mImportThreadHelper.end();
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
public class GpxToCache {
public static class Aborter {
private static boolean mAborted = false;
public Aborter() {
mAborted = false;
}
public void abort() {
mAborted = true;
}
public boolean isAborted() {
return mAborted;
}
public void reset() {
mAborted = false;
}
}
@SuppressWarnings("serial")
public static class CancelException extends Exception {
}
private final Aborter mAborter;
private final XmlPullParserWrapper mXmlPullParserWrapper;
GpxToCache(XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) {
mXmlPullParserWrapper = xmlPullParserWrapper;
mAborter = aborter;
}
public void abort() {
mAborter.abort();
}
public String getSource() {
return mXmlPullParserWrapper.getSource();
}
/**
* @param eventHelper
* @return false if this file has already been loaded.
* @throws XmlPullParserException
* @throws IOException
* @throws CancelException
*/
public boolean load(EventHelper eventHelper) throws XmlPullParserException, IOException,
CancelException {
int eventType;
for (eventType = mXmlPullParserWrapper.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = mXmlPullParserWrapper
.next()) {
if (mAborter.isAborted())
throw new CancelException();
// File already loaded.
if (!eventHelper.handleEvent(eventType))
return true;
}
// Pick up END_DOCUMENT event as well.
eventHelper.handleEvent(eventType);
return false;
}
public void open(String source, Reader reader) throws XmlPullParserException {
mXmlPullParserWrapper.open(source, reader);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import java.io.IOException;
interface EventHandler {
void endTag(String previousFullPath) throws IOException;
void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException;
boolean text(String mFullPath, String text) throws IOException;
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.database.CacheWriter;
/**
* @author sng
*/
public class CacheTagSqlWriter {
private final CacheTypeFactory mCacheTypeFactory;
private CacheType mCacheType;
private final CacheWriter mCacheWriter;
private int mContainer;
private int mDifficulty;
private boolean mFound;
private String mGpxName;
private CharSequence mId;
private double mLatitude;
private double mLongitude;
private CharSequence mName;
private String mSqlDate;
private int mTerrain;
public CacheTagSqlWriter(CacheWriter cacheWriter,
CacheTypeFactory cacheTypeFactory) {
mCacheWriter = cacheWriter;
mCacheTypeFactory = cacheTypeFactory;
}
public void cacheName(String name) {
mName = name;
}
public void cacheType(String type) {
mCacheType = mCacheTypeFactory.fromTag(type);
}
public void clear() { // TODO: ensure source is not reset
mId = mName = null;
mLatitude = mLongitude = 0;
mFound = false;
mCacheType = CacheType.NULL;
mDifficulty = 0;
mTerrain = 0;
}
public void container(String container) {
mContainer = mCacheTypeFactory.container(container);
}
public void difficulty(String difficulty) {
mDifficulty = mCacheTypeFactory.stars(difficulty);
}
public void end() {
mCacheWriter.clearEarlierLoads();
}
public void gpxName(String gpxName) {
mGpxName = gpxName;
}
/**
* @param gpxTime
* @return true if we should load this gpx; false if the gpx is already
* loaded.
*/
public boolean gpxTime(String gpxTime) {
mSqlDate = isoTimeToSql(gpxTime);
if (mCacheWriter.isGpxAlreadyLoaded(mGpxName, mSqlDate)) {
return false;
}
mCacheWriter.clearCaches(mGpxName);
return true;
}
public void id(CharSequence id) {
mId = id;
}
public String isoTimeToSql(String gpxTime) {
return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19);
}
public void latitudeLongitude(String latitude, String longitude) {
mLatitude = Double.parseDouble(latitude);
mLongitude = Double.parseDouble(longitude);
}
public void startWriting() {
mSqlDate = "2000-01-01T12:00:00";
mCacheWriter.startWriting();
}
public void stopWriting(boolean successfulGpxImport) {
mCacheWriter.stopWriting();
if (successfulGpxImport)
mCacheWriter.writeGpx(mGpxName, mSqlDate);
}
public void symbol(String symbol) {
mFound = symbol.equals("Geocache Found");
}
public void terrain(String terrain) {
mTerrain = mCacheTypeFactory.stars(terrain);
}
public void write(Source source) {
if (!mFound)
mCacheWriter.insertAndUpdateCache(mId, mName, mLatitude, mLongitude, source, mGpxName,
mCacheType, mDifficulty, mTerrain, mContainer);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class GpxAndZipFiles {
public static class GpxAndZipFilenameFilter implements FilenameFilter {
private final GpxFilenameFilter mGpxFilenameFilter;
public GpxAndZipFilenameFilter(GpxFilenameFilter gpxFilenameFilter) {
mGpxFilenameFilter = gpxFilenameFilter;
}
public boolean accept(File dir, String name) {
name = name.toLowerCase();
if (!name.startsWith(".") && name.endsWith(".zip"))
return true;
return mGpxFilenameFilter.accept(name);
}
}
public static class GpxFilenameFilter {
public boolean accept(String name) {
name = name.toLowerCase();
return !name.startsWith(".") && (name.endsWith(".gpx") || name.endsWith(".loc"));
}
}
public static class GpxFilesAndZipFilesIter {
private final String[] mFileList;
private final GpxFileIterAndZipFileIterFactory mGpxAndZipFileIterFactory;
private int mIxFileList;
private IGpxReaderIter mSubIter;
GpxFilesAndZipFilesIter(String[] fileList,
GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) {
mFileList = fileList;
mGpxAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory;
mIxFileList = 0;
}
public boolean hasNext() throws IOException {
// Iterate through actual zip and gpx files on the filesystem.
if (mSubIter != null && mSubIter.hasNext())
return true;
while (mIxFileList < mFileList.length) {
mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]);
if (mSubIter.hasNext())
return true;
}
return false;
}
public IGpxReader next() throws IOException {
return mSubIter.next();
}
}
public static final String GPX_DIR = "/sdcard/download/";
private final FilenameFilter mFilenameFilter;
private final GpxFileIterAndZipFileIterFactory mGpxFileIterAndZipFileIterFactory;
public GpxAndZipFiles(FilenameFilter filenameFilter,
GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) {
mFilenameFilter = filenameFilter;
mGpxFileIterAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory;
}
public GpxFilesAndZipFilesIter iterator() {
String[] fileList = new File(GPX_DIR).list(mFilenameFilter);
if (fileList == null)
return null;
mGpxFileIterAndZipFileIterFactory.resetAborter();
return new GpxFilesAndZipFilesIter(fileList, mGpxFileIterAndZipFileIterFactory);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.gpx.gpx.GpxFileOpener;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester;
import java.io.IOException;
/**
* @author sng Takes a filename and returns an IGpxReaderIter based on the
* extension: zip: ZipFileIter gpx/loc: GpxFileIter
*/
public class GpxFileIterAndZipFileIterFactory {
private final Aborter mAborter;
private final ZipInputFileTester mZipInputFileTester;
public GpxFileIterAndZipFileIterFactory(ZipInputFileTester zipInputFileTester, Aborter aborter) {
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
public IGpxReaderIter fromFile(String filename) throws IOException {
if (filename.endsWith(".zip")) {
return new ZipFileOpener(GpxAndZipFiles.GPX_DIR + filename,
new ZipInputStreamFactory(), mZipInputFileTester, mAborter).iterator();
}
return new GpxFileOpener(GpxAndZipFiles.GPX_DIR + filename, mAborter).iterator();
}
public void resetAborter() {
mAborter.reset();
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx.gpx;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
public GpxReader(String filename) {
mFilename = filename;
}
public String getFilename() {
return mFilename;
}
public Reader open() throws FileNotFoundException {
return new BufferedReader(new FileReader(mFilename));
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx.gpx;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter;
public class GpxFileOpener {
public class GpxFileIter implements IGpxReaderIter {
public boolean hasNext() {
if (mAborter.isAborted())
return false;
return mFilename != null;
}
public IGpxReader next() {
final IGpxReader gpxReader = new GpxReader(mFilename);
mFilename = null;
return gpxReader;
}
}
private Aborter mAborter;
private String mFilename;
public GpxFileOpener(String filename, Aborter aborter) {
mFilename = filename;
mAborter = aborter;
}
public GpxFileIter iterator() {
return new GpxFileIter();
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx;
import java.io.FileNotFoundException;
import java.io.Reader;
public interface IGpxReader {
String getFilename();
Reader open() throws FileNotFoundException;
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx;
import java.io.IOException;
public interface IGpxReaderIter {
public boolean hasNext() throws IOException;
public IGpxReader next() throws IOException;
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx.zip;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
private final Reader mReader;
GpxReader(String filename, Reader reader) {
mFilename = filename;
mReader = reader;
}
public String getFilename() {
return mFilename;
}
public Reader open() {
return mReader;
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx.zip;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
public class ZipFileOpener {
public static class ZipFileIter implements IGpxReaderIter {
private final Aborter mAborter;
private ZipEntry mNextZipEntry;
private final ZipInputFileTester mZipInputFileTester;
private final GpxZipInputStream mZipInputStream;
ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter,
ZipInputFileTester zipInputFileTester, ZipEntry nextZipEntry) {
mZipInputStream = zipInputStream;
mNextZipEntry = nextZipEntry;
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter,
ZipInputFileTester zipInputFileTester) {
mZipInputStream = zipInputStream;
mNextZipEntry = null;
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
public boolean hasNext() throws IOException {
// Iterate through zip file entries.
if (mNextZipEntry == null) {
do {
if (mAborter.isAborted())
break;
mNextZipEntry = mZipInputStream.getNextEntry();
} while (mNextZipEntry != null && !mZipInputFileTester.isValid(mNextZipEntry));
}
return mNextZipEntry != null;
}
public IGpxReader next() throws IOException {
final String name = mNextZipEntry.getName();
mNextZipEntry = null;
return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream()));
}
}
public static class ZipInputFileTester {
private final GpxFilenameFilter mGpxFilenameFilter;
public ZipInputFileTester(GpxFilenameFilter gpxFilenameFilter) {
mGpxFilenameFilter = gpxFilenameFilter;
}
public boolean isValid(ZipEntry zipEntry) {
return (!zipEntry.isDirectory() && mGpxFilenameFilter.accept(zipEntry.getName()));
}
}
private final Aborter mAborter;
private final String mFilename;
private final ZipInputFileTester mZipInputFileTester;
private final ZipInputStreamFactory mZipInputStreamFactory;
public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory,
ZipInputFileTester zipInputFileTester, Aborter aborter) {
mFilename = filename;
mZipInputStreamFactory = zipInputStreamFactory;
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
public ZipFileIter iterator() throws IOException {
return new ZipFileIter(mZipInputStreamFactory.create(mFilename), mAborter,
mZipInputFileTester);
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport.gpx.zip;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GpxZipInputStream {
private ZipEntry mNextEntry;
private final ZipInputStream mZipInputStream;
public GpxZipInputStream(ZipInputStream zipInputStream) {
mZipInputStream = zipInputStream;
}
ZipEntry getNextEntry() throws IOException {
mNextEntry = mZipInputStream.getNextEntry();
return mNextEntry;
}
InputStream getStream() {
return mZipInputStream;
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException;
import org.xmlpull.v1.XmlPullParserException;
import android.database.sqlite.SQLiteException;
import android.os.PowerManager.WakeLock;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
public class GpxLoader {
private final CachePersisterFacade mCachePersisterFacade;
private final ErrorDisplayer mErrorDisplayer;
private final GpxToCache mGpxToCache;
private final WakeLock mWakeLock;
public static final int WAKELOCK_DURATION = 15000;
GpxLoader(CachePersisterFacade cachePersisterFacade, ErrorDisplayer errorDisplayer,
GpxToCache gpxToCache, WakeLock wakeLock) {
mGpxToCache = gpxToCache;
mCachePersisterFacade = cachePersisterFacade;
mErrorDisplayer = errorDisplayer;
mWakeLock = wakeLock;
}
public void abort() {
mGpxToCache.abort();
}
public void end() {
mCachePersisterFacade.end();
}
/**
* @return true if we should continue loading more files, false if we should
* terminate.
*/
public boolean load(EventHelper eventHelper) {
boolean markLoadAsComplete = false;
boolean continueLoading = false;
try {
mWakeLock.acquire(WAKELOCK_DURATION);
boolean alreadyLoaded = mGpxToCache.load(eventHelper);
markLoadAsComplete = !alreadyLoaded;
continueLoading = true;
} catch (final SQLiteException e) {
mErrorDisplayer.displayError(R.string.error_writing_cache, mGpxToCache.getSource()
+ ": " + e.getMessage());
} catch (XmlPullParserException e) {
mErrorDisplayer.displayError(R.string.error_parsing_file, mGpxToCache.getSource()
+ ": " + e.getMessage());
} catch (FileNotFoundException e) {
mErrorDisplayer.displayError(R.string.file_not_found, mGpxToCache.getSource() + ": "
+ e.getMessage());
} catch (IOException e) {
mErrorDisplayer.displayError(R.string.error_reading_file, mGpxToCache.getSource()
+ ": " + e.getMessage());
} catch (CancelException e) {
}
mCachePersisterFacade.close(markLoadAsComplete);
return continueLoading;
}
public void open(String path, Reader reader) throws XmlPullParserException {
mGpxToCache.open(path, reader);
mCachePersisterFacade.open(path);
}
public void start() {
mCachePersisterFacade.start();
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import org.xmlpull.v1.XmlPullParser;
import java.io.IOException;
public class EventHelper {
public static class XmlPathBuilder {
private String mPath = "";
public void endTag(String currentTag) {
mPath = mPath.substring(0, mPath.length() - (currentTag.length() + 1));
}
public String getPath() {
return mPath;
}
public void startTag(String mCurrentTag) {
mPath += "/" + mCurrentTag;
}
}
private final EventHandler mEventHandler;
private final XmlPathBuilder mXmlPathBuilder;
private final XmlPullParserWrapper mXmlPullParser;
EventHelper(XmlPathBuilder xmlPathBuilder, EventHandler eventHandler,
XmlPullParserWrapper xmlPullParser) {
mXmlPathBuilder = xmlPathBuilder;
mXmlPullParser = xmlPullParser;
mEventHandler = eventHandler;
}
public boolean handleEvent(int eventType) throws IOException {
switch (eventType) {
case XmlPullParser.START_TAG:
mXmlPathBuilder.startTag(mXmlPullParser.getName());
mEventHandler.startTag(mXmlPathBuilder.getPath(), mXmlPullParser);
break;
case XmlPullParser.END_TAG:
mEventHandler.endTag(mXmlPathBuilder.getPath());
mXmlPathBuilder.endTag(mXmlPullParser.getName());
break;
case XmlPullParser.TEXT:
return mEventHandler.text(mXmlPathBuilder.getPath(), mXmlPullParser.getText());
}
return true;
}
}
| Java |
package com.google.code.geobeagle.xmlimport;
import java.util.HashMap;
public class EventHandlers {
private final HashMap<String, EventHandler> mEventHandlers = new HashMap<String, EventHandler>();
public void add(String extension, EventHandler eventHandler) {
mEventHandlers.put(extension.toLowerCase(), eventHandler);
}
public EventHandler get(String filename) {
int len = filename.length();
String extension = filename.substring(Math.max(0, len - 4), len);
return mEventHandlers.get(extension.toLowerCase());
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import java.io.IOException;
class EventHandlerGpx implements EventHandler {
static final String XPATH_CACHE_CONTAINER = "/gpx/wpt/groundspeak:cache/groundspeak:container";
static final String XPATH_CACHE_DIFFICULTY = "/gpx/wpt/groundspeak:cache/groundspeak:difficulty";
static final String XPATH_CACHE_TERRAIN = "/gpx/wpt/groundspeak:cache/groundspeak:terrain";
static final String XPATH_CACHE_TYPE = "/gpx/wpt/groundspeak:cache/groundspeak:type";
static final String XPATH_GEOCACHE_CONTAINER = "/gpx/wpt/geocache/container";
static final String XPATH_GEOCACHE_DIFFICULTY = "/gpx/wpt/geocache/difficulty";
static final String XPATH_GEOCACHE_TERRAIN = "/gpx/wpt/geocache/terrain";
static final String XPATH_GEOCACHE_TYPE = "/gpx/wpt/geocache/type";
static final String XPATH_GEOCACHEHINT = "/gpx/wpt/geocache/hints";
static final String XPATH_GEOCACHELOGDATE = "/gpx/wpt/geocache/logs/log/time";
static final String XPATH_GEOCACHENAME = "/gpx/wpt/geocache/name";
static final String XPATH_GPXNAME = "/gpx/name";
static final String XPATH_GPXTIME = "/gpx/time";
static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name";
static final String XPATH_HINT = "/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints";
static final String XPATH_LOGDATE = "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date";
static final String[] XPATH_PLAINLINES = {
"/gpx/wpt/cmt", "/gpx/wpt/desc", "/gpx/wpt/groundspeak:cache/groundspeak:type",
"/gpx/wpt/groundspeak:cache/groundspeak:container",
"/gpx/wpt/groundspeak:cache/groundspeak:short_description",
"/gpx/wpt/groundspeak:cache/groundspeak:long_description",
"/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type",
"/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder",
"/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text",
/* here are the geocaching.com.au entries */
"/gpx/wpt/geocache/owner", "/gpx/wpt/geocache/type", "/gpx/wpt/geocache/summary",
"/gpx/wpt/geocache/description", "/gpx/wpt/geocache/logs/log/geocacher",
"/gpx/wpt/geocache/logs/log/type", "/gpx/wpt/geocache/logs/log/text"
};
static final String XPATH_SYM = "/gpx/wpt/sym";
static final String XPATH_WPT = "/gpx/wpt";
static final String XPATH_WPTDESC = "/gpx/wpt/desc";
static final String XPATH_WPTNAME = "/gpx/wpt/name";
static final String XPATH_WAYPOINT_TYPE = "/gpx/wpt/type";
private final CachePersisterFacade mCachePersisterFacade;
public EventHandlerGpx(CachePersisterFacade cachePersisterFacade) {
mCachePersisterFacade = cachePersisterFacade;
}
public void endTag(String previousFullPath) throws IOException {
if (previousFullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.endCache(Source.GPX);
}
}
public void startTag(String fullPath, XmlPullParserWrapper xmlPullParser) {
if (fullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.startCache();
mCachePersisterFacade.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser
.getAttributeValue(null, "lon"));
}
}
public boolean text(String fullPath, String text) throws IOException {
text = text.trim();
//Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text);
if (fullPath.equals(XPATH_WPTNAME)) {
mCachePersisterFacade.wptName(text);
} else if (fullPath.equals(XPATH_WPTDESC)) {
mCachePersisterFacade.wptDesc(text);
} else if (fullPath.equals(XPATH_GPXTIME)) {
return mCachePersisterFacade.gpxTime(text);
} else if (fullPath.equals(XPATH_GROUNDSPEAKNAME) || fullPath.equals(XPATH_GEOCACHENAME)) {
mCachePersisterFacade.groundspeakName(text);
} else if (fullPath.equals(XPATH_LOGDATE) || fullPath.equals(XPATH_GEOCACHELOGDATE)) {
mCachePersisterFacade.logDate(text);
} else if (fullPath.equals(XPATH_SYM)) {
mCachePersisterFacade.symbol(text);
} else if (fullPath.equals(XPATH_HINT) || fullPath.equals(XPATH_GEOCACHEHINT)) {
if (!text.equals("")) {
mCachePersisterFacade.hint(text);
}
} else if (fullPath.equals(XPATH_CACHE_TYPE) || fullPath.equals(XPATH_GEOCACHE_TYPE)
|| fullPath.equals(XPATH_WAYPOINT_TYPE)) {
//Log.d("GeoBeagle", "Setting cache type " + text);
mCachePersisterFacade.cacheType(text);
} else if (fullPath.equals(XPATH_CACHE_DIFFICULTY)
|| fullPath.equals(XPATH_GEOCACHE_DIFFICULTY)) {
mCachePersisterFacade.difficulty(text);
} else if (fullPath.equals(XPATH_CACHE_TERRAIN) || fullPath.equals(XPATH_GEOCACHE_TERRAIN)) {
mCachePersisterFacade.terrain(text);
} else if (fullPath.equals(XPATH_CACHE_CONTAINER)
|| fullPath.equals(XPATH_GEOCACHE_CONTAINER)) {
mCachePersisterFacade.container(text);
}
for (String writeLineMatch : XPATH_PLAINLINES) {
if (fullPath.equals(writeLineMatch)) {
mCachePersisterFacade.line(text);
return true;
}
}
return true;
}
}
| Java |
/*
** 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.code.geobeagle.xmlimport;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.cachedetails.CacheDetailsWriter;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.FileFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import android.os.PowerManager.WakeLock;
import java.io.File;
import java.io.IOException;
public class CachePersisterFacade {
private final CacheDetailsWriter mCacheDetailsWriter;
private String mCacheName = "";
private final CacheTagSqlWriter mCacheTagWriter;
private final FileFactory mFileFactory;
private final MessageHandler mMessageHandler;
private final WakeLock mWakeLock;
CachePersisterFacade(CacheTagSqlWriter cacheTagSqlWriter, FileFactory fileFactory,
CacheDetailsWriter cacheDetailsWriter, MessageHandler messageHandler, WakeLock wakeLock) {
mCacheDetailsWriter = cacheDetailsWriter;
mCacheTagWriter = cacheTagSqlWriter;
mFileFactory = fileFactory;
mMessageHandler = messageHandler;
mWakeLock = wakeLock;
}
void cacheType(String text) {
mCacheTagWriter.cacheType(text);
}
void close(boolean success) {
mCacheTagWriter.stopWriting(success);
}
void container(String text) {
mCacheTagWriter.container(text);
}
void difficulty(String text) {
mCacheTagWriter.difficulty(text);
}
void end() {
mCacheTagWriter.end();
}
void endCache(Source source) throws IOException {
mMessageHandler.updateName(mCacheName);
mCacheDetailsWriter.close();
mCacheTagWriter.write(source);
}
boolean gpxTime(String gpxTime) {
return mCacheTagWriter.gpxTime(gpxTime);
}
void groundspeakName(String text) {
mCacheTagWriter.cacheName(text);
}
void hint(String text) throws IOException {
mCacheDetailsWriter.writeHint(text);
}
void line(String text) throws IOException {
mCacheDetailsWriter.writeLine(text);
}
void logDate(String text) throws IOException {
mCacheDetailsWriter.writeLogDate(text);
}
void open(String path) {
mMessageHandler.updateSource(path);
mCacheTagWriter.startWriting();
mCacheTagWriter.gpxName(path);
}
void start() {
File file = mFileFactory.createFile(CacheDetailsWriter.GEOBEAGLE_DIR);
file.mkdirs();
}
void startCache() {
mCacheName = "";
mCacheTagWriter.clear();
}
void symbol(String text) {
mCacheTagWriter.symbol(text);
}
void terrain(String text) {
mCacheTagWriter.terrain(text);
}
void wpt(String latitude, String longitude) {
mCacheTagWriter.latitudeLongitude(latitude, longitude);
mCacheDetailsWriter.latitudeLongitude(latitude, longitude);
}
void wptDesc(String cacheName) {
mCacheName = cacheName;
mCacheTagWriter.cacheName(cacheName);
}
void wptName(String wpt) throws IOException {
mCacheDetailsWriter.open(wpt);
mCacheDetailsWriter.writeWptName(wpt);
mCacheTagWriter.id(wpt);
mMessageHandler.updateWaypointId(wpt);
mWakeLock.acquire(GpxLoader.WAKELOCK_DURATION);
}
}
| Java |
/*
** 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.code.geobeagle.cachedetails;
import java.io.IOException;
public class CacheDetailsWriter {
public static final String GEOBEAGLE_DIR = "/sdcard/GeoBeagle";
private final HtmlWriter mHtmlWriter;
private String mLatitude;
private String mLongitude;
public CacheDetailsWriter(HtmlWriter htmlWriter) {
mHtmlWriter = htmlWriter;
}
public void close() throws IOException {
mHtmlWriter.writeFooter();
mHtmlWriter.close();
}
public void latitudeLongitude(String latitude, String longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
public void open(String wpt) throws IOException {
final String sanitized = replaceIllegalFileChars(wpt);
mHtmlWriter.open(CacheDetailsWriter.GEOBEAGLE_DIR + "/" + sanitized + ".html");
}
public static String replaceIllegalFileChars(String wpt) {
return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_");
}
public void writeHint(String text) throws IOException {
mHtmlWriter.write("<br />Hint: <font color=gray>" + text + "</font>");
}
public void writeLine(String text) throws IOException {
mHtmlWriter.write(text);
}
public void writeLogDate(String text) throws IOException {
mHtmlWriter.writeSeparator();
mHtmlWriter.write(text);
}
public void writeWptName(String wpt) throws IOException {
mHtmlWriter.writeHeader();
mHtmlWriter.write(wpt);
mHtmlWriter.write(mLatitude + ", " + mLongitude);
mLatitude = mLongitude = null;
}
}
| Java |
/*
** 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.code.geobeagle.cachedetails;
import com.google.code.geobeagle.R;
import android.app.Activity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CacheDetailsLoader {
static interface Details {
String getString();
}
static class DetailsError implements Details {
private final Activity mActivity;
private final String mPath;
private final int mResourceId;
DetailsError(Activity activity, int resourceId, String path) {
mActivity = activity;
mResourceId = resourceId;
mPath = path;
}
public String getString() {
return mActivity.getString(mResourceId, mPath);
}
}
static class DetailsImpl implements Details {
private final byte[] mBuffer;
DetailsImpl(byte[] buffer) {
mBuffer = buffer;
}
public String getString() {
return new String(mBuffer);
}
}
public static class DetailsOpener {
private final Activity mActivity;
public DetailsOpener(Activity activity) {
mActivity = activity;
}
DetailsReader open(File file) {
FileInputStream fileInputStream;
String absolutePath = file.getAbsolutePath();
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
return new DetailsReaderFileNotFound(mActivity, e.getMessage());
}
byte[] buffer = new byte[(int)file.length()];
return new DetailsReaderImpl(mActivity, absolutePath, fileInputStream, buffer);
}
}
interface DetailsReader {
Details read();
}
static class DetailsReaderFileNotFound implements DetailsReader {
private final Activity mActivity;
private final String mPath;
DetailsReaderFileNotFound(Activity activity, String path) {
mActivity = activity;
mPath = path;
}
public Details read() {
return new DetailsError(mActivity, R.string.error_opening_details_file, mPath);
}
}
static class DetailsReaderImpl implements DetailsReader {
private final Activity mActivity;
private final byte[] mBuffer;
private final FileInputStream mFileInputStream;
private final String mPath;
DetailsReaderImpl(Activity activity, String path, FileInputStream fileInputStream,
byte[] buffer) {
mActivity = activity;
mFileInputStream = fileInputStream;
mPath = path;
mBuffer = buffer;
}
public Details read() {
try {
mFileInputStream.read(mBuffer);
mFileInputStream.close();
return new DetailsImpl(mBuffer);
} catch (IOException e) {
return new DetailsError(mActivity, R.string.error_reading_details_file, mPath);
}
}
}
public static final String DETAILS_DIR = "/sdcard/GeoBeagle/";
private final DetailsOpener mDetailsOpener;
public CacheDetailsLoader(DetailsOpener detailsOpener) {
mDetailsOpener = detailsOpener;
}
public String load(CharSequence cacheId) {
final String sanitized = CacheDetailsWriter.replaceIllegalFileChars(cacheId.toString());
String path = DETAILS_DIR + sanitized + ".html";
File file = new File(path);
DetailsReader detailsReader = mDetailsOpener.open(file);
Details details = detailsReader.read();
return details.getString();
}
}
| Java |
/*
** 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.code.geobeagle.cachedetails;
import java.io.IOException;
public class HtmlWriter {
private final WriterWrapper mWriter;
public HtmlWriter(WriterWrapper writerWrapper) {
mWriter = writerWrapper;
}
public void close() throws IOException {
mWriter.close();
}
public void open(String path) throws IOException {
mWriter.open(path);
}
public void write(String text) throws IOException {
mWriter.write(text + "<br/>\n");
}
public void writeFooter() throws IOException {
mWriter.write(" </body>\n");
mWriter.write("</html>\n");
}
public void writeHeader() throws IOException {
mWriter.write("<html>\n");
mWriter.write(" <body>\n");
}
public void writeSeparator() throws IOException {
mWriter.write("<hr/>\n");
}
}
| Java |
/*
** 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.code.geobeagle;
import com.google.android.maps.GeoPoint;
import com.google.code.geobeagle.GeocacheFactory.Provider;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.main.GeoUtils;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Geocache or letterbox description, id, and coordinates.
*/
public class Geocache implements Parcelable {
static interface AttributeFormatter {
CharSequence formatAttributes(int difficulty, int terrain);
}
static class AttributeFormatterImpl implements AttributeFormatter {
public CharSequence formatAttributes(int difficulty, int terrain) {
return (difficulty / 2.0) + " / " + (terrain / 2.0);
}
}
static class AttributeFormatterNull implements AttributeFormatter {
public CharSequence formatAttributes(int difficulty, int terrain) {
return "";
}
}
public static final String CACHE_TYPE = "cacheType";
public static final String CONTAINER = "container";
public static Parcelable.Creator<Geocache> CREATOR = new GeocacheFactory.CreateGeocacheFromParcel();
public static final String DIFFICULTY = "difficulty";
public static final String ID = "id";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String NAME = "name";
public static final String SOURCE_NAME = "sourceName";
public static final String SOURCE_TYPE = "sourceType";
public static final String TERRAIN = "terrain";
private final AttributeFormatter mAttributeFormatter;
private final CacheType mCacheType;
private final int mContainer;
private final int mDifficulty;
private float[] mDistanceAndBearing = new float[2];
private GeoPoint mGeoPoint;
private final CharSequence mId;
private final double mLatitude;
private final double mLongitude;
private final CharSequence mName;
private final String mSourceName;
private final Source mSourceType;
private final int mTerrain;
Geocache(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container, AttributeFormatter attributeFormatter) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
mSourceType = sourceType;
mSourceName = sourceName;
mCacheType = cacheType;
mDifficulty = difficulty;
mTerrain = terrain;
mContainer = container;
mAttributeFormatter = attributeFormatter;
}
public float[] calculateDistanceAndBearing(Location here) {
if (here != null) {
Location.distanceBetween(here.getLatitude(), here.getLongitude(), getLatitude(),
getLongitude(), mDistanceAndBearing);
return mDistanceAndBearing;
}
mDistanceAndBearing[0] = -1;
mDistanceAndBearing[1] = -1;
return mDistanceAndBearing;
}
public int describeContents() {
return 0;
}
public CacheType getCacheType() {
return mCacheType;
}
public int getContainer() {
return mContainer;
}
public GeocacheFactory.Provider getContentProvider() {
// Must use toString() rather than mId.subSequence(0,2).equals("GC"),
// because editing the text in android produces a SpannableString rather
// than a String, so the CharSequences won't be equal.
String prefix = mId.subSequence(0, 2).toString();
for (Provider provider : GeocacheFactory.ALL_PROVIDERS) {
if (prefix.equals(provider.getPrefix()))
return provider;
}
return Provider.GROUNDSPEAK;
}
public int getDifficulty() {
return mDifficulty;
}
public CharSequence getFormattedAttributes() {
return mAttributeFormatter.formatAttributes(mDifficulty, mTerrain);
}
public GeoPoint getGeoPoint() {
if (mGeoPoint == null) {
int latE6 = (int)(mLatitude * GeoUtils.MILLION);
int lonE6 = (int)(mLongitude * GeoUtils.MILLION);
mGeoPoint = new GeoPoint(latE6, lonE6);
}
return mGeoPoint;
}
public CharSequence getId() {
return mId;
}
public CharSequence getIdAndName() {
if (mId.length() == 0)
return mName;
else if (mName.length() == 0)
return mId;
else
return mId + ": " + mName;
}
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
public CharSequence getName() {
return mName;
}
public CharSequence getShortId() {
if (mId.length() > 2)
return mId.subSequence(2, mId.length());
return "";
}
public String getSourceName() {
return mSourceName;
}
public Source getSourceType() {
return mSourceType;
}
public int getTerrain() {
return mTerrain;
}
public void saveToBundle(Bundle bundle) {
bundle.putCharSequence(ID, mId);
bundle.putCharSequence(NAME, mName);
bundle.putDouble(LATITUDE, mLatitude);
bundle.putDouble(LONGITUDE, mLongitude);
bundle.putInt(SOURCE_TYPE, mSourceType.toInt());
bundle.putString(SOURCE_NAME, mSourceName);
bundle.putInt(CACHE_TYPE, mCacheType.toInt());
bundle.putInt(DIFFICULTY, mDifficulty);
bundle.putInt(TERRAIN, mTerrain);
bundle.putInt(CONTAINER, mContainer);
}
public void writeToParcel(Parcel out, int flags) {
Bundle bundle = new Bundle();
saveToBundle(bundle);
out.writeBundle(bundle);
}
public void writeToPrefs(Editor editor) {
// Must use toString(), see comment above in getCommentProvider.
editor.putString(ID, mId.toString());
editor.putString(NAME, mName.toString());
editor.putFloat(LATITUDE, (float)mLatitude);
editor.putFloat(LONGITUDE, (float)mLongitude);
editor.putInt(SOURCE_TYPE, mSourceType.toInt());
editor.putString(SOURCE_NAME, mSourceName);
editor.putInt(CACHE_TYPE, mCacheType.toInt());
editor.putInt(DIFFICULTY, mDifficulty);
editor.putInt(TERRAIN, mTerrain);
editor.putInt(CONTAINER, mContainer);
}
}
| Java |
/*
** 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.code.geobeagle.location;
import com.google.code.geobeagle.LocationControlBuffered;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
/*
* Listener for the Location control.
*/
public class CombinedLocationListener implements LocationListener {
private final LocationControlBuffered mLocationControlBuffered;
private final LocationListener mLocationListener;
public CombinedLocationListener(LocationControlBuffered locationControlBuffered,
LocationListener locationListener) {
mLocationListener = locationListener;
mLocationControlBuffered = locationControlBuffered;
}
public void onLocationChanged(Location location) {
// Ask the location control to pick the most accurate location (might
// not be this one).
// Log.d("GeoBeagle", "onLocationChanged:" + location);
final Location chosenLocation = mLocationControlBuffered.getLocation();
// Log.d("GeoBeagle", "onLocationChanged chosen Location" +
// chosenLocation);
mLocationListener.onLocationChanged(chosenLocation);
}
public void onProviderDisabled(String provider) {
mLocationListener.onProviderDisabled(provider);
}
public void onProviderEnabled(String provider) {
mLocationListener.onProviderEnabled(provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
mLocationListener.onStatusChanged(provider, status, extras);
}
}
| Java |
/*
** 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.code.geobeagle.location;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import java.util.ArrayList;
public class CombinedLocationManager {
private final ArrayList<LocationListener> mLocationListeners;
private final LocationManager mLocationManager;
public CombinedLocationManager(LocationManager locationManager,
ArrayList<LocationListener> locationListeners) {
mLocationManager = locationManager;
mLocationListeners = locationListeners;
}
public boolean isProviderEnabled() {
return mLocationManager.isProviderEnabled("gps")
|| mLocationManager.isProviderEnabled("network");
}
public void removeUpdates() {
for (LocationListener locationListener : mLocationListeners) {
mLocationManager.removeUpdates(locationListener);
}
mLocationListeners.clear();
}
public void requestLocationUpdates(int minTime, int minDistance,
LocationListener locationListener) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime,
minDistance, locationListener);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance,
locationListener);
mLocationListeners.add(locationListener);
}
public Location getLastKnownLocation() {
Location gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null)
return gpsLocation;
return mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.