Extract common code for viewing identities and contacts

Side-effect: view contact page now shows QR code
This commit is contained in:
str4d
2014-11-25 04:45:13 +00:00
parent f16c90d8d1
commit 0963a8522c
7 changed files with 497 additions and 581 deletions

View File

@@ -45,12 +45,12 @@ public class AddressBookActivity extends ActionBarActivity implements
public void onContactSelected(Contact contact) {
if (Intent.ACTION_PICK.equals(getIntent().getAction())) {
Intent result = new Intent();
result.putExtra(ViewContactFragment.CONTACT_DESTINATION, contact.getBase64Dest());
result.putExtra(ViewContactFragment.ADDRESS, contact.getBase64Dest());
setResult(Activity.RESULT_OK, result);
finish();
} else {
Intent i = new Intent(this, ViewContactActivity.class);
i.putExtra(ViewContactFragment.CONTACT_DESTINATION, contact.getBase64Dest());
i.putExtra(ViewContactFragment.ADDRESS, contact.getBase64Dest());
startActivityForResult(i, ALTER_CONTACT_LIST);
}
}

View File

@@ -26,7 +26,7 @@ public class ViewContactActivity extends ActionBarActivity {
String destination = null;
Bundle args = getIntent().getExtras();
if (args != null)
destination = args.getString(ViewContactFragment.CONTACT_DESTINATION);
destination = args.getString(ViewContactFragment.ADDRESS);
ViewContactFragment f = ViewContactFragment.newInstance(destination);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, f).commit();

View File

@@ -1,227 +1,101 @@
package i2p.bote.android.addressbook;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.security.GeneralSecurityException;
import i2p.bote.android.Constants;
import i2p.bote.android.R;
import i2p.bote.android.util.BoteHelper;
import i2p.bote.android.util.ViewAddressFragment;
import i2p.bote.fileencryption.PasswordException;
import i2p.bote.packet.dht.Contact;
public class ViewContactFragment extends Fragment {
public static final String CONTACT_DESTINATION = "contact_destination";
private String mDestination;
public class ViewContactFragment extends ViewAddressFragment {
private Contact mContact;
Toolbar mToolbar;
ImageView mContactPicture;
TextView mNameField;
TextView mTextField;
TextView mCryptoField;
TextView mDestinationField;
TextView mFingerprintField;
public static ViewContactFragment newInstance(String destination) {
ViewContactFragment f = new ViewContactFragment();
Bundle args = new Bundle();
args.putString(CONTACT_DESTINATION, destination);
args.putString(ADDRESS, destination);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mDestination = getArguments().getString(CONTACT_DESTINATION);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_view_address, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mToolbar = (Toolbar) view.findViewById(R.id.main_toolbar);
mContactPicture = (ImageView) view.findViewById(R.id.picture);
mNameField = (TextView) view.findViewById(R.id.public_name);
mTextField = (TextView) view.findViewById(R.id.description);
mCryptoField = (TextView) view.findViewById(R.id.crypto_impl_name);
mDestinationField = (TextView) view.findViewById(R.id.email_dest);
mFingerprintField = (TextView) view.findViewById(R.id.fingerprint);
if (mDestination != null) {
try {
mContact = BoteHelper.getContact(mDestination);
} catch (PasswordException e) {
// TODO Handle
e.printStackTrace();
protected void loadAddress() {
try {
mContact = BoteHelper.getContact(mAddress);
if (mContact == null) {
// No contact found, finish
getActivity().setResult(Activity.RESULT_CANCELED);
getActivity().finish();
}
} catch (PasswordException e) {
// TODO Handle
e.printStackTrace();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBarActivity activity = ((ActionBarActivity)getActivity());
protected String getPublicName() {
return mContact.getName();
}
// Set the action bar
activity.setSupportActionBar(mToolbar);
// Enable ActionBar app icon to behave as action to go back
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
@Override
protected int getDeleteAddressMessage() {
return R.string.delete_contact;
}
@Override
public void onResume() {
super.onResume();
if (mContact != null) {
Bitmap picture = BoteHelper.decodePicture(mContact.getPictureBase64());
if (picture != null)
mContactPicture.setImageBitmap(picture);
else {
ViewGroup.LayoutParams lp = mContactPicture.getLayoutParams();
mContactPicture.setImageBitmap(BoteHelper.getIdenticonForAddress(mDestination, lp.width, lp.height));
}
mNameField.setText(mContact.getName());
if (mContact.getText().isEmpty())
mTextField.setVisibility(View.GONE);
else {
mTextField.setText(mContact.getText());
mTextField.setVisibility(View.VISIBLE);
}
mCryptoField.setText(mContact.getDestination().getCryptoImpl().getName());
mDestinationField.setText(mDestination);
try {
String locale = getActivity().getResources().getConfiguration().locale.getLanguage();
mFingerprintField.setText(BoteHelper.getFingerprint(mContact, locale));
} catch (GeneralSecurityException e) {
// Could not get fingerprint
mFingerprintField.setText(e.getLocalizedMessage());
}
Bitmap picture = BoteHelper.decodePicture(mContact.getPictureBase64());
if (picture != null)
mPicture.setImageBitmap(picture);
else {
ViewGroup.LayoutParams lp = mPicture.getLayoutParams();
mPicture.setImageBitmap(BoteHelper.getIdenticonForAddress(mAddress, lp.width, lp.height));
}
mPublicName.setText(mContact.getName());
if (mContact.getText().isEmpty())
mDescription.setVisibility(View.GONE);
else {
mDescription.setText(mContact.getText());
mDescription.setVisibility(View.VISIBLE);
}
mCryptoImplName.setText(mContact.getDestination().getCryptoImpl().getName());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.view_contact, menu);
protected void onEditAddress() {
Intent ei = new Intent(getActivity(), EditContactActivity.class);
ei.putExtra(EditContactFragment.CONTACT_DESTINATION, mAddress);
startActivity(ei);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit_contact:
Intent ei = new Intent(getActivity(), EditContactActivity.class);
ei.putExtra(EditContactFragment.CONTACT_DESTINATION, mDestination);
startActivity(ei);
return true;
case R.id.action_delete_contact:
DialogFragment df = new DialogFragment() {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.delete_contact)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
String err = BoteHelper.deleteContact(mDestination);
if (err == null) {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
} else
Toast.makeText(getActivity(), err, Toast.LENGTH_SHORT).show();
} catch (PasswordException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
};
df.show(getActivity().getSupportFragmentManager(), "deletecontact");
return true;
default:
return super.onOptionsItemSelected(item);
protected void onDeleteAddress() {
try {
String err = BoteHelper.deleteContact(mAddress);
if (err == null) {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
} else
Toast.makeText(getActivity(), err, Toast.LENGTH_SHORT).show();
} catch (PasswordException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public NdefMessage createNdefMessage() {
NdefMessage msg = new NdefMessage(new NdefRecord[]{
createNameRecord(),
createDestinationRecord()
});
return msg;
}
private NdefRecord createNameRecord() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
return new NdefRecord(
NdefRecord.TNF_EXTERNAL_TYPE,
Constants.NDEF_LEGACY_TYPE_CONTACT.getBytes(),
new byte[0],
mContact.getName().getBytes()
);
else
return NdefRecord.createExternal(
Constants.NDEF_DOMAIN, Constants.NDEF_TYPE_CONTACT,
mContact.getName().getBytes()
);
}
private NdefRecord createDestinationRecord() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
return new NdefRecord(
NdefRecord.TNF_EXTERNAL_TYPE,
Constants.NDEF_LEGACY_TYPE_CONTACT_DESTINATION.getBytes(),
new byte[0],
mContact.getDestination().getKey().getBytes()
);
else
return NdefRecord.createExternal(
Constants.NDEF_DOMAIN, Constants.NDEF_TYPE_CONTACT_DESTINATION,
mContact.getDestination().getKey().getBytes()
);
}
}

View File

@@ -8,7 +8,6 @@ import i2p.bote.android.util.SummaryEditTextPreference;
import i2p.bote.email.EmailIdentity;
import i2p.bote.fileencryption.PasswordException;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collection;
@@ -23,7 +22,6 @@ import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
@@ -35,14 +33,12 @@ import android.preference.PreferenceManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class SettingsActivity extends PreferenceActivity {
// Actions for legacy settings
@@ -209,7 +205,7 @@ public class SettingsActivity extends PreferenceActivity {
Header header = mIdentityListHeaders[index];
if (header != null && header.id != HEADER_ID_UNDEFINED) {
String key = header.extras.getString(
ViewIdentityFragment.IDENTITY_KEY);
ViewIdentityFragment.ADDRESS);
if (key != mDeletingIdentityKey) {
target.add(header);
if (key == mRequestedIdentityKey) {
@@ -428,7 +424,7 @@ public class SettingsActivity extends PreferenceActivity {
final Intent intent = new Intent(
getApplicationContext(), ViewIdentityActivity.class);
final Bundle args = new Bundle();
args.putString(ViewIdentityFragment.IDENTITY_KEY, key);
args.putString(ViewIdentityFragment.ADDRESS, key);
intent.putExtras(args);
final Header newHeader = new Header();
newHeader.id = id;

View File

@@ -7,10 +7,8 @@ import android.nfc.NfcEvent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import i2p.bote.android.InitActivities;
import i2p.bote.android.R;
public class ViewIdentityActivity extends ActionBarActivity {
NfcAdapter mNfcAdapter;
@@ -28,7 +26,7 @@ public class ViewIdentityActivity extends ActionBarActivity {
String key = null;
Bundle args = getIntent().getExtras();
if (args != null)
key = args.getString(ViewIdentityFragment.IDENTITY_KEY);
key = args.getString(ViewIdentityFragment.ADDRESS);
ViewIdentityFragment f = ViewIdentityFragment.newInstance(key);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, f).commit();

View File

@@ -1,440 +1,107 @@
package i2p.bote.android.config;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;
import java.io.IOException;
import java.security.GeneralSecurityException;
import i2p.bote.android.Constants;
import i2p.bote.android.R;
import i2p.bote.android.util.BoteHelper;
import i2p.bote.android.util.QrCodeUtils;
import i2p.bote.android.util.ViewAddressFragment;
import i2p.bote.email.EmailIdentity;
import i2p.bote.fileencryption.PasswordException;
public class ViewIdentityFragment extends Fragment {
public static final String IDENTITY_KEY = "identity_key";
private String mKey;
public class ViewIdentityFragment extends ViewAddressFragment {
private EmailIdentity mIdentity;
Toolbar mToolbar;
ImageView mIdentityPicture;
TextView mNameField;
TextView mDescField;
TextView mFingerprintField;
TextView mCryptoField;
TextView mKeyField;
ImageView mKeyQrCode;
ImageView mExpandedQrCode;
// Hold a reference to the current animator,
// so that it can be canceled mid-way.
private Animator mQrCodeAnimator;
// The system "short" animation time duration, in milliseconds. This
// duration is ideal for subtle animations or animations that occur
// very frequently.
private int mShortAnimationDuration;
public static ViewIdentityFragment newInstance(String key) {
ViewIdentityFragment f = new ViewIdentityFragment();
Bundle args = new Bundle();
args.putString(IDENTITY_KEY, key);
args.putString(ADDRESS, key);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mKey = getArguments().getString(IDENTITY_KEY);
// Retrieve and cache the system's default "short" animation time.
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_view_address, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mToolbar = (Toolbar) view.findViewById(R.id.main_toolbar);
mIdentityPicture = (ImageView) view.findViewById(R.id.picture);
mNameField = (TextView) view.findViewById(R.id.public_name);
mDescField = (TextView) view.findViewById(R.id.description);
mFingerprintField = (TextView) view.findViewById(R.id.fingerprint);
mCryptoField = (TextView) view.findViewById(R.id.crypto_impl_name);
mKeyField = (TextView) view.findViewById(R.id.email_dest);
mKeyQrCode = (ImageView) view.findViewById(R.id.email_dest_qr_code);
mExpandedQrCode = (ImageView) view.findViewById(R.id.expanded_qr_code);
if (mKey != null) {
try {
mIdentity = BoteHelper.getIdentity(mKey);
} catch (PasswordException e) {
// TODO Handle
e.printStackTrace();
} catch (IOException e) {
// TODO Handle
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Handle
e.printStackTrace();
protected void loadAddress() {
try {
mIdentity = BoteHelper.getIdentity(mAddress);
if (mIdentity == null) {
// No identity found, finish
getActivity().setResult(Activity.RESULT_CANCELED);
getActivity().finish();
}
} catch (PasswordException e) {
// TODO Handle
e.printStackTrace();
} catch (IOException e) {
// TODO Handle
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Handle
e.printStackTrace();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBarActivity activity = ((ActionBarActivity) getActivity());
protected String getPublicName() {
return mIdentity.getPublicName();
}
// Set the action bar
activity.setSupportActionBar(mToolbar);
// Enable ActionBar app icon to behave as action to go back
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
@Override
protected int getDeleteAddressMessage() {
return R.string.delete_identity;
}
@Override
public void onResume() {
super.onResume();
if (mIdentity != null) {
Bitmap picture = BoteHelper.decodePicture(mIdentity.getPictureBase64());
if (picture != null)
mIdentityPicture.setImageBitmap(picture);
else {
ViewGroup.LayoutParams lp = mIdentityPicture.getLayoutParams();
mIdentityPicture.setImageBitmap(BoteHelper.getIdenticonForAddress(mKey, lp.width, lp.height));
}
mNameField.setText(mIdentity.getPublicName());
if (mIdentity.getDescription().isEmpty())
mDescField.setVisibility(View.GONE);
else {
mDescField.setText(mIdentity.getDescription());
mDescField.setVisibility(View.VISIBLE);
}
try {
String locale = getActivity().getResources().getConfiguration().locale.getLanguage();
mFingerprintField.setText(BoteHelper.getFingerprint(mIdentity, locale));
} catch (GeneralSecurityException e) {
// Could not get fingerprint
mFingerprintField.setText(e.getLocalizedMessage());
}
mCryptoField.setText(mIdentity.getCryptoImpl().getName());
mKeyField.setText(mKey);
mKeyQrCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
zoomQrCode();
}
});
loadQrCode();
Bitmap picture = BoteHelper.decodePicture(mIdentity.getPictureBase64());
if (picture != null)
mPicture.setImageBitmap(picture);
else {
ViewGroup.LayoutParams lp = mPicture.getLayoutParams();
mPicture.setImageBitmap(BoteHelper.getIdenticonForAddress(mAddress, lp.width, lp.height));
}
mPublicName.setText(mIdentity.getPublicName());
if (mIdentity.getDescription().isEmpty())
mDescription.setVisibility(View.GONE);
else {
mDescription.setText(mIdentity.getDescription());
mDescription.setVisibility(View.VISIBLE);
}
mCryptoImplName.setText(mIdentity.getCryptoImpl().getName());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.view_identity, menu);
protected void onEditAddress() {
Intent ei = new Intent(getActivity(), EditIdentityActivity.class);
ei.putExtra(EditIdentityFragment.IDENTITY_KEY, mAddress);
startActivity(ei);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit_identity:
Intent ei = new Intent(getActivity(), EditIdentityActivity.class);
ei.putExtra(EditIdentityFragment.IDENTITY_KEY, mKey);
startActivity(ei);
return true;
case R.id.action_delete_identity:
DialogFragment df = new DialogFragment() {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.delete_identity)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
BoteHelper.deleteIdentity(mKey);
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
} catch (PasswordException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
};
df.show(getActivity().getSupportFragmentManager(), "deletecontact");
return true;
default:
return super.onOptionsItemSelected(item);
protected void onDeleteAddress() {
try {
BoteHelper.deleteIdentity(mAddress);
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
} catch (PasswordException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public NdefMessage createNdefMessage() {
NdefMessage msg = new NdefMessage(new NdefRecord[]{
createNameRecord(),
createDestinationRecord()
});
return msg;
}
private NdefRecord createNameRecord() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
return new NdefRecord(
NdefRecord.TNF_EXTERNAL_TYPE,
"i2p.bote:contact".getBytes(),
new byte[0],
mIdentity.getPublicName().getBytes()
);
else
return NdefRecord.createExternal(
"i2p.bote", "contact", mIdentity.getPublicName().getBytes()
);
}
private NdefRecord createDestinationRecord() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
return new NdefRecord(
NdefRecord.TNF_EXTERNAL_TYPE,
"i2p.bote:contactDestination".getBytes(),
new byte[0],
mIdentity.getKey().getBytes()
);
else
return NdefRecord.createExternal(
"i2p.bote", "contactDestination", mIdentity.getKey().getBytes()
);
}
/**
* Load QR Code asynchronously and with a fade in animation
*/
private void loadQrCode() {
AsyncTask<Void, Void, Bitmap> loadTask =
new AsyncTask<Void, Void, Bitmap>() {
protected Bitmap doInBackground(Void... unused) {
String qrCodeContent = Constants.EMAILDEST_SCHEME + ":" + mKey;
// render with minimal size
return QrCodeUtils.getQRCodeBitmap(qrCodeContent, 0);
}
protected void onPostExecute(Bitmap qrCode) {
// only change view, if fragment is attached to activity
if (ViewIdentityFragment.this.isAdded()) {
// scale the image up to our actual size. we do this in code rather
// than let the ImageView do this because we don't require filtering.
Bitmap scaled = Bitmap.createScaledBitmap(qrCode,
mKeyQrCode.getHeight(), mKeyQrCode.getHeight(),
false);
mKeyQrCode.setImageBitmap(scaled);
// scale for the expanded image
int smallestDimen = Math.min(mExpandedQrCode.getWidth(), mExpandedQrCode.getHeight());
scaled = Bitmap.createScaledBitmap(qrCode,
smallestDimen, smallestDimen,
false);
mExpandedQrCode.setImageBitmap(scaled);
// simple fade-in animation
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(200);
mKeyQrCode.startAnimation(anim);
}
}
};
loadTask.execute();
}
private void zoomQrCode() {
// If there's an animation in progress, cancel it
// immediately and proceed with this one.
if (mQrCodeAnimator != null) {
mQrCodeAnimator.cancel();
}
// Calculate the starting and ending bounds for the zoomed-in image.
// This step involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
// The start bounds are the global visible rectangle of the thumbnail,
// and the final bounds are the global visible rectangle of the container
// view. Also set the container view's offset as the origin for the
// bounds, since that's the origin for the positioning animation
// properties (X, Y).
mKeyQrCode.getGlobalVisibleRect(startBounds);
getActivity().findViewById(R.id.container)
.getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the "center crop" technique. This prevents undesirable
// stretching during the animation. Also calculate the start scaling
// factor (the end scaling factor is always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
> (float) startBounds.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
// Hide the thumbnail and show the zoomed-in view. When the animation
// begins, it will position the zoomed-in view in the place of the
// thumbnail.
ViewHelper.setAlpha(mKeyQrCode, 0f);
mExpandedQrCode.setVisibility(View.VISIBLE);
// Set the pivot point for SCALE_X and SCALE_Y transformations
// to the top-left corner of the zoomed-in view (the default
// is the center of the view).
ViewHelper.setPivotX(mExpandedQrCode, 0f);
ViewHelper.setPivotY(mExpandedQrCode, 0f);
// Construct and run the parallel animation of the four translation and
// scale properties (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set
.play(ObjectAnimator.ofFloat(mExpandedQrCode, "x",
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(mExpandedQrCode, "y",
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(mExpandedQrCode, "scaleX",
startScale, 1f))
.with(ObjectAnimator.ofFloat(mExpandedQrCode, "scaleY",
startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mQrCodeAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
mQrCodeAnimator = null;
}
});
set.start();
mQrCodeAnimator = set;
// Upon clicking the zoomed-in image, it should zoom back down
// to the original bounds and show the thumbnail instead of
// the expanded image.
final float startScaleFinal = startScale;
mExpandedQrCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mQrCodeAnimator != null) {
mQrCodeAnimator.cancel();
}
// Animate the four positioning/sizing properties in parallel,
// back to their original values.
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator
.ofFloat(mExpandedQrCode, "x", startBounds.left))
.with(ObjectAnimator
.ofFloat(mExpandedQrCode,
"y", startBounds.top))
.with(ObjectAnimator
.ofFloat(mExpandedQrCode,
"scaleX", startScaleFinal))
.with(ObjectAnimator
.ofFloat(mExpandedQrCode,
"scaleY", startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ViewHelper.setAlpha(mKeyQrCode, 1f);
mExpandedQrCode.setVisibility(View.GONE);
mQrCodeAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
ViewHelper.setAlpha(mKeyQrCode, 1f);
mExpandedQrCode.setVisibility(View.GONE);
mQrCodeAnimator = null;
}
});
set.start();
mQrCodeAnimator = set;
}
});
}
}

View File

@@ -0,0 +1,381 @@
package i2p.bote.android.util;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;
import i2p.bote.android.Constants;
import i2p.bote.android.R;
public abstract class ViewAddressFragment extends Fragment {
public static final String ADDRESS = "address";
protected String mAddress;
Toolbar mToolbar;
protected ImageView mPicture;
protected TextView mPublicName;
protected TextView mDescription;
protected TextView mCryptoImplName;
TextView mAddressField;
ImageView mAddressQrCode;
TextView mFingerprint;
ImageView mExpandedQrCode;
// Hold a reference to the current animator,
// so that it can be canceled mid-way.
private Animator mQrCodeAnimator;
// The system "short" animation time duration, in milliseconds. This
// duration is ideal for subtle animations or animations that occur
// very frequently.
private int mShortAnimationDuration;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mAddress = getArguments().getString(ADDRESS);
// Retrieve and cache the system's default "short" animation time.
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_view_address, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mToolbar = (Toolbar) view.findViewById(R.id.main_toolbar);
mPicture = (ImageView) view.findViewById(R.id.picture);
mPublicName = (TextView) view.findViewById(R.id.public_name);
mDescription = (TextView) view.findViewById(R.id.description);
mFingerprint = (TextView) view.findViewById(R.id.fingerprint);
mCryptoImplName = (TextView) view.findViewById(R.id.crypto_impl_name);
mAddressField = (TextView) view.findViewById(R.id.email_dest);
mAddressQrCode = (ImageView) view.findViewById(R.id.email_dest_qr_code);
mExpandedQrCode = (ImageView) view.findViewById(R.id.expanded_qr_code);
if (mAddress != null) {
loadAddress();
}
}
protected abstract void loadAddress();
protected abstract String getPublicName();
protected abstract int getDeleteAddressMessage();
protected abstract void onEditAddress();
protected abstract void onDeleteAddress();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ActionBarActivity activity = ((ActionBarActivity) getActivity());
// Set the action bar
activity.setSupportActionBar(mToolbar);
// Enable ActionBar app icon to behave as action to go back
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onResume() {
super.onResume();
mAddressField.setText(mAddress);
mAddressQrCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
zoomQrCode();
}
});
loadQrCode();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.view_identity, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit_identity:
onEditAddress();
return true;
case R.id.action_delete_identity:
DialogFragment df = new DialogFragment() {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getDeleteAddressMessage())
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
onDeleteAddress();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
};
df.show(getActivity().getSupportFragmentManager(), "deleteaddress");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public NdefMessage createNdefMessage() {
NdefMessage msg = new NdefMessage(new NdefRecord[]{
createNameRecord(),
createDestinationRecord()
});
return msg;
}
private NdefRecord createNameRecord() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
return new NdefRecord(
NdefRecord.TNF_EXTERNAL_TYPE,
"i2p.bote:contact".getBytes(),
new byte[0],
getPublicName().getBytes()
);
else
return NdefRecord.createExternal(
"i2p.bote", "contact", getPublicName().getBytes()
);
}
private NdefRecord createDestinationRecord() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
return new NdefRecord(
NdefRecord.TNF_EXTERNAL_TYPE,
"i2p.bote:contactDestination".getBytes(),
new byte[0],
mAddress.getBytes()
);
else
return NdefRecord.createExternal(
"i2p.bote", "contactDestination", mAddress.getBytes()
);
}
/**
* Load QR Code asynchronously and with a fade in animation
*/
private void loadQrCode() {
AsyncTask<Void, Void, Bitmap> loadTask =
new AsyncTask<Void, Void, Bitmap>() {
protected Bitmap doInBackground(Void... unused) {
String qrCodeContent = Constants.EMAILDEST_SCHEME + ":" + mAddress;
// render with minimal size
return QrCodeUtils.getQRCodeBitmap(qrCodeContent, 0);
}
protected void onPostExecute(Bitmap qrCode) {
// only change view, if fragment is attached to activity
if (ViewAddressFragment.this.isAdded()) {
// scale the image up to our actual size. we do this in code rather
// than let the ImageView do this because we don't require filtering.
Bitmap scaled = Bitmap.createScaledBitmap(qrCode,
mAddressQrCode.getHeight(), mAddressQrCode.getHeight(),
false);
mAddressQrCode.setImageBitmap(scaled);
// scale for the expanded image
int smallestDimen = Math.min(mExpandedQrCode.getWidth(), mExpandedQrCode.getHeight());
scaled = Bitmap.createScaledBitmap(qrCode,
smallestDimen, smallestDimen,
false);
mExpandedQrCode.setImageBitmap(scaled);
// simple fade-in animation
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(200);
mAddressQrCode.startAnimation(anim);
}
}
};
loadTask.execute();
}
private void zoomQrCode() {
// If there's an animation in progress, cancel it
// immediately and proceed with this one.
if (mQrCodeAnimator != null) {
mQrCodeAnimator.cancel();
}
// Calculate the starting and ending bounds for the zoomed-in image.
// This step involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
// The start bounds are the global visible rectangle of the thumbnail,
// and the final bounds are the global visible rectangle of the container
// view. Also set the container view's offset as the origin for the
// bounds, since that's the origin for the positioning animation
// properties (X, Y).
mAddressQrCode.getGlobalVisibleRect(startBounds);
getActivity().findViewById(R.id.container)
.getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the "center crop" technique. This prevents undesirable
// stretching during the animation. Also calculate the start scaling
// factor (the end scaling factor is always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
> (float) startBounds.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
// Hide the thumbnail and show the zoomed-in view. When the animation
// begins, it will position the zoomed-in view in the place of the
// thumbnail.
ViewHelper.setAlpha(mAddressQrCode, 0f);
mExpandedQrCode.setVisibility(View.VISIBLE);
// Set the pivot point for SCALE_X and SCALE_Y transformations
// to the top-left corner of the zoomed-in view (the default
// is the center of the view).
ViewHelper.setPivotX(mExpandedQrCode, 0f);
ViewHelper.setPivotY(mExpandedQrCode, 0f);
// Construct and run the parallel animation of the four translation and
// scale properties (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set
.play(ObjectAnimator.ofFloat(mExpandedQrCode, "x",
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(mExpandedQrCode, "y",
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(mExpandedQrCode, "scaleX",
startScale, 1f))
.with(ObjectAnimator.ofFloat(mExpandedQrCode, "scaleY",
startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mQrCodeAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
mQrCodeAnimator = null;
}
});
set.start();
mQrCodeAnimator = set;
// Upon clicking the zoomed-in image, it should zoom back down
// to the original bounds and show the thumbnail instead of
// the expanded image.
final float startScaleFinal = startScale;
mExpandedQrCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mQrCodeAnimator != null) {
mQrCodeAnimator.cancel();
}
// Animate the four positioning/sizing properties in parallel,
// back to their original values.
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator
.ofFloat(mExpandedQrCode, "x", startBounds.left))
.with(ObjectAnimator
.ofFloat(mExpandedQrCode,
"y", startBounds.top))
.with(ObjectAnimator
.ofFloat(mExpandedQrCode,
"scaleX", startScaleFinal))
.with(ObjectAnimator
.ofFloat(mExpandedQrCode,
"scaleY", startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ViewHelper.setAlpha(mAddressQrCode, 1f);
mExpandedQrCode.setVisibility(View.GONE);
mQrCodeAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
ViewHelper.setAlpha(mAddressQrCode, 1f);
mExpandedQrCode.setVisibility(View.GONE);
mQrCodeAnimator = null;
}
});
set.start();
mQrCodeAnimator = set;
}
});
}
}