repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/AttachmentTypeSelector.java | package org.thoughtcrime.securesms.components;
import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.OvershootInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.ViewUtil;
public class AttachmentTypeSelector extends PopupWindow {
public static final int ADD_IMAGE = 1;
public static final int ADD_VIDEO = 2;
public static final int ADD_SOUND = 3;
public static final int ADD_CONTACT_INFO = 4;
public static final int TAKE_PHOTO = 5;
private static final int ANIMATION_DURATION = 300;
private static final String TAG = AttachmentTypeSelector.class.getSimpleName();
private final @NonNull ImageView imageButton;
private final @NonNull ImageView audioButton;
private final @NonNull ImageView videoButton;
private final @NonNull ImageView contactButton;
private final @NonNull ImageView cameraButton;
private final @NonNull ImageView closeButton;
private @Nullable View currentAnchor;
private @Nullable AttachmentClickedListener listener;
public AttachmentTypeSelector(@NonNull Context context, @Nullable AttachmentClickedListener listener) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.attachment_type_selector, null, true);
this.listener = listener;
this.imageButton = ViewUtil.findById(layout, R.id.gallery_button);
this.audioButton = ViewUtil.findById(layout, R.id.audio_button);
this.videoButton = ViewUtil.findById(layout, R.id.video_button);
this.contactButton = ViewUtil.findById(layout, R.id.contact_button);
this.cameraButton = ViewUtil.findById(layout, R.id.camera_button);
this.closeButton = ViewUtil.findById(layout, R.id.close_button);
this.imageButton.setOnClickListener(new PropagatingClickListener(ADD_IMAGE));
this.audioButton.setOnClickListener(new PropagatingClickListener(ADD_SOUND));
this.videoButton.setOnClickListener(new PropagatingClickListener(ADD_VIDEO));
this.contactButton.setOnClickListener(new PropagatingClickListener(ADD_CONTACT_INFO));
this.cameraButton.setOnClickListener(new PropagatingClickListener(TAKE_PHOTO));
this.closeButton.setOnClickListener(new CloseClickListener());
setContentView(layout);
setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new BitmapDrawable());
setAnimationStyle(0);
setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
setFocusable(true);
setTouchable(true);
}
public void show(@NonNull Activity activity, final @NonNull View anchor) {
this.currentAnchor = anchor;
int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
showAtLocation(anchor, Gravity.NO_GRAVITY, 0, screenHeight - getHeight());
getContentView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
getContentView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
animateWindowInCircular(anchor, getContentView());
} else {
animateWindowInTranslate(getContentView());
}
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
animateButtonIn(imageButton, ANIMATION_DURATION / 2);
animateButtonIn(cameraButton, ANIMATION_DURATION / 2);
animateButtonIn(audioButton, ANIMATION_DURATION / 3);
animateButtonIn(videoButton, ANIMATION_DURATION / 4);
animateButtonIn(contactButton, 0);
animateButtonIn(closeButton, 0);
}
}
@Override
public void dismiss() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
animateWindowOutCircular(currentAnchor, getContentView());
} else {
animateWindowOutTranslate(getContentView());
}
}
public void setListener(@Nullable AttachmentClickedListener listener) {
this.listener = listener;
}
private void animateButtonIn(View button, int delay) {
AnimationSet animation = new AnimationSet(true);
Animation scale = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.0f);
animation.addAnimation(scale);
animation.setInterpolator(new OvershootInterpolator(1));
animation.setDuration(ANIMATION_DURATION);
animation.setStartOffset(delay);
button.startAnimation(animation);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void animateWindowInCircular(@Nullable View anchor, @NonNull View contentView) {
Pair<Integer, Integer> coordinates = getClickOrigin(anchor, contentView);
Animator animator = ViewAnimationUtils.createCircularReveal(contentView,
coordinates.first,
coordinates.second,
0,
Math.max(contentView.getWidth(), contentView.getHeight()));
animator.setDuration(ANIMATION_DURATION);
animator.start();
}
private void animateWindowInTranslate(@NonNull View contentView) {
Animation animation = new TranslateAnimation(0, 0, contentView.getHeight(), 0);
animation.setDuration(ANIMATION_DURATION);
getContentView().startAnimation(animation);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void animateWindowOutCircular(@Nullable View anchor, @NonNull View contentView) {
Pair<Integer, Integer> coordinates = getClickOrigin(anchor, contentView);
Animator animator = ViewAnimationUtils.createCircularReveal(getContentView(),
coordinates.first,
coordinates.second,
Math.max(getContentView().getWidth(), getContentView().getHeight()),
0);
animator.setDuration(ANIMATION_DURATION);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
AttachmentTypeSelector.super.dismiss();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
}
private void animateWindowOutTranslate(@NonNull View contentView) {
Animation animation = new TranslateAnimation(0, 0, 0, contentView.getTop() + contentView.getHeight());
animation.setDuration(ANIMATION_DURATION);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
AttachmentTypeSelector.super.dismiss();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
getContentView().startAnimation(animation);
}
private Pair<Integer, Integer> getClickOrigin(@Nullable View anchor, @NonNull View contentView) {
if (anchor == null) return new Pair<>(0, 0);
final int[] anchorCoordinates = new int[2];
anchor.getLocationOnScreen(anchorCoordinates);
anchorCoordinates[0] += anchor.getWidth() / 2;
anchorCoordinates[1] += anchor.getHeight() / 2;
final int[] contentCoordinates = new int[2];
contentView.getLocationOnScreen(contentCoordinates);
int x = anchorCoordinates[0] - contentCoordinates[0];
int y = anchorCoordinates[1] - contentCoordinates[1];
return new Pair<>(x, y);
}
private class PropagatingClickListener implements View.OnClickListener {
private final int type;
private PropagatingClickListener(int type) {
this.type = type;
}
@Override
public void onClick(View v) {
animateWindowOutTranslate(getContentView());
if (listener != null) listener.onClick(type);
}
}
private class CloseClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
dismiss();
}
}
public interface AttachmentClickedListener {
public void onClick(int type);
}
}
| 9,554 | 36.470588 | 149 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/AudioView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.pnikosis.materialishprogress.ProgressWheel;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.audio.AudioSlidePlayer;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.events.PartProgressEvent;
import org.thoughtcrime.securesms.mms.AudioSlide;
import org.thoughtcrime.securesms.mms.SlideClickListener;
import org.thoughtcrime.securesms.util.Util;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import de.greenrobot.event.EventBus;
public class AudioView extends FrameLayout implements AudioSlidePlayer.Listener {
private static final String TAG = AudioView.class.getSimpleName();
private final @NonNull AnimatingToggle controlToggle;
private final @NonNull ImageView playButton;
private final @NonNull ImageView pauseButton;
private final @NonNull ImageView downloadButton;
private final @NonNull ProgressWheel downloadProgress;
private final @NonNull SeekBar seekBar;
private final @NonNull TextView timestamp;
private @Nullable SlideClickListener downloadListener;
private @Nullable AudioSlidePlayer audioSlidePlayer;
private int backwardsCounter;
public AudioView(Context context) {
this(context, null);
}
public AudioView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AudioView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
inflate(context, R.layout.audio_view, this);
this.controlToggle = (AnimatingToggle) findViewById(R.id.control_toggle);
this.playButton = (ImageView) findViewById(R.id.play);
this.pauseButton = (ImageView) findViewById(R.id.pause);
this.downloadButton = (ImageView) findViewById(R.id.download);
this.downloadProgress = (ProgressWheel) findViewById(R.id.download_progress);
this.seekBar = (SeekBar) findViewById(R.id.seek);
this.timestamp = (TextView) findViewById(R.id.timestamp);
this.playButton.setOnClickListener(new PlayClickedListener());
this.pauseButton.setOnClickListener(new PauseClickedListener());
this.seekBar.setOnSeekBarChangeListener(new SeekBarModifiedListener());
if (attrs != null) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AudioView, 0, 0);
setTint(typedArray.getColor(R.styleable.AudioView_tintColor, Color.WHITE));
typedArray.recycle();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().registerSticky(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
EventBus.getDefault().unregister(this);
}
public void setAudio(final @NonNull MasterSecret masterSecret,
final @NonNull AudioSlide audio,
final boolean showControls)
{
if (showControls && audio.isPendingDownload()) {
controlToggle.displayQuick(downloadButton);
seekBar.setEnabled(false);
downloadButton.setOnClickListener(new DownloadClickedListener(audio));
if (downloadProgress.isSpinning()) downloadProgress.stopSpinning();
} else if (showControls && audio.getTransferState() == AttachmentDatabase.TRANSFER_PROGRESS_STARTED) {
controlToggle.displayQuick(downloadProgress);
seekBar.setEnabled(false);
downloadProgress.spin();
} else {
controlToggle.displayQuick(playButton);
seekBar.setEnabled(true);
if (downloadProgress.isSpinning()) downloadProgress.stopSpinning();
}
this.audioSlidePlayer = AudioSlidePlayer.createFor(getContext(), masterSecret, audio, this);
}
public void cleanup() {
if (this.audioSlidePlayer != null && pauseButton.getVisibility() == View.VISIBLE) {
this.audioSlidePlayer.stop();
}
}
public void setDownloadClickListener(@Nullable SlideClickListener listener) {
this.downloadListener = listener;
}
@Override
public void onStart() {
this.controlToggle.display(this.pauseButton);
}
@Override
public void onStop() {
this.controlToggle.display(this.playButton);
if (seekBar.getProgress() + 5 >= seekBar.getMax()) {
backwardsCounter = 4;
onProgress(0.0, 0);
}
}
@Override
public void onProgress(double progress, long millis) {
int seekProgress = (int)Math.floor(progress * this.seekBar.getMax());
if (seekProgress > seekBar.getProgress() || backwardsCounter > 3) {
backwardsCounter = 0;
this.seekBar.setProgress(seekProgress);
this.timestamp.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis)));
} else {
backwardsCounter++;
}
}
public void setTint(int tint) {
this.playButton.setColorFilter(tint, PorterDuff.Mode.SRC_IN);
this.pauseButton.setColorFilter(tint, PorterDuff.Mode.SRC_IN);
this.downloadButton.setColorFilter(tint, PorterDuff.Mode.SRC_IN);
this.downloadProgress.setBarColor(tint);
this.timestamp.setTextColor(tint);
this.seekBar.getProgressDrawable().setColorFilter(tint, PorterDuff.Mode.SRC_IN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
this.seekBar.getThumb().setColorFilter(tint, PorterDuff.Mode.SRC_IN);
}
}
private double getProgress() {
if (this.seekBar.getProgress() <= 0 || this.seekBar.getMax() <= 0) {
return 0;
} else {
return (double)this.seekBar.getProgress() / (double)this.seekBar.getMax();
}
}
private class PlayClickedListener implements View.OnClickListener {
@Override
public void onClick(View v) {
try {
Log.w(TAG, "playbutton onClick");
if (audioSlidePlayer != null) {
controlToggle.display(pauseButton);
audioSlidePlayer.play(getProgress());
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
private class PauseClickedListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Log.w(TAG, "pausebutton onClick");
if (audioSlidePlayer != null) {
controlToggle.display(playButton);
audioSlidePlayer.stop();
}
}
}
private class DownloadClickedListener implements View.OnClickListener {
private final @NonNull AudioSlide slide;
private DownloadClickedListener(@NonNull AudioSlide slide) {
this.slide = slide;
}
@Override
public void onClick(View v) {
if (downloadListener != null) downloadListener.onClick(v, slide);
}
}
private class SeekBarModifiedListener implements SeekBar.OnSeekBarChangeListener {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}
@Override
public synchronized void onStartTrackingTouch(SeekBar seekBar) {
if (audioSlidePlayer != null && pauseButton.getVisibility() == View.VISIBLE) {
audioSlidePlayer.stop();
}
}
@Override
public synchronized void onStopTrackingTouch(SeekBar seekBar) {
try {
if (audioSlidePlayer != null && pauseButton.getVisibility() == View.VISIBLE) {
audioSlidePlayer.play(getProgress());
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
@SuppressWarnings("unused")
public void onEventAsync(final PartProgressEvent event) {
if (audioSlidePlayer != null && event.attachment.equals(this.audioSlidePlayer.getAudioSlide().asAttachment())) {
Util.runOnMain(new Runnable() {
@Override
public void run() {
downloadProgress.setInstantProgress(((float) event.progress) / event.total);
}
});
}
}
}
| 8,457 | 32.43083 | 116 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/AvatarImageView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.Pair;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.color.MaterialColor;
import org.thoughtcrime.securesms.contacts.avatars.ContactColors;
import org.thoughtcrime.securesms.contacts.avatars.ContactPhotoFactory;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.DirectoryHelper;
import org.thoughtcrime.securesms.util.DirectoryHelper.UserCapabilities.Capability;
public class AvatarImageView extends ImageView {
private boolean inverted;
private boolean showBadge;
public AvatarImageView(Context context) {
super(context);
setScaleType(ScaleType.CENTER_CROP);
}
public AvatarImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.CENTER_CROP);
if (attrs != null) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AvatarImageView, 0, 0);
inverted = typedArray.getBoolean(0, false);
showBadge = typedArray.getBoolean(1, false);
typedArray.recycle();
}
}
public void setAvatar(final @Nullable Recipients recipients, boolean quickContactEnabled) {
if (recipients != null) {
MaterialColor backgroundColor = recipients.getColor();
setImageDrawable(recipients.getContactPhoto().asDrawable(getContext(), backgroundColor.toConversationColor(getContext()), inverted));
setAvatarClickHandler(recipients, quickContactEnabled);
setTag(recipients);
if (showBadge) new BadgeResolutionTask(getContext()).execute(recipients);
} else {
setImageDrawable(ContactPhotoFactory.getDefaultContactPhoto(null).asDrawable(getContext(), ContactColors.UNKNOWN_COLOR.toConversationColor(getContext()), inverted));
setOnClickListener(null);
setTag(null);
}
}
public void setAvatar(@Nullable Recipient recipient, boolean quickContactEnabled) {
setAvatar(RecipientFactory.getRecipientsFor(getContext(), recipient, true), quickContactEnabled);
}
private void setAvatarClickHandler(final Recipients recipients, boolean quickContactEnabled) {
if (!recipients.isGroupRecipient() && quickContactEnabled) {
setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Recipient recipient = recipients.getPrimaryRecipient();
if (recipient != null && recipient.getContactUri() != null) {
ContactsContract.QuickContact.showQuickContact(getContext(), AvatarImageView.this, recipient.getContactUri(), ContactsContract.QuickContact.MODE_LARGE, null);
} else if (recipient != null) {
final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, recipient.getNumber());
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
getContext().startActivity(intent);
}
}
});
} else {
setOnClickListener(null);
}
}
private class BadgeResolutionTask extends AsyncTask<Recipients,Void,Pair<Recipients, Boolean>> {
private final Context context;
public BadgeResolutionTask(Context context) {
this.context = context;
}
@Override
protected Pair<Recipients, Boolean> doInBackground(Recipients... recipients) {
Capability textCapability = DirectoryHelper.getUserCapabilities(context, recipients[0]).getTextCapability();
return new Pair<>(recipients[0], textCapability == Capability.SUPPORTED);
}
@Override
protected void onPostExecute(Pair<Recipients, Boolean> result) {
if (getTag() == result.first && result.second) {
final Drawable badged = new LayerDrawable(new Drawable[] {
getDrawable(),
ContextCompat.getDrawable(context, R.drawable.badge_drawable)
});
setImageDrawable(badged);
}
}
}
}
| 4,542 | 38.504348 | 171 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/BubbleDrawableBuilder.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import org.thoughtcrime.securesms.R;
public class BubbleDrawableBuilder {
private int color;
private int shadowColor;
private boolean hasShadow = true;
private boolean[] corners = new boolean[]{true,true,true,true};
protected BubbleDrawableBuilder() { }
public BubbleDrawableBuilder setColor(int color) {
this.color = color;
return this;
}
public BubbleDrawableBuilder setShadowColor(int shadowColor) {
this.shadowColor = shadowColor;
return this;
}
public BubbleDrawableBuilder setHasShadow(boolean hasShadow) {
this.hasShadow = hasShadow;
return this;
}
public BubbleDrawableBuilder setCorners(boolean[] corners) {
this.corners = corners;
return this;
}
public Drawable create(Context context) {
final GradientDrawable bubble = new GradientDrawable();
final int radius = context.getResources().getDimensionPixelSize(R.dimen.message_bubble_corner_radius);
final float[] radii = cornerBooleansToRadii(corners, radius);
bubble.setColor(color);
bubble.setCornerRadii(radii);
if (!hasShadow) {
return bubble;
} else {
final GradientDrawable shadow = new GradientDrawable();
final int distance = context.getResources().getDimensionPixelSize(R.dimen.message_bubble_shadow_distance);
shadow.setColor(shadowColor);
shadow.setCornerRadii(radii);
final LayerDrawable layers = new LayerDrawable(new Drawable[]{shadow, bubble});
layers.setLayerInset(1, 0, 0, 0, distance);
return layers;
}
}
private float[] cornerBooleansToRadii(boolean[] corners, int radius) {
if (corners == null || corners.length != 4) {
throw new AssertionError("there are four corners in a rectangle, silly");
}
float[] radii = new float[8];
int i = 0;
for (boolean corner : corners) {
radii[i] = radii[i+1] = corner ? radius : 0;
i += 2;
}
return radii;
}
}
| 2,197 | 27.545455 | 125 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/CircleColorImageView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import org.thoughtcrime.securesms.R;
public class CircleColorImageView extends ImageView {
public CircleColorImageView(Context context) {
this(context, null);
}
public CircleColorImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleColorImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
int circleColor = Color.WHITE;
if (attrs != null) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CircleColorImageView, 0, 0);
circleColor = typedArray.getColor(R.styleable.CircleColorImageView_circleColor, Color.WHITE);
typedArray.recycle();
}
Drawable circle = context.getResources().getDrawable(R.drawable.circle_tintable);
circle.setColorFilter(circleColor, PorterDuff.Mode.SRC_IN);
setBackgroundDrawable(circle);
}
}
| 1,245 | 29.390244 | 119 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/ComposeText.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import org.thoughtcrime.securesms.TransportOption;
import org.thoughtcrime.securesms.components.emoji.EmojiEditText;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
public class ComposeText extends EmojiEditText {
private SpannableString hint;
public ComposeText(Context context) {
super(context);
}
public ComposeText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ComposeText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (!TextUtils.isEmpty(hint)) {
setHint(ellipsizeToWidth(hint));
}
}
private CharSequence ellipsizeToWidth(CharSequence text) {
return TextUtils.ellipsize(text,
getPaint(),
getWidth() - getPaddingLeft() - getPaddingRight(),
TruncateAt.END);
}
public void setHint(@NonNull String hint) {
this.hint = new SpannableString(hint);
this.hint.setSpan(new RelativeSizeSpan(0.8f), 0, hint.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
super.setHint(ellipsizeToWidth(this.hint));
}
public void appendInvite(String invite) {
if (!TextUtils.isEmpty(getText()) && !getText().toString().equals(" ")) {
append(" ");
}
append(invite);
setSelection(getText().length());
}
private boolean isLandscape() {
return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
public void setTransport(TransportOption transport) {
final boolean enterSends = TextSecurePreferences.isEnterSendsEnabled(getContext());
final boolean useSystemEmoji = TextSecurePreferences.isSystemEmojiPreferred(getContext());
int imeOptions = (getImeOptions() & ~EditorInfo.IME_MASK_ACTION) | EditorInfo.IME_ACTION_SEND;
int inputType = getInputType();
if (isLandscape()) setImeActionLabel(transport.getComposeHint(), EditorInfo.IME_ACTION_SEND);
else setImeActionLabel(null, 0);
if (useSystemEmoji) {
inputType = (inputType & ~InputType.TYPE_MASK_VARIATION) | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE;
}
inputType = !isLandscape() && enterSends
? inputType & ~InputType.TYPE_TEXT_FLAG_MULTI_LINE
: inputType | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
imeOptions = enterSends
? imeOptions & ~EditorInfo.IME_FLAG_NO_ENTER_ACTION
: imeOptions | EditorInfo.IME_FLAG_NO_ENTER_ACTION;
setInputType(inputType);
setImeOptions(imeOptions);
setHint(transport.getComposeHint());
}
}
| 3,234 | 33.414894 | 109 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/ContactFilterToolbar.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.TouchDelegate;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.ServiceUtil;
import org.thoughtcrime.securesms.util.ViewUtil;
public class ContactFilterToolbar extends Toolbar {
private OnFilterChangedListener listener;
private EditText searchText;
private AnimatingToggle toggle;
private ImageView action;
private ImageView keyboardToggle;
private ImageView dialpadToggle;
private ImageView clearToggle;
private LinearLayout toggleContainer;
public ContactFilterToolbar(Context context) {
this(context, null);
}
public ContactFilterToolbar(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.toolbarStyle);
}
public ContactFilterToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
inflate(context, R.layout.contact_filter_toolbar, this);
this.action = ViewUtil.findById(this, R.id.action_icon);
this.searchText = ViewUtil.findById(this, R.id.search_view);
this.toggle = ViewUtil.findById(this, R.id.button_toggle);
this.keyboardToggle = ViewUtil.findById(this, R.id.search_keyboard);
this.dialpadToggle = ViewUtil.findById(this, R.id.search_dialpad);
this.clearToggle = ViewUtil.findById(this, R.id.search_clear);
this.toggleContainer = ViewUtil.findById(this, R.id.toggle_container);
this.keyboardToggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
ServiceUtil.getInputMethodManager(getContext()).showSoftInput(searchText, 0);
displayTogglingView(dialpadToggle);
}
});
this.dialpadToggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchText.setInputType(InputType.TYPE_CLASS_PHONE);
ServiceUtil.getInputMethodManager(getContext()).showSoftInput(searchText, 0);
displayTogglingView(keyboardToggle);
}
});
this.clearToggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchText.setText("");
if (SearchUtil.isTextInput(searchText)) displayTogglingView(dialpadToggle);
else displayTogglingView(keyboardToggle);
}
});
this.searchText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!SearchUtil.isEmpty(searchText)) displayTogglingView(clearToggle);
else if (SearchUtil.isTextInput(searchText)) displayTogglingView(dialpadToggle);
else if (SearchUtil.isPhoneInput(searchText)) displayTogglingView(keyboardToggle);
notifyListener();
}
});
expandTapArea(this, action, 500);
expandTapArea(toggleContainer, dialpadToggle, 500);
}
@Override
public void setNavigationIcon(int resId) {
action.setImageResource(resId);
}
@Override
public void setNavigationOnClickListener(OnClickListener listener) {
super.setNavigationOnClickListener(listener);
action.setOnClickListener(listener);
}
public void setShowCustomNavigationButton(boolean show) {
action.setVisibility(show ? VISIBLE : GONE);
}
public void clear() {
searchText.setText("");
notifyListener();
}
public void setOnFilterChangedListener(OnFilterChangedListener listener) {
this.listener = listener;
}
private void notifyListener() {
if (listener != null) listener.onFilterChanged(searchText.getText().toString());
}
private void displayTogglingView(View view) {
toggle.display(view);
expandTapArea(toggleContainer, view, 500);
}
private void expandTapArea(final View container, final View child, final int padding) {
container.post(new Runnable() {
@Override
public void run() {
Rect rect = new Rect();
child.getHitRect(rect);
rect.top -= padding;
rect.left -= padding;
rect.right += padding;
rect.bottom += padding;
container.setTouchDelegate(new TouchDelegate(rect, child));
}
});
}
private static class SearchUtil {
public static boolean isTextInput(EditText editText) {
return (editText.getInputType() & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT;
}
public static boolean isPhoneInput(EditText editText) {
return (editText.getInputType() & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_PHONE;
}
public static boolean isEmpty(EditText editText) {
return editText.getText().length() <= 0;
}
}
public interface OnFilterChangedListener {
void onFilterChanged(String filter);
}
}
| 5,502 | 30.994186 | 103 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/CustomDefaultPreference.java | package org.thoughtcrime.securesms.components;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.net.URI;
import java.net.URISyntaxException;
public class CustomDefaultPreference extends DialogPreference {
private static final String TAG = CustomDefaultPreference.class.getSimpleName();
private final int inputType;
private final String customPreference;
private final String customToggle;
private CustomPreferenceValidator validator;
private String defaultValue;
private Spinner spinner;
private EditText customText;
private TextView defaultLabel;
private Button positiveButton;
public CustomDefaultPreference(Context context, AttributeSet attrs) {
super(context, attrs);
int[] attributeNames = new int[]{android.R.attr.inputType, R.attr.custom_pref_toggle};
TypedArray attributes = context.obtainStyledAttributes(attrs, attributeNames);
this.inputType = attributes.getInt(0, 0);
this.customPreference = getKey();
this.customToggle = attributes.getString(1);
this.validator = new NullValidator();
attributes.recycle();
setPersistent(false);
setDialogLayoutResource(R.layout.custom_default_preference_dialog);
}
public CustomDefaultPreference setValidator(CustomPreferenceValidator validator) {
this.validator = validator;
return this;
}
public CustomDefaultPreference setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
this.setSummary(getSummary());
return this;
}
@Override
public String getSummary() {
if (isCustom()) {
return getContext().getString(R.string.CustomDefaultPreference_using_custom,
getPrettyPrintValue(getCustomValue()));
} else {
return getContext().getString(R.string.CustomDefaultPreference_using_default,
getPrettyPrintValue(getDefaultValue()));
}
}
@Override
protected void onBindDialogView(@NonNull View view) {
super.onBindDialogView(view);
this.spinner = (Spinner) view.findViewById(R.id.default_or_custom);
this.defaultLabel = (TextView) view.findViewById(R.id.default_label);
this.customText = (EditText) view.findViewById(R.id.custom_edit);
this.customText.setInputType(inputType);
this.customText.addTextChangedListener(new TextValidator());
this.customText.setText(getCustomValue());
this.spinner.setOnItemSelectedListener(new SelectionLister());
this.defaultLabel.setText(getPrettyPrintValue(defaultValue));
}
@Override
protected void showDialog(Bundle instanceState) {
super.showDialog(instanceState);
positiveButton = ((AlertDialog)getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
if (isCustom()) spinner.setSelection(1, true);
else spinner.setSelection(0, true);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
if (spinner != null) setCustom(spinner.getSelectedItemPosition() == 1);
if (customText != null) setCustomValue(customText.getText().toString());
setSummary(getSummary());
}
}
private String getPrettyPrintValue(String value) {
if (TextUtils.isEmpty(value)) return getContext().getString(R.string.CustomDefaultPreference_none);
else return value;
}
private boolean isCustom() {
return TextSecurePreferences.getBooleanPreference(getContext(), customToggle, false);
}
private void setCustom(boolean custom) {
TextSecurePreferences.setBooleanPreference(getContext(), customToggle, custom);
}
private String getCustomValue() {
return TextSecurePreferences.getStringPreference(getContext(), customPreference, "");
}
private void setCustomValue(String value) {
TextSecurePreferences.setStringPreference(getContext(), customPreference, value);
}
private String getDefaultValue() {
return defaultValue;
}
private class SelectionLister implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
defaultLabel.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
customText.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
positiveButton.setEnabled(position == 0 || validator.isValid(customText.getText().toString()));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
defaultLabel.setVisibility(View.VISIBLE);
customText.setVisibility(View.GONE);
}
}
private class TextValidator implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (spinner.getSelectedItemPosition() == 1) {
positiveButton.setEnabled(validator.isValid(s.toString()));
}
}
}
protected interface CustomPreferenceValidator {
public boolean isValid(String value);
}
private static class NullValidator implements CustomPreferenceValidator {
@Override
public boolean isValid(String value) {
return true;
}
}
public static class UriValidator implements CustomPreferenceValidator {
@Override
public boolean isValid(String value) {
if (TextUtils.isEmpty(value)) return true;
try {
new URI(value);
return true;
} catch (URISyntaxException mue) {
return false;
}
}
}
public static class HostnameValidator implements CustomPreferenceValidator {
@Override
public boolean isValid(String value) {
if (TextUtils.isEmpty(value)) return true;
try {
URI uri = new URI(null, value, null, null);
return true;
} catch (URISyntaxException mue) {
return false;
}
}
}
public static class PortValidator implements CustomPreferenceValidator {
@Override
public boolean isValid(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
}
| 6,888 | 29.214912 | 103 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/FromTextView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.util.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.emoji.EmojiTextView;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
public class FromTextView extends EmojiTextView {
private static final String TAG = FromTextView.class.getSimpleName();
public FromTextView(Context context) {
super(context);
}
public FromTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setText(Recipient recipient) {
setText(RecipientFactory.getRecipientsFor(getContext(), recipient, true));
}
public void setText(Recipients recipients) {
setText(recipients, true);
}
public void setText(Recipients recipients, boolean read) {
int attributes[] = new int[]{R.attr.conversation_list_item_count_color};
TypedArray colors = getContext().obtainStyledAttributes(attributes);
boolean isUnnamedGroup = recipients.isGroupRecipient() && TextUtils.isEmpty(recipients.getPrimaryRecipient().getName());
String fromString;
if (isUnnamedGroup) {
fromString = getContext().getString(R.string.ConversationActivity_unnamed_group);
} else {
fromString = recipients.toShortString();
}
int typeface;
if (isUnnamedGroup) {
if (!read) typeface = Typeface.BOLD_ITALIC;
else typeface = Typeface.ITALIC;
} else if (!read) {
typeface = Typeface.BOLD;
} else {
typeface = Typeface.NORMAL;
}
SpannableStringBuilder builder = new SpannableStringBuilder(fromString);
builder.setSpan(new StyleSpan(typeface), 0, builder.length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
colors.recycle();
setText(builder);
if (recipients.isBlocked()) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_block_grey600_18dp, 0, 0, 0);
else if (recipients.isMuted()) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_volume_off_grey600_18dp, 0, 0, 0);
else setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
| 2,578 | 31.64557 | 127 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/ImageDivet.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import org.thoughtcrime.securesms.R;
public class ImageDivet extends ImageView {
private static final float CORNER_OFFSET = 12F;
private static final String[] POSITIONS = new String[] {"bottom_right"};
private Drawable drawable;
private int drawableIntrinsicWidth;
private int drawableIntrinsicHeight;
private int position;
private float density;
public ImageDivet(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize(attrs);
}
public ImageDivet(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(attrs);
}
public ImageDivet(Context context) {
super(context);
initialize(null);
}
private void initialize(AttributeSet attrs) {
if (attrs != null) {
position = attrs.getAttributeListValue(null, "position", POSITIONS, -1);
}
density = getContext().getResources().getDisplayMetrics().density;
setDrawable();
}
private void setDrawable() {
int attributes[] = new int[] {R.attr.lower_right_divet};
TypedArray drawables = getContext().obtainStyledAttributes(attributes);
switch (position) {
case 0:
drawable = drawables.getDrawable(0);
break;
}
drawableIntrinsicWidth = drawable.getIntrinsicWidth();
drawableIntrinsicHeight = drawable.getIntrinsicHeight();
drawables.recycle();
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
c.save();
computeBounds(c);
drawable.draw(c);
c.restore();
}
public void setPosition(int position) {
this.position = position;
setDrawable();
invalidate();
}
public int getPosition() {
return position;
}
public float getCloseOffset() {
return CORNER_OFFSET * density;
}
public ImageView asImageView() {
return this;
}
public float getFarOffset() {
return getCloseOffset() + drawableIntrinsicHeight;
}
private void computeBounds(Canvas c) {
final int right = getWidth();
final int bottom = getHeight();
switch (position) {
case 0:
drawable.setBounds(
right - drawableIntrinsicWidth,
bottom - drawableIntrinsicHeight,
right,
bottom);
break;
}
}
}
| 2,499 | 21.727273 | 78 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/InputAwareLayout.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.EditText;
import org.thoughtcrime.securesms.components.KeyboardAwareLinearLayout.OnKeyboardShownListener;
import org.thoughtcrime.securesms.util.ServiceUtil;
public class InputAwareLayout extends KeyboardAwareLinearLayout implements OnKeyboardShownListener {
private InputView current;
public InputAwareLayout(Context context) {
this(context, null);
}
public InputAwareLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public InputAwareLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
addOnKeyboardShownListener(this);
}
@Override public void onKeyboardShown() {
hideAttachedInput(true);
}
public void show(@NonNull final EditText imeTarget, @NonNull final InputView input) {
if (isKeyboardOpen()) {
hideSoftkey(imeTarget, new Runnable() {
@Override public void run() {
hideAttachedInput(true);
input.show(getKeyboardHeight(), true);
current = input;
}
});
} else {
if (current != null) current.hide(true);
input.show(getKeyboardHeight(), current != null);
current = input;
}
}
public InputView getCurrentInput() {
return current;
}
public void hideCurrentInput(EditText imeTarget) {
if (isKeyboardOpen()) hideSoftkey(imeTarget, null);
else hideAttachedInput(false);
}
public void hideAttachedInput(boolean instant) {
if (current != null) current.hide(instant);
current = null;
}
public boolean isInputOpen() {
return (isKeyboardOpen() || (current != null && current.isShowing()));
}
public void showSoftkey(final EditText inputTarget) {
postOnKeyboardOpen(new Runnable() {
@Override public void run() {
hideAttachedInput(true);
}
});
inputTarget.post(new Runnable() {
@Override public void run() {
inputTarget.requestFocus();
ServiceUtil.getInputMethodManager(inputTarget.getContext()).showSoftInput(inputTarget, 0);
}
});
}
private void hideSoftkey(final EditText inputTarget, @Nullable Runnable runAfterClose) {
if (runAfterClose != null) postOnKeyboardClose(runAfterClose);
ServiceUtil.getInputMethodManager(inputTarget.getContext())
.hideSoftInputFromWindow(inputTarget.getWindowToken(), 0);
}
public interface InputView {
void show(int height, boolean immediate);
void hide(boolean immediate);
boolean isShowing();
}
}
| 2,729 | 28.042553 | 100 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/KeyboardAwareLinearLayout.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.components;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.ServiceUtil;
import org.thoughtcrime.securesms.util.Util;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
/**
* LinearLayout that, when a view container, will report back when it thinks a soft keyboard
* has been opened and what its height would be.
*/
public class KeyboardAwareLinearLayout extends LinearLayoutCompat {
private static final String TAG = KeyboardAwareLinearLayout.class.getSimpleName();
private final Rect rect = new Rect();
private final Set<OnKeyboardHiddenListener> hiddenListeners = new HashSet<>();
private final Set<OnKeyboardShownListener> shownListeners = new HashSet<>();
private final int minKeyboardSize;
private final int minCustomKeyboardSize;
private final int defaultCustomKeyboardSize;
private final int minCustomKeyboardTopMargin;
private final int statusBarHeight;
private int viewInset;
private boolean keyboardOpen = false;
private int rotation = -1;
public KeyboardAwareLinearLayout(Context context) {
this(context, null);
}
public KeyboardAwareLinearLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public KeyboardAwareLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final int statusBarRes = getResources().getIdentifier("status_bar_height", "dimen", "android");
minKeyboardSize = getResources().getDimensionPixelSize(R.dimen.min_keyboard_size);
minCustomKeyboardSize = getResources().getDimensionPixelSize(R.dimen.min_custom_keyboard_size);
defaultCustomKeyboardSize = getResources().getDimensionPixelSize(R.dimen.default_custom_keyboard_size);
minCustomKeyboardTopMargin = getResources().getDimensionPixelSize(R.dimen.min_custom_keyboard_top_margin);
statusBarHeight = statusBarRes > 0 ? getResources().getDimensionPixelSize(statusBarRes) : 0;
viewInset = getViewInset();
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
updateRotation();
updateKeyboardState();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void updateRotation() {
int oldRotation = rotation;
rotation = getDeviceRotation();
if (oldRotation != rotation) {
Log.w(TAG, "rotation changed");
onKeyboardClose();
}
}
private void updateKeyboardState() {
if (isLandscape()) {
if (keyboardOpen) onKeyboardClose();
return;
}
if (viewInset == 0 && Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) viewInset = getViewInset();
final int availableHeight = this.getRootView().getHeight() - statusBarHeight - viewInset;
getWindowVisibleDisplayFrame(rect);
final int keyboardHeight = availableHeight - (rect.bottom - rect.top);
if (keyboardHeight > minKeyboardSize) {
if (getKeyboardHeight() != keyboardHeight) setKeyboardPortraitHeight(keyboardHeight);
if (!keyboardOpen) onKeyboardOpen(keyboardHeight);
} else if (keyboardOpen) {
onKeyboardClose();
}
}
@TargetApi(VERSION_CODES.LOLLIPOP)
private int getViewInset() {
try {
Field attachInfoField = View.class.getDeclaredField("mAttachInfo");
attachInfoField.setAccessible(true);
Object attachInfo = attachInfoField.get(this);
if (attachInfo != null) {
Field stableInsetsField = attachInfo.getClass().getDeclaredField("mStableInsets");
stableInsetsField.setAccessible(true);
Rect insets = (Rect)stableInsetsField.get(attachInfo);
return insets.bottom;
}
} catch (NoSuchFieldException nsfe) {
Log.w(TAG, "field reflection error when measuring view inset", nsfe);
} catch (IllegalAccessException iae) {
Log.w(TAG, "access reflection error when measuring view inset", iae);
}
return 0;
}
protected void onKeyboardOpen(int keyboardHeight) {
Log.w(TAG, "onKeyboardOpen(" + keyboardHeight + ")");
keyboardOpen = true;
notifyShownListeners();
}
protected void onKeyboardClose() {
Log.w(TAG, "onKeyboardClose()");
keyboardOpen = false;
notifyHiddenListeners();
}
public boolean isKeyboardOpen() {
return keyboardOpen;
}
public int getKeyboardHeight() {
return isLandscape() ? getKeyboardLandscapeHeight() : getKeyboardPortraitHeight();
}
public boolean isLandscape() {
int rotation = getDeviceRotation();
return rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270;
}
private int getDeviceRotation() {
return ServiceUtil.getWindowManager(getContext()).getDefaultDisplay().getRotation();
}
private int getKeyboardLandscapeHeight() {
return Math.max(getHeight(), getRootView().getHeight()) / 2;
}
private int getKeyboardPortraitHeight() {
int keyboardHeight = PreferenceManager.getDefaultSharedPreferences(getContext())
.getInt("keyboard_height_portrait", defaultCustomKeyboardSize);
return Util.clamp(keyboardHeight, minCustomKeyboardSize, getRootView().getHeight() - minCustomKeyboardTopMargin);
}
private void setKeyboardPortraitHeight(int height) {
PreferenceManager.getDefaultSharedPreferences(getContext())
.edit().putInt("keyboard_height_portrait", height).apply();
}
public void postOnKeyboardClose(final Runnable runnable) {
if (keyboardOpen) {
addOnKeyboardHiddenListener(new OnKeyboardHiddenListener() {
@Override public void onKeyboardHidden() {
removeOnKeyboardHiddenListener(this);
runnable.run();
}
});
} else {
runnable.run();
}
}
public void postOnKeyboardOpen(final Runnable runnable) {
if (!keyboardOpen) {
addOnKeyboardShownListener(new OnKeyboardShownListener() {
@Override public void onKeyboardShown() {
removeOnKeyboardShownListener(this);
runnable.run();
}
});
} else {
runnable.run();
}
}
public void addOnKeyboardHiddenListener(OnKeyboardHiddenListener listener) {
hiddenListeners.add(listener);
}
public void removeOnKeyboardHiddenListener(OnKeyboardHiddenListener listener) {
hiddenListeners.remove(listener);
}
public void addOnKeyboardShownListener(OnKeyboardShownListener listener) {
shownListeners.add(listener);
}
public void removeOnKeyboardShownListener(OnKeyboardShownListener listener) {
shownListeners.remove(listener);
}
private void notifyHiddenListeners() {
final Set<OnKeyboardHiddenListener> listeners = new HashSet<>(hiddenListeners);
for (OnKeyboardHiddenListener listener : listeners) {
listener.onKeyboardHidden();
}
}
private void notifyShownListeners() {
final Set<OnKeyboardShownListener> listeners = new HashSet<>(shownListeners);
for (OnKeyboardShownListener listener : listeners) {
listener.onKeyboardShown();
}
}
public interface OnKeyboardHiddenListener {
void onKeyboardHidden();
}
public interface OnKeyboardShownListener {
void onKeyboardShown();
}
}
| 8,517 | 34.198347 | 117 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/PushRecipientsPanel.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.components;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.contacts.ContactAccessor;
import org.thoughtcrime.securesms.contacts.RecipientsAdapter;
import org.thoughtcrime.securesms.contacts.RecipientsEditor;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.recipients.Recipients.RecipientsModifiedListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Panel component combining both an editable field with a button for
* a list-based contact selector.
*
* @author Moxie Marlinspike
*/
public class PushRecipientsPanel extends RelativeLayout implements RecipientsModifiedListener {
private final String TAG = PushRecipientsPanel.class.getSimpleName();
private RecipientsPanelChangedListener panelChangeListener;
private RecipientsEditor recipientsText;
private View panel;
private static final int RECIPIENTS_MAX_LENGTH = 312;
public PushRecipientsPanel(Context context) {
super(context);
initialize();
}
public PushRecipientsPanel(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public PushRecipientsPanel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void addRecipient(String name, String number) {
if (name != null) recipientsText.append(name + "< " + number + ">, ");
else recipientsText.append(number + ", ");
}
public void addRecipients(Recipients recipients) {
List<Recipient> recipientList = recipients.getRecipientsList();
Iterator<Recipient> iterator = recipientList.iterator();
while (iterator.hasNext()) {
Recipient recipient = iterator.next();
addRecipient(recipient.getName(), recipient.getNumber());
}
}
public Recipients getRecipients() throws RecipientFormattingException {
String rawText = recipientsText.getText().toString();
Recipients recipients = RecipientFactory.getRecipientsFromString(getContext(), rawText, true);
if (recipients.isEmpty())
throw new RecipientFormattingException("Recipient List Is Empty!");
return recipients;
}
public void disable() {
recipientsText.setText("");
panel.setVisibility(View.GONE);
}
public void setPanelChangeListener(RecipientsPanelChangedListener panelChangeListener) {
this.panelChangeListener = panelChangeListener;
}
private void initialize() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.push_recipients_panel, this, true);
View imageButton = findViewById(R.id.contacts_button);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
((MarginLayoutParams) imageButton.getLayoutParams()).topMargin = 0;
panel = findViewById(R.id.recipients_panel);
initRecipientsEditor();
}
private void initRecipientsEditor() {
Recipients recipients;
recipientsText = (RecipientsEditor)findViewById(R.id.recipients_text);
try {
recipients = getRecipients();
} catch (RecipientFormattingException e) {
recipients = RecipientFactory.getRecipientsFor(getContext(), new LinkedList<Recipient>(), true);
}
recipients.addListener(this);
recipientsText.setAdapter(new RecipientsAdapter(this.getContext()));
recipientsText.populate(recipients);
recipientsText.setOnFocusChangeListener(new FocusChangedListener());
recipientsText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (panelChangeListener != null) {
try {
panelChangeListener.onRecipientsPanelUpdate(getRecipients());
} catch (RecipientFormattingException rfe) {
panelChangeListener.onRecipientsPanelUpdate(null);
}
}
recipientsText.setText("");
}
});
}
@Override public void onModified(Recipients recipients) {
recipientsText.populate(recipients);
}
private class FocusChangedListener implements View.OnFocusChangeListener {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus && (panelChangeListener != null)) {
try {
panelChangeListener.onRecipientsPanelUpdate(getRecipients());
} catch (RecipientFormattingException rfe) {
panelChangeListener.onRecipientsPanelUpdate(null);
}
}
}
}
public interface RecipientsPanelChangedListener {
public void onRecipientsPanelUpdate(Recipients recipients);
}
} | 6,036 | 33.695402 | 110 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/RatingManager.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.util.concurrent.TimeUnit;
public class RatingManager {
private static final int DAYS_SINCE_INSTALL_THRESHOLD = 7;
private static final int DAYS_UNTIL_REPROMPT_THRESHOLD = 4;
private static final String TAG = RatingManager.class.getSimpleName();
public static void showRatingDialogIfNecessary(Context context) {
if (!TextSecurePreferences.isRatingEnabled(context)) return;
long daysSinceInstall = getDaysSinceInstalled(context);
long laterTimestamp = TextSecurePreferences.getRatingLaterTimestamp(context);
if (daysSinceInstall >= DAYS_SINCE_INSTALL_THRESHOLD &&
System.currentTimeMillis() >= laterTimestamp)
{
showRatingDialog(context);
}
}
private static void showRatingDialog(final Context context) {
new AlertDialog.Builder(context)
.setTitle(R.string.RatingManager_rate_this_app)
.setMessage(R.string.RatingManager_if_you_enjoy_using_this_app_please_take_a_moment)
.setPositiveButton(R.string.RatingManager_rate_now, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TextSecurePreferences.setRatingEnabled(context, false);
startPlayStore(context);
}
})
.setNegativeButton(R.string.RatingManager_no_thanks, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TextSecurePreferences.setRatingEnabled(context, false);
}
})
.setNeutralButton(R.string.RatingManager_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
long waitUntil = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(DAYS_UNTIL_REPROMPT_THRESHOLD);
TextSecurePreferences.setRatingLaterTimestamp(context, waitUntil);
}
})
.show();
}
private static void startPlayStore(Context context) {
Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
private static long getDaysSinceInstalled(Context context) {
try {
long installTimestamp = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0)
.firstInstallTime;
return TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - installTimestamp);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
return 0;
}
}
}
| 3,011 | 35.731707 | 111 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/RecyclerViewFastScroller.java | /**
* Modified version of
* https://github.com/AndroidDeveloperLB/LollipopContactsRecyclerViewFastScroller
*
* Their license:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thoughtcrime.securesms.components;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.Util;
import org.thoughtcrime.securesms.util.ViewUtil;
public class RecyclerViewFastScroller extends LinearLayout {
private static final int BUBBLE_ANIMATION_DURATION = 100;
private static final int TRACK_SNAP_RANGE = 5;
private TextView bubble;
private View handle;
private RecyclerView recyclerView;
private int height;
private ObjectAnimator currentAnimator;
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
if (bubble == null || handle.isSelected())
return;
final int verticalScrollOffset = recyclerView.computeVerticalScrollOffset();
final int verticalScrollRange = recyclerView.computeVerticalScrollRange();
float proportion = (float)verticalScrollOffset / ((float)verticalScrollRange - height);
setBubbleAndHandlePosition(height * proportion);
}
};
public interface FastScrollAdapter {
CharSequence getBubbleText(int pos);
}
public RecyclerViewFastScroller(final Context context) {
this(context, null);
}
public RecyclerViewFastScroller(final Context context, final AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
setClipChildren(false);
inflate(context, R.layout.recycler_view_fast_scroller, this);
bubble = ViewUtil.findById(this, R.id.fastscroller_bubble);
handle = ViewUtil.findById(this, R.id.fastscroller_handle);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
height = h;
}
@Override
@TargetApi(11)
public boolean onTouchEvent(@NonNull MotionEvent event) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (event.getX() < ViewUtil.getX(handle) - handle.getPaddingLeft() ||
event.getY() < ViewUtil.getY(handle) - handle.getPaddingTop() ||
event.getY() > ViewUtil.getY(handle) + handle.getHeight() + handle.getPaddingBottom())
{
return false;
}
if (currentAnimator != null) {
currentAnimator.cancel();
}
if (bubble.getVisibility() != VISIBLE) {
showBubble();
}
handle.setSelected(true);
case MotionEvent.ACTION_MOVE:
final float y = event.getY();
setBubbleAndHandlePosition(y);
setRecyclerViewPosition(y);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handle.setSelected(false);
hideBubble();
return true;
}
return super.onTouchEvent(event);
}
public void setRecyclerView(final RecyclerView recyclerView) {
this.recyclerView = recyclerView;
recyclerView.addOnScrollListener(onScrollListener);
recyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
if (bubble == null || handle.isSelected())
return true;
final int verticalScrollOffset = recyclerView.computeVerticalScrollOffset();
final int verticalScrollRange = recyclerView.computeVerticalScrollRange();
float proportion = (float)verticalScrollOffset / ((float)verticalScrollRange - height);
setBubbleAndHandlePosition(height * proportion);
return true;
}
});
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (recyclerView != null)
recyclerView.removeOnScrollListener(onScrollListener);
}
private void setRecyclerViewPosition(float y) {
if (recyclerView != null) {
final int itemCount = recyclerView.getAdapter().getItemCount();
float proportion;
if (ViewUtil.getY(handle) == 0)
proportion = 0f;
else if (ViewUtil.getY(handle) + handle.getHeight() >= height - TRACK_SNAP_RANGE)
proportion = 1f;
else
proportion = y / (float) height;
final int targetPos = Util.clamp((int)(proportion * (float)itemCount), 0, itemCount - 1);
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(targetPos, 0);
final CharSequence bubbleText = ((FastScrollAdapter) recyclerView.getAdapter()).getBubbleText(targetPos);
if (bubble != null)
bubble.setText(bubbleText);
}
}
private void setBubbleAndHandlePosition(float y) {
final int handleHeight = handle.getHeight();
final int bubbleHeight = bubble.getHeight();
ViewUtil.setY(handle, Util.clamp((int)(y - handleHeight / 2), 0, height - handleHeight));
ViewUtil.setY(bubble, Util.clamp((int)(y - bubbleHeight), 0, height - bubbleHeight - handleHeight / 2));
}
@TargetApi(11)
private void showBubble() {
bubble.setVisibility(VISIBLE);
if (VERSION.SDK_INT >= 11) {
if (currentAnimator != null) currentAnimator.cancel();
currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 0f, 1f).setDuration(BUBBLE_ANIMATION_DURATION);
currentAnimator.start();
}
}
@TargetApi(11)
private void hideBubble() {
if (VERSION.SDK_INT >= 11) {
if (currentAnimator != null) currentAnimator.cancel();
currentAnimator = ObjectAnimator.ofFloat(bubble, "alpha", 1f, 0f).setDuration(BUBBLE_ANIMATION_DURATION);
currentAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
bubble.setVisibility(INVISIBLE);
currentAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
bubble.setVisibility(INVISIBLE);
currentAnimator = null;
}
});
currentAnimator.start();
} else {
bubble.setVisibility(INVISIBLE);
}
}
}
| 7,495 | 35.21256 | 111 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/RemovableMediaView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import org.thoughtcrime.securesms.R;
public class RemovableMediaView extends FrameLayout {
private final @NonNull ImageView remove;
private final int removeSize;
private @Nullable View current;
public RemovableMediaView(Context context) {
this(context, null);
}
public RemovableMediaView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RemovableMediaView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.remove = (ImageView)LayoutInflater.from(context).inflate(R.layout.media_view_remove_button, this, false);
this.removeSize = getResources().getDimensionPixelSize(R.dimen.media_bubble_remove_button_size);
this.remove.setVisibility(View.GONE);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
this.addView(remove);
}
public void display(@Nullable View view) {
if (view == current) return;
if (current != null) current.setVisibility(View.GONE);
if (view != null) {
MarginLayoutParams params = (MarginLayoutParams)view.getLayoutParams();
params.setMargins(0, removeSize / 2, removeSize / 2, 0);
view.setLayoutParams(params);
view.setVisibility(View.VISIBLE);
remove.setVisibility(View.VISIBLE);
} else {
remove.setVisibility(View.GONE);
}
current = view;
}
public void setRemoveClickListener(View.OnClickListener listener) {
this.remove.setOnClickListener(listener);
}
}
| 1,843 | 26.939394 | 118 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/RepeatableImageKey.java | package org.thoughtcrime.securesms.components;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.EditText;
import android.widget.ImageButton;
public class RepeatableImageKey extends ImageButton {
private KeyEventListener listener;
public RepeatableImageKey(Context context) {
super(context);
init();
}
public RepeatableImageKey(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RepeatableImageKey(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(VERSION_CODES.LOLLIPOP)
public RepeatableImageKey(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes)
{
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
setOnClickListener(new RepeaterClickListener());
setOnTouchListener(new RepeaterTouchListener());
}
public void setOnKeyEventListener(KeyEventListener listener) {
this.listener = listener;
}
private void notifyListener() {
if (this.listener != null) this.listener.onKeyEvent();
}
private class RepeaterClickListener implements OnClickListener {
@Override public void onClick(View v) {
notifyListener();
}
}
private class Repeater implements Runnable {
@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
@Override
public void run() {
notifyListener();
postDelayed(this, VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1
? ViewConfiguration.getKeyRepeatDelay()
: 50);
}
}
private class RepeaterTouchListener implements OnTouchListener {
private Repeater repeater;
public RepeaterTouchListener() {
this.repeater = new Repeater();
}
@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
view.postDelayed(repeater, VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1
? ViewConfiguration.getKeyRepeatTimeout()
: ViewConfiguration.getLongPressTimeout());
performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
return false;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
view.removeCallbacks(repeater);
return false;
default:
return false;
}
}
}
public interface KeyEventListener {
void onKeyEvent();
}
}
| 2,911 | 27 | 84 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/SendButton.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageButton;
import org.thoughtcrime.securesms.TransportOption;
import org.thoughtcrime.securesms.TransportOptions;
import org.thoughtcrime.securesms.TransportOptions.OnTransportChangedListener;
import org.thoughtcrime.securesms.TransportOptionsPopup;
import org.whispersystems.libaxolotl.util.guava.Optional;
public class SendButton extends ImageButton
implements TransportOptions.OnTransportChangedListener,
TransportOptionsPopup.SelectedListener,
View.OnLongClickListener
{
private final TransportOptions transportOptions;
private Optional<TransportOptionsPopup> transportOptionsPopup = Optional.absent();
@SuppressWarnings("unused")
public SendButton(Context context) {
super(context);
this.transportOptions = initializeTransportOptions(false);
}
@SuppressWarnings("unused")
public SendButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.transportOptions = initializeTransportOptions(false);
}
@SuppressWarnings("unused")
public SendButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.transportOptions = initializeTransportOptions(false);
}
private TransportOptions initializeTransportOptions(boolean media) {
TransportOptions transportOptions = new TransportOptions(getContext(), media);
transportOptions.addOnTransportChangedListener(this);
setOnLongClickListener(this);
return transportOptions;
}
private TransportOptionsPopup getTransportOptionsPopup() {
if (!transportOptionsPopup.isPresent()) {
transportOptionsPopup = Optional.of(new TransportOptionsPopup(getContext(), this, this));
}
return transportOptionsPopup.get();
}
public boolean isManualSelection() {
return transportOptions.isManualSelection();
}
public void addOnTransportChangedListener(OnTransportChangedListener listener) {
transportOptions.addOnTransportChangedListener(listener);
}
public TransportOption getSelectedTransport() {
return transportOptions.getSelectedTransport();
}
public void resetAvailableTransports(boolean isMediaMessage) {
transportOptions.reset(isMediaMessage);
}
public void disableTransport(TransportOption.Type type) {
transportOptions.disableTransport(type);
}
public void setDefaultTransport(TransportOption.Type type) {
transportOptions.setDefaultTransport(type);
}
@Override
public void onSelected(TransportOption option) {
transportOptions.setSelectedTransport(option.getType());
getTransportOptionsPopup().dismiss();
}
@Override
public void onChange(TransportOption newTransport) {
setImageResource(newTransport.getDrawable());
setContentDescription(newTransport.getDescription());
}
@Override
public boolean onLongClick(View v) {
if (transportOptions.getEnabledTransports().size() > 1) {
getTransportOptionsPopup().display(transportOptions.getEnabledTransports());
return true;
}
return false;
}
}
| 3,186 | 29.644231 | 95 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/SingleRecipientPanel.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.components;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.contacts.ContactAccessor;
import org.thoughtcrime.securesms.contacts.RecipientsAdapter;
import org.thoughtcrime.securesms.contacts.RecipientsEditor;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.recipients.Recipients.RecipientsModifiedListener;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Panel component combining both an editable field with a button for
* a list-based contact selector.
*
* @author Moxie Marlinspike
*/
public class SingleRecipientPanel extends RelativeLayout implements RecipientsModifiedListener {
private final String TAG = SingleRecipientPanel.class.getSimpleName();
private RecipientsPanelChangedListener panelChangeListener;
private RecipientsEditor recipientsText;
private View panel;
private static final int RECIPIENTS_MAX_LENGTH = 312;
public SingleRecipientPanel(Context context) {
super(context);
initialize();
}
public SingleRecipientPanel(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public SingleRecipientPanel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void addRecipient(String name, String number) {
Log.i(TAG, "addRecipient for " + name + "/" + number);
if (name != null) recipientsText.append(name + "< " + number + ">, ");
else recipientsText.append(number + ", ");
}
public void addRecipients(Recipients recipients) {
List<Recipient> recipientList = recipients.getRecipientsList();
Iterator<Recipient> iterator = recipientList.iterator();
while (iterator.hasNext()) {
Recipient recipient = iterator.next();
addRecipient(recipient.getName(), recipient.getNumber());
}
}
public void addContacts(List<ContactAccessor.ContactData> contacts) {
for (ContactAccessor.ContactData contact : contacts) {
for (ContactAccessor.NumberData number : contact.numbers) {
addRecipient(contact.name, number.number);
}
}
}
public Recipients getRecipients() throws RecipientFormattingException {
String rawText = recipientsText.getText().toString();
Recipients recipients = RecipientFactory.getRecipientsFromString(getContext(), rawText, true);
if (recipients.isEmpty())
throw new RecipientFormattingException("Recipient List Is Empty!");
return recipients;
}
public void disable() {
clear();
panel.setVisibility(View.GONE);
}
public void clear() {
recipientsText.setText("");
}
public void setPanelChangeListener(RecipientsPanelChangedListener panelChangeListener) {
this.panelChangeListener = panelChangeListener;
}
private void initialize() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.single_recipient_panel, this, true);
panel = findViewById(R.id.recipients_panel);
initRecipientsEditor();
}
private void initRecipientsEditor() {
Recipients recipients;
recipientsText = (RecipientsEditor)findViewById(R.id.recipients_text);
try {
recipients = getRecipients();
} catch (RecipientFormattingException e) {
recipients = RecipientFactory.getRecipientsFor(getContext(), new LinkedList<Recipient>(), true);
}
recipients.addListener(this);
recipientsText.setAdapter(new RecipientsAdapter(this.getContext()));
recipientsText.populate(recipients);
recipientsText.setOnFocusChangeListener(new FocusChangedListener());
recipientsText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (panelChangeListener != null) {
try {
panelChangeListener.onRecipientsPanelUpdate(getRecipients());
} catch (RecipientFormattingException rfe) {
panelChangeListener.onRecipientsPanelUpdate(null);
}
}
recipientsText.setText("");
}
});
}
@Override public void onModified(Recipients recipients) {
recipientsText.populate(recipients);
}
private class FocusChangedListener implements OnFocusChangeListener {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus && (panelChangeListener != null)) {
try {
panelChangeListener.onRecipientsPanelUpdate(getRecipients());
} catch (RecipientFormattingException rfe) {
panelChangeListener.onRecipientsPanelUpdate(null);
}
}
}
}
public interface RecipientsPanelChangedListener {
public void onRecipientsPanelUpdate(Recipients recipients);
}
} | 6,018 | 33.198864 | 110 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/SquareFrameLayout.java | package org.thoughtcrime.securesms.components;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.widget.FrameLayout;
public class SquareFrameLayout extends FrameLayout {
@SuppressWarnings("unused")
public SquareFrameLayout(Context context) {
super(context);
}
@SuppressWarnings("unused")
public SquareFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(VERSION_CODES.HONEYCOMB) @SuppressWarnings("unused")
public SquareFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(VERSION_CODES.LOLLIPOP) @SuppressWarnings("unused")
public SquareFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//noinspection SuspiciousNameCombination
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
| 1,123 | 30.222222 | 100 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/SquareLinearLayout.java | package org.thoughtcrime.securesms.components;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.widget.LinearLayout;
public class SquareLinearLayout extends LinearLayout {
@SuppressWarnings("unused")
public SquareLinearLayout(Context context) {
super(context);
}
@SuppressWarnings("unused")
public SquareLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(VERSION_CODES.HONEYCOMB) @SuppressWarnings("unused")
public SquareLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(VERSION_CODES.LOLLIPOP) @SuppressWarnings("unused")
public SquareLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//noinspection SuspiciousNameCombination
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
| 1,130 | 30.416667 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/SwitchPreferenceCompat.java | package org.thoughtcrime.securesms.components;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;
import org.thoughtcrime.securesms.R;
public class SwitchPreferenceCompat extends CheckBoxPreference {
public SwitchPreferenceCompat(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setLayoutRes();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SwitchPreferenceCompat(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setLayoutRes();
}
public SwitchPreferenceCompat(Context context, AttributeSet attrs) {
super(context, attrs);
setLayoutRes();
}
public SwitchPreferenceCompat(Context context) {
super(context);
setLayoutRes();
}
private void setLayoutRes() {
setWidgetLayoutResource(R.layout.switch_compat_preference);
}
}
| 1,089 | 27.684211 | 107 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/ThumbnailView.java | package org.thoughtcrime.securesms.components;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.bumptech.glide.DrawableRequestBuilder;
import com.bumptech.glide.GenericRequestBuilder;
import com.bumptech.glide.Glide;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri;
import org.thoughtcrime.securesms.mms.RoundedCorners;
import org.thoughtcrime.securesms.mms.Slide;
import org.thoughtcrime.securesms.mms.SlideClickListener;
import org.thoughtcrime.securesms.util.Util;
import org.thoughtcrime.securesms.util.ViewUtil;
import org.whispersystems.libaxolotl.util.guava.Optional;
public class ThumbnailView extends FrameLayout {
private static final String TAG = ThumbnailView.class.getSimpleName();
private ImageView image;
private int backgroundColorHint;
private int radius;
private OnClickListener parentClickListener;
private Optional<TransferControlView> transferControls = Optional.absent();
private SlideClickListener thumbnailClickListener = null;
private SlideClickListener downloadClickListener = null;
private Slide slide = null;
public ThumbnailView(Context context) {
this(context, null);
}
public ThumbnailView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ThumbnailView(final Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
inflate(context, R.layout.thumbnail_view, this);
this.radius = getResources().getDimensionPixelSize(R.dimen.message_bubble_corner_radius);
this.image = (ImageView) findViewById(R.id.thumbnail_image);
super.setOnClickListener(new ThumbnailClickDispatcher());
if (attrs != null) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ThumbnailView, 0, 0);
backgroundColorHint = typedArray.getColor(0, Color.BLACK);
typedArray.recycle();
}
}
@Override
public void setOnClickListener(OnClickListener l) {
parentClickListener = l;
}
@Override
public void setFocusable(boolean focusable) {
super.setFocusable(focusable);
if (transferControls.isPresent()) transferControls.get().setFocusable(focusable);
}
@Override
public void setClickable(boolean clickable) {
super.setClickable(clickable);
if (transferControls.isPresent()) transferControls.get().setClickable(clickable);
}
private TransferControlView getTransferControls() {
if (!transferControls.isPresent()) {
transferControls = Optional.of((TransferControlView)ViewUtil.inflateStub(this, R.id.transfer_controls_stub));
}
return transferControls.get();
}
public void setBackgroundColorHint(int color) {
this.backgroundColorHint = color;
}
public void setImageResource(@NonNull MasterSecret masterSecret, @NonNull Slide slide, boolean showControls) {
if (showControls) {
getTransferControls().setSlide(slide);
getTransferControls().setDownloadClickListener(new DownloadClickDispatcher());
} else if (transferControls.isPresent()) {
getTransferControls().setVisibility(View.GONE);
}
if (Util.equals(slide, this.slide)) {
Log.w(TAG, "Not re-loading slide " + slide.asAttachment().getDataUri());
return;
}
if (!isContextValid()) {
Log.w(TAG, "Not loading slide, context is invalid");
return;
}
Log.w(TAG, "loading part with id " + slide.asAttachment().getDataUri()
+ ", progress " + slide.getTransferState());
this.slide = slide;
if (slide.getThumbnailUri() != null) buildThumbnailGlideRequest(slide, masterSecret).into(image);
else if (slide.hasPlaceholder()) buildPlaceholderGlideRequest(slide).into(image);
else Glide.clear(image);
}
public void setImageResource(@NonNull MasterSecret masterSecret, @NonNull Uri uri) {
if (transferControls.isPresent()) getTransferControls().setVisibility(View.GONE);
Glide.with(getContext()).load(new DecryptableUri(masterSecret, uri))
.crossFade()
.transform(new RoundedCorners(getContext(), true, radius, backgroundColorHint))
.into(image);
}
public void setThumbnailClickListener(SlideClickListener listener) {
this.thumbnailClickListener = listener;
}
public void setDownloadClickListener(SlideClickListener listener) {
this.downloadClickListener = listener;
}
public void clear() {
if (isContextValid()) Glide.clear(image);
if (transferControls.isPresent()) getTransferControls().clear();
slide = null;
}
public void showProgressSpinner() {
getTransferControls().showProgressSpinner();
}
@TargetApi(VERSION_CODES.JELLY_BEAN_MR1)
private boolean isContextValid() {
return !(getContext() instanceof Activity) ||
VERSION.SDK_INT < VERSION_CODES.JELLY_BEAN_MR1 ||
!((Activity)getContext()).isDestroyed();
}
private GenericRequestBuilder buildThumbnailGlideRequest(@NonNull Slide slide, @NonNull MasterSecret masterSecret) {
DrawableRequestBuilder<DecryptableUri> builder = Glide.with(getContext()).load(new DecryptableUri(masterSecret, slide.getThumbnailUri()))
.crossFade()
.transform(new RoundedCorners(getContext(), true, radius, backgroundColorHint));
if (slide.isInProgress()) return builder;
else return builder.error(R.drawable.ic_missing_thumbnail_picture);
}
private GenericRequestBuilder buildPlaceholderGlideRequest(Slide slide) {
return Glide.with(getContext()).load(slide.getPlaceholderRes(getContext().getTheme()))
.asBitmap()
.fitCenter();
}
private class ThumbnailClickDispatcher implements View.OnClickListener {
@Override
public void onClick(View view) {
if (thumbnailClickListener != null &&
slide != null &&
slide.asAttachment().getDataUri() != null &&
slide.getTransferState() == AttachmentDatabase.TRANSFER_PROGRESS_DONE)
{
thumbnailClickListener.onClick(view, slide);
} else if (parentClickListener != null) {
parentClickListener.onClick(view);
}
}
}
private class DownloadClickDispatcher implements View.OnClickListener {
@Override
public void onClick(View view) {
if (downloadClickListener != null && slide != null) {
downloadClickListener.onClick(view, slide);
}
}
}
}
| 7,304 | 35.343284 | 141 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/TransferControlView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.animation.ValueAnimator.AnimatorUpdateListener;
import com.pnikosis.materialishprogress.ProgressWheel;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.events.PartProgressEvent;
import org.thoughtcrime.securesms.mms.Slide;
import org.thoughtcrime.securesms.util.Util;
import org.thoughtcrime.securesms.util.ViewUtil;
import de.greenrobot.event.EventBus;
public class TransferControlView extends FrameLayout {
private static final int TRANSITION_MS = 300;
@Nullable private Slide slide;
@Nullable private View current;
private final ProgressWheel progressWheel;
private final TextView downloadDetails;
private final int contractedWidth;
private final int expandedWidth;
public TransferControlView(Context context) {
this(context, null);
}
public TransferControlView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TransferControlView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
inflate(context, R.layout.transfer_controls_view, this);
final Drawable background = ContextCompat.getDrawable(context, R.drawable.transfer_controls_background);
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
background.setColorFilter(0x66ffffff, Mode.MULTIPLY);
}
setLongClickable(false);
ViewUtil.setBackground(this, background);
setVisibility(GONE);
this.progressWheel = ViewUtil.findById(this, R.id.progress_wheel);
this.downloadDetails = ViewUtil.findById(this, R.id.download_details);
this.contractedWidth = getResources().getDimensionPixelSize(R.dimen.transfer_controls_contracted_width);
this.expandedWidth = getResources().getDimensionPixelSize(R.dimen.transfer_controls_expanded_width);
}
@Override
public void setFocusable(boolean focusable) {
super.setFocusable(focusable);
downloadDetails.setFocusable(focusable);
}
@Override
public void setClickable(boolean clickable) {
super.setClickable(clickable);
downloadDetails.setClickable(clickable);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().registerSticky(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
EventBus.getDefault().unregister(this);
}
public void setSlide(final @NonNull Slide slide) {
this.slide = slide;
if (slide.getTransferState() == AttachmentDatabase.TRANSFER_PROGRESS_STARTED) {
showProgressSpinner();
} else if (slide.isPendingDownload()) {
downloadDetails.setText(slide.getContentDescription());
display(downloadDetails);
} else {
display(null);
}
}
public void showProgressSpinner() {
progressWheel.spin();
display(progressWheel);
}
public void setDownloadClickListener(final @Nullable OnClickListener listener) {
downloadDetails.setOnClickListener(listener);
}
public void clear() {
clearAnimation();
setVisibility(GONE);
if (current != null) {
current.clearAnimation();
current.setVisibility(GONE);
}
current = null;
slide = null;
}
private void display(@Nullable final View view) {
final int sourceWidth = current == downloadDetails ? expandedWidth : contractedWidth;
final int targetWidth = view == downloadDetails ? expandedWidth : contractedWidth;
if (current == view || current == null) {
ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width = targetWidth;
setLayoutParams(layoutParams);
} else {
ViewUtil.fadeOut(current, TRANSITION_MS);
Animator anim = getWidthAnimator(sourceWidth, targetWidth);
anim.start();
}
if (view == null) {
ViewUtil.fadeOut(this, TRANSITION_MS);
} else {
ViewUtil.fadeIn(this, TRANSITION_MS);
ViewUtil.fadeIn(view, TRANSITION_MS);
}
current = view;
}
private Animator getWidthAnimator(final int from, final int to) {
final ValueAnimator anim = ValueAnimator.ofInt(from, to);
anim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
final int val = (Integer)animation.getAnimatedValue();
final ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width = val;
setLayoutParams(layoutParams);
}
});
anim.setInterpolator(new FastOutSlowInInterpolator());
anim.setDuration(TRANSITION_MS);
return anim;
}
@SuppressWarnings("unused")
public void onEventAsync(final PartProgressEvent event) {
if (this.slide != null && event.attachment.equals(this.slide.asAttachment())) {
Util.runOnMain(new Runnable() {
@Override
public void run() {
progressWheel.setInstantProgress(((float)event.progress) / event.total);
}
});
}
}
}
| 5,789 | 31.711864 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/ZoomingImageView.java | package org.thoughtcrime.securesms.components;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri;
import uk.co.senab.photoview.PhotoViewAttacher;
public class ZoomingImageView extends ImageView {
private PhotoViewAttacher attacher = new PhotoViewAttacher(this);
public ZoomingImageView(Context context) {
super(context);
}
public ZoomingImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZoomingImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setImageUri(MasterSecret masterSecret, Uri uri) {
Glide.with(getContext())
.load(new DecryptableUri(masterSecret, uri))
.dontTransform()
.dontAnimate()
.into(new GlideDrawableImageViewTarget(this) {
@Override protected void setResource(GlideDrawable resource) {
super.setResource(resource);
attacher.update();
}
});
}
}
| 1,471 | 30.319149 | 82 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/camera/CameraSurfaceView.java | package org.thoughtcrime.securesms.components.camera;
import android.content.Context;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private boolean ready;
@SuppressWarnings("deprecation")
public CameraSurfaceView(Context context) {
super(context);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
getHolder().addCallback(this);
}
public boolean isReady() {
return ready;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
ready = true;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
ready = false;
}
}
| 810 | 22.852941 | 88 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/camera/CameraUtils.java | package org.thoughtcrime.securesms.components.camera;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Surface;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("deprecation")
public class CameraUtils {
/*
* modified from: https://github.com/commonsguy/cwac-camera/blob/master/camera/src/com/commonsware/cwac/camera/CameraUtils.java
*/
public static @Nullable Size getPreferredPreviewSize(int displayOrientation,
int width,
int height,
@NonNull Camera camera) {
double targetRatio = (double)width / height;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
if (displayOrientation == 90 || displayOrientation == 270) {
targetRatio = (double)height / width;
}
List<Size> sizes = camera.getParameters().getSupportedPreviewSizes();
Collections.sort(sizes, Collections.reverseOrder(new SizeComparator()));
for (Size size : sizes) {
double ratio = (double)size.width / size.height;
if (Math.abs(ratio - targetRatio) < minDiff) {
optimalSize = size;
minDiff = Math.abs(ratio - targetRatio);
}
}
return optimalSize;
}
// based on
// http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)
// and http://stackoverflow.com/a/10383164/115145
public static int getCameraDisplayOrientation(@NonNull Activity activity,
@NonNull CameraInfo info)
{
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
return (360 - ((info.orientation + degrees) % 360)) % 360;
} else {
return (info.orientation - degrees + 360) % 360;
}
}
private static class SizeComparator implements Comparator<Size> {
@Override
public int compare(Size lhs, Size rhs) {
int left = lhs.width * lhs.height;
int right = rhs.width * rhs.height;
if (left < right) return -1;
if (left > right) return 1;
else return 0;
}
}
}
| 2,929 | 32.678161 | 129 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/camera/CameraView.java | /***
Copyright (c) 2013-2014 CommonsWare, LLC
Portions Copyright (C) 2007 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.thoughtcrime.securesms.components.camera;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.OrientationEventListener;
import android.widget.FrameLayout;
import java.io.IOException;
import java.util.List;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.Job;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.libaxolotl.util.guava.Optional;
@SuppressWarnings("deprecation")
public class CameraView extends FrameLayout {
private static final String TAG = CameraView.class.getSimpleName();
private final CameraSurfaceView surface;
private final OnOrientationChange onOrientationChange;
private @NonNull volatile Optional<Camera> camera = Optional.absent();
private volatile int cameraId = CameraInfo.CAMERA_FACING_BACK;
private boolean started;
private @Nullable CameraViewListener listener;
private int displayOrientation = -1;
private int outputOrientation = -1;
public CameraView(Context context) {
this(context, null);
}
public CameraView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CameraView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setBackgroundColor(Color.BLACK);
if (isMultiCamera()) cameraId = TextSecurePreferences.getDirectCaptureCameraId(context);
surface = new CameraSurfaceView(getContext());
onOrientationChange = new OnOrientationChange(context.getApplicationContext());
addView(surface);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onResume() {
if (started) return;
started = true;
Log.w(TAG, "onResume() queued");
enqueueTask(new SerialAsyncTask<Camera>() {
@Override
protected @Nullable Camera onRunBackground() {
try {
return Camera.open(cameraId);
} catch (Exception e) {
Log.w(TAG, e);
return null;
}
}
@Override
protected void onPostMain(@Nullable Camera camera) {
if (camera == null) {
Log.w(TAG, "tried to open camera but got null");
if (listener != null) listener.onCameraFail();
return;
}
CameraView.this.camera = Optional.of(camera);
try {
if (getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
onOrientationChange.enable();
}
onCameraReady();
synchronized (CameraView.this) {
CameraView.this.notifyAll();
}
requestLayout();
invalidate();
Log.w(TAG, "onResume() completed");
} catch (RuntimeException e) {
Log.w(TAG, "exception when starting camera preview", e);
onPause();
}
}
});
}
public void onPause() {
if (!started) return;
started = false;
Log.w(TAG, "onPause() queued");
enqueueTask(new SerialAsyncTask<Void>() {
private Optional<Camera> cameraToDestroy;
@Override protected void onPreMain() {
cameraToDestroy = camera;
camera = Optional.absent();
}
@Override protected Void onRunBackground() {
if (cameraToDestroy.isPresent()) {
try {
stopPreview();
cameraToDestroy.get().release();
Log.w(TAG, "released old camera instance");
} catch (Exception e) {
Log.w(TAG, e);
}
}
return null;
}
@Override protected void onPostMain(Void avoid) {
onOrientationChange.disable();
displayOrientation = -1;
outputOrientation = -1;
Log.w(TAG, "onPause() completed");
}
});
}
public boolean isStarted() {
return started;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getMeasuredWidth() > 0 && getMeasuredHeight() > 0 && camera.isPresent()) {
final Size preferredPreviewSize = CameraUtils.getPreferredPreviewSize(displayOrientation,
getMeasuredWidth(),
getMeasuredHeight(),
camera.get());
final Parameters parameters = camera.get().getParameters();
if (preferredPreviewSize != null && !parameters.getPreviewSize().equals(preferredPreviewSize)) {
Log.w(TAG, "setting preview size to " + preferredPreviewSize.width + "x" + preferredPreviewSize.height);
stopPreview();
parameters.setPreviewSize(preferredPreviewSize.width, preferredPreviewSize.height);
camera.get().setParameters(parameters);
requestLayout();
startPreview();
}
}
}
@SuppressWarnings("SuspiciousNameCombination")
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
final int height = b - t;
final int previewWidth;
final int previewHeight;
if (camera.isPresent()) {
final Size previewSize = camera.get().getParameters().getPreviewSize();
if (displayOrientation == 90 || displayOrientation == 270) {
previewWidth = previewSize.height;
previewHeight = previewSize.width;
} else {
previewWidth = previewSize.width;
previewHeight = previewSize.height;
}
} else {
previewWidth = width;
previewHeight = height;
}
if (previewHeight == 0 || previewWidth == 0) {
Log.w(TAG, "skipping layout due to zero-width/height preview size");
return;
}
Log.w(TAG, "layout " + width + "x" + height + ", target " + previewWidth + "x" + previewHeight);
if (width * previewHeight > height * previewWidth) {
final int scaledChildHeight = previewHeight * width / previewWidth;
surface.layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2);
} else {
final int scaledChildWidth = previewWidth * height / previewHeight;
surface.layout((width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height);
}
}
public void setListener(@Nullable CameraViewListener listener) {
this.listener = listener;
}
public boolean isMultiCamera() {
return Camera.getNumberOfCameras() > 1;
}
public boolean isRearCamera() {
return cameraId == CameraInfo.CAMERA_FACING_BACK;
}
public void flipCamera() {
if (Camera.getNumberOfCameras() > 1) {
cameraId = cameraId == CameraInfo.CAMERA_FACING_BACK
? CameraInfo.CAMERA_FACING_FRONT
: CameraInfo.CAMERA_FACING_BACK;
onPause();
onResume();
TextSecurePreferences.setDirectCaptureCameraId(getContext(), cameraId);
}
}
@TargetApi(14)
private void onCameraReady() {
if (!camera.isPresent()) return;
final Parameters parameters = camera.get().getParameters();
if (VERSION.SDK_INT >= 14) {
parameters.setRecordingHint(true);
final List<String> focusModes = parameters.getSupportedFocusModes();
if (focusModes.contains(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else if (focusModes.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
}
displayOrientation = CameraUtils.getCameraDisplayOrientation(getActivity(), getCameraInfo());
camera.get().setDisplayOrientation(displayOrientation);
camera.get().setParameters(parameters);
enqueueTask(new PostInitializationTask<Void>() {
@Override protected void onPostMain(Void avoid) {
if (camera.isPresent()) {
try {
camera.get().setPreviewDisplay(surface.getHolder());
requestLayout();
} catch (Exception e) {
Log.w(TAG, e);
}
}
}
});
}
private void startPreview() {
if (camera.isPresent()) {
try {
camera.get().startPreview();
} catch (Exception e) {
Log.w(TAG, e);
}
}
}
private void stopPreview() {
if (camera.isPresent()) {
try {
camera.get().stopPreview();
} catch (Exception e) {
Log.w(TAG, e);
}
}
}
public int getCameraPictureOrientation() {
if (getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
outputOrientation = getCameraPictureRotation(getActivity().getWindowManager()
.getDefaultDisplay()
.getOrientation());
} else if (getCameraInfo().facing == CameraInfo.CAMERA_FACING_FRONT) {
outputOrientation = (360 - displayOrientation) % 360;
} else {
outputOrientation = displayOrientation;
}
return outputOrientation;
}
private @NonNull CameraInfo getCameraInfo() {
final CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info;
}
// XXX this sucks
private Activity getActivity() {
return (Activity)getContext();
}
public int getCameraPictureRotation(int orientation) {
final CameraInfo info = getCameraInfo();
final int rotation;
orientation = (orientation + 45) / 90 * 90;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} else {
rotation = (info.orientation + orientation) % 360;
}
return rotation;
}
private class OnOrientationChange extends OrientationEventListener {
public OnOrientationChange(Context context) {
super(context);
disable();
}
@Override
public void onOrientationChanged(int orientation) {
if (camera.isPresent() && orientation != ORIENTATION_UNKNOWN) {
int newOutputOrientation = getCameraPictureRotation(orientation);
if (newOutputOrientation != outputOrientation) {
outputOrientation = newOutputOrientation;
Camera.Parameters params = camera.get().getParameters();
params.setRotation(outputOrientation);
try {
camera.get().setParameters(params);
}
catch (Exception e) {
Log.e(TAG, "Exception updating camera parameters in orientation change", e);
}
}
}
}
}
public void takePicture(final Rect previewRect) {
if (!camera.isPresent() || camera.get().getParameters() == null) {
Log.w(TAG, "camera not in capture-ready state");
return;
}
camera.get().setOneShotPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, final Camera camera) {
final int rotation = getCameraPictureOrientation();
final Size previewSize = camera.getParameters().getPreviewSize();
final Rect croppingRect = getCroppedRect(previewSize, previewRect, rotation);
Log.w(TAG, "previewSize: " + previewSize.width + "x" + previewSize.height);
Log.w(TAG, "data bytes: " + data.length);
Log.w(TAG, "previewFormat: " + camera.getParameters().getPreviewFormat());
Log.w(TAG, "croppingRect: " + croppingRect.toString());
Log.w(TAG, "rotation: " + rotation);
new CaptureTask(previewSize, rotation, croppingRect).execute(data);
}
});
}
private Rect getCroppedRect(Size cameraPreviewSize, Rect visibleRect, int rotation) {
final int previewWidth = cameraPreviewSize.width;
final int previewHeight = cameraPreviewSize.height;
if (rotation % 180 > 0) rotateRect(visibleRect);
float scale = (float) previewWidth / visibleRect.width();
if (visibleRect.height() * scale > previewHeight) {
scale = (float) previewHeight / visibleRect.height();
}
final float newWidth = visibleRect.width() * scale;
final float newHeight = visibleRect.height() * scale;
final float centerX = (VERSION.SDK_INT < 14) ? previewWidth - newWidth / 2 : previewWidth / 2;
final float centerY = previewHeight / 2;
visibleRect.set((int) (centerX - newWidth / 2),
(int) (centerY - newHeight / 2),
(int) (centerX + newWidth / 2),
(int) (centerY + newHeight / 2));
if (rotation % 180 > 0) rotateRect(visibleRect);
return visibleRect;
}
@SuppressWarnings("SuspiciousNameCombination")
private void rotateRect(Rect rect) {
rect.set(rect.top, rect.left, rect.bottom, rect.right);
}
private void enqueueTask(SerialAsyncTask job) {
ApplicationContext.getInstance(getContext()).getJobManager().add(job);
}
private static abstract class SerialAsyncTask<Result> extends Job {
public SerialAsyncTask() {
super(JobParameters.newBuilder().withGroupId(CameraView.class.getSimpleName()).create());
}
@Override public void onAdded() {}
@Override public final void onRun() {
try {
onWait();
Util.runOnMainSync(new Runnable() {
@Override public void run() {
onPreMain();
}
});
final Result result = onRunBackground();
Util.runOnMainSync(new Runnable() {
@Override public void run() {
onPostMain(result);
}
});
} catch (PreconditionsNotMetException e) {
Log.w(TAG, "skipping task, preconditions not met in onWait()");
}
}
@Override public boolean onShouldRetry(Exception e) {
return false;
}
@Override public void onCanceled() { }
protected void onWait() throws PreconditionsNotMetException {}
protected void onPreMain() {}
protected Result onRunBackground() { return null; }
protected void onPostMain(Result result) {}
}
private abstract class PostInitializationTask<Result> extends SerialAsyncTask<Result> {
@Override protected void onWait() throws PreconditionsNotMetException {
synchronized (CameraView.this) {
if (!camera.isPresent()) {
throw new PreconditionsNotMetException();
}
while (getMeasuredHeight() <= 0 || getMeasuredWidth() <= 0 || !surface.isReady()) {
Log.w(TAG, String.format("waiting. surface ready? %s", surface.isReady()));
Util.wait(CameraView.this, 0);
}
}
}
}
private class CaptureTask extends AsyncTask<byte[], Void, byte[]> {
private final Size previewSize;
private final int rotation;
private final Rect croppingRect;
public CaptureTask(Size previewSize, int rotation, Rect croppingRect) {
this.previewSize = previewSize;
this.rotation = rotation;
this.croppingRect = croppingRect;
}
@Override
protected byte[] doInBackground(byte[]... params) {
final byte[] data = params[0];
try {
return BitmapUtil.createFromNV21(data,
previewSize.width,
previewSize.height,
rotation,
croppingRect);
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
}
@Override
protected void onPostExecute(byte[] imageBytes) {
if (imageBytes != null && listener != null) listener.onImageCapture(imageBytes);
}
}
private static class PreconditionsNotMetException extends Exception {}
public interface CameraViewListener {
void onImageCapture(@NonNull final byte[] imageBytes);
void onCameraFail();
}
}
| 17,284 | 32.304432 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/camera/HidingImageButton.java | package org.thoughtcrime.securesms.components.camera;
import android.content.Context;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import org.thoughtcrime.securesms.R;
public class HidingImageButton extends ImageButton {
public HidingImageButton(Context context) {
super(context);
}
public HidingImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HidingImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void hide() {
if (!isEnabled() || getVisibility() == GONE) return;
final Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_to_right);
animation.setAnimationListener(new AnimationListener() {
@Override public void onAnimationStart(Animation animation) {}
@Override public void onAnimationRepeat(Animation animation) {}
@Override public void onAnimationEnd(Animation animation) {
setVisibility(GONE);
}
});
animateWith(animation);
}
public void show() {
if (!isEnabled() || getVisibility() == VISIBLE) return;
setVisibility(VISIBLE);
animateWith(AnimationUtils.loadAnimation(getContext(), R.anim.slide_from_right));
}
private void animateWith(Animation animation) {
animation.setDuration(150);
animation.setInterpolator(new FastOutSlowInInterpolator());
startAnimation(animation);
}
public void disable() {
setVisibility(GONE);
setEnabled(false);
}
}
| 1,799 | 30.034483 | 98 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/camera/QuickAttachmentDrawer.java | package org.thoughtcrime.securesms.components.camera;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.annotation.NonNull;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.nineoldandroids.animation.ObjectAnimator;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.InputAwareLayout.InputView;
import org.thoughtcrime.securesms.components.KeyboardAwareLinearLayout;
import org.thoughtcrime.securesms.components.camera.CameraView.CameraViewListener;
import org.thoughtcrime.securesms.util.ServiceUtil;
import org.thoughtcrime.securesms.util.Util;
import org.thoughtcrime.securesms.util.ViewUtil;
public class QuickAttachmentDrawer extends ViewGroup implements InputView {
private static final String TAG = QuickAttachmentDrawer.class.getSimpleName();
private final ViewDragHelper dragHelper;
private CameraView cameraView;
private int coverViewPosition;
private KeyboardAwareLinearLayout container;
private View coverView;
private View controls;
private ImageButton fullScreenButton;
private ImageButton swapCameraButton;
private ImageButton shutterButton;
private int slideOffset;
private float initialMotionX;
private float initialMotionY;
private int rotation;
private AttachmentDrawerListener listener;
private int halfExpandedHeight;
private ObjectAnimator animator;
private DrawerState drawerState = DrawerState.COLLAPSED;
private Rect drawChildrenRect = new Rect();
private boolean paused = false;
public QuickAttachmentDrawer(Context context) {
this(context, null);
}
public QuickAttachmentDrawer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public QuickAttachmentDrawer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
dragHelper = ViewDragHelper.create(this, 1.f, new ViewDragHelperCallback());
initializeView();
updateHalfExpandedAnchorPoint();
onConfigurationChanged();
}
private void initializeView() {
inflate(getContext(), R.layout.quick_attachment_drawer, this);
cameraView = ViewUtil.findById(this, R.id.quick_camera);
updateControlsView();
coverViewPosition = getChildCount();
controls.setVisibility(GONE);
cameraView.setVisibility(GONE);
}
public static boolean isDeviceSupported(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) &&
Camera.getNumberOfCameras() > 0;
}
@Override
public boolean isShowing() {
return drawerState.isVisible();
}
@Override
public void hide(boolean immediate) {
setDrawerStateAndUpdate(DrawerState.COLLAPSED, immediate);
}
@Override
public void show(int height, boolean immediate) {
setDrawerStateAndUpdate(DrawerState.HALF_EXPANDED, immediate);
}
public void onConfigurationChanged() {
int rotation = ServiceUtil.getWindowManager(getContext()).getDefaultDisplay().getRotation();
final boolean rotationChanged = this.rotation != rotation;
this.rotation = rotation;
if (rotationChanged) {
if (isShowing()) {
cameraView.onPause();
}
updateControlsView();
setDrawerStateAndUpdate(drawerState, true);
}
}
private void updateControlsView() {
Log.w(TAG, "updateControlsView()");
View controls = LayoutInflater.from(getContext()).inflate(isLandscape() ? R.layout.quick_camera_controls_land
: R.layout.quick_camera_controls,
this, false);
shutterButton = (ImageButton) controls.findViewById(R.id.shutter_button);
swapCameraButton = (ImageButton) controls.findViewById(R.id.swap_camera_button);
fullScreenButton = (ImageButton) controls.findViewById(R.id.fullscreen_button);
if (cameraView.isMultiCamera()) {
swapCameraButton.setVisibility(View.VISIBLE);
swapCameraButton.setImageResource(cameraView.isRearCamera() ? R.drawable.quick_camera_front
: R.drawable.quick_camera_rear);
swapCameraButton.setOnClickListener(new CameraFlipClickListener());
}
shutterButton.setOnClickListener(new ShutterClickListener());
fullScreenButton.setOnClickListener(new FullscreenClickListener());
ViewUtil.swapChildInPlace(this, this.controls, controls, indexOfChild(cameraView) + 1);
this.controls = controls;
}
private boolean isLandscape() {
return rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270;
}
private View getCoverView() {
if (coverView == null) coverView = getChildAt(coverViewPosition);
return coverView;
}
private KeyboardAwareLinearLayout getContainer() {
if (container == null) container = (KeyboardAwareLinearLayout)getParent();
return container;
}
private void updateHalfExpandedAnchorPoint() {
if (getContainer() != null) {
halfExpandedHeight = getContainer().getKeyboardHeight();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && drawerState == DrawerState.FULL_EXPANDED) {
setSlideOffset(getMeasuredHeight());
}
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
final int childHeight = child.getMeasuredHeight();
int childTop = paddingTop;
int childLeft = paddingLeft;
int childBottom;
if (child == cameraView) {
childTop = computeCameraTopPosition(slideOffset);
childBottom = childTop + childHeight;
if (cameraView.getMeasuredWidth() < getMeasuredWidth())
childLeft = (getMeasuredWidth() - cameraView.getMeasuredWidth()) / 2 + paddingLeft;
} else if (child == controls) {
childBottom = getMeasuredHeight();
} else {
childTop = computeCoverTopPosition(slideOffset);
childBottom = childTop + childHeight;
}
final int childRight = childLeft + child.getMeasuredWidth();
child.layout(childLeft, childTop, childRight, childBottom);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Width must have an exact value or MATCH_PARENT");
} else if (heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Height must have an exact value or MATCH_PARENT");
}
int layoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
final LayoutParams lp = child.getLayoutParams();
if (child.getVisibility() == GONE && i == 0) {
continue;
}
int childWidthSpec;
switch (lp.width) {
case LayoutParams.WRAP_CONTENT:
childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.AT_MOST);
break;
case LayoutParams.MATCH_PARENT:
childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
break;
default:
childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
break;
}
int childHeightSpec;
switch (lp.height) {
case LayoutParams.WRAP_CONTENT:
childHeightSpec = MeasureSpec.makeMeasureSpec(layoutHeight, MeasureSpec.AT_MOST);
break;
case LayoutParams.MATCH_PARENT:
childHeightSpec = MeasureSpec.makeMeasureSpec(layoutHeight, MeasureSpec.EXACTLY);
break;
default:
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
break;
}
child.measure(childWidthSpec, childHeightSpec);
}
setMeasuredDimension(widthSize, heightSize);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (h != oldh) updateHalfExpandedAnchorPoint();
}
@Override
protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
boolean result;
final int save = canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.getClipBounds(drawChildrenRect);
if (child == coverView) {
drawChildrenRect.bottom = Math.min(drawChildrenRect.bottom, child.getBottom());
} else if (coverView != null) {
drawChildrenRect.top = Math.max(drawChildrenRect.top, coverView.getBottom());
}
canvas.clipRect(drawChildrenRect);
result = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(save);
return result;
}
@Override
public void computeScroll() {
if (dragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
if (slideOffset == 0 && cameraView.isStarted()) {
cameraView.onPause();
controls.setVisibility(GONE);
cameraView.setVisibility(GONE);
} else if (slideOffset != 0 && !cameraView.isStarted() & !paused) {
controls.setVisibility(VISIBLE);
cameraView.setVisibility(VISIBLE);
cameraView.onResume();
}
}
private void setDrawerState(DrawerState drawerState) {
switch (drawerState) {
case COLLAPSED:
fullScreenButton.setImageResource(R.drawable.quick_camera_fullscreen);
break;
case HALF_EXPANDED:
if (isLandscape()) {
setDrawerState(DrawerState.FULL_EXPANDED);
return;
}
fullScreenButton.setImageResource(R.drawable.quick_camera_fullscreen);
break;
case FULL_EXPANDED:
fullScreenButton.setImageResource(isLandscape() ? R.drawable.quick_camera_hide
: R.drawable.quick_camera_exit_fullscreen);
break;
}
if (listener != null && drawerState != this.drawerState) {
this.drawerState = drawerState;
listener.onAttachmentDrawerStateChanged(drawerState);
}
}
@SuppressWarnings("unused")
public void setSlideOffset(int slideOffset) {
this.slideOffset = slideOffset;
requestLayout();
}
public int getTargetSlideOffset() {
switch (drawerState) {
case FULL_EXPANDED: return getMeasuredHeight();
case HALF_EXPANDED: return halfExpandedHeight;
default: return 0;
}
}
public void setDrawerStateAndUpdate(final DrawerState requestedDrawerState) {
setDrawerStateAndUpdate(requestedDrawerState, false);
}
public void setDrawerStateAndUpdate(final DrawerState requestedDrawerState, boolean instant) {
DrawerState oldDrawerState = this.drawerState;
setDrawerState(requestedDrawerState);
if (oldDrawerState != drawerState) {
updateHalfExpandedAnchorPoint();
slideTo(getTargetSlideOffset(), instant);
}
}
public void setListener(AttachmentDrawerListener listener) {
this.listener = listener;
if (cameraView != null) cameraView.setListener(listener);
}
public interface AttachmentDrawerListener extends CameraViewListener {
void onAttachmentDrawerStateChanged(DrawerState drawerState);
}
private class ViewDragHelperCallback extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return child == controls;
}
@Override
public void onViewDragStateChanged(int state) {
if (dragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) {
setDrawerState(drawerState);
slideOffset = getTargetSlideOffset();
requestLayout();
}
}
@Override
public void onViewCaptured(View capturedChild, int activePointerId) {
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
slideOffset = Util.clamp(slideOffset - dy, 0, getMeasuredHeight());
requestLayout();
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
if (releasedChild == controls) {
float direction = -yvel;
DrawerState drawerState = DrawerState.COLLAPSED;
if (direction > 1) {
drawerState = DrawerState.FULL_EXPANDED;
} else if (direction < -1) {
boolean halfExpand = (slideOffset > halfExpandedHeight && !isLandscape());
drawerState = halfExpand ? DrawerState.HALF_EXPANDED : DrawerState.COLLAPSED;
} else if (!isLandscape()) {
if (slideOffset >= (halfExpandedHeight + getMeasuredHeight()) / 2) {
drawerState = DrawerState.FULL_EXPANDED;
} else if (slideOffset >= halfExpandedHeight / 2) {
drawerState = DrawerState.HALF_EXPANDED;
}
}
setDrawerState(drawerState);
int slideOffset = getTargetSlideOffset();
dragHelper.captureChildView(coverView, 0);
dragHelper.settleCapturedViewAt(coverView.getLeft(), computeCoverTopPosition(slideOffset));
dragHelper.captureChildView(cameraView, 0);
dragHelper.settleCapturedViewAt(cameraView.getLeft(), computeCameraTopPosition(slideOffset));
ViewCompat.postInvalidateOnAnimation(QuickAttachmentDrawer.this);
}
}
@Override
public int getViewVerticalDragRange(View child) {
return getMeasuredHeight();
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return top;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
dragHelper.cancel();
return false;
}
final float x = event.getX();
final float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
initialMotionX = x;
initialMotionY = y;
break;
case MotionEvent.ACTION_MOVE:
final float adx = Math.abs(x - initialMotionX);
final float ady = Math.abs(y - initialMotionY);
final int dragSlop = dragHelper.getTouchSlop();
if (adx > dragSlop && ady < dragSlop) {
return super.onInterceptTouchEvent(event);
}
if ((ady > dragSlop && adx > ady) || !isDragViewUnder((int) initialMotionX, (int) initialMotionY)) {
dragHelper.cancel();
return false;
}
break;
}
return dragHelper.shouldInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
dragHelper.processTouchEvent(event);
return true;
}
// NOTE: Android Studio bug misreports error, squashing the warning.
// https://code.google.com/p/android/issues/detail?id=175977
@SuppressWarnings("ResourceType")
private boolean isDragViewUnder(int x, int y) {
int[] viewLocation = new int[2];
cameraView.getLocationOnScreen(viewLocation);
int[] parentLocation = new int[2];
this.getLocationOnScreen(parentLocation);
int screenX = parentLocation[0] + x;
int screenY = parentLocation[1] + y;
return screenX >= viewLocation[0] && screenX < viewLocation[0] + cameraView.getWidth() &&
screenY >= viewLocation[1] && screenY < viewLocation[1] + cameraView.getHeight();
}
private int computeCameraTopPosition(int slideOffset) {
if (VERSION.SDK_INT < VERSION_CODES.ICE_CREAM_SANDWICH) {
return getPaddingTop();
}
final int baseCameraTop = (cameraView.getMeasuredHeight() - halfExpandedHeight) / 2;
final int baseOffset = getMeasuredHeight() - slideOffset - baseCameraTop;
final float slop = Util.clamp((float)(slideOffset - halfExpandedHeight) / (getMeasuredHeight() - halfExpandedHeight),
0f,
1f);
return baseOffset + (int)(slop * baseCameraTop);
}
private int computeCoverTopPosition(int slideOffset) {
return getMeasuredHeight() - getPaddingBottom() - slideOffset - getCoverView().getMeasuredHeight();
}
private void slideTo(int slideOffset, boolean forceInstant) {
if (animator != null) {
animator.cancel();
animator = null;
}
if (!forceInstant) {
animator = ObjectAnimator.ofInt(this, "slideOffset", this.slideOffset, slideOffset);
animator.setInterpolator(new FastOutSlowInInterpolator());
animator.setDuration(400);
animator.start();
ViewCompat.postInvalidateOnAnimation(this);
} else {
this.slideOffset = slideOffset;
requestLayout();
invalidate();
}
}
public void onPause() {
paused = true;
cameraView.onPause();
}
public void onResume() {
paused = false;
if (drawerState.isVisible()) cameraView.onResume();
}
public enum DrawerState {
COLLAPSED, HALF_EXPANDED, FULL_EXPANDED;
public boolean isVisible() {
return this != COLLAPSED;
}
}
private class ShutterClickListener implements OnClickListener {
@Override
public void onClick(View v) {
boolean crop = drawerState != DrawerState.FULL_EXPANDED;
int imageHeight = crop ? getContainer().getKeyboardHeight() : cameraView.getMeasuredHeight();
Rect previewRect = new Rect(0, 0, cameraView.getMeasuredWidth(), imageHeight);
cameraView.takePicture(previewRect);
}
}
private class CameraFlipClickListener implements OnClickListener {
@Override
public void onClick(View v) {
cameraView.flipCamera();
swapCameraButton.setImageResource(cameraView.isRearCamera() ? R.drawable.quick_camera_front
: R.drawable.quick_camera_rear);
}
}
private class FullscreenClickListener implements OnClickListener {
@Override
public void onClick(View v) {
if (drawerState != DrawerState.FULL_EXPANDED) {
setDrawerStateAndUpdate(DrawerState.FULL_EXPANDED);
} else if (isLandscape()) {
setDrawerStateAndUpdate(DrawerState.COLLAPSED);
} else {
setDrawerStateAndUpdate(DrawerState.HALF_EXPANDED);
}
}
}
}
| 19,323 | 33.818018 | 130 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/AnimatingImageSpan.java | package org.thoughtcrime.securesms.components.emoji;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.Callback;
import android.text.style.ImageSpan;
public class AnimatingImageSpan extends ImageSpan {
public AnimatingImageSpan(Drawable drawable, Callback callback) {
super(drawable, ALIGN_BOTTOM);
drawable.setCallback(callback);
}
}
| 384 | 28.615385 | 67 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiDrawer.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import com.astuetz.PagerSlidingTabStrip;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.InputAwareLayout.InputView;
import org.thoughtcrime.securesms.components.RepeatableImageKey;
import org.thoughtcrime.securesms.components.RepeatableImageKey.KeyEventListener;
import org.thoughtcrime.securesms.components.emoji.EmojiPageView.EmojiSelectionListener;
import org.thoughtcrime.securesms.util.ResUtil;
import java.util.LinkedList;
import java.util.List;
public class EmojiDrawer extends LinearLayout implements InputView {
private static final KeyEvent DELETE_KEY_EVENT = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
private ViewPager pager;
private List<EmojiPageModel> models;
private PagerSlidingTabStrip strip;
private RecentEmojiPageModel recentModel;
private EmojiEventListener listener;
private EmojiDrawerListener drawerListener;
public EmojiDrawer(Context context) {
this(context, null);
}
public EmojiDrawer(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
}
private void initView() {
final View v = LayoutInflater.from(getContext()).inflate(R.layout.emoji_drawer, this, true);
initializeResources(v);
initializePageModels();
initializeEmojiGrid();
}
public void setEmojiEventListener(EmojiEventListener listener) {
this.listener = listener;
}
public void setDrawerListener(EmojiDrawerListener listener) {
this.drawerListener = listener;
}
private void initializeResources(View v) {
Log.w("EmojiDrawer", "initializeResources()");
this.pager = (ViewPager) v.findViewById(R.id.emoji_pager);
this.strip = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
RepeatableImageKey backspace = (RepeatableImageKey)v.findViewById(R.id.backspace);
backspace.setOnKeyEventListener(new KeyEventListener() {
@Override public void onKeyEvent() {
if (listener != null) listener.onKeyEvent(DELETE_KEY_EVENT);
}
});
}
@Override
public boolean isShowing() {
return getVisibility() == VISIBLE;
}
@Override
public void show(int height, boolean immediate) {
if (this.pager == null) initView();
ViewGroup.LayoutParams params = getLayoutParams();
params.height = height;
Log.w("EmojiDrawer", "showing emoji drawer with height " + params.height);
setLayoutParams(params);
setVisibility(VISIBLE);
if (drawerListener != null) drawerListener.onShown();
}
@Override
public void hide(boolean immediate) {
setVisibility(GONE);
if (drawerListener != null) drawerListener.onHidden();
Log.w("EmojiDrawer", "hide()");
}
private void initializeEmojiGrid() {
pager.setAdapter(new EmojiPagerAdapter(getContext(),
models,
new EmojiSelectionListener() {
@Override public void onEmojiSelected(String emoji) {
Log.w("EmojiDrawer", "onEmojiSelected()");
recentModel.onCodePointSelected(emoji);
if (listener != null) listener.onEmojiSelected(emoji);
}
}));
if (recentModel.getEmoji().length == 0) {
pager.setCurrentItem(1);
}
strip.setViewPager(pager);
}
private void initializePageModels() {
this.models = new LinkedList<>();
this.recentModel = new RecentEmojiPageModel(getContext());
this.models.add(recentModel);
this.models.addAll(EmojiPages.PAGES);
}
public static class EmojiPagerAdapter extends PagerAdapter
implements PagerSlidingTabStrip.CustomTabProvider
{
private Context context;
private List<EmojiPageModel> pages;
private EmojiSelectionListener listener;
public EmojiPagerAdapter(@NonNull Context context,
@NonNull List<EmojiPageModel> pages,
@Nullable EmojiSelectionListener listener)
{
super();
this.context = context;
this.pages = pages;
this.listener = listener;
}
@Override
public int getCount() {
return pages.size();
}
@Override public Object instantiateItem(ViewGroup container, int position) {
EmojiPageView page = new EmojiPageView(context);
page.setModel(pages.get(position));
page.setEmojiSelectedListener(listener);
container.addView(page);
return page;
}
@Override public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
@Override public void setPrimaryItem(ViewGroup container, int position, Object object) {
EmojiPageView current = (EmojiPageView) object;
current.onSelected();
super.setPrimaryItem(container, position, object);
}
@Override public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override public View getCustomTabView(ViewGroup viewGroup, int i) {
ImageView image = new ImageView(context);
image.setScaleType(ScaleType.CENTER_INSIDE);
image.setImageResource(ResUtil.getDrawableRes(context, pages.get(i).getIconAttr()));
return image;
}
}
public interface EmojiEventListener extends EmojiSelectionListener {
void onKeyEvent(KeyEvent keyEvent);
}
public interface EmojiDrawerListener {
void onShown();
void onHidden();
}
}
| 6,207 | 32.556757 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiEditText.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatEditText;
import android.text.InputFilter;
import android.util.AttributeSet;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.emoji.EmojiProvider.EmojiDrawable;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
public class EmojiEditText extends AppCompatEditText {
private static final String TAG = EmojiEditText.class.getSimpleName();
public EmojiEditText(Context context) {
this(context, null);
}
public EmojiEditText(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.editTextStyle);
}
public EmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!TextSecurePreferences.isSystemEmojiPreferred(getContext())) {
setFilters(new InputFilter[]{ new EmojiFilter(this) });
}
}
public void insertEmoji(String emoji) {
final int start = getSelectionStart();
final int end = getSelectionEnd();
getText().replace(Math.min(start, end), Math.max(start, end), emoji);
setSelection(start + emoji.length());
}
@Override public void invalidateDrawable(@NonNull Drawable drawable) {
if (drawable instanceof EmojiDrawable) invalidate();
else super.invalidateDrawable(drawable);
}
}
| 1,535 | 32.391304 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiFilter.java | package org.thoughtcrime.securesms.components.emoji;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.TextView;
public class EmojiFilter implements InputFilter {
private TextView view;
public EmojiFilter(TextView view) {
this.view = view;
}
@Override public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend)
{
char[] v = new char[end - start];
TextUtils.getChars(source, start, end, v, 0);
Spannable emojified = EmojiProvider.getInstance(view.getContext()).emojify(new String(v), view);
if (source instanceof Spanned && emojified != null) {
TextUtils.copySpansFrom((Spanned) source, start, end, null, emojified, 0);
}
return emojified;
}
}
| 873 | 30.214286 | 100 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiPageModel.java | package org.thoughtcrime.securesms.components.emoji;
public interface EmojiPageModel {
int getIconAttr();
String[] getEmoji();
boolean hasSpriteMap();
String getSprite();
boolean isDynamic();
}
| 205 | 19.6 | 52 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiPageView.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import org.thoughtcrime.securesms.R;
public class EmojiPageView extends FrameLayout {
private static final String TAG = EmojiPageView.class.getSimpleName();
private EmojiPageModel model;
private EmojiSelectionListener listener;
private GridView grid;
public EmojiPageView(Context context) {
this(context, null);
}
public EmojiPageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EmojiPageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final View view = LayoutInflater.from(getContext()).inflate(R.layout.emoji_grid_layout, this, true);
grid = (GridView) view.findViewById(R.id.emoji);
grid.setColumnWidth(getResources().getDimensionPixelSize(R.dimen.emoji_drawer_size) + 2 * getResources().getDimensionPixelSize(R.dimen.emoji_drawer_item_padding));
grid.setOnItemClickListener(new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (listener != null) listener.onEmojiSelected(((EmojiView)view).getEmoji());
}
});
}
public void onSelected() {
if (model.isDynamic() && grid != null && grid.getAdapter() != null) {
((EmojiGridAdapter)grid.getAdapter()).notifyDataSetChanged();
}
}
public void setModel(EmojiPageModel model) {
this.model = model;
grid.setAdapter(new EmojiGridAdapter(getContext(), model));
}
public void setEmojiSelectedListener(EmojiSelectionListener listener) {
this.listener = listener;
}
private static class EmojiGridAdapter extends BaseAdapter {
protected final Context context;
private final int emojiSize;
private final EmojiPageModel model;
public EmojiGridAdapter(Context context, EmojiPageModel model) {
this.context = context;
this.emojiSize = (int) context.getResources().getDimension(R.dimen.emoji_drawer_size);
this.model = model;
}
@Override public int getCount() {
return model.getEmoji().length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final EmojiView view;
final int pad = context.getResources().getDimensionPixelSize(R.dimen.emoji_drawer_item_padding);
if (convertView != null && convertView instanceof EmojiView) {
view = (EmojiView)convertView;
} else {
final EmojiView emojiView = new EmojiView(context);
emojiView.setPadding(pad, pad, pad, pad);
emojiView.setLayoutParams(new AbsListView.LayoutParams(emojiSize + 2 * pad, emojiSize + 2 * pad));
view = emojiView;
}
view.setEmoji(model.getEmoji()[position]);
return view;
}
}
public interface EmojiSelectionListener {
void onEmojiSelected(String emoji);
}
}
| 3,522 | 31.925234 | 167 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiPages.java | package org.thoughtcrime.securesms.components.emoji;
import org.thoughtcrime.securesms.R;
import java.util.Arrays;
import java.util.List;
public class EmojiPages {
public static final List<EmojiPageModel> PAGES = Arrays.<EmojiPageModel>asList(
new StaticEmojiPageModel(R.attr.emoji_category_people, new String[] {
"\u263a", "\ud83d\ude0a", "\ud83d\ude00", "\ud83d\ude01", "\ud83d\ude02", "\ud83d\ude03",
"\ud83d\ude04", "\ud83d\ude05", "\ud83d\ude06", "\ud83d\ude07", "\ud83d\ude08", "\ud83d\ude09",
"\ud83d\ude2f", "\ud83d\ude10", "\ud83d\ude11", "\ud83d\ude15", "\ud83d\ude20", "\ud83d\ude2c",
"\ud83d\ude21", "\ud83d\ude22", "\ud83d\ude34", "\ud83d\ude2e", "\ud83d\ude23", "\ud83d\ude24",
"\ud83d\ude25", "\ud83d\ude26", "\ud83d\ude27", "\ud83d\ude28", "\ud83d\ude29", "\ud83d\ude30",
"\ud83d\ude1f", "\ud83d\ude31", "\ud83d\ude32", "\ud83d\ude33", "\ud83d\ude35", "\ud83d\ude36",
"\ud83d\ude37", "\ud83d\ude1e", "\ud83d\ude12", "\ud83d\ude0d", "\ud83d\ude1b", "\ud83d\ude1c",
"\ud83d\ude1d", "\ud83d\ude0b", "\ud83d\ude17", "\ud83d\ude19", "\ud83d\ude18", "\ud83d\ude1a",
"\ud83d\ude0e", "\ud83d\ude2d", "\ud83d\ude0c", "\ud83d\ude16", "\ud83d\ude14", "\ud83d\ude2a",
"\ud83d\ude0f", "\ud83d\ude13", "\ud83d\ude2b", "\ud83d\ude4b", "\ud83d\ude4c", "\ud83d\ude4d",
"\ud83d\ude45", "\ud83d\ude46", "\ud83d\ude47", "\ud83d\ude4e", "\ud83d\ude4f", "\ud83d\ude3a",
"\ud83d\ude3c", "\ud83d\ude38", "\ud83d\ude39", "\ud83d\ude3b", "\ud83d\ude3d", "\ud83d\ude3f",
"\ud83d\ude3e", "\ud83d\ude40", "\ud83d\ude48", "\ud83d\ude49", "\ud83d\ude4a", "\ud83d\udca9",
"\ud83d\udc76", "\ud83d\udc66", "\ud83d\udc67", "\ud83d\udc68", "\ud83d\udc69", "\ud83d\udc74",
"\ud83d\udc75", "\ud83d\udc8f", "\ud83d\udc91", "\ud83d\udc6a", "\ud83d\udc6b", "\ud83d\udc6c",
"\ud83d\udc6d", "\ud83d\udc64", "\ud83d\udc65", "\ud83d\udc6e", "\ud83d\udc77", "\ud83d\udc81",
"\ud83d\udc82", "\ud83d\udc6f", "\ud83d\udc70", "\ud83d\udc78", "\ud83c\udf85", "\ud83d\udc7c",
"\ud83d\udc71", "\ud83d\udc72", "\ud83d\udc73", "\ud83d\udc83", "\ud83d\udc86", "\ud83d\udc87",
"\ud83d\udc85", "\ud83d\udc7b", "\ud83d\udc79", "\ud83d\udc7a", "\ud83d\udc7d", "\ud83d\udc7e",
"\ud83d\udc7f", "\ud83d\udc80", "\ud83d\udcaa", "\ud83d\udc40", "\ud83d\udc42", "\ud83d\udc43",
"\ud83d\udc63", "\ud83d\udc44", "\ud83d\udc45", "\ud83d\udc8b", "\u2764", "\ud83d\udc99",
"\ud83d\udc9a", "\ud83d\udc9b", "\ud83d\udc9c", "\ud83d\udc93", "\ud83d\udc94", "\ud83d\udc95",
"\ud83d\udc96", "\ud83d\udc97", "\ud83d\udc98", "\ud83d\udc9d", "\ud83d\udc9e", "\ud83d\udc9f",
"\ud83d\udc4d", "\ud83d\udc4e", "\ud83d\udc4c", "\u270a", "\u270c", "\u270b",
"\ud83d\udc4a", "\u261d", "\ud83d\udc46", "\ud83d\udc47", "\ud83d\udc48", "\ud83d\udc49",
"\ud83d\udc4b", "\ud83d\udc4f", "\ud83d\udc50",
}, "emoji-people.png"),
new StaticEmojiPageModel(R.attr.emoji_category_objects, new String[] {
"\ud83d\udd30", "\ud83d\udc84", "\ud83d\udc5e", "\ud83d\udc5f", "\ud83d\udc51", "\ud83d\udc52",
"\ud83c\udfa9", "\ud83c\udf93", "\ud83d\udc53", "\u231a", "\ud83d\udc54", "\ud83d\udc55",
"\ud83d\udc56", "\ud83d\udc57", "\ud83d\udc58", "\ud83d\udc59", "\ud83d\udc60", "\ud83d\udc61",
"\ud83d\udc62", "\ud83d\udc5a", "\ud83d\udc5c", "\ud83d\udcbc", "\ud83c\udf92", "\ud83d\udc5d",
"\ud83d\udc5b", "\ud83d\udcb0", "\ud83d\udcb3", "\ud83d\udcb2", "\ud83d\udcb5", "\ud83d\udcb4",
"\ud83d\udcb6", "\ud83d\udcb7", "\ud83d\udcb8", "\ud83d\udcb1", "\ud83d\udcb9", "\ud83d\udd2b",
"\ud83d\udd2a", "\ud83d\udca3", "\ud83d\udc89", "\ud83d\udc8a", "\ud83d\udeac", "\ud83d\udd14",
"\ud83d\udd15", "\ud83d\udeaa", "\ud83d\udd2c", "\ud83d\udd2d", "\ud83d\udd2e", "\ud83d\udd26",
"\ud83d\udd0b", "\ud83d\udd0c", "\ud83d\udcdc", "\ud83d\udcd7", "\ud83d\udcd8", "\ud83d\udcd9",
"\ud83d\udcda", "\ud83d\udcd4", "\ud83d\udcd2", "\ud83d\udcd1", "\ud83d\udcd3", "\ud83d\udcd5",
"\ud83d\udcd6", "\ud83d\udcf0", "\ud83d\udcdb", "\ud83c\udf83", "\ud83c\udf84", "\ud83c\udf80",
"\ud83c\udf81", "\ud83c\udf82", "\ud83c\udf88", "\ud83c\udf86", "\ud83c\udf87", "\ud83c\udf89",
"\ud83c\udf8a", "\ud83c\udf8d", "\ud83c\udf8f", "\ud83c\udf8c", "\ud83c\udf90", "\ud83c\udf8b",
"\ud83c\udf8e", "\ud83d\udcf1", "\ud83d\udcf2", "\ud83d\udcdf", "\u260e", "\ud83d\udcde",
"\ud83d\udce0", "\ud83d\udce6", "\u2709", "\ud83d\udce8", "\ud83d\udce9", "\ud83d\udcea",
"\ud83d\udceb", "\ud83d\udced", "\ud83d\udcec", "\ud83d\udcee", "\ud83d\udce4", "\ud83d\udce5",
"\ud83d\udcef", "\ud83d\udce2", "\ud83d\udce3", "\ud83d\udce1", "\ud83d\udcac", "\ud83d\udcad",
"\u2712", "\u270f", "\ud83d\udcdd", "\ud83d\udccf", "\ud83d\udcd0", "\ud83d\udccd",
"\ud83d\udccc", "\ud83d\udcce", "\u2702", "\ud83d\udcba", "\ud83d\udcbb", "\ud83d\udcbd",
"\ud83d\udcbe", "\ud83d\udcbf", "\ud83d\udcc6", "\ud83d\udcc5", "\ud83d\udcc7", "\ud83d\udccb",
"\ud83d\udcc1", "\ud83d\udcc2", "\ud83d\udcc3", "\ud83d\udcc4", "\ud83d\udcca", "\ud83d\udcc8",
"\ud83d\udcc9", "\u26fa", "\ud83c\udfa1", "\ud83c\udfa2", "\ud83c\udfa0", "\ud83c\udfaa",
"\ud83c\udfa8", "\ud83c\udfac", "\ud83c\udfa5", "\ud83d\udcf7", "\ud83d\udcf9", "\ud83c\udfa6",
"\ud83c\udfad", "\ud83c\udfab", "\ud83c\udfae", "\ud83c\udfb2", "\ud83c\udfb0", "\ud83c\udccf",
"\ud83c\udfb4", "\ud83c\udc04", "\ud83c\udfaf", "\ud83d\udcfa", "\ud83d\udcfb", "\ud83d\udcc0",
"\ud83d\udcfc", "\ud83c\udfa7", "\ud83c\udfa4", "\ud83c\udfb5", "\ud83c\udfb6", "\ud83c\udfbc",
"\ud83c\udfbb", "\ud83c\udfb9", "\ud83c\udfb7", "\ud83c\udfba", "\ud83c\udfb8", "\u303d",
}, "emoji-objects.png"),
new StaticEmojiPageModel(R.attr.emoji_category_nature, new String[] {
"\ud83d\udc15", "\ud83d\udc36", "\ud83d\udc29", "\ud83d\udc08", "\ud83d\udc31", "\ud83d\udc00",
"\ud83d\udc01", "\ud83d\udc2d", "\ud83d\udc39", "\ud83d\udc22", "\ud83d\udc07", "\ud83d\udc30",
"\ud83d\udc13", "\ud83d\udc14", "\ud83d\udc23", "\ud83d\udc24", "\ud83d\udc25", "\ud83d\udc26",
"\ud83d\udc0f", "\ud83d\udc11", "\ud83d\udc10", "\ud83d\udc3a", "\ud83d\udc03", "\ud83d\udc02",
"\ud83d\udc04", "\ud83d\udc2e", "\ud83d\udc34", "\ud83d\udc17", "\ud83d\udc16", "\ud83d\udc37",
"\ud83d\udc3d", "\ud83d\udc38", "\ud83d\udc0d", "\ud83d\udc3c", "\ud83d\udc27", "\ud83d\udc18",
"\ud83d\udc28", "\ud83d\udc12", "\ud83d\udc35", "\ud83d\udc06", "\ud83d\udc2f", "\ud83d\udc3b",
"\ud83d\udc2b", "\ud83d\udc2a", "\ud83d\udc0a", "\ud83d\udc33", "\ud83d\udc0b", "\ud83d\udc1f",
"\ud83d\udc20", "\ud83d\udc21", "\ud83d\udc19", "\ud83d\udc1a", "\ud83d\udc2c", "\ud83d\udc0c",
"\ud83d\udc1b", "\ud83d\udc1c", "\ud83d\udc1d", "\ud83d\udc1e", "\ud83d\udc32", "\ud83d\udc09",
"\ud83d\udc3e", "\ud83c\udf78", "\ud83c\udf7a", "\ud83c\udf7b", "\ud83c\udf77", "\ud83c\udf79",
"\ud83c\udf76", "\u2615", "\ud83c\udf75", "\ud83c\udf7c", "\ud83c\udf74", "\ud83c\udf68",
"\ud83c\udf67", "\ud83c\udf66", "\ud83c\udf69", "\ud83c\udf70", "\ud83c\udf6a", "\ud83c\udf6b",
"\ud83c\udf6c", "\ud83c\udf6d", "\ud83c\udf6e", "\ud83c\udf6f", "\ud83c\udf73", "\ud83c\udf54",
"\ud83c\udf5f", "\ud83c\udf5d", "\ud83c\udf55", "\ud83c\udf56", "\ud83c\udf57", "\ud83c\udf64",
"\ud83c\udf63", "\ud83c\udf71", "\ud83c\udf5e", "\ud83c\udf5c", "\ud83c\udf59", "\ud83c\udf5a",
"\ud83c\udf5b", "\ud83c\udf72", "\ud83c\udf65", "\ud83c\udf62", "\ud83c\udf61", "\ud83c\udf58",
"\ud83c\udf60", "\ud83c\udf4c", "\ud83c\udf4e", "\ud83c\udf4f", "\ud83c\udf4a", "\ud83c\udf4b",
"\ud83c\udf44", "\ud83c\udf45", "\ud83c\udf46", "\ud83c\udf47", "\ud83c\udf48", "\ud83c\udf49",
"\ud83c\udf50", "\ud83c\udf51", "\ud83c\udf52", "\ud83c\udf53", "\ud83c\udf4d", "\ud83c\udf30",
"\ud83c\udf31", "\ud83c\udf32", "\ud83c\udf33", "\ud83c\udf34", "\ud83c\udf35", "\ud83c\udf37",
"\ud83c\udf38", "\ud83c\udf39", "\ud83c\udf40", "\ud83c\udf41", "\ud83c\udf42", "\ud83c\udf43",
"\ud83c\udf3a", "\ud83c\udf3b", "\ud83c\udf3c", "\ud83c\udf3d", "\ud83c\udf3e", "\ud83c\udf3f",
"\u2600", "\ud83c\udf08", "\u26c5", "\u2601", "\ud83c\udf01", "\ud83c\udf02",
"\u2614", "\ud83d\udca7", "\u26a1", "\ud83c\udf00", "\u2744", "\u26c4",
"\ud83c\udf19", "\ud83c\udf1e", "\ud83c\udf1d", "\ud83c\udf1a", "\ud83c\udf1b", "\ud83c\udf1c",
"\ud83c\udf11", "\ud83c\udf12", "\ud83c\udf13", "\ud83c\udf14", "\ud83c\udf15", "\ud83c\udf16",
"\ud83c\udf17", "\ud83c\udf18", "\ud83c\udf91", "\ud83c\udf04", "\ud83c\udf05", "\ud83c\udf07",
"\ud83c\udf06", "\ud83c\udf03", "\ud83c\udf0c", "\ud83c\udf09", "\ud83c\udf0a", "\ud83c\udf0b",
"\ud83c\udf0e", "\ud83c\udf0f", "\ud83c\udf0d", "\ud83c\udf10",
}, "emoji-nature.png"),
new StaticEmojiPageModel(R.attr.emoji_category_places, new String[] {
"\ud83c\udfe0", "\ud83c\udfe1", "\ud83c\udfe2", "\ud83c\udfe3", "\ud83c\udfe4", "\ud83c\udfe5",
"\ud83c\udfe6", "\ud83c\udfe7", "\ud83c\udfe8", "\ud83c\udfe9", "\ud83c\udfea", "\ud83c\udfeb",
"\u26ea", "\u26f2", "\ud83c\udfec", "\ud83c\udfef", "\ud83c\udff0", "\ud83c\udfed",
"\ud83d\uddfb", "\ud83d\uddfc", "\ud83d\uddfd", "\ud83d\uddfe", "\ud83d\uddff", "\u2693",
"\ud83c\udfee", "\ud83d\udc88", "\ud83d\udd27", "\ud83d\udd28", "\ud83d\udd29", "\ud83d\udebf",
"\ud83d\udec1", "\ud83d\udec0", "\ud83d\udebd", "\ud83d\udebe", "\ud83c\udfbd", "\ud83c\udfa3",
"\ud83c\udfb1", "\ud83c\udfb3", "\u26be", "\u26f3", "\ud83c\udfbe", "\u26bd",
"\ud83c\udfbf", "\ud83c\udfc0", "\ud83c\udfc1", "\ud83c\udfc2", "\ud83c\udfc3", "\ud83c\udfc4",
"\ud83c\udfc6", "\ud83c\udfc7", "\ud83d\udc0e", "\ud83c\udfc8", "\ud83c\udfc9", "\ud83c\udfca",
"\ud83d\ude82", "\ud83d\ude83", "\ud83d\ude84", "\ud83d\ude85", "\ud83d\ude86", "\ud83d\ude87",
"\u24c2", "\ud83d\ude88", "\ud83d\ude8a", "\ud83d\ude8b", "\ud83d\ude8c", "\ud83d\ude8d",
"\ud83d\ude8e", "\ud83d\ude8f", "\ud83d\ude90", "\ud83d\ude91", "\ud83d\ude92", "\ud83d\ude93",
"\ud83d\ude94", "\ud83d\ude95", "\ud83d\ude96", "\ud83d\ude97", "\ud83d\ude98", "\ud83d\ude99",
"\ud83d\ude9a", "\ud83d\ude9b", "\ud83d\ude9c", "\ud83d\ude9d", "\ud83d\ude9e", "\ud83d\ude9f",
"\ud83d\udea0", "\ud83d\udea1", "\ud83d\udea2", "\ud83d\udea3", "\ud83d\ude81", "\u2708",
"\ud83d\udec2", "\ud83d\udec3", "\ud83d\udec4", "\ud83d\udec5", "\u26f5", "\ud83d\udeb2",
"\ud83d\udeb3", "\ud83d\udeb4", "\ud83d\udeb5", "\ud83d\udeb7", "\ud83d\udeb8", "\ud83d\ude89",
"\ud83d\ude80", "\ud83d\udea4", "\ud83d\udeb6", "\u26fd", "\ud83c\udd7f", "\ud83d\udea5",
"\ud83d\udea6", "\ud83d\udea7", "\ud83d\udea8", "\u2668", "\ud83d\udc8c", "\ud83d\udc8d",
"\ud83d\udc8e", "\ud83d\udc90", "\ud83d\udc92",
}, "emoji-places.png"),
new StaticEmojiPageModel(R.attr.emoji_category_symbol, new String[] {
"\ud83d\udd1d", "\ud83d\udd19", "\ud83d\udd1b", "\ud83d\udd1c", "\ud83d\udd1a", "\u23f3",
"\u231b", "\u23f0", "\u2648", "\u2649", "\u264a", "\u264b",
"\u264c", "\u264d", "\u264e", "\u264f", "\u2650", "\u2651",
"\u2652", "\u2653", "\u26ce", "\ud83d\udd31", "\ud83d\udd2f", "\ud83d\udebb",
"\ud83d\udeae", "\ud83d\udeaf", "\ud83d\udeb0", "\ud83d\udeb1", "\ud83c\udd70", "\ud83c\udd71",
"\ud83c\udd8e", "\ud83c\udd7e", "\ud83d\udcae", "\ud83d\udcaf", "\ud83d\udd20", "\ud83d\udd21",
"\ud83d\udd22", "\ud83d\udd23", "\ud83d\udd24", "\u27bf", "\ud83d\udcf6", "\ud83d\udcf3",
"\ud83d\udcf4", "\ud83d\udcf5", "\ud83d\udeb9", "\ud83d\udeba", "\ud83d\udebc", "\u267f",
"\u267b", "\ud83d\udead", "\ud83d\udea9", "\u26a0", "\ud83c\ude01", "\ud83d\udd1e",
"\u26d4", "\ud83c\udd92", "\ud83c\udd97", "\ud83c\udd95", "\ud83c\udd98", "\ud83c\udd99",
"\ud83c\udd93", "\ud83c\udd96", "\ud83c\udd9a", "\ud83c\ude32", "\ud83c\ude33", "\ud83c\ude34",
"\ud83c\ude35", "\ud83c\ude36", "\ud83c\ude37", "\ud83c\ude38", "\ud83c\ude39", "\ud83c\ude02",
"\ud83c\ude3a", "\ud83c\ude50", "\ud83c\ude51", "\u3299", "\u00ae", "\u00a9",
"\u2122", "\ud83c\ude1a", "\ud83c\ude2f", "\u3297", "\u2b55", "\u274c",
"\u274e", "\u2139", "\ud83d\udeab", "\u2705", "\u2714", "\ud83d\udd17",
"\u2734", "\u2733", "\u2795", "\u2796", "\u2716", "\u2797",
"\ud83d\udca0", "\ud83d\udca1", "\ud83d\udca4", "\ud83d\udca2", "\ud83d\udd25", "\ud83d\udca5",
"\ud83d\udca8", "\ud83d\udca6", "\ud83d\udcab", "\ud83d\udd5b", "\ud83d\udd67", "\ud83d\udd50",
"\ud83d\udd5c", "\ud83d\udd51", "\ud83d\udd5d", "\ud83d\udd52", "\ud83d\udd5e", "\ud83d\udd53",
"\ud83d\udd5f", "\ud83d\udd54", "\ud83d\udd60", "\ud83d\udd55", "\ud83d\udd61", "\ud83d\udd56",
"\ud83d\udd62", "\ud83d\udd57", "\ud83d\udd63", "\ud83d\udd58", "\ud83d\udd64", "\ud83d\udd59",
"\ud83d\udd65", "\ud83d\udd5a", "\ud83d\udd66", "\u2195", "\u2b06", "\u2197",
"\u27a1", "\u2198", "\u2b07", "\u2199", "\u2b05", "\u2196",
"\u2194", "\u2934", "\u2935", "\u23ea", "\u23eb", "\u23ec",
"\u23e9", "\u25c0", "\u25b6", "\ud83d\udd3d", "\ud83d\udd3c", "\u2747",
"\u2728", "\ud83d\udd34", "\ud83d\udd35", "\u26aa", "\u26ab", "\ud83d\udd33",
"\ud83d\udd32", "\u2b50", "\ud83c\udf1f", "\ud83c\udf20", "\u25ab", "\u25aa",
"\u25fd", "\u25fe", "\u25fb", "\u25fc", "\u2b1c", "\u2b1b",
"\ud83d\udd38", "\ud83d\udd39", "\ud83d\udd36", "\ud83d\udd37", "\ud83d\udd3a", "\ud83d\udd3b",
"\u2754", "\u2753", "\u2755", "\u2757", "\u203c", "\u2049",
"\u3030", "\u27b0", "\u2660", "\u2665", "\u2663", "\u2666",
"\ud83c\udd94", "\ud83d\udd11", "\u21a9", "\ud83c\udd91", "\ud83d\udd0d", "\ud83d\udd12",
"\ud83d\udd13", "\u21aa", "\ud83d\udd10", "\u2611", "\ud83d\udd18", "\ud83d\udd0e",
"\ud83d\udd16", "\ud83d\udd0f", "\ud83d\udd03", "\ud83d\udd00", "\ud83d\udd01", "\ud83d\udd02",
"\ud83d\udd04", "\ud83d\udce7", "\ud83d\udd05", "\ud83d\udd06", "\ud83d\udd07", "\ud83d\udd08",
"\ud83d\udd09", "\ud83d\udd0a",
}, "emoji-symbol.png"),
new StaticEmojiPageModel(R.attr.emoji_category_emoticons, new String[] {
"=-O", ":-P", ";-)", ":-(", ":-)", ":-!",
":-$", "B-)", ":O", ":-*", ":-D", ":'(",
":-\\", "O:-)", ":-[",
}, null));
}
| 14,844 | 88.969697 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiProvider.java | package org.thoughtcrime.securesms.components.emoji;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.util.SparseArray;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.FutureTaskListener;
import org.thoughtcrime.securesms.util.ListenableFutureTask;
import org.thoughtcrime.securesms.util.Util;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmojiProvider {
private static final String TAG = EmojiProvider.class.getSimpleName();
private static volatile EmojiProvider instance = null;
private static final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
private final SparseArray<DrawInfo> offsets = new SparseArray<>();
@SuppressWarnings("MalformedRegex")
// 0x203c,0x2049 0x20a0-0x32ff 0x1f00-0x1fff 0xfe4e5-0xfe4ee
// |== !!, ?! ==||==== misc ====||======== emoticons ========||========= flags ==========|
private static final Pattern EMOJI_RANGE = Pattern.compile("[\\u203c\\u2049\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee]");
public static final int EMOJI_RAW_HEIGHT = 64;
public static final int EMOJI_RAW_WIDTH = 64;
public static final int EMOJI_VERT_PAD = 0;
public static final int EMOJI_PER_ROW = 32;
private final Context context;
private final float decodeScale;
private final float verticalPad;
public static EmojiProvider getInstance(Context context) {
if (instance == null) {
synchronized (EmojiProvider.class) {
if (instance == null) {
instance = new EmojiProvider(context);
}
}
}
return instance;
}
private EmojiProvider(Context context) {
this.context = context.getApplicationContext();
this.decodeScale = Math.min(1f, context.getResources().getDimension(R.dimen.emoji_drawer_size) / EMOJI_RAW_HEIGHT);
this.verticalPad = EMOJI_VERT_PAD * this.decodeScale;
for (EmojiPageModel page : EmojiPages.PAGES) {
if (page.hasSpriteMap()) {
final EmojiPageBitmap pageBitmap = new EmojiPageBitmap(page);
for (int i=0; i < page.getEmoji().length; i++) {
offsets.put(Character.codePointAt(page.getEmoji()[i], 0), new DrawInfo(pageBitmap, i));
}
}
}
}
public @Nullable Spannable emojify(@Nullable CharSequence text, @NonNull TextView tv) {
if (text == null) return null;
Matcher matches = EMOJI_RANGE.matcher(text);
SpannableStringBuilder builder = new SpannableStringBuilder(text);
while (matches.find()) {
int codePoint = matches.group().codePointAt(0);
Drawable drawable = getEmojiDrawable(codePoint);
if (drawable != null) {
builder.setSpan(new EmojiSpan(drawable, tv), matches.start(), matches.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return builder;
}
public Drawable getEmojiDrawable(int emojiCode) {
return getEmojiDrawable(offsets.get(emojiCode));
}
private Drawable getEmojiDrawable(DrawInfo drawInfo) {
if (drawInfo == null) {
return null;
}
final EmojiDrawable drawable = new EmojiDrawable(drawInfo, decodeScale);
drawInfo.page.get().addListener(new FutureTaskListener<Bitmap>() {
@Override public void onSuccess(final Bitmap result) {
Util.runOnMain(new Runnable() {
@Override public void run() {
drawable.setBitmap(result);
}
});
}
@Override public void onFailure(Throwable error) {
Log.w(TAG, error);
}
});
return drawable;
}
public class EmojiDrawable extends Drawable {
private final DrawInfo info;
private Bitmap bmp;
private float intrinsicWidth;
private float intrinsicHeight;
@Override public int getIntrinsicWidth() {
return (int)intrinsicWidth;
}
@Override public int getIntrinsicHeight() {
return (int)intrinsicHeight;
}
public EmojiDrawable(DrawInfo info, float decodeScale) {
this.info = info;
this.intrinsicWidth = EMOJI_RAW_WIDTH * decodeScale;
this.intrinsicHeight = EMOJI_RAW_HEIGHT * decodeScale;
}
@Override
public void draw(Canvas canvas) {
if (bmp == null) {
return;
}
final int row = info.index / EMOJI_PER_ROW;
final int row_index = info.index % EMOJI_PER_ROW;
canvas.drawBitmap(bmp,
new Rect((int)(row_index * intrinsicWidth),
(int)(row * intrinsicHeight + row * verticalPad),
(int)((row_index + 1) * intrinsicWidth),
(int)((row + 1) * intrinsicHeight + row * verticalPad)),
getBounds(),
paint);
}
@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
public void setBitmap(Bitmap bitmap) {
Util.assertMainThread();
if (VERSION.SDK_INT < VERSION_CODES.HONEYCOMB_MR1 || bmp == null || !bmp.sameAs(bitmap)) {
bmp = bitmap;
invalidateSelf();
}
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) { }
@Override
public void setColorFilter(ColorFilter cf) { }
}
private static class DrawInfo {
EmojiPageBitmap page;
int index;
public DrawInfo(final EmojiPageBitmap page, final int index) {
this.page = page;
this.index = index;
}
@Override
public String toString() {
return "DrawInfo{" +
"page=" + page +
", index=" + index +
'}';
}
}
private class EmojiPageBitmap {
private EmojiPageModel model;
private SoftReference<Bitmap> bitmapReference;
private ListenableFutureTask<Bitmap> task;
public EmojiPageBitmap(EmojiPageModel model) {
this.model = model;
}
private ListenableFutureTask<Bitmap> get() {
Util.assertMainThread();
if (bitmapReference != null && bitmapReference.get() != null) {
return new ListenableFutureTask<>(bitmapReference.get());
} else if (task != null) {
return task;
} else {
Callable<Bitmap> callable = new Callable<Bitmap>() {
@Override public Bitmap call() throws Exception {
try {
Log.w(TAG, "loading page " + model.getSprite());
return loadPage();
} catch (IOException | ExecutionException ioe) {
Log.w(TAG, ioe);
}
return null;
}
};
task = new ListenableFutureTask<>(callable);
new AsyncTask<Void, Void, Void>() {
@Override protected Void doInBackground(Void... params) {
task.run();
return null;
}
@Override protected void onPostExecute(Void aVoid) {
task = null;
}
}.execute();
}
return task;
}
private Bitmap loadPage() throws IOException, ExecutionException {
if (bitmapReference != null && bitmapReference.get() != null) return bitmapReference.get();
try {
final Bitmap bitmap = BitmapUtil.createScaledBitmap(context,
"file:///android_asset/" + model.getSprite(),
decodeScale);
bitmapReference = new SoftReference<>(bitmap);
Log.w(TAG, "onPageLoaded(" + model.getSprite() + ")");
return bitmap;
} catch (ExecutionException e) {
Log.w(TAG, e);
throw e;
}
}
@Override public String toString() {
return model.getSprite();
}
}
}
| 8,726 | 31.808271 | 154 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiSpan.java | package org.thoughtcrime.securesms.components.emoji;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
public class EmojiSpan extends AnimatingImageSpan {
private final int size;
private final FontMetricsInt fm;
public EmojiSpan(@NonNull Drawable drawable, @NonNull TextView tv) {
super(drawable, tv);
fm = tv.getPaint().getFontMetricsInt();
size = fm != null ? Math.abs(fm.descent) + Math.abs(fm.ascent)
: tv.getResources().getDimensionPixelSize(R.dimen.conversation_item_body_text_size);
getDrawable().setBounds(0, 0, size, size);
}
@Override public int getSize(Paint paint, CharSequence text, int start, int end,
FontMetricsInt fm)
{
if (fm != null && this.fm != null) {
fm.ascent = this.fm.ascent;
fm.descent = this.fm.descent;
fm.top = this.fm.top;
fm.bottom = this.fm.bottom;
return size;
} else {
return super.getSize(paint, text, start, end, fm);
}
}
}
| 1,198 | 31.405405 | 106 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiTextView.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import org.thoughtcrime.securesms.components.emoji.EmojiProvider.EmojiDrawable;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.ViewUtil;
public class EmojiTextView extends AppCompatTextView {
private CharSequence source;
private boolean needsEllipsizing;
public EmojiTextView(Context context) {
this(context, null);
}
public EmojiTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EmojiTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override public void setText(@Nullable CharSequence text, BufferType type) {
if (useSystemEmoji()) {
super.setText(text, type);
return;
}
source = EmojiProvider.getInstance(getContext()).emojify(text, this);
setTextEllipsized(source);
}
private boolean useSystemEmoji() {
return TextSecurePreferences.isSystemEmojiPreferred(getContext());
}
private void setTextEllipsized(final @Nullable CharSequence source) {
super.setText(needsEllipsizing ? ViewUtil.ellipsize(source, this) : source, BufferType.SPANNABLE);
}
@Override public void invalidateDrawable(@NonNull Drawable drawable) {
if (drawable instanceof EmojiDrawable) invalidate();
else super.invalidateDrawable(drawable);
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int size = MeasureSpec.getSize(widthMeasureSpec);
final int mode = MeasureSpec.getMode(widthMeasureSpec);
if (!useSystemEmoji() &&
getEllipsize() == TruncateAt.END &&
!TextUtils.isEmpty(source) &&
(mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) &&
getPaint().breakText(source, 0, source.length()-1, true, size, null) != source.length())
{
needsEllipsizing = true;
FontMetricsInt font = getPaint().getFontMetricsInt();
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(Math.abs(font.top - font.bottom), MeasureSpec.EXACTLY));
} else {
needsEllipsizing = false;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (changed && !useSystemEmoji()) setTextEllipsized(source);
super.onLayout(changed, left, top, right, bottom);
}
}
| 3,024 | 36.8125 | 106 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiToggle.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageButton;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.emoji.EmojiDrawer.EmojiDrawerListener;
public class EmojiToggle extends ImageButton implements EmojiDrawerListener {
private Drawable emojiToggle;
private Drawable imeToggle;
public EmojiToggle(Context context) {
super(context);
initialize();
}
public EmojiToggle(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public EmojiToggle(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void setToEmoji() {
setImageDrawable(emojiToggle);
}
public void setToIme() {
setImageDrawable(imeToggle);
}
private void initialize() {
int attributes[] = new int[] {R.attr.conversation_emoji_toggle,
R.attr.conversation_keyboard_toggle};
TypedArray drawables = getContext().obtainStyledAttributes(attributes);
this.emojiToggle = drawables.getDrawable(0);
this.imeToggle = drawables.getDrawable(1);
drawables.recycle();
setToEmoji();
}
public void attach(EmojiDrawer drawer) {
drawer.setDrawerListener(this);
}
@Override public void onShown() {
setToIme();
}
@Override public void onHidden() {
setToEmoji();
}
}
| 1,542 | 22.738462 | 83 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/EmojiView.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.ResUtil;
public class EmojiView extends View implements Drawable.Callback {
private String emoji;
private Drawable drawable;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private final Rect textBounds = new Rect();
public EmojiView(Context context) {
this(context, null);
}
public EmojiView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EmojiView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setEmoji(String emoji) {
this.emoji = emoji;
this.drawable = EmojiProvider.getInstance(getContext())
.getEmojiDrawable(Character.codePointAt(emoji, 0));
postInvalidate();
}
public String getEmoji() {
return emoji;
}
@Override protected void onDraw(Canvas canvas) {
if (drawable != null) {
drawable.setBounds(getPaddingLeft(),
getPaddingTop(),
getWidth() - getPaddingRight(),
getHeight() - getPaddingBottom());
drawable.setCallback(this);
drawable.draw(canvas);
} else {
float targetFontSize = 0.75f * getHeight() - getPaddingTop() - getPaddingBottom();
paint.setTextSize(targetFontSize);
paint.setColor(ResUtil.getColor(getContext(), R.attr.emoji_text_color));
paint.getTextBounds(emoji, 0, emoji.length(), textBounds);
float overflow = textBounds.width() / (getWidth() - getPaddingLeft() - getPaddingRight());
if (overflow > 1f) {
paint.setTextSize(targetFontSize / overflow);
}
canvas.drawText(emoji, 0.5f * (getWidth() - textBounds.width()), 0.5f * (getHeight() + textBounds.height()), paint);
}
}
@Override public void invalidateDrawable(@NonNull Drawable drawable) {
super.invalidateDrawable(drawable);
postInvalidate();
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
| 2,490 | 32.213333 | 122 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/RecentEmojiPageModel.java | package org.thoughtcrime.securesms.components.emoji;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.JsonUtils;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class RecentEmojiPageModel implements EmojiPageModel {
private static final String TAG = RecentEmojiPageModel.class.getSimpleName();
private static final String EMOJI_LRU_PREFERENCE = "pref_recent_emoji2";
private static final int EMOJI_LRU_SIZE = 50;
private final SharedPreferences prefs;
private final LinkedHashSet<String> recentlyUsed;
public RecentEmojiPageModel(Context context) {
this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.recentlyUsed = getPersistedCache();
}
private LinkedHashSet<String> getPersistedCache() {
String serialized = prefs.getString(EMOJI_LRU_PREFERENCE, "[]");
try {
CollectionType collectionType = TypeFactory.defaultInstance()
.constructCollectionType(LinkedHashSet.class, String.class);
return JsonUtils.getMapper().readValue(serialized, collectionType);
} catch (IOException e) {
Log.w(TAG, e);
return new LinkedHashSet<>();
}
}
@Override public int getIconAttr() {
return R.attr.emoji_category_recent;
}
@Override public String[] getEmoji() {
return toReversePrimitiveArray(recentlyUsed);
}
@Override public boolean hasSpriteMap() {
return false;
}
@Override public String getSprite() {
return null;
}
@Override public boolean isDynamic() {
return true;
}
public void onCodePointSelected(String emoji) {
Log.w(TAG, "onCodePointSelected(" + emoji + ")");
recentlyUsed.remove(emoji);
recentlyUsed.add(emoji);
if (recentlyUsed.size() > EMOJI_LRU_SIZE) {
Iterator<String> iterator = recentlyUsed.iterator();
iterator.next();
iterator.remove();
}
final LinkedHashSet<String> latestRecentlyUsed = new LinkedHashSet<>(recentlyUsed);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
String serialized = JsonUtils.toJson(latestRecentlyUsed);
prefs.edit()
.putString(EMOJI_LRU_PREFERENCE, serialized)
.apply();
} catch (IOException e) {
Log.w(TAG, e);
}
return null;
}
}.execute();
}
private String[] toReversePrimitiveArray(@NonNull LinkedHashSet<String> emojiSet) {
String[] emojis = new String[emojiSet.size()];
int i = emojiSet.size() - 1;
for (String emoji : emojiSet) {
emojis[i--] = emoji;
}
return emojis;
}
}
| 3,090 | 28.721154 | 109 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/emoji/StaticEmojiPageModel.java | package org.thoughtcrime.securesms.components.emoji;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class StaticEmojiPageModel implements EmojiPageModel {
@AttrRes private final int iconAttr;
@NonNull private final String[] emoji;
@Nullable private final String sprite;
public StaticEmojiPageModel(@AttrRes int iconAttr, @NonNull String[] emoji, @Nullable String sprite) {
this.iconAttr = iconAttr;
this.emoji = emoji;
this.sprite = sprite;
}
public int getIconAttr() {
return iconAttr;
}
@NonNull public String[] getEmoji() {
return emoji;
}
@Override public boolean hasSpriteMap() {
return sprite != null;
}
@Override @Nullable public String getSprite() {
return sprite;
}
@Override public boolean isDynamic() {
return false;
}
}
| 909 | 22.947368 | 104 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/DefaultSmsReminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build.VERSION_CODES;
import android.provider.Telephony;
import android.view.View;
import android.view.View.OnClickListener;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
public class DefaultSmsReminder extends Reminder {
@TargetApi(VERSION_CODES.KITKAT)
public DefaultSmsReminder(final Context context) {
super(context.getString(R.string.reminder_header_sms_default_title),
context.getString(R.string.reminder_header_sms_default_text));
final OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(View v) {
TextSecurePreferences.setPromptedDefaultSmsProvider(context, true);
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());
context.startActivity(intent);
}
};
final OnClickListener dismissListener = new OnClickListener() {
@Override
public void onClick(View v) {
TextSecurePreferences.setPromptedDefaultSmsProvider(context, true);
}
};
setOkListener(okListener);
setDismissListener(dismissListener);
}
public static boolean isEligible(Context context) {
final boolean isDefault = Util.isDefaultSmsProvider(context);
if (isDefault) {
TextSecurePreferences.setPromptedDefaultSmsProvider(context, false);
}
return !isDefault && !TextSecurePreferences.hasPromptedDefaultSmsProvider(context);
}
}
| 1,756 | 34.14 | 92 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/ExpiredBuildReminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.Util;
public class ExpiredBuildReminder extends Reminder {
private static final String TAG = ExpiredBuildReminder.class.getSimpleName();
public ExpiredBuildReminder(final Context context) {
super(context.getString(R.string.reminder_header_expired_build),
context.getString(R.string.reminder_header_expired_build_details));
setOkListener(new OnClickListener() {
@Override public void onClick(View v) {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
} catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName())));
}
}
});
}
@Override
public boolean isDismissable() {
return false;
}
public static boolean isEligible(Context context) {
return !Util.isBuildFresh();
}
}
| 1,276 | 31.74359 | 152 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/InviteReminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.View.OnClickListener;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
public class InviteReminder extends Reminder {
public InviteReminder(final @NonNull Context context,
final @NonNull Recipients recipients)
{
super(context.getString(R.string.reminder_header_invite_title),
context.getString(R.string.reminder_header_invite_text, recipients.toShortString()));
setDismissListener(new OnClickListener() {
@Override public void onClick(View v) {
new AsyncTask<Void,Void,Void>() {
@Override protected Void doInBackground(Void... params) {
DatabaseFactory.getRecipientPreferenceDatabase(context).setSeenInviteReminder(recipients, true);
return null;
}
}.execute();
}
});
}
}
| 1,113 | 31.764706 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/PushRegistrationReminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.RegistrationActivity;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.crypto.MasterSecret;
public class PushRegistrationReminder extends Reminder {
public PushRegistrationReminder(final Context context, final MasterSecret masterSecret) {
super(context.getString(R.string.reminder_header_push_title),
context.getString(R.string.reminder_header_push_text));
final OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, RegistrationActivity.class);
intent.putExtra("master_secret", masterSecret);
intent.putExtra("cancel_button", true);
context.startActivity(intent);
}
};
setOkListener(okListener);
}
@Override
public boolean isDismissable() {
return false;
}
public static boolean isEligible(Context context) {
return !TextSecurePreferences.isPushRegistered(context);
}
}
| 1,257 | 29.682927 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/Reminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.support.annotation.NonNull;
import android.view.View.OnClickListener;
public abstract class Reminder {
private CharSequence title;
private CharSequence text;
private OnClickListener okListener;
private OnClickListener dismissListener;
public Reminder(@NonNull CharSequence title,
@NonNull CharSequence text)
{
this.title = title;
this.text = text;
}
public CharSequence getTitle() {
return title;
}
public CharSequence getText() {
return text;
}
public OnClickListener getOkListener() {
return okListener;
}
public OnClickListener getDismissListener() {
return dismissListener;
}
public void setOkListener(OnClickListener okListener) {
this.okListener = okListener;
}
public void setDismissListener(OnClickListener dismissListener) {
this.dismissListener = dismissListener;
}
public boolean isDismissable() {
return true;
}
}
| 1,015 | 20.166667 | 67 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/ReminderView.java | package org.thoughtcrime.securesms.components.reminder;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.util.ViewUtil;
/**
* View to display actionable reminders to the user
*/
public class ReminderView extends LinearLayout {
private ViewGroup container;
private ImageButton closeButton;
private TextView title;
private TextView text;
private OnDismissListener dismissListener;
public ReminderView(Context context) {
super(context);
initialize();
}
public ReminderView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
@TargetApi(VERSION_CODES.HONEYCOMB)
public ReminderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
private void initialize() {
LayoutInflater.from(getContext()).inflate(R.layout.reminder_header, this, true);
container = ViewUtil.findById(this, R.id.container);
closeButton = ViewUtil.findById(this, R.id.cancel);
title = ViewUtil.findById(this, R.id.reminder_title);
text = ViewUtil.findById(this, R.id.reminder_text);
}
public void showReminder(final Reminder reminder) {
title.setText(reminder.getTitle());
text.setText(reminder.getText());
setOnClickListener(reminder.getOkListener());
closeButton.setVisibility(reminder.isDismissable() ? View.VISIBLE : View.GONE);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hide();
if (reminder.getDismissListener() != null) reminder.getDismissListener().onClick(v);
if (dismissListener != null) dismissListener.onDismiss();
}
});
container.setVisibility(View.VISIBLE);
}
public void setOnDismissListener(OnDismissListener dismissListener) {
this.dismissListener = dismissListener;
}
public void requestDismiss() {
closeButton.performClick();
}
public void hide() {
container.setVisibility(View.GONE);
}
public interface OnDismissListener {
void onDismiss();
}
}
| 2,470 | 27.732558 | 92 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/ShareReminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.View.OnClickListener;
import org.thoughtcrime.securesms.InviteActivity;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
public class ShareReminder extends Reminder {
public ShareReminder(final @NonNull Context context) {
super(context.getString(R.string.reminder_header_share_title),
context.getString(R.string.reminder_header_share_text));
setDismissListener(new OnClickListener() {
@Override public void onClick(View v) {
TextSecurePreferences.setPromptedShare(context, true);
}
});
setOkListener(new OnClickListener() {
@Override public void onClick(View v) {
TextSecurePreferences.setPromptedShare(context, true);
context.startActivity(new Intent(context, InviteActivity.class));
}
});
}
public static boolean isEligible(final @NonNull Context context) {
if (!TextSecurePreferences.isPushRegistered(context) ||
TextSecurePreferences.hasPromptedShare(context))
{
return false;
}
Cursor cursor = null;
try {
cursor = DatabaseFactory.getThreadDatabase(context).getConversationList();
return cursor.getCount() >= 1;
} finally {
if (cursor != null) cursor.close();
}
}
}
| 1,575 | 29.901961 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/components/reminder/SystemSmsImportReminder.java | package org.thoughtcrime.securesms.components.reminder;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import org.thoughtcrime.securesms.ConversationListActivity;
import org.thoughtcrime.securesms.DatabaseMigrationActivity;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.service.ApplicationMigrationService;
import org.thoughtcrime.securesms.crypto.MasterSecret;
public class SystemSmsImportReminder extends Reminder {
public SystemSmsImportReminder(final Context context, final MasterSecret masterSecret) {
super(context.getString(R.string.reminder_header_sms_import_title),
context.getString(R.string.reminder_header_sms_import_text));
final OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ApplicationMigrationService.class);
intent.setAction(ApplicationMigrationService.MIGRATE_DATABASE);
intent.putExtra("master_secret", masterSecret);
context.startService(intent);
Intent nextIntent = new Intent(context, ConversationListActivity.class);
intent.putExtra("master_secret", masterSecret);
Intent activityIntent = new Intent(context, DatabaseMigrationActivity.class);
activityIntent.putExtra("master_secret", masterSecret);
activityIntent.putExtra("next_intent", nextIntent);
context.startActivity(activityIntent);
}
};
final OnClickListener cancelListener = new OnClickListener() {
@Override
public void onClick(View v) {
ApplicationMigrationService.setDatabaseImported(context);
}
};
setOkListener(okListener);
setDismissListener(cancelListener);
}
public static boolean isEligible(Context context) {
return !ApplicationMigrationService.isDatabaseImported(context);
}
}
| 1,944 | 37.137255 | 90 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ArrayListCursor.java | package org.thoughtcrime.securesms.contacts;
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.database.AbstractCursor;
import android.database.CursorWindow;
import java.lang.System;
import java.util.ArrayList;
/**
* A convenience class that presents a two-dimensional ArrayList
* as a Cursor.
*/
public class ArrayListCursor extends AbstractCursor {
private String[] mColumnNames;
private ArrayList<Object>[] mRows;
@SuppressWarnings({"unchecked"})
public ArrayListCursor(String[] columnNames, ArrayList<ArrayList> rows) {
int colCount = columnNames.length;
boolean foundID = false;
// Add an _id column if not in columnNames
for (int i = 0; i < colCount; ++i) {
if (columnNames[i].compareToIgnoreCase("_id") == 0) {
mColumnNames = columnNames;
foundID = true;
break;
}
}
if (!foundID) {
mColumnNames = new String[colCount + 1];
System.arraycopy(columnNames, 0, mColumnNames, 0, columnNames.length);
mColumnNames[colCount] = "_id";
}
int rowCount = rows.size();
mRows = new ArrayList[rowCount];
for (int i = 0; i < rowCount; ++i) {
mRows[i] = rows.get(i);
if (!foundID) {
mRows[i].add(i);
}
}
}
@Override
public void fillWindow(int position, CursorWindow window) {
if (position < 0 || position > getCount()) {
return;
}
window.acquireReference();
try {
int oldpos = mPos;
mPos = position - 1;
window.clear();
window.setStartPosition(position);
int columnNum = getColumnCount();
window.setNumColumns(columnNum);
while (moveToNext() && window.allocRow()) {
for (int i = 0; i < columnNum; i++) {
final Object data = mRows[mPos].get(i);
if (data != null) {
if (data instanceof byte[]) {
byte[] field = (byte[]) data;
if (!window.putBlob(field, mPos, i)) {
window.freeLastRow();
break;
}
} else {
String field = data.toString();
if (!window.putString(field, mPos, i)) {
window.freeLastRow();
break;
}
}
} else {
if (!window.putNull(mPos, i)) {
window.freeLastRow();
break;
}
}
}
}
mPos = oldpos;
} catch (IllegalStateException e){
// simply ignore it
} finally {
window.releaseReference();
}
}
@Override
public int getCount() {
return mRows.length;
}
public boolean deleteRow() {
return false;
}
@Override
public String[] getColumnNames() {
return mColumnNames;
}
@Override
public byte[] getBlob(int columnIndex) {
return (byte[]) mRows[mPos].get(columnIndex);
}
@Override
public String getString(int columnIndex) {
Object cell = mRows[mPos].get(columnIndex);
return (cell == null) ? null : cell.toString();
}
@Override
public short getShort(int columnIndex) {
Number num = (Number) mRows[mPos].get(columnIndex);
return num.shortValue();
}
@Override
public int getInt(int columnIndex) {
Number num = (Number) mRows[mPos].get(columnIndex);
return num.intValue();
}
@Override
public long getLong(int columnIndex) {
Number num = (Number) mRows[mPos].get(columnIndex);
return num.longValue();
}
@Override
public float getFloat(int columnIndex) {
Number num = (Number) mRows[mPos].get(columnIndex);
return num.floatValue();
}
@Override
public double getDouble(int columnIndex) {
Number num = (Number) mRows[mPos].get(columnIndex);
return num.doubleValue();
}
@Override
public boolean isNull(int columnIndex) {
return mRows[mPos].get(columnIndex) == null;
}
}
| 5,087 | 28.929412 | 82 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactAccessor.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.contacts;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.MergeCursor;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneNumberUtils;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.database.TextSecureDirectory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static org.thoughtcrime.securesms.database.GroupDatabase.GroupRecord;
/**
* This class was originally a layer of indirection between
* ContactAccessorNewApi and ContactAccesorOldApi, which corresponded
* to the API changes between 1.x and 2.x.
*
* Now that we no longer support 1.x, this class mostly serves as a place
* to encapsulate Contact-related logic. It's still a singleton, mostly
* just because that's how it's currently called from everywhere.
*
* @author Moxie Marlinspike
*/
public class ContactAccessor {
public static final String PUSH_COLUMN = "push";
private static final ContactAccessor instance = new ContactAccessor();
public static synchronized ContactAccessor getInstance() {
return instance;
}
public Collection<ContactData> getContactsWithPush(Context context) {
final ContentResolver resolver = context.getContentResolver();
final String[] inProjection = new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME};
List<String> pushNumbers = TextSecureDirectory.getInstance(context).getActiveNumbers();
final Collection<ContactData> lookupData = new ArrayList<ContactData>(pushNumbers.size());
for (String pushNumber : pushNumbers) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(pushNumber));
Cursor lookupCursor = resolver.query(uri, inProjection, null, null, null);
try {
if (lookupCursor != null && lookupCursor.moveToFirst()) {
final ContactData contactData = new ContactData(lookupCursor.getLong(0), lookupCursor.getString(1));
contactData.numbers.add(new NumberData("TextSecure", pushNumber));
lookupData.add(contactData);
}
} finally {
if (lookupCursor != null)
lookupCursor.close();
}
}
return lookupData;
}
public String getNameFromContact(Context context, Uri uri) {
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[] {Contacts.DISPLAY_NAME},
null, null, null);
if (cursor != null && cursor.moveToFirst())
return cursor.getString(0);
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public ContactData getContactData(Context context, Uri uri) {
return getContactData(context, getNameFromContact(context, uri), Long.parseLong(uri.getLastPathSegment()));
}
private ContactData getContactData(Context context, String displayName, long id) {
ContactData contactData = new ContactData(id, displayName);
Cursor numberCursor = null;
try {
numberCursor = context.getContentResolver().query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = ?",
new String[] {contactData.id + ""}, null);
while (numberCursor != null && numberCursor.moveToNext()) {
int type = numberCursor.getInt(numberCursor.getColumnIndexOrThrow(Phone.TYPE));
String label = numberCursor.getString(numberCursor.getColumnIndexOrThrow(Phone.LABEL));
String number = numberCursor.getString(numberCursor.getColumnIndexOrThrow(Phone.NUMBER));
String typeLabel = Phone.getTypeLabel(context.getResources(), type, label).toString();
contactData.numbers.add(new NumberData(typeLabel, number));
}
} finally {
if (numberCursor != null)
numberCursor.close();
}
return contactData;
}
public List<String> getNumbersForThreadSearchFilter(Context context, String constraint) {
LinkedList<String> numberList = new LinkedList<>();
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI,
Uri.encode(constraint)),
null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
numberList.add(cursor.getString(cursor.getColumnIndexOrThrow(Phone.NUMBER)));
}
} finally {
if (cursor != null)
cursor.close();
}
GroupDatabase.Reader reader = null;
GroupRecord record;
try {
reader = DatabaseFactory.getGroupDatabase(context).getGroupsFilteredByTitle(constraint);
while ((record = reader.getNext()) != null) {
numberList.add(record.getEncodedId());
}
} finally {
if (reader != null)
reader.close();
}
return numberList;
}
public CharSequence phoneTypeToString(Context mContext, int type, CharSequence label) {
return Phone.getTypeLabel(mContext.getResources(), type, label);
}
public static class NumberData implements Parcelable {
public static final Parcelable.Creator<NumberData> CREATOR = new Parcelable.Creator<NumberData>() {
public NumberData createFromParcel(Parcel in) {
return new NumberData(in);
}
public NumberData[] newArray(int size) {
return new NumberData[size];
}
};
public final String number;
public final String type;
public NumberData(String type, String number) {
this.type = type;
this.number = number;
}
public NumberData(Parcel in) {
number = in.readString();
type = in.readString();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(number);
dest.writeString(type);
}
}
public static class ContactData implements Parcelable {
public static final Parcelable.Creator<ContactData> CREATOR = new Parcelable.Creator<ContactData>() {
public ContactData createFromParcel(Parcel in) {
return new ContactData(in);
}
public ContactData[] newArray(int size) {
return new ContactData[size];
}
};
public final long id;
public final String name;
public final List<NumberData> numbers;
public ContactData(long id, String name) {
this.id = id;
this.name = name;
this.numbers = new LinkedList<NumberData>();
}
public ContactData(Parcel in) {
id = in.readLong();
name = in.readString();
numbers = new LinkedList<NumberData>();
in.readTypedList(numbers, NumberData.CREATOR);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(name);
dest.writeTypedList(numbers);
}
}
/***
* If the code below looks shitty to you, that's because it was taken
* directly from the Android source, where shitty code is all you get.
*/
public Cursor getCursorForRecipientFilter(CharSequence constraint,
ContentResolver mContentResolver)
{
final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," +
Contacts.DISPLAY_NAME + "," +
Contacts.Data.IS_SUPER_PRIMARY + " DESC," +
Phone.TYPE;
final String[] PROJECTION_PHONE = {
Phone._ID, // 0
Phone.CONTACT_ID, // 1
Phone.TYPE, // 2
Phone.NUMBER, // 3
Phone.LABEL, // 4
Phone.DISPLAY_NAME, // 5
};
String phone = "";
String cons = null;
if (constraint != null) {
cons = constraint.toString();
if (RecipientsAdapter.usefulAsDigits(cons)) {
phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons);
if (phone.equals(cons) && !PhoneNumberUtils.isWellFormedSmsAddress(phone)) {
phone = "";
} else {
phone = phone.trim();
}
}
}
Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(cons));
String selection = String.format("%s=%s OR %s=%s OR %s=%s",
Phone.TYPE,
Phone.TYPE_MOBILE,
Phone.TYPE,
Phone.TYPE_WORK_MOBILE,
Phone.TYPE,
Phone.TYPE_MMS);
Cursor phoneCursor = mContentResolver.query(uri,
PROJECTION_PHONE,
null,
null,
SORT_ORDER);
if (phone.length() > 0) {
ArrayList result = new ArrayList();
result.add(Integer.valueOf(-1)); // ID
result.add(Long.valueOf(-1)); // CONTACT_ID
result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE
result.add(phone); // NUMBER
/*
* The "\u00A0" keeps Phone.getDisplayLabel() from deciding
* to display the default label ("Home") next to the transformation
* of the letters into numbers.
*/
result.add("\u00A0"); // LABEL
result.add(cons); // NAME
ArrayList<ArrayList> wrap = new ArrayList<ArrayList>();
wrap.add(result);
ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap);
return new MergeCursor(new Cursor[] { translated, phoneCursor });
} else {
return phoneCursor;
}
}
}
| 11,082 | 32.789634 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactIdentityManager.java | package org.thoughtcrime.securesms.contacts;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import java.util.List;
public abstract class ContactIdentityManager {
public static ContactIdentityManager getInstance(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
return new ContactIdentityManagerICS(context);
else
return new ContactIdentityManagerGingerbread(context);
}
protected final Context context;
public ContactIdentityManager(Context context) {
this.context = context.getApplicationContext();
}
public abstract Uri getSelfIdentityUri();
public abstract boolean isSelfIdentityAutoDetected();
public abstract List<Long> getSelfIdentityRawContactIds();
}
| 789 | 26.241379 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactIdentityManagerGingerbread.java | package org.thoughtcrime.securesms.contacts;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.telephony.TelephonyManager;
import org.thoughtcrime.securesms.ApplicationPreferencesActivity;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.util.ArrayList;
import java.util.List;
class ContactIdentityManagerGingerbread extends ContactIdentityManager {
public ContactIdentityManagerGingerbread(Context context) {
super(context);
}
@Override
public Uri getSelfIdentityUri() {
String contactUriString = TextSecurePreferences.getIdentityContactUri(context);
if (hasLocalNumber()) return getContactUriForNumber(getLocalNumber());
else if (contactUriString != null) return Uri.parse(contactUriString);
return null;
}
@Override
public boolean isSelfIdentityAutoDetected() {
return hasLocalNumber() && getContactUriForNumber(getLocalNumber()) != null;
}
@Override
public List<Long> getSelfIdentityRawContactIds() {
long selfIdentityContactId = getSelfIdentityContactId();
if (selfIdentityContactId == -1)
return null;
Cursor cursor = null;
ArrayList<Long> rawContactIds = new ArrayList<Long>();
try {
cursor = context.getContentResolver().query(RawContacts.CONTENT_URI,
new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + " = ?",
new String[] {selfIdentityContactId+""},
null);
if (cursor == null || cursor.getCount() == 0)
return null;
while (cursor.moveToNext()) {
rawContactIds.add(Long.valueOf(cursor.getLong(0)));
}
return rawContactIds;
} finally {
if (cursor != null)
cursor.close();
}
}
private Uri getContactUriForNumber(String number) {
String[] PROJECTION = new String[] {
PhoneLookup.DISPLAY_NAME,
PhoneLookup.LOOKUP_KEY,
PhoneLookup._ID,
};
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, PROJECTION, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return Contacts.getLookupUri(cursor.getLong(2), cursor.getString(1));
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private long getSelfIdentityContactId() {
Uri contactUri = getSelfIdentityUri();
if (contactUri == null)
return -1;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(contactUri,
new String[] {ContactsContract.Contacts._ID},
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return cursor.getLong(0);
} else {
return -1;
}
} finally {
if (cursor != null)
cursor.close();
}
}
private String getLocalNumber() {
return ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE))
.getLine1Number();
}
private boolean hasLocalNumber() {
String number = getLocalNumber();
return (number != null) && (number.trim().length() > 0);
}
}
| 3,788 | 27.066667 | 95 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactIdentityManagerICS.java | package org.thoughtcrime.securesms.contacts;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import java.util.LinkedList;
import java.util.List;
class ContactIdentityManagerICS extends ContactIdentityManager {
public ContactIdentityManagerICS(Context context) {
super(context);
}
@SuppressLint("NewApi")
@Override
public Uri getSelfIdentityUri() {
String[] PROJECTION = new String[] {
PhoneLookup.DISPLAY_NAME,
PhoneLookup.LOOKUP_KEY,
PhoneLookup._ID,
};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(ContactsContract.Profile.CONTENT_URI,
PROJECTION, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return Contacts.getLookupUri(cursor.getLong(2), cursor.getString(1));
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
@Override
public boolean isSelfIdentityAutoDetected() {
return true;
}
@SuppressLint("NewApi")
@Override
public List<Long> getSelfIdentityRawContactIds() {
List<Long> results = new LinkedList<Long>();
String[] PROJECTION = new String[] {
ContactsContract.Profile._ID
};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI,
PROJECTION, null, null, null);
if (cursor == null || cursor.getCount() == 0)
return null;
while (cursor.moveToNext()) {
results.add(cursor.getLong(0));
}
return results;
} finally {
if (cursor != null)
cursor.close();
}
}
}
| 1,964 | 23.5625 | 100 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactSelectionListAdapter.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.contacts;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.RecyclerViewFastScroller.FastScrollAdapter;
import org.thoughtcrime.securesms.ContactSelectionListFragment.StickyHeaderAdapter;
import org.thoughtcrime.securesms.contacts.ContactSelectionListAdapter.HeaderViewHolder;
import org.thoughtcrime.securesms.contacts.ContactSelectionListAdapter.ViewHolder;
import org.thoughtcrime.securesms.database.CursorRecyclerViewAdapter;
import java.util.HashMap;
import java.util.Map;
/**
* List adapter to display all contacts and their related information
*
* @author Jake McGinty
*/
public class ContactSelectionListAdapter extends CursorRecyclerViewAdapter<ViewHolder>
implements FastScrollAdapter,
StickyHeaderAdapter<HeaderViewHolder>
{
private final static String TAG = ContactSelectionListAdapter.class.getSimpleName();
private final static int STYLE_ATTRIBUTES[] = new int[]{R.attr.contact_selection_push_user,
R.attr.contact_selection_lay_user};
private final boolean multiSelect;
private final LayoutInflater li;
private final TypedArray drawables;
private final ItemClickListener clickListener;
private final HashMap<Long, String> selectedContacts = new HashMap<>();
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(@NonNull final View itemView,
@Nullable final ItemClickListener clickListener)
{
super(itemView);
itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (clickListener != null) clickListener.onItemClick(getView());
}
});
}
public ContactSelectionListItem getView() {
return (ContactSelectionListItem) itemView;
}
}
public static class HeaderViewHolder extends RecyclerView.ViewHolder {
public HeaderViewHolder(View itemView) {
super(itemView);
}
}
public ContactSelectionListAdapter(@NonNull Context context,
@Nullable Cursor cursor,
@Nullable ItemClickListener clickListener,
boolean multiSelect)
{
super(context, cursor);
this.li = LayoutInflater.from(context);
this.drawables = context.obtainStyledAttributes(STYLE_ATTRIBUTES);
this.multiSelect = multiSelect;
this.clickListener = clickListener;
}
@Override
public long getHeaderId(int i) {
return getHeaderString(i).hashCode();
}
@Override
public ViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(li.inflate(R.layout.contact_selection_list_item, parent, false), clickListener);
}
@Override
public void onBindItemViewHolder(ViewHolder viewHolder, @NonNull Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(ContactsDatabase.ID_COLUMN));
int contactType = cursor.getInt(cursor.getColumnIndexOrThrow(ContactsDatabase.CONTACT_TYPE_COLUMN));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NAME_COLUMN));
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NUMBER_COLUMN));
int numberType = cursor.getInt(cursor.getColumnIndexOrThrow(ContactsDatabase.NUMBER_TYPE_COLUMN));
String label = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.LABEL_COLUMN));
String labelText = ContactsContract.CommonDataKinds.Phone.getTypeLabel(getContext().getResources(),
numberType, label).toString();
int color = (contactType == ContactsDatabase.PUSH_TYPE) ? drawables.getColor(0, 0xa0000000) :
drawables.getColor(1, 0xff000000);
viewHolder.getView().unbind();
viewHolder.getView().set(id, contactType, name, number, labelText, color, multiSelect);
viewHolder.getView().setChecked(selectedContacts.containsKey(id));
}
@Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
return new HeaderViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.contact_selection_recyclerview_header, parent, false));
}
@Override
public void onBindHeaderViewHolder(HeaderViewHolder viewHolder, int position) {
((TextView)viewHolder.itemView).setText(getSpannedHeaderString(position, R.drawable.ic_signal_grey_24dp));
}
@Override
public CharSequence getBubbleText(int position) {
return getSpannedHeaderString(position, R.drawable.ic_signal_white_48dp);
}
public Map<Long, String> getSelectedContacts() {
return selectedContacts;
}
private CharSequence getSpannedHeaderString(int position, @DrawableRes int drawable) {
Cursor cursor = getCursorAtPositionOrThrow(position);
if (cursor.getInt(cursor.getColumnIndexOrThrow(ContactsDatabase.CONTACT_TYPE_COLUMN)) == ContactsDatabase.PUSH_TYPE) {
SpannableString spannable = new SpannableString(" ");
spannable.setSpan(new ImageSpan(getContext(), drawable, ImageSpan.ALIGN_BOTTOM), 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
} else {
return getHeaderString(position);
}
}
private String getHeaderString(int position) {
Cursor cursor = getCursorAtPositionOrThrow(position);
if (cursor.getInt(cursor.getColumnIndexOrThrow(ContactsDatabase.CONTACT_TYPE_COLUMN)) == ContactsDatabase.PUSH_TYPE) {
return getContext().getString(R.string.app_name);
} else {
String letter = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NAME_COLUMN))
.trim()
.substring(0,1)
.toUpperCase();
if (Character.isLetterOrDigit(letter.codePointAt(0))) {
return letter;
} else {
return "#";
}
}
}
private Cursor getCursorAtPositionOrThrow(int position) {
Cursor cursor = getCursor();
if (cursor == null) {
throw new IllegalStateException("Cursor should not be null here.");
}
if (!cursor.moveToPosition(position));
return cursor;
}
public interface ItemClickListener {
void onItemClick(ContactSelectionListItem item);
}
}
| 7,792 | 39.170103 | 144 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactSelectionListItem.java | package org.thoughtcrime.securesms.contacts;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.AvatarImageView;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
public class ContactSelectionListItem extends LinearLayout implements Recipients.RecipientsModifiedListener {
private AvatarImageView contactPhotoImage;
private TextView numberView;
private TextView nameView;
private TextView labelView;
private CheckBox checkBox;
private long id;
private String number;
private Recipients recipients;
public ContactSelectionListItem(Context context) {
super(context);
}
public ContactSelectionListItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
this.contactPhotoImage = (AvatarImageView) findViewById(R.id.contact_photo_image);
this.numberView = (TextView) findViewById(R.id.number);
this.labelView = (TextView) findViewById(R.id.label);
this.nameView = (TextView) findViewById(R.id.name);
this.checkBox = (CheckBox) findViewById(R.id.check_box);
}
public void set(long id, int type, String name, String number, String label, int color, boolean multiSelect) {
this.id = id;
this.number = number;
if (type == ContactsDatabase.NEW_TYPE) {
this.recipients = null;
this.contactPhotoImage.setAvatar(Recipient.getUnknownRecipient(), false);
} else if (!TextUtils.isEmpty(number)) {
this.recipients = RecipientFactory.getRecipientsFromString(getContext(), number, true);
if (this.recipients.getPrimaryRecipient() != null &&
this.recipients.getPrimaryRecipient().getName() != null)
{
name = this.recipients.getPrimaryRecipient().getName();
}
this.recipients.addListener(this);
}
this.nameView.setTextColor(color);
this.numberView.setTextColor(color);
this.contactPhotoImage.setAvatar(recipients, false);
setText(type, name, number, label);
if (multiSelect) this.checkBox.setVisibility(View.VISIBLE);
else this.checkBox.setVisibility(View.GONE);
}
public void setChecked(boolean selected) {
this.checkBox.setChecked(selected);
}
public void unbind() {
if (recipients != null) {
recipients.removeListener(this);
recipients = null;
}
}
private void setText(int type, String name, String number, String label) {
if (number == null || number.isEmpty()) {
this.nameView.setEnabled(false);
this.numberView.setText("");
this.labelView.setVisibility(View.GONE);
} else if (type == ContactsDatabase.PUSH_TYPE) {
this.numberView.setText(number);
this.nameView.setEnabled(true);
this.labelView.setVisibility(View.GONE);
} else {
this.numberView.setText(number);
this.nameView.setEnabled(true);
this.labelView.setText(label);
this.labelView.setVisibility(View.VISIBLE);
}
this.nameView.setText(name);
}
public long getContactId() {
return id;
}
public String getNumber() {
return number;
}
@Override
public void onModified(final Recipients recipients) {
if (this.recipients == recipients) {
this.contactPhotoImage.post(new Runnable() {
@Override
public void run() {
contactPhotoImage.setAvatar(recipients, false);
nameView.setText(recipients.toShortString());
}
});
}
}
}
| 3,928 | 29.937008 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactsCursorLoader.java | /**
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.contacts;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.content.CursorLoader;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.DirectoryHelper;
import org.thoughtcrime.securesms.util.DirectoryHelper.UserCapabilities.Capability;
import org.thoughtcrime.securesms.util.NumberUtil;
import java.util.ArrayList;
/**
* CursorLoader that initializes a ContactsDatabase instance
*
* @author Jake McGinty
*/
public class ContactsCursorLoader extends CursorLoader {
private static final String TAG = ContactsCursorLoader.class.getSimpleName();
public final static int MODE_ALL = 0;
public final static int MODE_PUSH_ONLY = 1;
public final static int MODE_OTHER_ONLY = 2;
private final String filter;
private final int mode;
public ContactsCursorLoader(Context context, int mode, String filter) {
super(context);
this.filter = filter;
this.mode = mode;
}
@Override
public Cursor loadInBackground() {
ContactsDatabase contactsDatabase = DatabaseFactory.getContactsDatabase(getContext());
ArrayList<Cursor> cursorList = new ArrayList<>(3);
if (mode != MODE_OTHER_ONLY) {
cursorList.add(contactsDatabase.queryTextSecureContacts(filter));
}
if (mode == MODE_ALL) {
cursorList.add(contactsDatabase.querySystemContacts(filter));
} else if (mode == MODE_OTHER_ONLY) {
cursorList.add(filterNonPushContacts(contactsDatabase.querySystemContacts(filter)));
}
if (!TextUtils.isEmpty(filter) && NumberUtil.isValidSmsOrEmail(filter)) {
MatrixCursor newNumberCursor = new MatrixCursor(new String[] {ContactsDatabase.ID_COLUMN,
ContactsDatabase.NAME_COLUMN,
ContactsDatabase.NUMBER_COLUMN,
ContactsDatabase.NUMBER_TYPE_COLUMN,
ContactsDatabase.LABEL_COLUMN,
ContactsDatabase.CONTACT_TYPE_COLUMN}, 1);
newNumberCursor.addRow(new Object[] {-1L, getContext().getString(R.string.contact_selection_list__unknown_contact),
filter, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM,
"\u21e2", ContactsDatabase.NEW_TYPE});
cursorList.add(newNumberCursor);
}
return new MergeCursor(cursorList.toArray(new Cursor[0]));
}
private @NonNull Cursor filterNonPushContacts(@NonNull Cursor cursor) {
try {
final long startMillis = System.currentTimeMillis();
final MatrixCursor matrix = new MatrixCursor(new String[]{ContactsDatabase.ID_COLUMN,
ContactsDatabase.NAME_COLUMN,
ContactsDatabase.NUMBER_COLUMN,
ContactsDatabase.NUMBER_TYPE_COLUMN,
ContactsDatabase.LABEL_COLUMN,
ContactsDatabase.CONTACT_TYPE_COLUMN});
while (cursor.moveToNext()) {
final String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NUMBER_COLUMN));
final Recipients recipients = RecipientFactory.getRecipientsFromString(getContext(), number, true);
if (DirectoryHelper.getUserCapabilities(getContext(), recipients)
.getTextCapability() != Capability.SUPPORTED)
{
matrix.addRow(new Object[]{cursor.getLong(cursor.getColumnIndexOrThrow(ContactsDatabase.ID_COLUMN)),
cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NAME_COLUMN)),
number,
cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.NUMBER_TYPE_COLUMN)),
cursor.getString(cursor.getColumnIndexOrThrow(ContactsDatabase.LABEL_COLUMN)),
ContactsDatabase.NORMAL_TYPE});
}
}
Log.w(TAG, "filterNonPushContacts() -> " + (System.currentTimeMillis() - startMillis) + "ms");
return matrix;
} finally {
cursor.close();
}
}
}
| 5,669 | 44 | 121 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactsDatabase.java | /**
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.contacts;
import android.accounts.Account;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.net.Uri;
import android.os.Build;
import android.os.RemoteException;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.R;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.push.ContactTokenDetails;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Database to supply all types of contacts that TextSecure needs to know about
*
* @author Jake McGinty
*/
public class ContactsDatabase {
private static final String TAG = ContactsDatabase.class.getSimpleName();
private static final String CONTACT_MIMETYPE = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact";
private static final String CALL_MIMETYPE = "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call";
private static final String SYNC = "__TS";
public static final String ID_COLUMN = "_id";
public static final String NAME_COLUMN = "name";
public static final String NUMBER_COLUMN = "number";
public static final String NUMBER_TYPE_COLUMN = "number_type";
public static final String LABEL_COLUMN = "label";
public static final String CONTACT_TYPE_COLUMN = "contact_type";
public static final int NORMAL_TYPE = 0;
public static final int PUSH_TYPE = 1;
public static final int NEW_TYPE = 2;
private final Context context;
public ContactsDatabase(Context context) {
this.context = context;
}
public synchronized @NonNull List<String> setRegisteredUsers(@NonNull Account account,
@NonNull String localNumber,
@NonNull List<ContactTokenDetails> registeredContacts,
boolean remove)
throws RemoteException, OperationApplicationException
{
Map<String, ContactTokenDetails> registeredNumbers = new HashMap<>();
List<String> addedNumbers = new LinkedList<>();
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
Map<String, SignalContact> currentContacts = getSignalRawContacts(account, localNumber);
for (ContactTokenDetails registeredContact : registeredContacts) {
String registeredNumber = registeredContact.getNumber();
registeredNumbers.put(registeredNumber, registeredContact);
if (!currentContacts.containsKey(registeredNumber)) {
Optional<SystemContactInfo> systemContactInfo = getSystemContactInfo(registeredNumber, localNumber);
if (systemContactInfo.isPresent()) {
Log.w(TAG, "Adding number: " + registeredNumber);
addedNumbers.add(registeredNumber);
addTextSecureRawContact(operations, account, systemContactInfo.get().number,
systemContactInfo.get().id, registeredContact.isVoice());
}
}
}
for (Map.Entry<String, SignalContact> currentContactEntry : currentContacts.entrySet()) {
ContactTokenDetails tokenDetails = registeredNumbers.get(currentContactEntry.getKey());
if (tokenDetails == null) {
if (remove) {
Log.w(TAG, "Removing number: " + currentContactEntry.getKey());
removeTextSecureRawContact(operations, account, currentContactEntry.getValue().getId());
}
} else if (tokenDetails.isVoice() && !currentContactEntry.getValue().isVoiceSupported()) {
Log.w(TAG, "Adding voice support: " + currentContactEntry.getKey());
addContactVoiceSupport(operations, currentContactEntry.getKey(), currentContactEntry.getValue().getId());
} else if (!tokenDetails.isVoice() && currentContactEntry.getValue().isVoiceSupported()) {
Log.w(TAG, "Removing voice support: " + currentContactEntry.getKey());
removeContactVoiceSupport(operations, currentContactEntry.getValue().getId());
}
}
if (!operations.isEmpty()) {
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);
}
return addedNumbers;
}
public @NonNull Cursor querySystemContacts(String filter) {
Uri uri;
if (!TextUtils.isEmpty(filter)) {
uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(filter));
} else {
uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
}
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
uri = uri.buildUpon().appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true").build();
}
String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL};
String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC";
Map<String, String> projectionMap = new HashMap<String, String>() {{
put(ID_COLUMN, ContactsContract.CommonDataKinds.Phone._ID);
put(NAME_COLUMN, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
put(NUMBER_COLUMN, ContactsContract.CommonDataKinds.Phone.NUMBER);
put(NUMBER_TYPE_COLUMN, ContactsContract.CommonDataKinds.Phone.TYPE);
put(LABEL_COLUMN, ContactsContract.CommonDataKinds.Phone.LABEL);
}};
String excludeSelection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " NOT IN (" +
"SELECT data.contact_id FROM raw_contacts, view_data data WHERE raw_contacts._id = data.raw_contact_id AND " +
"data.mimetype = '" + CONTACT_MIMETYPE + "')";
String fallbackSelection = ContactsContract.Data.SYNC2 + " IS NULL OR " + ContactsContract.Data.SYNC2 + " != '" + SYNC + "'";
Cursor cursor;
try {
cursor = context.getContentResolver().query(uri, projection, excludeSelection, null, sort);
} catch (Exception e) {
Log.w(TAG, e);
cursor = context.getContentResolver().query(uri, projection, fallbackSelection, null, sort);
}
return new ProjectionMappingCursor(cursor, projectionMap,
new Pair<String, Object>(CONTACT_TYPE_COLUMN, NORMAL_TYPE));
}
public @NonNull Cursor queryTextSecureContacts(String filter) {
String[] projection = new String[] {ContactsContract.Data._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Data.DATA1};
String sort = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE NOCASE ASC";
Map<String, String> projectionMap = new HashMap<String, String>(){{
put(ID_COLUMN, ContactsContract.Data._ID);
put(NAME_COLUMN, ContactsContract.Contacts.DISPLAY_NAME);
put(NUMBER_COLUMN, ContactsContract.Data.DATA1);
}};
Cursor cursor;
if (TextUtils.isEmpty(filter)) {
cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
projection,
ContactsContract.Data.MIMETYPE + " = ?",
new String[] {CONTACT_MIMETYPE},
sort);
} else {
cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
projection,
ContactsContract.Data.MIMETYPE + " = ? AND (" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR " + ContactsContract.Data.DATA1 + " LIKE ?)",
new String[] {CONTACT_MIMETYPE,
"%" + filter + "%", "%" + filter + "%"},
sort);
}
return new ProjectionMappingCursor(cursor, projectionMap,
new Pair<String, Object>(LABEL_COLUMN, "TextSecure"),
new Pair<String, Object>(NUMBER_TYPE_COLUMN, 0),
new Pair<String, Object>(CONTACT_TYPE_COLUMN, PUSH_TYPE));
}
private void addContactVoiceSupport(List<ContentProviderOperation> operations,
@NonNull String e164number, long rawContactId)
{
operations.add(ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI)
.withSelection(RawContacts._ID + " = ?", new String[] {String.valueOf(rawContactId)})
.withValue(RawContacts.SYNC4, "true")
.build());
operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build())
.withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
.withValue(ContactsContract.Data.MIMETYPE, CALL_MIMETYPE)
.withValue(ContactsContract.Data.DATA1, e164number)
.withValue(ContactsContract.Data.DATA2, context.getString(R.string.app_name))
.withValue(ContactsContract.Data.DATA3, context.getString(R.string.ContactsDatabase_signal_call_s, e164number))
.withYieldAllowed(true)
.build());
}
private void removeContactVoiceSupport(List<ContentProviderOperation> operations, long rawContactId) {
operations.add(ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI)
.withSelection(RawContacts._ID + " = ?", new String[] {String.valueOf(rawContactId)})
.withValue(RawContacts.SYNC4, "false")
.build());
operations.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build())
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?",
new String[] {String.valueOf(rawContactId), CALL_MIMETYPE})
.withYieldAllowed(true)
.build());
}
private void addTextSecureRawContact(List<ContentProviderOperation> operations,
Account account, String e164number,
long aggregateId, boolean supportsVoice)
{
int index = operations.size();
Uri dataUri = ContactsContract.Data.CONTENT_URI.buildUpon()
.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")
.build();
operations.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_NAME, account.name)
.withValue(RawContacts.ACCOUNT_TYPE, account.type)
.withValue(RawContacts.SYNC1, e164number)
.withValue(RawContacts.SYNC4, String.valueOf(supportsVoice))
.build());
operations.add(ContentProviderOperation.newInsert(dataUri)
.withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, index)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, e164number)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_OTHER)
.withValue(ContactsContract.Data.SYNC2, SYNC)
.build());
operations.add(ContentProviderOperation.newInsert(dataUri)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, index)
.withValue(ContactsContract.Data.MIMETYPE, CONTACT_MIMETYPE)
.withValue(ContactsContract.Data.DATA1, e164number)
.withValue(ContactsContract.Data.DATA2, context.getString(R.string.app_name))
.withValue(ContactsContract.Data.DATA3, context.getString(R.string.ContactsDatabase_message_s, e164number))
.withYieldAllowed(true)
.build());
if (supportsVoice) {
operations.add(ContentProviderOperation.newInsert(dataUri)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, index)
.withValue(ContactsContract.Data.MIMETYPE, CALL_MIMETYPE)
.withValue(ContactsContract.Data.DATA1, e164number)
.withValue(ContactsContract.Data.DATA2, context.getString(R.string.app_name))
.withValue(ContactsContract.Data.DATA3, context.getString(R.string.ContactsDatabase_signal_call_s, e164number))
.withYieldAllowed(true)
.build());
}
if (Build.VERSION.SDK_INT >= 11) {
operations.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
.withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, aggregateId)
.withValueBackReference(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, index)
.withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER)
.build());
}
}
private void removeTextSecureRawContact(List<ContentProviderOperation> operations,
Account account, long rowId)
{
operations.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build())
.withYieldAllowed(true)
.withSelection(BaseColumns._ID + " = ?", new String[] {String.valueOf(rowId)})
.build());
}
private @NonNull Map<String, SignalContact> getSignalRawContacts(@NonNull Account account,
@NonNull String localNumber)
{
Uri currentContactsUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();
Map<String, SignalContact> signalContacts = new HashMap<>();
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(currentContactsUri, new String[] {BaseColumns._ID, RawContacts.SYNC1, RawContacts.SYNC4}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
String currentNumber;
try {
currentNumber = PhoneNumberFormatter.formatNumber(cursor.getString(1), localNumber);
} catch (InvalidNumberException e) {
Log.w(TAG, e);
currentNumber = cursor.getString(1);
}
signalContacts.put(currentNumber, new SignalContact(cursor.getLong(0), cursor.getString(2)));
}
} finally {
if (cursor != null)
cursor.close();
}
return signalContacts;
}
private Optional<SystemContactInfo> getSystemContactInfo(@NonNull String e164number,
@NonNull String localNumber)
{
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(e164number));
String[] projection = {ContactsContract.PhoneLookup.NUMBER,
ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME};
Cursor numberCursor = null;
Cursor idCursor = null;
try {
numberCursor = context.getContentResolver().query(uri, projection, null, null, null);
while (numberCursor != null && numberCursor.moveToNext()) {
try {
String systemNumber = numberCursor.getString(0);
String canonicalizedSystemNumber = PhoneNumberFormatter.formatNumber(systemNumber, localNumber);
if (canonicalizedSystemNumber.equals(e164number)) {
idCursor = context.getContentResolver().query(RawContacts.CONTENT_URI,
new String[] {RawContacts._ID},
RawContacts.CONTACT_ID + " = ? ",
new String[] {String.valueOf(numberCursor.getLong(1))},
null);
if (idCursor != null && idCursor.moveToNext()) {
return Optional.of(new SystemContactInfo(numberCursor.getString(2),
numberCursor.getString(0),
idCursor.getLong(0)));
}
}
} catch (InvalidNumberException e) {
Log.w(TAG, e);
}
}
} finally {
if (numberCursor != null) numberCursor.close();
if (idCursor != null) idCursor.close();
}
return Optional.absent();
}
private static class ProjectionMappingCursor extends CursorWrapper {
private final Map<String, String> projectionMap;
private final Pair<String, Object>[] extras;
@SafeVarargs
public ProjectionMappingCursor(Cursor cursor,
Map<String, String> projectionMap,
Pair<String, Object>... extras)
{
super(cursor);
this.projectionMap = projectionMap;
this.extras = extras;
}
@Override
public int getColumnCount() {
return super.getColumnCount() + extras.length;
}
@Override
public int getColumnIndex(String columnName) {
for (int i=0;i<extras.length;i++) {
if (extras[i].first.equals(columnName)) {
return super.getColumnCount() + i;
}
}
return super.getColumnIndex(projectionMap.get(columnName));
}
@Override
public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
int index = getColumnIndex(columnName);
if (index == -1) throw new IllegalArgumentException("Bad column name!");
else return index;
}
@Override
public String getColumnName(int columnIndex) {
int baseColumnCount = super.getColumnCount();
if (columnIndex >= baseColumnCount) {
int offset = columnIndex - baseColumnCount;
return extras[offset].first;
}
return getReverseProjection(super.getColumnName(columnIndex));
}
@Override
public String[] getColumnNames() {
String[] names = super.getColumnNames();
String[] allNames = new String[names.length + extras.length];
for (int i=0;i<names.length;i++) {
allNames[i] = getReverseProjection(names[i]);
}
for (int i=0;i<extras.length;i++) {
allNames[names.length + i] = extras[i].first;
}
return allNames;
}
@Override
public int getInt(int columnIndex) {
if (columnIndex >= super.getColumnCount()) {
int offset = columnIndex - super.getColumnCount();
return (Integer)extras[offset].second;
}
return super.getInt(columnIndex);
}
@Override
public String getString(int columnIndex) {
if (columnIndex >= super.getColumnCount()) {
int offset = columnIndex - super.getColumnCount();
return (String)extras[offset].second;
}
return super.getString(columnIndex);
}
private @Nullable String getReverseProjection(String columnName) {
for (Map.Entry<String, String> entry : projectionMap.entrySet()) {
if (entry.getValue().equals(columnName)) {
return entry.getKey();
}
}
return null;
}
}
private static class SystemContactInfo {
private final String name;
private final String number;
private final long id;
private SystemContactInfo(String name, String number, long id) {
this.name = name;
this.number = number;
this.id = id;
}
}
private static class SignalContact {
private final long id;
@Nullable private final String supportsVoice;
public SignalContact(long id, @Nullable String supportsVoice) {
this.id = id;
this.supportsVoice = supportsVoice;
}
public long getId() {
return id;
}
public boolean isVoiceSupported() {
return "true".equals(supportsVoice);
}
}
}
| 24,083 | 45.494208 | 196 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/ContactsSyncAdapter.java | package org.thoughtcrime.securesms.contacts;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.util.Log;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.thoughtcrime.securesms.util.DirectoryHelper;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.io.IOException;
public class ContactsSyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = ContactsSyncAdapter.class.getSimpleName();
public ContactsSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult)
{
Log.w(TAG, "onPerformSync(" + authority +")");
if (TextSecurePreferences.isPushRegistered(getContext())) {
try {
DirectoryHelper.refreshDirectory(getContext(), KeyCachingService.getMasterSecret(getContext()));
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
}
| 1,256 | 29.658537 | 104 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/NameAndNumber.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.contacts;
/**
* Name and number tuple.
*
* @author Moxie Marlinspike
*
*/
public class NameAndNumber {
public String name;
public String number;
public NameAndNumber(String name, String number) {
this.name = name;
this.number = number;
}
public NameAndNumber() {}
}
| 1,026 | 27.527778 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/RecipientsAdapter.java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thoughtcrime.securesms.contacts;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.recipients.RecipientsFormatter;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.text.Annotation;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
/**
* This adapter is used to filter contacts on both name and number.
*/
public class RecipientsAdapter extends ResourceCursorAdapter {
public static final int CONTACT_ID_INDEX = 1;
public static final int TYPE_INDEX = 2;
public static final int NUMBER_INDEX = 3;
public static final int LABEL_INDEX = 4;
public static final int NAME_INDEX = 5;
private final Context mContext;
private final ContentResolver mContentResolver;
private ContactAccessor mContactAccessor;
public RecipientsAdapter(Context context) {
super(context, R.layout.recipient_filter_item, null);
mContext = context;
mContentResolver = context.getContentResolver();
mContactAccessor = ContactAccessor.getInstance();
}
@Override
public final CharSequence convertToString(Cursor cursor) {
String name = cursor.getString(RecipientsAdapter.NAME_INDEX);
int type = cursor.getInt(RecipientsAdapter.TYPE_INDEX);
String number = cursor.getString(RecipientsAdapter.NUMBER_INDEX).trim();
String label = cursor.getString(RecipientsAdapter.LABEL_INDEX);
CharSequence displayLabel = mContactAccessor.phoneTypeToString(mContext, type, label);
if (number.length() == 0) {
return number;
}
if (name == null) {
name = "";
} else {
// Names with commas are the bane of the recipient editor's existence.
// We've worked around them by using spans, but there are edge cases
// where the spans get deleted. Furthermore, having commas in names
// can be confusing to the user since commas are used as separators
// between recipients. The best solution is to simply remove commas
// from names.
name = name.replace(", ", " ")
.replace(",", " "); // Make sure we leave a space between parts of names.
}
String nameAndNumber = RecipientsFormatter.formatNameAndNumber(name, number);
SpannableString out = new SpannableString(nameAndNumber);
int len = out.length();
if (!TextUtils.isEmpty(name)) {
out.setSpan(new Annotation("name", name), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
out.setSpan(new Annotation("name", number), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
String person_id = cursor.getString(RecipientsAdapter.CONTACT_ID_INDEX);
out.setSpan(new Annotation("person_id", person_id), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(new Annotation("label", displayLabel.toString()), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(new Annotation("number", number), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return out;
}
@Override
public final void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(NAME_INDEX));
TextView label = (TextView) view.findViewById(R.id.label);
int type = cursor.getInt(TYPE_INDEX);
label.setText(mContactAccessor.phoneTypeToString(mContext, type, cursor.getString(LABEL_INDEX)));
TextView number = (TextView) view.findViewById(R.id.number);
number.setText("(" + cursor.getString(NUMBER_INDEX) + ")");
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
return mContactAccessor.getCursorForRecipientFilter( constraint, mContentResolver );
}
/**
* Returns true if all the characters are meaningful as digits
* in a phone number -- letters, digits, and a few punctuation marks.
*/
public static boolean usefulAsDigits(CharSequence cons) {
int len = cons.length();
for (int i = 0; i < len; i++) {
char c = cons.charAt(i);
if ((c >= '0') && (c <= '9')) {
continue;
}
if ((c == ' ') || (c == '-') || (c == '(') || (c == ')') || (c == '.') || (c == '+')
|| (c == '#') || (c == '*')) {
continue;
}
if ((c >= 'A') && (c <= 'Z')) {
continue;
}
if ((c >= 'a') && (c <= 'z')) {
continue;
}
return false;
}
return true;
}
}
| 5,717 | 36.12987 | 105 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/RecipientsEditor.java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thoughtcrime.securesms.contacts;
import android.content.Context;
import android.support.v7.widget.AppCompatMultiAutoCompleteTextView;
import android.telephony.PhoneNumberUtils;
import android.text.Annotation;
import android.text.Editable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MotionEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.MultiAutoCompleteTextView;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.recipients.RecipientsFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* Provide UI for editing the recipients of multi-media messages.
*/
public class RecipientsEditor extends AppCompatMultiAutoCompleteTextView {
private int mLongPressedPosition = -1;
private final RecipientsEditorTokenizer mTokenizer;
private char mLastSeparator = ',';
private Context mContext;
public RecipientsEditor(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mTokenizer = new RecipientsEditorTokenizer(context, this);
setTokenizer(mTokenizer);
// For the focus to move to the message body when soft Next is pressed
setImeOptions(EditorInfo.IME_ACTION_NEXT);
/*
* The point of this TextWatcher is that when the user chooses
* an address completion from the AutoCompleteTextView menu, it
* is marked up with Annotation objects to tie it back to the
* address book entry that it came from. If the user then goes
* back and edits that part of the text, it no longer corresponds
* to that address book entry and needs to have the Annotations
* claiming that it does removed.
*/
addTextChangedListener(new TextWatcher() {
private Annotation[] mAffected;
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
mAffected = ((Spanned) s).getSpans(start, start + count,
Annotation.class);
}
public void onTextChanged(CharSequence s, int start,
int before, int after) {
if (before == 0 && after == 1) { // inserting a character
char c = s.charAt(start);
if (c == ',' || c == ';') {
// Remember the delimiter the user typed to end this recipient. We'll
// need it shortly in terminateToken().
mLastSeparator = c;
}
}
}
public void afterTextChanged(Editable s) {
if (mAffected != null) {
for (Annotation a : mAffected) {
s.removeSpan(a);
}
}
mAffected = null;
}
});
}
@Override
public boolean enoughToFilter() {
if (!super.enoughToFilter()) {
return false;
}
// If the user is in the middle of editing an existing recipient, don't offer the
// auto-complete menu. Without this, when the user selects an auto-complete menu item,
// it will get added to the list of recipients so we end up with the old before-editing
// recipient and the new post-editing recipient. As a precedent, gmail does not show
// the auto-complete menu when editing an existing recipient.
int end = getSelectionEnd();
int len = getText().length();
return end == len;
}
public int getRecipientCount() {
return mTokenizer.getNumbers().size();
}
public List<String> getNumbers() {
return mTokenizer.getNumbers();
}
public Recipients constructContactsFromInput() {
return RecipientFactory.getRecipientsFromString(mContext, mTokenizer.getRawString(), false);
}
private boolean isValidAddress(String number, boolean isMms) {
/*if (isMms) {
return MessageUtils.isValidMmsAddress(number);
} else {*/
// TODO: PhoneNumberUtils.isWellFormedSmsAddress() only check if the number is a valid
// GSM SMS address. If the address contains a dialable char, it considers it a well
// formed SMS addr. CDMA doesn't work that way and has a different parser for SMS
// address (see CdmaSmsAddress.parse(String address)). We should definitely fix this!!!
return PhoneNumberUtils.isWellFormedSmsAddress(number);
}
public boolean hasValidRecipient(boolean isMms) {
for (String number : mTokenizer.getNumbers()) {
if (isValidAddress(number, isMms))
return true;
}
return false;
}
/*public boolean hasInvalidRecipient(boolean isMms) {
for (String number : mTokenizer.getNumbers()) {
if (!isValidAddress(number, isMms)) {
/* TODO if (MmsConfig.getEmailGateway() == null) {
return true;
} else if (!MessageUtils.isAlias(number)) {
return true;
}
}
}
return false;
}*/
public String formatInvalidNumbers(boolean isMms) {
StringBuilder sb = new StringBuilder();
for (String number : mTokenizer.getNumbers()) {
if (!isValidAddress(number, isMms)) {
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(number);
}
}
return sb.toString();
}
/*public boolean containsEmail() {
if (TextUtils.indexOf(getText(), '@') == -1)
return false;
List<String> numbers = mTokenizer.getNumbers();
for (String number : numbers) {
if (Mms.isEmailAddress(number))
return true;
}
return false;
}*/
public static CharSequence contactToToken(Recipient c) {
String name = c.getName();
String number = c.getNumber();
SpannableString s = new SpannableString(RecipientsFormatter.formatNameAndNumber(name, number));
int len = s.length();
if (len == 0) {
return s;
}
s.setSpan(new Annotation("number", c.getNumber()), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return s;
}
public void populate(Recipients list) {
SpannableStringBuilder sb = new SpannableStringBuilder();
for (Recipient c : list.getRecipientsList()) {
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(contactToToken(c));
}
setText(sb);
}
private int pointToPosition(int x, int y) {
x -= getCompoundPaddingLeft();
y -= getExtendedPaddingTop();
x += getScrollX();
y += getScrollY();
Layout layout = getLayout();
if (layout == null) {
return -1;
}
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
return off;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
if (action == MotionEvent.ACTION_DOWN) {
mLongPressedPosition = pointToPosition(x, y);
}
return super.onTouchEvent(ev);
}
private static String getNumberAt(Spanned sp, int start, int end, Context context) {
return getFieldAt("number", sp, start, end, context);
}
private static int getSpanLength(Spanned sp, int start, int end, Context context) {
// TODO: there's a situation where the span can lose its annotations:
// - add an auto-complete contact
// - add another auto-complete contact
// - delete that second contact and keep deleting into the first
// - we lose the annotation and can no longer get the span.
// Need to fix this case because it breaks auto-complete contacts with commas in the name.
Annotation[] a = sp.getSpans(start, end, Annotation.class);
if (a.length > 0) {
return sp.getSpanEnd(a[0]);
}
return 0;
}
private static String getFieldAt(String field, Spanned sp, int start, int end,
Context context) {
Annotation[] a = sp.getSpans(start, end, Annotation.class);
String fieldValue = getAnnotation(a, field);
if (TextUtils.isEmpty(fieldValue)) {
fieldValue = TextUtils.substring(sp, start, end);
}
return fieldValue;
}
private static String getAnnotation(Annotation[] a, String key) {
for (int i = 0; i < a.length; i++) {
if (a[i].getKey().equals(key)) {
return a[i].getValue();
}
}
return "";
}
private class RecipientsEditorTokenizer
implements MultiAutoCompleteTextView.Tokenizer {
private final MultiAutoCompleteTextView mList;
private final Context mContext;
RecipientsEditorTokenizer(Context context, MultiAutoCompleteTextView list) {
mList = list;
mContext = context;
}
/**
* Returns the start of the token that ends at offset
* <code>cursor</code> within <code>text</code>.
* It is a method from the MultiAutoCompleteTextView.Tokenizer interface.
*/
public int findTokenStart(CharSequence text, int cursor) {
int i = cursor;
char c;
while (i > 0 && (c = text.charAt(i - 1)) != ',' && c != ';') {
i--;
}
while (i < cursor && text.charAt(i) == ' ') {
i++;
}
return i;
}
/**
* Returns the end of the token (minus trailing punctuation)
* that begins at offset <code>cursor</code> within <code>text</code>.
* It is a method from the MultiAutoCompleteTextView.Tokenizer interface.
*/
public int findTokenEnd(CharSequence text, int cursor) {
int i = cursor;
int len = text.length();
char c;
while (i < len) {
if ((c = text.charAt(i)) == ',' || c == ';') {
return i;
} else {
i++;
}
}
return len;
}
/**
* Returns <code>text</code>, modified, if necessary, to ensure that
* it ends with a token terminator (for example a space or comma).
* It is a method from the MultiAutoCompleteTextView.Tokenizer interface.
*/
public CharSequence terminateToken(CharSequence text) {
int i = text.length();
while (i > 0 && text.charAt(i - 1) == ' ') {
i--;
}
char c;
if (i > 0 && ((c = text.charAt(i - 1)) == ',' || c == ';')) {
return text;
} else {
// Use the same delimiter the user just typed.
// This lets them have a mixture of commas and semicolons in their list.
String separator = mLastSeparator + " ";
if (text instanceof Spanned) {
SpannableString sp = new SpannableString(text + separator);
TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
Object.class, sp, 0);
return sp;
} else {
return text + separator;
}
}
}
public String getRawString() {
return mList.getText().toString();
}
public List<String> getNumbers() {
Spanned sp = mList.getText();
int len = sp.length();
List<String> list = new ArrayList<String>();
int start = 0;
int i = 0;
while (i < len + 1) {
char c;
if ((i == len) || ((c = sp.charAt(i)) == ',') || (c == ';')) {
if (i > start) {
list.add(getNumberAt(sp, start, i, mContext));
// calculate the recipients total length. This is so if the name contains
// commas or semis, we'll skip over the whole name to the next
// recipient, rather than parsing this single name into multiple
// recipients.
int spanLen = getSpanLength(sp, start, i, mContext);
if (spanLen > i) {
i = spanLen;
}
}
i++;
while ((i < len) && (sp.charAt(i) == ' ')) {
i++;
}
start = i;
} else {
i++;
}
}
return list;
}
}
static class RecipientContextMenuInfo implements ContextMenuInfo {
final Recipient recipient;
RecipientContextMenuInfo(Recipient r) {
recipient = r;
}
}
}
| 14,551 | 33.565321 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/BitmapContactPhoto.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import com.makeramen.roundedimageview.RoundedDrawable;
public class BitmapContactPhoto implements ContactPhoto {
private final Bitmap bitmap;
BitmapContactPhoto(Bitmap bitmap) {
this.bitmap = bitmap;
}
@Override
public Drawable asDrawable(Context context, int color) {
return asDrawable(context, color, false);
}
@Override
public Drawable asDrawable(Context context, int color, boolean inverted) {
return RoundedDrawable.fromBitmap(bitmap)
.setScaleType(ImageView.ScaleType.CENTER_CROP)
.setOval(true);
}
@Override
public Drawable asCallCard(Context context) {
return new BitmapDrawable(context.getResources(), bitmap);
}
}
| 966 | 25.861111 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/ContactColors.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.support.annotation.NonNull;
import org.thoughtcrime.securesms.color.MaterialColor;
import org.thoughtcrime.securesms.color.MaterialColors;
public class ContactColors {
public static final MaterialColor UNKNOWN_COLOR = MaterialColor.GREY;
public static MaterialColor generateFor(@NonNull String name) {
return MaterialColors.CONVERSATION_PALETTE.get(Math.abs(name.hashCode()) % MaterialColors.CONVERSATION_PALETTE.size());
}
}
| 510 | 29.058824 | 123 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/ContactPhoto.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.content.Context;
import android.graphics.drawable.Drawable;
public interface ContactPhoto {
public Drawable asDrawable(Context context, int color);
public Drawable asDrawable(Context context, int color, boolean inverted);
public Drawable asCallCard(Context context);
}
| 347 | 25.769231 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/ContactPhotoFactory.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.bumptech.glide.Glide;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.mms.ContactPhotoUriLoader.ContactPhotoUri;
import java.util.concurrent.ExecutionException;
public class ContactPhotoFactory {
private static final String TAG = ContactPhotoFactory.class.getSimpleName();
public static ContactPhoto getLoadingPhoto() {
return new TransparentContactPhoto();
}
public static ContactPhoto getDefaultContactPhoto(@Nullable String name) {
if (!TextUtils.isEmpty(name)) return new GeneratedContactPhoto(name);
else return new GeneratedContactPhoto("#");
}
public static ContactPhoto getResourceContactPhoto(@DrawableRes int resourceId) {
return new ResourceContactPhoto(resourceId);
}
public static ContactPhoto getDefaultGroupPhoto() {
return new ResourceContactPhoto(R.drawable.ic_group_white_24dp);
}
public static ContactPhoto getContactPhoto(Context context, Uri uri, String name) {
try {
int targetSize = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size);
Bitmap bitmap = Glide.with(context)
.load(new ContactPhotoUri(uri)).asBitmap()
.centerCrop().into(targetSize, targetSize).get();
return new BitmapContactPhoto(bitmap);
} catch (ExecutionException e) {
return getDefaultContactPhoto(name);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
public static ContactPhoto getGroupContactPhoto(@Nullable byte[] avatar) {
if (avatar == null) return getDefaultGroupPhoto();
return new BitmapContactPhoto(BitmapFactory.decodeByteArray(avatar, 0, avatar.length));
}
}
| 2,041 | 33.610169 | 103 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/GeneratedContactPhoto.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.thoughtcrime.securesms.R;
public class GeneratedContactPhoto implements ContactPhoto {
private final String name;
GeneratedContactPhoto(@NonNull String name) {
this.name = name;
}
@Override
public Drawable asDrawable(Context context, int color) {
return asDrawable(context, color, false);
}
@Override
public Drawable asDrawable(Context context, int color, boolean inverted) {
int targetSize = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size);
return TextDrawable.builder()
.beginConfig()
.width(targetSize)
.height(targetSize)
.textColor(inverted ? color : Color.WHITE)
.endConfig()
.buildRound(String.valueOf(name.charAt(0)), inverted ? Color.WHITE : color);
}
@Override
public Drawable asCallCard(Context context) {
return context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
| 1,340 | 29.477273 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/ResourceContactPhoto.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.support.annotation.DrawableRes;
import android.support.v4.graphics.ColorUtils;
import android.widget.ImageView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.makeramen.roundedimageview.RoundedDrawable;
public class ResourceContactPhoto implements ContactPhoto {
private final int resourceId;
ResourceContactPhoto(@DrawableRes int resourceId) {
this.resourceId = resourceId;
}
@Override
public Drawable asDrawable(Context context, int color) {
return asDrawable(context, color, false);
}
@Override
public Drawable asDrawable(Context context, int color, boolean inverted) {
Drawable background = TextDrawable.builder().buildRound(" ", inverted ? Color.WHITE : color);
RoundedDrawable foreground = (RoundedDrawable) RoundedDrawable.fromDrawable(context.getResources().getDrawable(resourceId));
foreground.setScaleType(ImageView.ScaleType.CENTER);
if (inverted) {
foreground.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
return new ExpandingLayerDrawable(new Drawable[] {background, foreground});
}
@Override
public Drawable asCallCard(Context context) {
return context.getResources().getDrawable(resourceId);
}
private static class ExpandingLayerDrawable extends LayerDrawable {
public ExpandingLayerDrawable(Drawable[] layers) {
super(layers);
}
@Override
public int getIntrinsicWidth() {
return -1;
}
@Override
public int getIntrinsicHeight() {
return -1;
}
}
}
| 1,818 | 26.984615 | 128 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/contacts/avatars/TransparentContactPhoto.java | package org.thoughtcrime.securesms.contacts.avatars;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.makeramen.roundedimageview.RoundedDrawable;
import org.thoughtcrime.securesms.R;
public class TransparentContactPhoto implements ContactPhoto {
TransparentContactPhoto() {}
@Override
public Drawable asDrawable(Context context, int color) {
return asDrawable(context, color, false);
}
@Override
public Drawable asDrawable(Context context, int color, boolean inverted) {
return RoundedDrawable.fromDrawable(context.getResources().getDrawable(android.R.color.transparent));
}
@Override
public Drawable asCallCard(Context context) {
return context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
| 786 | 26.137931 | 105 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterCipher.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import org.thoughtcrime.securesms.util.Base64;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.ecc.ECKeyPair;
import org.whispersystems.libaxolotl.ecc.ECPrivateKey;
import org.whispersystems.libaxolotl.ecc.ECPublicKey;
import org.thoughtcrime.securesms.util.Conversions;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* This class is used to asymmetricly encrypt local data. This is used in the case
* where TextSecure receives an SMS, but the user's local encryption passphrase is
* not cached (either because of a timeout, or because it hasn't yet been entered).
*
* In this case, we have access to the public key of a local keypair. We encrypt
* the message with this, and put it into the DB. When the user enters their passphrase,
* we can get access to the private key of the local keypair, decrypt the message, and
* replace it into the DB with symmetric encryption.
*
* The encryption protocol is as follows:
*
* 1) Generate an ephemeral keypair.
* 2) Do ECDH with the public key of the local durable keypair.
* 3) Do KMF with the ECDH result to obtain a master secret.
* 4) Encrypt the message with that master secret.
*
* @author Moxie Marlinspike
*
*/
public class AsymmetricMasterCipher {
private final AsymmetricMasterSecret asymmetricMasterSecret;
public AsymmetricMasterCipher(AsymmetricMasterSecret asymmetricMasterSecret) {
this.asymmetricMasterSecret = asymmetricMasterSecret;
}
public byte[] encryptBytes(byte[] body) {
try {
ECPublicKey theirPublic = asymmetricMasterSecret.getDjbPublicKey();
ECKeyPair ourKeyPair = Curve.generateKeyPair();
byte[] secret = Curve.calculateAgreement(theirPublic, ourKeyPair.getPrivateKey());
MasterCipher masterCipher = getMasterCipherForSecret(secret);
byte[] encryptedBodyBytes = masterCipher.encryptBytes(body);
PublicKey ourPublicKey = new PublicKey(31337, ourKeyPair.getPublicKey());
byte[] publicKeyBytes = ourPublicKey.serialize();
return Util.combine(publicKeyBytes, encryptedBodyBytes);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public byte[] decryptBytes(byte[] combined) throws IOException, InvalidMessageException {
try {
byte[][] parts = Util.split(combined, PublicKey.KEY_SIZE, combined.length - PublicKey.KEY_SIZE);
PublicKey theirPublicKey = new PublicKey(parts[0], 0);
ECPrivateKey ourPrivateKey = asymmetricMasterSecret.getPrivateKey();
byte[] secret = Curve.calculateAgreement(theirPublicKey.getKey(), ourPrivateKey);
MasterCipher masterCipher = getMasterCipherForSecret(secret);
return masterCipher.decryptBytes(parts[1]);
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
}
}
public String decryptBody(String body) throws IOException, InvalidMessageException {
byte[] combined = Base64.decode(body);
return new String(decryptBytes(combined));
}
public String encryptBody(String body) {
return Base64.encodeBytes(encryptBytes(body.getBytes()));
}
private MasterCipher getMasterCipherForSecret(byte[] secretBytes) {
SecretKeySpec cipherKey = deriveCipherKey(secretBytes);
SecretKeySpec macKey = deriveMacKey(secretBytes);
MasterSecret masterSecret = new MasterSecret(cipherKey, macKey);
return new MasterCipher(masterSecret);
}
private SecretKeySpec deriveMacKey(byte[] secretBytes) {
byte[] digestedBytes = getDigestedBytes(secretBytes, 1);
byte[] macKeyBytes = new byte[20];
System.arraycopy(digestedBytes, 0, macKeyBytes, 0, macKeyBytes.length);
return new SecretKeySpec(macKeyBytes, "HmacSHA1");
}
private SecretKeySpec deriveCipherKey(byte[] secretBytes) {
byte[] digestedBytes = getDigestedBytes(secretBytes, 0);
byte[] cipherKeyBytes = new byte[16];
System.arraycopy(digestedBytes, 0, cipherKeyBytes, 0, cipherKeyBytes.length);
return new SecretKeySpec(cipherKeyBytes, "AES");
}
private byte[] getDigestedBytes(byte[] secretBytes, int iteration) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secretBytes, "HmacSHA256"));
return mac.doFinal(Conversions.intToByteArray(iteration));
} catch (NoSuchAlgorithmException | java.security.InvalidKeyException e) {
throw new AssertionError(e);
}
}
}
| 5,534 | 38.820144 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/AsymmetricMasterSecret.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import org.whispersystems.libaxolotl.ecc.ECPrivateKey;
import org.whispersystems.libaxolotl.ecc.ECPublicKey;
/**
* When a user first initializes TextSecure, a few secrets
* are generated. These are:
*
* 1) A 128bit symmetric encryption key.
* 2) A 160bit symmetric MAC key.
* 3) An ECC keypair.
*
* The first two, along with the ECC keypair's private key, are
* then encrypted on disk using PBE.
*
* This class represents the ECC keypair.
*
* @author Moxie Marlinspike
*
*/
public class AsymmetricMasterSecret {
private final ECPublicKey djbPublicKey;
private final ECPrivateKey djbPrivateKey;
public AsymmetricMasterSecret(ECPublicKey djbPublicKey, ECPrivateKey djbPrivateKey)
{
this.djbPublicKey = djbPublicKey;
this.djbPrivateKey = djbPrivateKey;
}
public ECPublicKey getDjbPublicKey() {
return djbPublicKey;
}
public ECPrivateKey getPrivateKey() {
return djbPrivateKey;
}
}
| 1,729 | 26.903226 | 85 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/DecryptingPartInputStream.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.lang.System;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Log;
/**
* Class for streaming an encrypted MMS "part" off the disk.
*
* @author Moxie Marlinspike
*/
public class DecryptingPartInputStream extends FileInputStream {
private static final String TAG = DecryptingPartInputStream.class.getSimpleName();
private static final int IV_LENGTH = 16;
private static final int MAC_LENGTH = 20;
private Cipher cipher;
private Mac mac;
private boolean done;
private long totalDataSize;
private long totalRead;
private byte[] overflowBuffer;
public DecryptingPartInputStream(File file, MasterSecret masterSecret) throws FileNotFoundException {
super(file);
try {
if (file.length() <= IV_LENGTH + MAC_LENGTH)
throw new FileNotFoundException("Part shorter than crypto overhead!");
done = false;
mac = initializeMac(masterSecret.getMacKey());
cipher = initializeCipher(masterSecret.getEncryptionKey());
totalDataSize = file.length() - cipher.getBlockSize() - mac.getMacLength();
totalRead = 0;
} catch (InvalidKeyException ike) {
Log.w(TAG, ike);
throw new FileNotFoundException("Invalid key!");
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
throw new AssertionError(e);
} catch (IOException e) {
Log.w(TAG, e);
throw new FileNotFoundException("IOException while reading IV!");
}
}
@Override
public int read(byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
if (totalRead != totalDataSize)
return readIncremental(buffer, offset, length);
else if (!done)
return readFinal(buffer, offset, length);
else
return -1;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public long skip(long byteCount) throws IOException {
long skipped = 0L;
while (skipped < byteCount) {
byte[] buf = new byte[Math.min(4096, (int)(byteCount-skipped))];
int read = read(buf);
skipped += read;
}
return skipped;
}
private int readFinal(byte[] buffer, int offset, int length) throws IOException {
try {
int flourish = cipher.doFinal(buffer, offset);
//mac.update(buffer, offset, flourish);
byte[] ourMac = mac.doFinal();
byte[] theirMac = new byte[mac.getMacLength()];
readFully(theirMac);
if (!Arrays.equals(ourMac, theirMac))
throw new IOException("MAC doesn't match! Potential tampering?");
done = true;
return flourish;
} catch (IllegalBlockSizeException e) {
Log.w(TAG, e);
throw new IOException("Illegal block size exception!");
} catch (ShortBufferException e) {
Log.w(TAG, e);
throw new IOException("Short buffer exception!");
} catch (BadPaddingException e) {
Log.w(TAG, e);
throw new IOException("Bad padding exception!");
}
}
private int readIncremental(byte[] buffer, int offset, int length) throws IOException {
int readLength = 0;
if (null != overflowBuffer) {
if (overflowBuffer.length > length) {
System.arraycopy(overflowBuffer, 0, buffer, offset, length);
overflowBuffer = Arrays.copyOfRange(overflowBuffer, length, overflowBuffer.length);
return length;
} else if (overflowBuffer.length == length) {
System.arraycopy(overflowBuffer, 0, buffer, offset, length);
overflowBuffer = null;
return length;
} else {
System.arraycopy(overflowBuffer, 0, buffer, offset, overflowBuffer.length);
readLength += overflowBuffer.length;
offset += readLength;
length -= readLength;
overflowBuffer = null;
}
}
if (length + totalRead > totalDataSize)
length = (int)(totalDataSize - totalRead);
byte[] internalBuffer = new byte[length];
int read = super.read(internalBuffer, 0, internalBuffer.length <= cipher.getBlockSize() ? internalBuffer.length : internalBuffer.length - cipher.getBlockSize());
totalRead += read;
try {
mac.update(internalBuffer, 0, read);
int outputLen = cipher.getOutputSize(read);
if (outputLen <= length) {
readLength += cipher.update(internalBuffer, 0, read, buffer, offset);
return readLength;
}
byte[] transientBuffer = new byte[outputLen];
outputLen = cipher.update(internalBuffer, 0, read, transientBuffer, 0);
if (outputLen <= length) {
System.arraycopy(transientBuffer, 0, buffer, offset, outputLen);
readLength += outputLen;
} else {
System.arraycopy(transientBuffer, 0, buffer, offset, length);
overflowBuffer = Arrays.copyOfRange(transientBuffer, length, outputLen);
readLength += length;
}
return readLength;
} catch (ShortBufferException e) {
throw new AssertionError(e);
}
}
private Mac initializeMac(SecretKeySpec key) throws NoSuchAlgorithmException, InvalidKeyException {
Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(key);
return hmac;
}
private Cipher initializeCipher(SecretKeySpec key)
throws InvalidKeyException, InvalidAlgorithmParameterException,
NoSuchAlgorithmException, NoSuchPaddingException, IOException
{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = readIv(cipher.getBlockSize());
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher;
}
private IvParameterSpec readIv(int size) throws IOException {
byte[] iv = new byte[size];
readFully(iv);
mac.update(iv);
return new IvParameterSpec(iv);
}
private void readFully(byte[] buffer) throws IOException {
int offset = 0;
for (;;) {
int read = super.read(buffer, offset, buffer.length-offset);
if (read + offset < buffer.length) offset += read;
else return;
}
}
}
| 7,453 | 31.12931 | 178 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/EncryptingPartOutputStream.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import android.util.Log;
/**
* A class for streaming an encrypted MMS "part" to disk.
*
* @author Moxie Marlinspike
*/
public class EncryptingPartOutputStream extends FileOutputStream {
private Cipher cipher;
private Mac mac;
private boolean closed;
public EncryptingPartOutputStream(File file, MasterSecret masterSecret) throws FileNotFoundException {
super(file);
try {
mac = initializeMac(masterSecret.getMacKey());
cipher = initializeCipher(mac, masterSecret.getEncryptionKey());
closed = false;
} catch (IOException ioe) {
Log.w("EncryptingPartOutputStream", ioe);
throw new FileNotFoundException("Couldn't write IV");
} catch (InvalidKeyException e) {
throw new AssertionError(e);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
} catch (NoSuchPaddingException e) {
throw new AssertionError(e);
}
}
@Override
public void write(byte[] buffer) throws IOException {
this.write(buffer, 0, buffer.length);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
byte[] encryptedBuffer = cipher.update(buffer, offset, length);
if (encryptedBuffer != null) {
mac.update(encryptedBuffer);
super.write(encryptedBuffer, 0, encryptedBuffer.length);
}
}
@Override
public void close() throws IOException {
try {
if (!closed) {
byte[] encryptedRemainder = cipher.doFinal();
mac.update(encryptedRemainder);
byte[] macBytes = mac.doFinal();
super.write(encryptedRemainder, 0, encryptedRemainder.length);
super.write(macBytes, 0, macBytes.length);
closed = true;
}
super.close();
} catch (BadPaddingException bpe) {
throw new AssertionError(bpe);
} catch (IllegalBlockSizeException e) {
throw new AssertionError(e);
}
}
private Mac initializeMac(SecretKeySpec key) throws NoSuchAlgorithmException, InvalidKeyException {
Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(key);
return hmac;
}
private Cipher initializeCipher(Mac mac, SecretKeySpec key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] ivBytes = cipher.getIV();
mac.update(ivBytes);
super.write(ivBytes, 0, ivBytes.length);
return cipher;
}
}
| 3,674 | 28.878049 | 153 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/IdentityKeyParcelable.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.os.Parcel;
import android.os.Parcelable;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.InvalidKeyException;
public class IdentityKeyParcelable implements Parcelable {
public static final Parcelable.Creator<IdentityKeyParcelable> CREATOR = new Parcelable.Creator<IdentityKeyParcelable>() {
public IdentityKeyParcelable createFromParcel(Parcel in) {
try {
return new IdentityKeyParcelable(in);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public IdentityKeyParcelable[] newArray(int size) {
return new IdentityKeyParcelable[size];
}
};
private final IdentityKey identityKey;
public IdentityKeyParcelable(IdentityKey identityKey) {
this.identityKey = identityKey;
}
public IdentityKeyParcelable(Parcel in) throws InvalidKeyException {
int serializedLength = in.readInt();
byte[] serialized = new byte[serializedLength];
in.readByteArray(serialized);
this.identityKey = new IdentityKey(serialized, 0);
}
public IdentityKey get() {
return identityKey;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(identityKey.serialize().length);
dest.writeByteArray(identityKey.serialize());
}
}
| 2,126 | 29.385714 | 123 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/IdentityKeyUtil.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.support.annotation.NonNull;
import org.thoughtcrime.securesms.util.Base64;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.ecc.ECKeyPair;
import org.whispersystems.libaxolotl.ecc.ECPrivateKey;
import java.io.IOException;
/**
* Utility class for working with identity keys.
*
* @author Moxie Marlinspike
*/
public class IdentityKeyUtil {
private static final String TAG = IdentityKeyUtil.class.getSimpleName();
private static final String IDENTITY_PUBLIC_KEY_CIPHERTEXT_LEGACY_PREF = "pref_identity_public_curve25519";
private static final String IDENTITY_PRIVATE_KEY_CIPHERTEXT_LEGACY_PREF = "pref_identity_private_curve25519";
private static final String IDENTITY_PUBLIC_KEY_PREF = "pref_identity_public_v3";
private static final String IDENTITY_PRIVATE_KEY_PREF = "pref_identity_private_v3";
public static boolean hasIdentityKey(Context context) {
SharedPreferences preferences = context.getSharedPreferences(MasterSecretUtil.PREFERENCES_NAME, 0);
return
preferences.contains(IDENTITY_PUBLIC_KEY_PREF) &&
preferences.contains(IDENTITY_PRIVATE_KEY_PREF);
}
public static @NonNull IdentityKey getIdentityKey(@NonNull Context context) {
if (!hasIdentityKey(context)) throw new AssertionError("There isn't one!");
try {
byte[] publicKeyBytes = Base64.decode(retrieve(context, IDENTITY_PUBLIC_KEY_PREF));
return new IdentityKey(publicKeyBytes, 0);
} catch (IOException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
public static @NonNull IdentityKeyPair getIdentityKeyPair(@NonNull Context context) {
if (!hasIdentityKey(context)) throw new AssertionError("There isn't one!");
try {
IdentityKey publicKey = getIdentityKey(context);
ECPrivateKey privateKey = Curve.decodePrivatePoint(Base64.decode(retrieve(context, IDENTITY_PRIVATE_KEY_PREF)));
return new IdentityKeyPair(publicKey, privateKey);
} catch (IOException e) {
throw new AssertionError(e);
}
}
public static void generateIdentityKeys(Context context) {
ECKeyPair djbKeyPair = Curve.generateKeyPair();
IdentityKey djbIdentityKey = new IdentityKey(djbKeyPair.getPublicKey());
ECPrivateKey djbPrivateKey = djbKeyPair.getPrivateKey();
save(context, IDENTITY_PUBLIC_KEY_PREF, Base64.encodeBytes(djbIdentityKey.serialize()));
save(context, IDENTITY_PRIVATE_KEY_PREF, Base64.encodeBytes(djbPrivateKey.serialize()));
}
public static void migrateIdentityKeys(@NonNull Context context,
@NonNull MasterSecret masterSecret)
{
if (!hasIdentityKey(context)) {
if (hasLegacyIdentityKeys(context)) {
IdentityKeyPair legacyPair = getLegacyIdentityKeyPair(context, masterSecret);
save(context, IDENTITY_PUBLIC_KEY_PREF, Base64.encodeBytes(legacyPair.getPublicKey().serialize()));
save(context, IDENTITY_PRIVATE_KEY_PREF, Base64.encodeBytes(legacyPair.getPrivateKey().serialize()));
delete(context, IDENTITY_PUBLIC_KEY_CIPHERTEXT_LEGACY_PREF);
delete(context, IDENTITY_PRIVATE_KEY_CIPHERTEXT_LEGACY_PREF);
} else {
generateIdentityKeys(context);
}
}
}
private static boolean hasLegacyIdentityKeys(Context context) {
return
retrieve(context, IDENTITY_PUBLIC_KEY_CIPHERTEXT_LEGACY_PREF) != null &&
retrieve(context, IDENTITY_PRIVATE_KEY_CIPHERTEXT_LEGACY_PREF) != null;
}
private static IdentityKeyPair getLegacyIdentityKeyPair(@NonNull Context context,
@NonNull MasterSecret masterSecret)
{
try {
MasterCipher masterCipher = new MasterCipher(masterSecret);
byte[] publicKeyBytes = Base64.decode(retrieve(context, IDENTITY_PUBLIC_KEY_CIPHERTEXT_LEGACY_PREF));
IdentityKey identityKey = new IdentityKey(publicKeyBytes, 0);
ECPrivateKey privateKey = masterCipher.decryptKey(Base64.decode(retrieve(context, IDENTITY_PRIVATE_KEY_CIPHERTEXT_LEGACY_PREF)));
return new IdentityKeyPair(identityKey, privateKey);
} catch (IOException | InvalidKeyException e) {
throw new AssertionError(e);
}
}
private static String retrieve(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(MasterSecretUtil.PREFERENCES_NAME, 0);
return preferences.getString(key, null);
}
private static void save(Context context, String key, String value) {
SharedPreferences preferences = context.getSharedPreferences(MasterSecretUtil.PREFERENCES_NAME, 0);
Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(key, value);
if (!preferencesEditor.commit()) throw new AssertionError("failed to save identity key/value to shared preferences");
}
private static void delete(Context context, String key) {
context.getSharedPreferences(MasterSecretUtil.PREFERENCES_NAME, 0).edit().remove(key).commit();
}
}
| 6,147 | 40.261745 | 139 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/InvalidPassphraseException.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
public class InvalidPassphraseException extends Exception {
public InvalidPassphraseException() {
super();
// TODO Auto-generated constructor stub
}
public InvalidPassphraseException(String detailMessage) {
super(detailMessage);
// TODO Auto-generated constructor stub
}
public InvalidPassphraseException(Throwable throwable) {
super(throwable);
// TODO Auto-generated constructor stub
}
public InvalidPassphraseException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
// TODO Auto-generated constructor stub
}
}
| 1,339 | 30.904762 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/MasterCipher.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.support.annotation.NonNull;
import android.util.Log;
import org.thoughtcrime.securesms.util.Base64;
import org.thoughtcrime.securesms.util.Hex;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.ecc.ECPrivateKey;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Class that handles encryption for local storage.
*
* The protocol format is roughly:
*
* 1) 16 byte random IV.
* 2) AES-CBC(plaintext)
* 3) HMAC-SHA1 of 1 and 2
*
* @author Moxie Marlinspike
*/
public class MasterCipher {
private final MasterSecret masterSecret;
private final Cipher encryptingCipher;
private final Cipher decryptingCipher;
private final Mac hmac;
public MasterCipher(MasterSecret masterSecret) {
try {
this.masterSecret = masterSecret;
this.encryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
this.decryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
this.hmac = Mac.getInstance("HmacSHA1");
} catch (NoSuchPaddingException | NoSuchAlgorithmException nspe) {
throw new AssertionError(nspe);
}
}
public byte[] encryptKey(ECPrivateKey privateKey) {
return encryptBytes(privateKey.serialize());
}
public String encryptBody(String body) {
return encryptAndEncodeBytes(body.getBytes());
}
public String decryptBody(String body) throws InvalidMessageException {
return new String(decodeAndDecryptBytes(body));
}
public ECPrivateKey decryptKey(byte[] key)
throws org.whispersystems.libaxolotl.InvalidKeyException
{
try {
return Curve.decodePrivatePoint(decryptBytes(key));
} catch (InvalidMessageException ime) {
throw new org.whispersystems.libaxolotl.InvalidKeyException(ime);
}
}
public byte[] decryptBytes(@NonNull byte[] decodedBody) throws InvalidMessageException {
try {
Mac mac = getMac(masterSecret.getMacKey());
byte[] encryptedBody = verifyMacBody(mac, decodedBody);
Cipher cipher = getDecryptingCipher(masterSecret.getEncryptionKey(), encryptedBody);
byte[] encrypted = getDecryptedBody(cipher, encryptedBody);
return encrypted;
} catch (GeneralSecurityException ge) {
throw new InvalidMessageException(ge);
}
}
public byte[] encryptBytes(byte[] body) {
try {
Cipher cipher = getEncryptingCipher(masterSecret.getEncryptionKey());
Mac mac = getMac(masterSecret.getMacKey());
byte[] encryptedBody = getEncryptedBody(cipher, body);
byte[] encryptedAndMacBody = getMacBody(mac, encryptedBody);
return encryptedAndMacBody;
} catch (GeneralSecurityException ge) {
Log.w("bodycipher", ge);
return null;
}
}
public boolean verifyMacFor(String content, byte[] theirMac) {
byte[] ourMac = getMacFor(content);
Log.w("MasterCipher", "Our Mac: " + Hex.toString(ourMac));
Log.w("MasterCipher", "Thr Mac: " + Hex.toString(theirMac));
return Arrays.equals(ourMac, theirMac);
}
public byte[] getMacFor(String content) {
Log.w("MasterCipher", "Macing: " + content);
try {
Mac mac = getMac(masterSecret.getMacKey());
return mac.doFinal(content.getBytes());
} catch (GeneralSecurityException ike) {
throw new AssertionError(ike);
}
}
private byte[] decodeAndDecryptBytes(String body) throws InvalidMessageException {
try {
byte[] decodedBody = Base64.decode(body);
return decryptBytes(decodedBody);
} catch (IOException e) {
throw new InvalidMessageException("Bad Base64 Encoding...", e);
}
}
private String encryptAndEncodeBytes(byte[] bytes) {
byte[] encryptedAndMacBody = encryptBytes(bytes);
return Base64.encodeBytes(encryptedAndMacBody);
}
private byte[] verifyMacBody(@NonNull Mac hmac, @NonNull byte[] encryptedAndMac) throws InvalidMessageException {
if (encryptedAndMac.length < hmac.getMacLength()) {
throw new InvalidMessageException("length(encrypted body + MAC) < length(MAC)");
}
byte[] encrypted = new byte[encryptedAndMac.length - hmac.getMacLength()];
System.arraycopy(encryptedAndMac, 0, encrypted, 0, encrypted.length);
byte[] remoteMac = new byte[hmac.getMacLength()];
System.arraycopy(encryptedAndMac, encryptedAndMac.length - remoteMac.length, remoteMac, 0, remoteMac.length);
byte[] localMac = hmac.doFinal(encrypted);
if (!Arrays.equals(remoteMac, localMac))
throw new InvalidMessageException("MAC doesen't match.");
return encrypted;
}
private byte[] getDecryptedBody(Cipher cipher, byte[] encryptedBody) throws IllegalBlockSizeException, BadPaddingException {
return cipher.doFinal(encryptedBody, cipher.getBlockSize(), encryptedBody.length - cipher.getBlockSize());
}
private byte[] getEncryptedBody(Cipher cipher, byte[] body) throws IllegalBlockSizeException, BadPaddingException {
byte[] encrypted = cipher.doFinal(body);
byte[] iv = cipher.getIV();
byte[] ivAndBody = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, ivAndBody, 0, iv.length);
System.arraycopy(encrypted, 0, ivAndBody, iv.length, encrypted.length);
return ivAndBody;
}
private Mac getMac(SecretKeySpec key) throws NoSuchAlgorithmException, InvalidKeyException {
// Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(key);
return hmac;
}
private byte[] getMacBody(Mac hmac, byte[] encryptedBody) {
byte[] mac = hmac.doFinal(encryptedBody);
byte[] encryptedAndMac = new byte[encryptedBody.length + mac.length];
System.arraycopy(encryptedBody, 0, encryptedAndMac, 0, encryptedBody.length);
System.arraycopy(mac, 0, encryptedAndMac, encryptedBody.length, mac.length);
return encryptedAndMac;
}
private Cipher getDecryptingCipher(SecretKeySpec key, byte[] encryptedBody) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
// Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(encryptedBody, 0, decryptingCipher.getBlockSize());
decryptingCipher.init(Cipher.DECRYPT_MODE, key, iv);
return decryptingCipher;
}
private Cipher getEncryptingCipher(SecretKeySpec key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
// Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptingCipher.init(Cipher.ENCRYPT_MODE, key);
return encryptingCipher;
}
}
| 7,954 | 34.513393 | 192 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/MasterSecret.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.os.Parcel;
import android.os.Parcelable;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
/**
* When a user first initializes TextSecure, a few secrets
* are generated. These are:
*
* 1) A 128bit symmetric encryption key.
* 2) A 160bit symmetric MAC key.
* 3) An ECC keypair.
*
* The first two, along with the ECC keypair's private key, are
* then encrypted on disk using PBE.
*
* This class represents 1 and 2.
*
* @author Moxie Marlinspike
*/
public class MasterSecret implements Parcelable {
private final SecretKeySpec encryptionKey;
private final SecretKeySpec macKey;
public static final Parcelable.Creator<MasterSecret> CREATOR = new Parcelable.Creator<MasterSecret>() {
@Override
public MasterSecret createFromParcel(Parcel in) {
return new MasterSecret(in);
}
@Override
public MasterSecret[] newArray(int size) {
return new MasterSecret[size];
}
};
public MasterSecret(SecretKeySpec encryptionKey, SecretKeySpec macKey) {
this.encryptionKey = encryptionKey;
this.macKey = macKey;
}
private MasterSecret(Parcel in) {
byte[] encryptionKeyBytes = new byte[in.readInt()];
in.readByteArray(encryptionKeyBytes);
byte[] macKeyBytes = new byte[in.readInt()];
in.readByteArray(macKeyBytes);
this.encryptionKey = new SecretKeySpec(encryptionKeyBytes, "AES");
this.macKey = new SecretKeySpec(macKeyBytes, "HmacSHA1");
// SecretKeySpec does an internal copy in its constructor.
Arrays.fill(encryptionKeyBytes, (byte) 0x00);
Arrays.fill(macKeyBytes, (byte)0x00);
}
public SecretKeySpec getEncryptionKey() {
return this.encryptionKey;
}
public SecretKeySpec getMacKey() {
return this.macKey;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(encryptionKey.getEncoded().length);
out.writeByteArray(encryptionKey.getEncoded());
out.writeInt(macKey.getEncoded().length);
out.writeByteArray(macKey.getEncoded());
}
@Override
public int describeContents() {
return 0;
}
public MasterSecret parcelClone() {
Parcel thisParcel = Parcel.obtain();
Parcel thatParcel = Parcel.obtain();
byte[] bytes = null;
thisParcel.writeValue(this);
bytes = thisParcel.marshall();
thatParcel.unmarshall(bytes, 0, bytes.length);
thatParcel.setDataPosition(0);
MasterSecret that = (MasterSecret)thatParcel.readValue(MasterSecret.class.getClassLoader());
thisParcel.recycle();
thatParcel.recycle();
return that;
}
}
| 3,328 | 26.741667 | 105 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/MasterSecretUnion.java | package org.thoughtcrime.securesms.crypto;
import android.support.annotation.NonNull;
import org.whispersystems.libaxolotl.util.guava.Optional;
public class MasterSecretUnion {
private final Optional<MasterSecret> masterSecret;
private final Optional<AsymmetricMasterSecret> asymmetricMasterSecret;
public MasterSecretUnion(@NonNull MasterSecret masterSecret) {
this.masterSecret = Optional.of(masterSecret);
this.asymmetricMasterSecret = Optional.absent();
}
public MasterSecretUnion(@NonNull AsymmetricMasterSecret asymmetricMasterSecret) {
this.masterSecret = Optional.absent();
this.asymmetricMasterSecret = Optional.of(asymmetricMasterSecret);
}
public Optional<MasterSecret> getMasterSecret() {
return masterSecret;
}
public Optional<AsymmetricMasterSecret> getAsymmetricMasterSecret() {
return asymmetricMasterSecret;
}
}
| 911 | 29.4 | 84 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.util.Base64;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.ecc.ECKeyPair;
import org.whispersystems.libaxolotl.ecc.ECPrivateKey;
import org.whispersystems.libaxolotl.ecc.ECPublicKey;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Helper class for generating and securely storing a MasterSecret.
*
* @author Moxie Marlinspike
*/
public class MasterSecretUtil {
public static final String UNENCRYPTED_PASSPHRASE = "unencrypted";
public static final String PREFERENCES_NAME = "SecureSMS-Preferences";
private static final String ASYMMETRIC_LOCAL_PUBLIC_DJB = "asymmetric_master_secret_curve25519_public";
private static final String ASYMMETRIC_LOCAL_PRIVATE_DJB = "asymmetric_master_secret_curve25519_private";
public static MasterSecret changeMasterSecretPassphrase(Context context,
MasterSecret masterSecret,
String newPassphrase)
{
try {
byte[] combinedSecrets = Util.combine(masterSecret.getEncryptionKey().getEncoded(),
masterSecret.getMacKey().getEncoded());
byte[] encryptionSalt = generateSalt();
int iterations = generateIterationCount(newPassphrase, encryptionSalt);
byte[] encryptedMasterSecret = encryptWithPassphrase(encryptionSalt, iterations, combinedSecrets, newPassphrase);
byte[] macSalt = generateSalt();
byte[] encryptedAndMacdMasterSecret = macWithPassphrase(macSalt, iterations, encryptedMasterSecret, newPassphrase);
save(context, "encryption_salt", encryptionSalt);
save(context, "mac_salt", macSalt);
save(context, "passphrase_iterations", iterations);
save(context, "master_secret", encryptedAndMacdMasterSecret);
save(context, "passphrase_initialized", true);
return masterSecret;
} catch (GeneralSecurityException gse) {
throw new AssertionError(gse);
}
}
public static MasterSecret changeMasterSecretPassphrase(Context context,
String originalPassphrase,
String newPassphrase)
throws InvalidPassphraseException
{
MasterSecret masterSecret = getMasterSecret(context, originalPassphrase);
changeMasterSecretPassphrase(context, masterSecret, newPassphrase);
return masterSecret;
}
public static MasterSecret getMasterSecret(Context context, String passphrase)
throws InvalidPassphraseException
{
try {
byte[] encryptedAndMacdMasterSecret = retrieve(context, "master_secret");
byte[] macSalt = retrieve(context, "mac_salt");
int iterations = retrieve(context, "passphrase_iterations", 100);
byte[] encryptedMasterSecret = verifyMac(macSalt, iterations, encryptedAndMacdMasterSecret, passphrase);
byte[] encryptionSalt = retrieve(context, "encryption_salt");
byte[] combinedSecrets = decryptWithPassphrase(encryptionSalt, iterations, encryptedMasterSecret, passphrase);
byte[] encryptionSecret = Util.split(combinedSecrets, 16, 20)[0];
byte[] macSecret = Util.split(combinedSecrets, 16, 20)[1];
return new MasterSecret(new SecretKeySpec(encryptionSecret, "AES"),
new SecretKeySpec(macSecret, "HmacSHA1"));
} catch (GeneralSecurityException e) {
Log.w("keyutil", e);
return null; //XXX
} catch (IOException e) {
Log.w("keyutil", e);
return null; //XXX
}
}
public static AsymmetricMasterSecret getAsymmetricMasterSecret(@NonNull Context context,
@Nullable MasterSecret masterSecret)
{
try {
byte[] djbPublicBytes = retrieve(context, ASYMMETRIC_LOCAL_PUBLIC_DJB);
byte[] djbPrivateBytes = retrieve(context, ASYMMETRIC_LOCAL_PRIVATE_DJB);
ECPublicKey djbPublicKey = null;
ECPrivateKey djbPrivateKey = null;
if (djbPublicBytes != null) {
djbPublicKey = Curve.decodePoint(djbPublicBytes, 0);
}
if (masterSecret != null) {
MasterCipher masterCipher = new MasterCipher(masterSecret);
if (djbPrivateBytes != null) {
djbPrivateKey = masterCipher.decryptKey(djbPrivateBytes);
}
}
return new AsymmetricMasterSecret(djbPublicKey, djbPrivateKey);
} catch (InvalidKeyException | IOException ike) {
throw new AssertionError(ike);
}
}
public static AsymmetricMasterSecret generateAsymmetricMasterSecret(Context context,
MasterSecret masterSecret)
{
MasterCipher masterCipher = new MasterCipher(masterSecret);
ECKeyPair keyPair = Curve.generateKeyPair();
save(context, ASYMMETRIC_LOCAL_PUBLIC_DJB, keyPair.getPublicKey().serialize());
save(context, ASYMMETRIC_LOCAL_PRIVATE_DJB, masterCipher.encryptKey(keyPair.getPrivateKey()));
return new AsymmetricMasterSecret(keyPair.getPublicKey(), keyPair.getPrivateKey());
}
public static MasterSecret generateMasterSecret(Context context, String passphrase) {
try {
byte[] encryptionSecret = generateEncryptionSecret();
byte[] macSecret = generateMacSecret();
byte[] masterSecret = Util.combine(encryptionSecret, macSecret);
byte[] encryptionSalt = generateSalt();
int iterations = generateIterationCount(passphrase, encryptionSalt);
byte[] encryptedMasterSecret = encryptWithPassphrase(encryptionSalt, iterations, masterSecret, passphrase);
byte[] macSalt = generateSalt();
byte[] encryptedAndMacdMasterSecret = macWithPassphrase(macSalt, iterations, encryptedMasterSecret, passphrase);
save(context, "encryption_salt", encryptionSalt);
save(context, "mac_salt", macSalt);
save(context, "passphrase_iterations", iterations);
save(context, "master_secret", encryptedAndMacdMasterSecret);
save(context, "passphrase_initialized", true);
return new MasterSecret(new SecretKeySpec(encryptionSecret, "AES"),
new SecretKeySpec(macSecret, "HmacSHA1"));
} catch (GeneralSecurityException e) {
Log.w("keyutil", e);
return null;
}
}
public static boolean hasAsymmericMasterSecret(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, 0);
return settings.contains(ASYMMETRIC_LOCAL_PUBLIC_DJB);
}
public static boolean isPassphraseInitialized(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFERENCES_NAME, 0);
return preferences.getBoolean("passphrase_initialized", false);
}
private static void save(Context context, String key, int value) {
if (!context.getSharedPreferences(PREFERENCES_NAME, 0)
.edit()
.putInt(key, value)
.commit())
{
throw new AssertionError("failed to save a shared pref in MasterSecretUtil");
}
}
private static void save(Context context, String key, byte[] value) {
if (!context.getSharedPreferences(PREFERENCES_NAME, 0)
.edit()
.putString(key, Base64.encodeBytes(value))
.commit())
{
throw new AssertionError("failed to save a shared pref in MasterSecretUtil");
}
}
private static void save(Context context, String key, boolean value) {
if (!context.getSharedPreferences(PREFERENCES_NAME, 0)
.edit()
.putBoolean(key, value)
.commit())
{
throw new AssertionError("failed to save a shared pref in MasterSecretUtil");
}
}
private static byte[] retrieve(Context context, String key) throws IOException {
SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, 0);
String encodedValue = settings.getString(key, "");
if (TextUtils.isEmpty(encodedValue)) return null;
else return Base64.decode(encodedValue);
}
private static int retrieve(Context context, String key, int defaultValue) throws IOException {
SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, 0);
return settings.getInt(key, defaultValue);
}
private static byte[] generateEncryptionSecret() {
try {
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
SecretKey key = generator.generateKey();
return key.getEncoded();
} catch (NoSuchAlgorithmException ex) {
Log.w("keyutil", ex);
return null;
}
}
private static byte[] generateMacSecret() {
try {
KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
return generator.generateKey().getEncoded();
} catch (NoSuchAlgorithmException e) {
Log.w("keyutil", e);
return null;
}
}
private static byte[] generateSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
private static int generateIterationCount(String passphrase, byte[] salt) {
int TARGET_ITERATION_TIME = 50; //ms
int MINIMUM_ITERATION_COUNT = 100; //default for low-end devices
int BENCHMARK_ITERATION_COUNT = 10000; //baseline starting iteration count
try {
PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, BENCHMARK_ITERATION_COUNT);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHSHA1AND128BITAES-CBC-BC");
long startTime = System.currentTimeMillis();
skf.generateSecret(keyspec);
long finishTime = System.currentTimeMillis();
int scaledIterationTarget = (int) (((double)BENCHMARK_ITERATION_COUNT / (double)(finishTime - startTime)) * TARGET_ITERATION_TIME);
if (scaledIterationTarget < MINIMUM_ITERATION_COUNT) return MINIMUM_ITERATION_COUNT;
else return scaledIterationTarget;
} catch (NoSuchAlgorithmException e) {
Log.w("MasterSecretUtil", e);
return MINIMUM_ITERATION_COUNT;
} catch (InvalidKeySpecException e) {
Log.w("MasterSecretUtil", e);
return MINIMUM_ITERATION_COUNT;
}
}
private static SecretKey getKeyFromPassphrase(String passphrase, byte[] salt, int iterations)
throws GeneralSecurityException
{
PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, iterations);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHSHA1AND128BITAES-CBC-BC");
return skf.generateSecret(keyspec);
}
private static Cipher getCipherFromPassphrase(String passphrase, byte[] salt, int iterations, int opMode)
throws GeneralSecurityException
{
SecretKey key = getKeyFromPassphrase(passphrase, salt, iterations);
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(opMode, key, new PBEParameterSpec(salt, iterations));
return cipher;
}
private static byte[] encryptWithPassphrase(byte[] encryptionSalt, int iterations, byte[] data, String passphrase)
throws GeneralSecurityException
{
Cipher cipher = getCipherFromPassphrase(passphrase, encryptionSalt, iterations, Cipher.ENCRYPT_MODE);
return cipher.doFinal(data);
}
private static byte[] decryptWithPassphrase(byte[] encryptionSalt, int iterations, byte[] data, String passphrase)
throws GeneralSecurityException, IOException
{
Cipher cipher = getCipherFromPassphrase(passphrase, encryptionSalt, iterations, Cipher.DECRYPT_MODE);
return cipher.doFinal(data);
}
private static Mac getMacForPassphrase(String passphrase, byte[] salt, int iterations)
throws GeneralSecurityException
{
SecretKey key = getKeyFromPassphrase(passphrase, salt, iterations);
byte[] pbkdf2 = key.getEncoded();
SecretKeySpec hmacKey = new SecretKeySpec(pbkdf2, "HmacSHA1");
Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(hmacKey);
return hmac;
}
private static byte[] verifyMac(byte[] macSalt, int iterations, byte[] encryptedAndMacdData, String passphrase) throws InvalidPassphraseException, GeneralSecurityException, IOException {
Mac hmac = getMacForPassphrase(passphrase, macSalt, iterations);
byte[] encryptedData = new byte[encryptedAndMacdData.length - hmac.getMacLength()];
System.arraycopy(encryptedAndMacdData, 0, encryptedData, 0, encryptedData.length);
byte[] givenMac = new byte[hmac.getMacLength()];
System.arraycopy(encryptedAndMacdData, encryptedAndMacdData.length-hmac.getMacLength(), givenMac, 0, givenMac.length);
byte[] localMac = hmac.doFinal(encryptedData);
if (Arrays.equals(givenMac, localMac)) return encryptedData;
else throw new InvalidPassphraseException("MAC Error");
}
private static byte[] macWithPassphrase(byte[] macSalt, int iterations, byte[] data, String passphrase) throws GeneralSecurityException {
Mac hmac = getMacForPassphrase(passphrase, macSalt, iterations);
byte[] mac = hmac.doFinal(data);
byte[] result = new byte[data.length + mac.length];
System.arraycopy(data, 0, result, 0, data.length);
System.arraycopy(mac, 0, result, data.length, mac.length);
return result;
}
}
| 15,368 | 40.425876 | 188 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/MediaKey.java | package org.thoughtcrime.securesms.crypto;
import android.support.annotation.NonNull;
import org.thoughtcrime.securesms.util.Base64;
import org.whispersystems.libaxolotl.InvalidMessageException;
import java.io.IOException;
public class MediaKey {
public static String getEncrypted(@NonNull MasterSecretUnion masterSecret, @NonNull byte[] key) {
if (masterSecret.getMasterSecret().isPresent()) {
return Base64.encodeBytes(new MasterCipher(masterSecret.getMasterSecret().get()).encryptBytes(key));
} else {
return "?ASYNC-" + Base64.encodeBytes(new AsymmetricMasterCipher(masterSecret.getAsymmetricMasterSecret().get()).encryptBytes(key));
}
}
public static byte[] getDecrypted(@NonNull MasterSecret masterSecret,
@NonNull AsymmetricMasterSecret asymmetricMasterSecret,
@NonNull String encodedKey)
throws IOException, InvalidMessageException
{
if (encodedKey.startsWith("?ASYNC-")) {
return new AsymmetricMasterCipher(asymmetricMasterSecret).decryptBytes(Base64.decode(encodedKey.substring("?ASYNC-".length())));
} else {
return new MasterCipher(masterSecret).decryptBytes(Base64.decode(encodedKey));
}
}
}
| 1,247 | 38 | 138 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/PRNGFixes.java | /*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will Google be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, as long as the origin is not misrepresented.
*/
package org.thoughtcrime.securesms.crypto;
import android.os.Build;
import android.os.Process;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.SecureRandomSpi;
import java.security.Security;
/**
* This class is taken directly from the Android blog post announcing this bug:
* http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html
*
* Since I still don't know exactly what the source of this bug was, I'm using
* this class verbatim under the assumption that the Android team knows what
* they're doing. Although, at this point, that is perhaps a foolish assumption.
*/
/**
* Fixes for the output of the default PRNG having low entropy.
*
* The fixes need to be applied via {@link #apply()} before any use of Java
* Cryptography Architecture primitives. A good place to invoke them is in the
* application's {@code onCreate}.
*/
public final class PRNGFixes {
private static final int VERSION_CODE_JELLY_BEAN = 16;
private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18;
private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL =
getBuildFingerprintAndDeviceSerial();
/** Hidden constructor to prevent instantiation. */
private PRNGFixes() {}
/**
* Applies all fixes.
*
* @throws SecurityException if a fix is needed but could not be applied.
*/
public static void apply() {
applyOpenSSLFix();
installLinuxPRNGSecureRandom();
}
/**
* Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the
* fix is not needed.
*
* @throws SecurityException if the fix is needed but could not be applied.
*/
private static void applyOpenSSLFix() throws SecurityException {
if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN)
|| (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) {
// No need to apply the fix
return;
}
try {
// Mix in the device- and invocation-specific seed.
Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
.getMethod("RAND_seed", byte[].class)
.invoke(null, generateSeed());
// Mix output of Linux PRNG into OpenSSL's PRNG
int bytesRead = (Integer) Class.forName(
"org.apache.harmony.xnet.provider.jsse.NativeCrypto")
.getMethod("RAND_load_file", String.class, long.class)
.invoke(null, "/dev/urandom", 1024);
if (bytesRead != 1024) {
throw new IOException(
"Unexpected number of bytes read from Linux PRNG: "
+ bytesRead);
}
} catch (Exception e) {
throw new SecurityException("Failed to seed OpenSSL PRNG", e);
}
}
/**
* Installs a Linux PRNG-backed {@code SecureRandom} implementation as the
* default. Does nothing if the implementation is already the default or if
* there is not need to install the implementation.
*
* @throws SecurityException if the fix is needed but could not be applied.
*/
private static void installLinuxPRNGSecureRandom()
throws SecurityException {
if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) {
// No need to apply the fix
return;
}
// Install a Linux PRNG-based SecureRandom implementation as the
// default, if not yet installed.
Provider[] secureRandomProviders =
Security.getProviders("SecureRandom.SHA1PRNG");
if ((secureRandomProviders == null)
|| (secureRandomProviders.length < 1)
|| (!LinuxPRNGSecureRandomProvider.class.equals(
secureRandomProviders[0].getClass()))) {
Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
}
// Assert that new SecureRandom() and
// SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
// by the Linux PRNG-based SecureRandom implementation.
SecureRandom rng1 = new SecureRandom();
if (!LinuxPRNGSecureRandomProvider.class.equals(
rng1.getProvider().getClass())) {
throw new SecurityException(
"new SecureRandom() backed by wrong Provider: "
+ rng1.getProvider().getClass());
}
SecureRandom rng2;
try {
rng2 = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
throw new SecurityException("SHA1PRNG not available", e);
}
if (!LinuxPRNGSecureRandomProvider.class.equals(
rng2.getProvider().getClass())) {
throw new SecurityException(
"SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
+ " Provider: " + rng2.getProvider().getClass());
}
}
/**
* {@code Provider} of {@code SecureRandom} engines which pass through
* all requests to the Linux PRNG.
*/
private static class LinuxPRNGSecureRandomProvider extends Provider {
public LinuxPRNGSecureRandomProvider() {
super("LinuxPRNG",
1.0,
"A Linux-specific random number provider that uses"
+ " /dev/urandom");
// Although /dev/urandom is not a SHA-1 PRNG, some apps
// explicitly request a SHA1PRNG SecureRandom and we thus need to
// prevent them from getting the default implementation whose output
// may have low entropy.
put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName());
put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
}
}
/**
* {@link SecureRandomSpi} which passes all requests to the Linux PRNG
* ({@code /dev/urandom}).
*/
public static class LinuxPRNGSecureRandom extends SecureRandomSpi {
/*
* IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed
* are passed through to the Linux PRNG (/dev/urandom). Instances of
* this class seed themselves by mixing in the current time, PID, UID,
* build fingerprint, and hardware serial number (where available) into
* Linux PRNG.
*
* Concurrency: Read requests to the underlying Linux PRNG are
* serialized (on sLock) to ensure that multiple threads do not get
* duplicated PRNG output.
*/
private static final File URANDOM_FILE = new File("/dev/urandom");
private static final Object sLock = new Object();
/**
* Input stream for reading from Linux PRNG or {@code null} if not yet
* opened.
*
* @GuardedBy("sLock")
*/
private static DataInputStream sUrandomIn;
/**
* Output stream for writing to Linux PRNG or {@code null} if not yet
* opened.
*
* @GuardedBy("sLock")
*/
private static OutputStream sUrandomOut;
/**
* Whether this engine instance has been seeded. This is needed because
* each instance needs to seed itself if the client does not explicitly
* seed it.
*/
private boolean mSeeded;
@Override
protected void engineSetSeed(byte[] bytes) {
try {
OutputStream out;
synchronized (sLock) {
out = getUrandomOutputStream();
}
out.write(bytes);
out.flush();
} catch (IOException e) {
// On a small fraction of devices /dev/urandom is not writable.
// Log and ignore.
Log.w(PRNGFixes.class.getSimpleName(),
"Failed to mix seed into " + URANDOM_FILE);
} finally {
mSeeded = true;
}
}
@Override
protected void engineNextBytes(byte[] bytes) {
if (!mSeeded) {
// Mix in the device- and invocation-specific seed.
engineSetSeed(generateSeed());
}
try {
DataInputStream in;
synchronized (sLock) {
in = getUrandomInputStream();
}
synchronized (in) {
in.readFully(bytes);
}
} catch (IOException e) {
throw new SecurityException(
"Failed to read from " + URANDOM_FILE, e);
}
}
@Override
protected byte[] engineGenerateSeed(int size) {
byte[] seed = new byte[size];
engineNextBytes(seed);
return seed;
}
private DataInputStream getUrandomInputStream() {
synchronized (sLock) {
if (sUrandomIn == null) {
// NOTE: Consider inserting a BufferedInputStream between
// DataInputStream and FileInputStream if you need higher
// PRNG output performance and can live with future PRNG
// output being pulled into this process prematurely.
try {
sUrandomIn = new DataInputStream(
new FileInputStream(URANDOM_FILE));
} catch (IOException e) {
throw new SecurityException("Failed to open "
+ URANDOM_FILE + " for reading", e);
}
}
return sUrandomIn;
}
}
private OutputStream getUrandomOutputStream() throws IOException {
synchronized (sLock) {
if (sUrandomOut == null) {
sUrandomOut = new FileOutputStream(URANDOM_FILE);
}
return sUrandomOut;
}
}
}
/**
* Generates a device- and invocation-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] generateSeed() {
try {
ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
DataOutputStream seedBufferOut =
new DataOutputStream(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
seedBufferOut.close();
return seedBuffer.toByteArray();
} catch (IOException e) {
throw new SecurityException("Failed to generate seed", e);
}
}
/**
* Gets the hardware serial number of this device.
*
* @return serial number or {@code null} if not available.
*/
private static String getDeviceSerialNumber() {
// We're using the Reflection API because Build.SERIAL is only available
// since API Level 9 (Gingerbread, Android 2.3).
try {
return (String) Build.class.getField("SERIAL").get(null);
} catch (Exception ignored) {
return null;
}
}
private static byte[] getBuildFingerprintAndDeviceSerial() {
StringBuilder result = new StringBuilder();
String fingerprint = Build.FINGERPRINT;
if (fingerprint != null) {
result.append(fingerprint);
}
String serial = getDeviceSerialNumber();
if (serial != null) {
result.append(serial);
}
try {
return result.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding not supported");
}
}
} | 11,550 | 32.481159 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/PreKeyUtil.java | /**
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.content.Context;
import android.util.Log;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.thoughtcrime.securesms.crypto.storage.TextSecurePreKeyStore;
import org.thoughtcrime.securesms.util.JsonUtils;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.ecc.ECKeyPair;
import org.whispersystems.libaxolotl.state.PreKeyRecord;
import org.whispersystems.libaxolotl.state.PreKeyStore;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import org.whispersystems.libaxolotl.util.Medium;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
public class PreKeyUtil {
public static final int BATCH_SIZE = 100;
public static List<PreKeyRecord> generatePreKeys(Context context) {
PreKeyStore preKeyStore = new TextSecurePreKeyStore(context);
List<PreKeyRecord> records = new LinkedList<>();
int preKeyIdOffset = getNextPreKeyId(context);
for (int i=0;i<BATCH_SIZE;i++) {
int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
ECKeyPair keyPair = Curve.generateKeyPair();
PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
preKeyStore.storePreKey(preKeyId, record);
records.add(record);
}
setNextPreKeyId(context, (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE);
return records;
}
public static SignedPreKeyRecord generateSignedPreKey(Context context, IdentityKeyPair identityKeyPair)
{
try {
SignedPreKeyStore signedPreKeyStore = new TextSecurePreKeyStore(context);
int signedPreKeyId = getNextSignedPreKeyId(context);
ECKeyPair keyPair = Curve.generateKeyPair();
byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
SignedPreKeyRecord record = new SignedPreKeyRecord(signedPreKeyId, System.currentTimeMillis(), keyPair, signature);
signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
setNextSignedPreKeyId(context, (signedPreKeyId + 1) % Medium.MAX_VALUE);
return record;
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public static PreKeyRecord generateLastResortKey(Context context) {
PreKeyStore preKeyStore = new TextSecurePreKeyStore(context);
if (preKeyStore.containsPreKey(Medium.MAX_VALUE)) {
try {
return preKeyStore.loadPreKey(Medium.MAX_VALUE);
} catch (InvalidKeyIdException e) {
Log.w("PreKeyUtil", e);
preKeyStore.removePreKey(Medium.MAX_VALUE);
}
}
ECKeyPair keyPair = Curve.generateKeyPair();
PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
preKeyStore.storePreKey(Medium.MAX_VALUE, record);
return record;
}
private static void setNextPreKeyId(Context context, int id) {
try {
File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME);
FileOutputStream fout = new FileOutputStream(nextFile);
fout.write(JsonUtils.toJson(new PreKeyIndex(id)).getBytes());
fout.close();
} catch (IOException e) {
Log.w("PreKeyUtil", e);
}
}
private static void setNextSignedPreKeyId(Context context, int id) {
try {
File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME);
FileOutputStream fout = new FileOutputStream(nextFile);
fout.write(JsonUtils.toJson(new SignedPreKeyIndex(id)).getBytes());
fout.close();
} catch (IOException e) {
Log.w("PreKeyUtil", e);
}
}
private static int getNextPreKeyId(Context context) {
try {
File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME);
if (!nextFile.exists()) {
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
} else {
InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
PreKeyIndex index = JsonUtils.fromJson(reader, PreKeyIndex.class);
reader.close();
return index.nextPreKeyId;
}
} catch (IOException e) {
Log.w("PreKeyUtil", e);
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
}
}
private static int getNextSignedPreKeyId(Context context) {
try {
File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME);
if (!nextFile.exists()) {
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
} else {
InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
SignedPreKeyIndex index = JsonUtils.fromJson(reader, SignedPreKeyIndex.class);
reader.close();
return index.nextSignedPreKeyId;
}
} catch (IOException e) {
Log.w("PreKeyUtil", e);
return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
}
}
private static File getPreKeysDirectory(Context context) {
return getKeysDirectory(context, TextSecurePreKeyStore.PREKEY_DIRECTORY);
}
private static File getSignedPreKeysDirectory(Context context) {
return getKeysDirectory(context, TextSecurePreKeyStore.SIGNED_PREKEY_DIRECTORY);
}
private static File getKeysDirectory(Context context, String name) {
File directory = new File(context.getFilesDir(), name);
if (!directory.exists())
directory.mkdirs();
return directory;
}
private static class PreKeyIndex {
public static final String FILE_NAME = "index.dat";
@JsonProperty
private int nextPreKeyId;
public PreKeyIndex() {}
public PreKeyIndex(int nextPreKeyId) {
this.nextPreKeyId = nextPreKeyId;
}
}
private static class SignedPreKeyIndex {
public static final String FILE_NAME = "index.dat";
@JsonProperty
private int nextSignedPreKeyId;
public SignedPreKeyIndex() {}
public SignedPreKeyIndex(int nextSignedPreKeyId) {
this.nextSignedPreKeyId = nextSignedPreKeyId;
}
}
}
| 7,250 | 33.528571 | 139 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/PublicKey.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.crypto;
import android.util.Log;
import org.thoughtcrime.securesms.util.Hex;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.ecc.Curve;
import org.whispersystems.libaxolotl.ecc.ECPublicKey;
import org.thoughtcrime.securesms.util.Conversions;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class PublicKey {
public static final int KEY_SIZE = 3 + ECPublicKey.KEY_SIZE;
private final ECPublicKey publicKey;
private int id;
public PublicKey(PublicKey publicKey) {
this.id = publicKey.id;
// FIXME :: This not strictly an accurate copy constructor.
this.publicKey = publicKey.publicKey;
}
public PublicKey(int id, ECPublicKey publicKey) {
this.publicKey = publicKey;
this.id = id;
}
public PublicKey(byte[] bytes, int offset) throws InvalidKeyException {
Log.w("PublicKey", "PublicKey Length: " + (bytes.length - offset));
if ((bytes.length - offset) < KEY_SIZE)
throw new InvalidKeyException("Provided bytes are too short.");
this.id = Conversions.byteArrayToMedium(bytes, offset);
this.publicKey = Curve.decodePoint(bytes, offset + 3);
}
public PublicKey(byte[] bytes) throws InvalidKeyException {
this(bytes, 0);
}
public int getType() {
return publicKey.getType();
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public ECPublicKey getKey() {
return publicKey;
}
public String getFingerprint() {
return Hex.toString(getFingerprintBytes());
}
public byte[] getFingerprintBytes() {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
return md.digest(serialize());
} catch (NoSuchAlgorithmException nsae) {
Log.w("LocalKeyPair", nsae);
throw new IllegalArgumentException("SHA-1 isn't supported!");
}
}
public byte[] serialize() {
byte[] keyIdBytes = Conversions.mediumToByteArray(id);
byte[] serializedPoint = publicKey.serialize();
Log.w("PublicKey", "Serializing public key point: " + Hex.toString(serializedPoint));
return Util.combine(keyIdBytes, serializedPoint);
}
}
| 3,048 | 28.317308 | 89 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/SecurityEvent.java | package org.thoughtcrime.securesms.crypto;
import android.content.Context;
import android.content.Intent;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.service.KeyCachingService;
/**
* This class processes key exchange interactions.
*
* @author Moxie Marlinspike
*/
public class SecurityEvent {
public static final String SECURITY_UPDATE_EVENT = "org.thoughtcrime.securesms.KEY_EXCHANGE_UPDATE";
public static void broadcastSecurityUpdateEvent(Context context) {
Intent intent = new Intent(SECURITY_UPDATE_EVENT);
intent.setPackage(context.getPackageName());
context.sendBroadcast(intent, KeyCachingService.KEY_PERMISSION);
}
}
| 701 | 26 | 102 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/SessionUtil.java | package org.thoughtcrime.securesms.crypto;
import android.content.Context;
import android.support.annotation.NonNull;
import org.thoughtcrime.securesms.crypto.storage.TextSecureSessionStore;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.whispersystems.libaxolotl.AxolotlAddress;
import org.whispersystems.libaxolotl.state.SessionStore;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
public class SessionUtil {
public static boolean hasSession(Context context, MasterSecret masterSecret, Recipient recipient) {
return hasSession(context, masterSecret, recipient.getNumber());
}
public static boolean hasSession(Context context, MasterSecret masterSecret, @NonNull String number) {
SessionStore sessionStore = new TextSecureSessionStore(context, masterSecret);
AxolotlAddress axolotlAddress = new AxolotlAddress(number, TextSecureAddress.DEFAULT_DEVICE_ID);
return sessionStore.containsSession(axolotlAddress);
}
}
| 986 | 38.48 | 104 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/storage/TextSecureAxolotlStore.java | package org.thoughtcrime.securesms.crypto.storage;
import android.content.Context;
import org.whispersystems.libaxolotl.AxolotlAddress;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.state.AxolotlStore;
import org.whispersystems.libaxolotl.state.IdentityKeyStore;
import org.whispersystems.libaxolotl.state.PreKeyRecord;
import org.whispersystems.libaxolotl.state.PreKeyStore;
import org.whispersystems.libaxolotl.state.SessionRecord;
import org.whispersystems.libaxolotl.state.SessionStore;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import java.util.List;
public class TextSecureAxolotlStore implements AxolotlStore {
private final PreKeyStore preKeyStore;
private final SignedPreKeyStore signedPreKeyStore;
private final IdentityKeyStore identityKeyStore;
private final SessionStore sessionStore;
public TextSecureAxolotlStore(Context context) {
this.preKeyStore = new TextSecurePreKeyStore(context);
this.signedPreKeyStore = new TextSecurePreKeyStore(context);
this.identityKeyStore = new TextSecureIdentityKeyStore(context);
this.sessionStore = new TextSecureSessionStore(context);
}
@Override
public IdentityKeyPair getIdentityKeyPair() {
return identityKeyStore.getIdentityKeyPair();
}
@Override
public int getLocalRegistrationId() {
return identityKeyStore.getLocalRegistrationId();
}
@Override
public void saveIdentity(String number, IdentityKey identityKey) {
identityKeyStore.saveIdentity(number, identityKey);
}
@Override
public boolean isTrustedIdentity(String number, IdentityKey identityKey) {
return identityKeyStore.isTrustedIdentity(number, identityKey);
}
@Override
public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
return preKeyStore.loadPreKey(preKeyId);
}
@Override
public void storePreKey(int preKeyId, PreKeyRecord record) {
preKeyStore.storePreKey(preKeyId, record);
}
@Override
public boolean containsPreKey(int preKeyId) {
return preKeyStore.containsPreKey(preKeyId);
}
@Override
public void removePreKey(int preKeyId) {
preKeyStore.removePreKey(preKeyId);
}
@Override
public SessionRecord loadSession(AxolotlAddress axolotlAddress) {
return sessionStore.loadSession(axolotlAddress);
}
@Override
public List<Integer> getSubDeviceSessions(String number) {
return sessionStore.getSubDeviceSessions(number);
}
@Override
public void storeSession(AxolotlAddress axolotlAddress, SessionRecord record) {
sessionStore.storeSession(axolotlAddress, record);
}
@Override
public boolean containsSession(AxolotlAddress axolotlAddress) {
return sessionStore.containsSession(axolotlAddress);
}
@Override
public void deleteSession(AxolotlAddress axolotlAddress) {
sessionStore.deleteSession(axolotlAddress);
}
@Override
public void deleteAllSessions(String number) {
sessionStore.deleteAllSessions(number);
}
@Override
public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
return signedPreKeyStore.loadSignedPreKey(signedPreKeyId);
}
@Override
public List<SignedPreKeyRecord> loadSignedPreKeys() {
return signedPreKeyStore.loadSignedPreKeys();
}
@Override
public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
}
@Override
public boolean containsSignedPreKey(int signedPreKeyId) {
return signedPreKeyStore.containsSignedPreKey(signedPreKeyId);
}
@Override
public void removeSignedPreKey(int signedPreKeyId) {
signedPreKeyStore.removeSignedPreKey(signedPreKeyId);
}
}
| 3,932 | 29.488372 | 95 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/storage/TextSecureIdentityKeyStore.java | package org.thoughtcrime.securesms.crypto.storage;
import android.content.Context;
import org.thoughtcrime.securesms.crypto.IdentityKeyUtil;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.state.IdentityKeyStore;
public class TextSecureIdentityKeyStore implements IdentityKeyStore {
private final Context context;
public TextSecureIdentityKeyStore(Context context) {
this.context = context;
}
@Override
public IdentityKeyPair getIdentityKeyPair() {
return IdentityKeyUtil.getIdentityKeyPair(context);
}
@Override
public int getLocalRegistrationId() {
return TextSecurePreferences.getLocalRegistrationId(context);
}
@Override
public void saveIdentity(String name, IdentityKey identityKey) {
long recipientId = RecipientFactory.getRecipientsFromString(context, name, true).getPrimaryRecipient().getRecipientId();
DatabaseFactory.getIdentityDatabase(context).saveIdentity(recipientId, identityKey);
}
@Override
public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
long recipientId = RecipientFactory.getRecipientsFromString(context, name, true).getPrimaryRecipient().getRecipientId();
return DatabaseFactory.getIdentityDatabase(context)
.isValidIdentity(recipientId, identityKey);
}
}
| 1,573 | 34.772727 | 124 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/storage/TextSecurePreKeyStore.java | package org.thoughtcrime.securesms.crypto.storage;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import org.whispersystems.libaxolotl.state.PreKeyRecord;
import org.whispersystems.libaxolotl.state.PreKeyStore;
import org.thoughtcrime.securesms.util.Conversions;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.List;
public class TextSecurePreKeyStore implements PreKeyStore, SignedPreKeyStore {
public static final String PREKEY_DIRECTORY = "prekeys";
public static final String SIGNED_PREKEY_DIRECTORY = "signed_prekeys";
private static final int PLAINTEXT_VERSION = 2;
private static final int CURRENT_VERSION_MARKER = 2;
private static final Object FILE_LOCK = new Object();
private static final String TAG = TextSecurePreKeyStore.class.getSimpleName();
@NonNull private final Context context;
@Nullable private final MasterSecret masterSecret;
public TextSecurePreKeyStore(@NonNull Context context) {
this(context, null);
}
public TextSecurePreKeyStore(@NonNull Context context, @Nullable MasterSecret masterSecret) {
this.context = context;
this.masterSecret = masterSecret;
}
@Override
public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
synchronized (FILE_LOCK) {
try {
return new PreKeyRecord(loadSerializedRecord(getPreKeyFile(preKeyId)));
} catch (IOException | InvalidMessageException e) {
Log.w(TAG, e);
throw new InvalidKeyIdException(e);
}
}
}
@Override
public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
synchronized (FILE_LOCK) {
try {
return new SignedPreKeyRecord(loadSerializedRecord(getSignedPreKeyFile(signedPreKeyId)));
} catch (IOException | InvalidMessageException e) {
Log.w(TAG, e);
throw new InvalidKeyIdException(e);
}
}
}
@Override
public List<SignedPreKeyRecord> loadSignedPreKeys() {
synchronized (FILE_LOCK) {
File directory = getSignedPreKeyDirectory();
List<SignedPreKeyRecord> results = new LinkedList<>();
for (File signedPreKeyFile : directory.listFiles()) {
try {
results.add(new SignedPreKeyRecord(loadSerializedRecord(signedPreKeyFile)));
} catch (IOException | InvalidMessageException e) {
Log.w(TAG, e);
}
}
return results;
}
}
@Override
public void storePreKey(int preKeyId, PreKeyRecord record) {
synchronized (FILE_LOCK) {
try {
storeSerializedRecord(getPreKeyFile(preKeyId), record.serialize());
} catch (IOException e) {
throw new AssertionError(e);
}
}
}
@Override
public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
synchronized (FILE_LOCK) {
try {
storeSerializedRecord(getSignedPreKeyFile(signedPreKeyId), record.serialize());
} catch (IOException e) {
throw new AssertionError(e);
}
}
}
@Override
public boolean containsPreKey(int preKeyId) {
File record = getPreKeyFile(preKeyId);
return record.exists();
}
@Override
public boolean containsSignedPreKey(int signedPreKeyId) {
File record = getSignedPreKeyFile(signedPreKeyId);
return record.exists();
}
@Override
public void removePreKey(int preKeyId) {
File record = getPreKeyFile(preKeyId);
record.delete();
}
@Override
public void removeSignedPreKey(int signedPreKeyId) {
File record = getSignedPreKeyFile(signedPreKeyId);
record.delete();
}
public void migrateRecords() {
synchronized (FILE_LOCK) {
File preKeyRecords = getPreKeyDirectory();
for (File preKeyRecord : preKeyRecords.listFiles()) {
try {
int preKeyId = Integer.parseInt(preKeyRecord.getName());
PreKeyRecord record = loadPreKey(preKeyId);
storePreKey(preKeyId, record);
} catch (InvalidKeyIdException | NumberFormatException e) {
Log.w(TAG, e);
}
}
File signedPreKeyRecords = getSignedPreKeyDirectory();
for (File signedPreKeyRecord : signedPreKeyRecords.listFiles()) {
try {
int signedPreKeyId = Integer.parseInt(signedPreKeyRecord.getName());
SignedPreKeyRecord record = loadSignedPreKey(signedPreKeyId);
storeSignedPreKey(signedPreKeyId, record);
} catch (InvalidKeyIdException | NumberFormatException e) {
Log.w(TAG, e);
}
}
}
}
private byte[] loadSerializedRecord(File recordFile)
throws IOException, InvalidMessageException
{
FileInputStream fin = new FileInputStream(recordFile);
int recordVersion = readInteger(fin);
if (recordVersion > CURRENT_VERSION_MARKER) {
throw new AssertionError("Invalid version: " + recordVersion);
}
byte[] serializedRecord = readBlob(fin);
if (recordVersion < PLAINTEXT_VERSION && masterSecret != null) {
MasterCipher masterCipher = new MasterCipher(masterSecret);
serializedRecord = masterCipher.decryptBytes(serializedRecord);
} else if (recordVersion < PLAINTEXT_VERSION) {
throw new AssertionError("Migration didn't happen!");
}
fin.close();
return serializedRecord;
}
private void storeSerializedRecord(File file, byte[] serialized) throws IOException {
RandomAccessFile recordFile = new RandomAccessFile(file, "rw");
FileChannel out = recordFile.getChannel();
out.position(0);
writeInteger(CURRENT_VERSION_MARKER, out);
writeBlob(serialized, out);
out.truncate(out.position());
recordFile.close();
}
private File getPreKeyFile(int preKeyId) {
return new File(getPreKeyDirectory(), String.valueOf(preKeyId));
}
private File getSignedPreKeyFile(int signedPreKeyId) {
return new File(getSignedPreKeyDirectory(), String.valueOf(signedPreKeyId));
}
private File getPreKeyDirectory() {
return getRecordsDirectory(PREKEY_DIRECTORY);
}
private File getSignedPreKeyDirectory() {
return getRecordsDirectory(SIGNED_PREKEY_DIRECTORY);
}
private File getRecordsDirectory(String directoryName) {
File directory = new File(context.getFilesDir(), directoryName);
if (!directory.exists()) {
if (!directory.mkdirs()) {
Log.w(TAG, "PreKey directory creation failed!");
}
}
return directory;
}
private byte[] readBlob(FileInputStream in) throws IOException {
int length = readInteger(in);
byte[] blobBytes = new byte[length];
in.read(blobBytes, 0, blobBytes.length);
return blobBytes;
}
private void writeBlob(byte[] blobBytes, FileChannel out) throws IOException {
writeInteger(blobBytes.length, out);
out.write(ByteBuffer.wrap(blobBytes));
}
private int readInteger(FileInputStream in) throws IOException {
byte[] integer = new byte[4];
in.read(integer, 0, integer.length);
return Conversions.byteArrayToInt(integer);
}
private void writeInteger(int value, FileChannel out) throws IOException {
byte[] valueBytes = Conversions.intToByteArray(value);
out.write(ByteBuffer.wrap(valueBytes));
}
}
| 7,929 | 29.736434 | 99 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/crypto/storage/TextSecureSessionStore.java | package org.thoughtcrime.securesms.crypto.storage;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.util.Conversions;
import org.whispersystems.libaxolotl.AxolotlAddress;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.state.SessionRecord;
import org.whispersystems.libaxolotl.state.SessionState;
import org.whispersystems.libaxolotl.state.SessionStore;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;
import java.util.List;
import static org.whispersystems.libaxolotl.state.StorageProtos.SessionStructure;
public class TextSecureSessionStore implements SessionStore {
private static final String TAG = TextSecureSessionStore.class.getSimpleName();
private static final String SESSIONS_DIRECTORY_V2 = "sessions-v2";
private static final Object FILE_LOCK = new Object();
private static final int SINGLE_STATE_VERSION = 1;
private static final int ARCHIVE_STATES_VERSION = 2;
private static final int PLAINTEXT_VERSION = 3;
private static final int CURRENT_VERSION = 3;
@NonNull private final Context context;
@Nullable private final MasterSecret masterSecret;
public TextSecureSessionStore(@NonNull Context context) {
this(context, null);
}
public TextSecureSessionStore(@NonNull Context context, @Nullable MasterSecret masterSecret) {
this.context = context.getApplicationContext();
this.masterSecret = masterSecret;
}
@Override
public SessionRecord loadSession(@NonNull AxolotlAddress address) {
synchronized (FILE_LOCK) {
try {
FileInputStream in = new FileInputStream(getSessionFile(address));
int versionMarker = readInteger(in);
if (versionMarker > CURRENT_VERSION) {
throw new AssertionError("Unknown version: " + versionMarker);
}
byte[] serialized = readBlob(in);
in.close();
if (versionMarker < PLAINTEXT_VERSION && masterSecret != null) {
serialized = new MasterCipher(masterSecret).decryptBytes(serialized);
} else if (versionMarker < PLAINTEXT_VERSION) {
throw new AssertionError("Session didn't get migrated: (" + versionMarker + "," + address + ")");
}
if (versionMarker == SINGLE_STATE_VERSION) {
SessionStructure sessionStructure = SessionStructure.parseFrom(serialized);
SessionState sessionState = new SessionState(sessionStructure);
return new SessionRecord(sessionState);
} else if (versionMarker >= ARCHIVE_STATES_VERSION) {
return new SessionRecord(serialized);
} else {
throw new AssertionError("Unknown version: " + versionMarker);
}
} catch (InvalidMessageException | IOException e) {
Log.w(TAG, "No existing session information found.");
return new SessionRecord();
}
}
}
@Override
public void storeSession(@NonNull AxolotlAddress address, @NonNull SessionRecord record) {
synchronized (FILE_LOCK) {
try {
RandomAccessFile sessionFile = new RandomAccessFile(getSessionFile(address), "rw");
FileChannel out = sessionFile.getChannel();
out.position(0);
writeInteger(CURRENT_VERSION, out);
writeBlob(record.serialize(), out);
out.truncate(out.position());
sessionFile.close();
} catch (IOException e) {
throw new AssertionError(e);
}
}
}
@Override
public boolean containsSession(AxolotlAddress address) {
return getSessionFile(address).exists() &&
loadSession(address).getSessionState().hasSenderChain();
}
@Override
public void deleteSession(AxolotlAddress address) {
getSessionFile(address).delete();
}
@Override
public void deleteAllSessions(String name) {
List<Integer> devices = getSubDeviceSessions(name);
deleteSession(new AxolotlAddress(name, TextSecureAddress.DEFAULT_DEVICE_ID));
for (int device : devices) {
deleteSession(new AxolotlAddress(name, device));
}
}
@Override
public List<Integer> getSubDeviceSessions(String name) {
long recipientId = RecipientFactory.getRecipientsFromString(context, name, true).getPrimaryRecipient().getRecipientId();
List<Integer> results = new LinkedList<>();
File parent = getSessionDirectory();
String[] children = parent.list();
if (children == null) return results;
for (String child : children) {
try {
String[] parts = child.split("[.]", 2);
long sessionRecipientId = Long.parseLong(parts[0]);
if (sessionRecipientId == recipientId && parts.length > 1) {
results.add(Integer.parseInt(parts[1]));
}
} catch (NumberFormatException e) {
Log.w(TAG, e);
}
}
return results;
}
public void migrateSessions() {
synchronized (FILE_LOCK) {
File directory = getSessionDirectory();
for (File session : directory.listFiles()) {
if (session.isFile()) {
AxolotlAddress address = getAddressName(session);
if (address != null) {
SessionRecord sessionRecord = loadSession(address);
storeSession(address, sessionRecord);
}
}
}
}
}
private File getSessionFile(AxolotlAddress address) {
return new File(getSessionDirectory(), getSessionName(address));
}
private File getSessionDirectory() {
File directory = new File(context.getFilesDir(), SESSIONS_DIRECTORY_V2);
if (!directory.exists()) {
if (!directory.mkdirs()) {
Log.w(TAG, "Session directory creation failed!");
}
}
return directory;
}
private String getSessionName(AxolotlAddress axolotlAddress) {
Recipient recipient = RecipientFactory.getRecipientsFromString(context, axolotlAddress.getName(), true)
.getPrimaryRecipient();
long recipientId = recipient.getRecipientId();
int deviceId = axolotlAddress.getDeviceId();
return recipientId + (deviceId == TextSecureAddress.DEFAULT_DEVICE_ID ? "" : "." + deviceId);
}
private @Nullable AxolotlAddress getAddressName(File sessionFile) {
try {
String[] parts = sessionFile.getName().split("[.]");
Recipient recipient = RecipientFactory.getRecipientForId(context, Integer.valueOf(parts[0]), true);
int deviceId;
if (parts.length > 1) deviceId = Integer.parseInt(parts[1]);
else deviceId = TextSecureAddress.DEFAULT_DEVICE_ID;
return new AxolotlAddress(recipient.getNumber(), deviceId);
} catch (NumberFormatException e) {
Log.w(TAG, e);
return null;
}
}
private byte[] readBlob(FileInputStream in) throws IOException {
int length = readInteger(in);
byte[] blobBytes = new byte[length];
in.read(blobBytes, 0, blobBytes.length);
return blobBytes;
}
private void writeBlob(byte[] blobBytes, FileChannel out) throws IOException {
writeInteger(blobBytes.length, out);
out.write(ByteBuffer.wrap(blobBytes));
}
private int readInteger(FileInputStream in) throws IOException {
byte[] integer = new byte[4];
in.read(integer, 0, integer.length);
return Conversions.byteArrayToInt(integer);
}
private void writeInteger(int value, FileChannel out) throws IOException {
byte[] valueBytes = Conversions.intToByteArray(value);
out.write(ByteBuffer.wrap(valueBytes));
}
}
| 8,152 | 32.970833 | 133 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/ApnDatabase.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.mms.LegacyMmsConnection.Apn;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Database to query APN and MMSC information
*/
public class ApnDatabase {
private static final String TAG = ApnDatabase.class.getSimpleName();
private final SQLiteDatabase db;
private final Context context;
private static final String DATABASE_NAME = "apns.db";
private static final String ASSET_PATH = "databases" + File.separator + DATABASE_NAME;
private static final String TABLE_NAME = "apns";
private static final String ID_COLUMN = "_id";
private static final String MCC_MNC_COLUMN = "mccmnc";
private static final String MCC_COLUMN = "mcc";
private static final String MNC_COLUMN = "mnc";
private static final String CARRIER_COLUMN = "carrier";
private static final String APN_COLUMN = "apn";
private static final String MMSC_COLUMN = "mmsc";
private static final String PORT_COLUMN = "port";
private static final String TYPE_COLUMN = "type";
private static final String PROTOCOL_COLUMN = "protocol";
private static final String BEARER_COLUMN = "bearer";
private static final String ROAMING_PROTOCOL_COLUMN = "roaming_protocol";
private static final String CARRIER_ENABLED_COLUMN = "carrier_enabled";
private static final String MMS_PROXY_COLUMN = "mmsproxy";
private static final String MMS_PORT_COLUMN = "mmsport";
private static final String PROXY_COLUMN = "proxy";
private static final String MVNO_MATCH_DATA_COLUMN = "mvno_match_data";
private static final String MVNO_TYPE_COLUMN = "mvno";
private static final String AUTH_TYPE_COLUMN = "authtype";
private static final String USER_COLUMN = "user";
private static final String PASSWORD_COLUMN = "password";
private static final String SERVER_COLUMN = "server";
private static final String BASE_SELECTION = MCC_MNC_COLUMN + " = ?";
private static ApnDatabase instance = null;
public synchronized static ApnDatabase getInstance(Context context) throws IOException {
if (instance == null) instance = new ApnDatabase(context.getApplicationContext());
return instance;
}
private ApnDatabase(final Context context) throws IOException {
this.context = context;
File dbFile = context.getDatabasePath(DATABASE_NAME);
if (!dbFile.getParentFile().exists() && !dbFile.getParentFile().mkdir()) {
throw new IOException("couldn't make databases directory");
}
Util.copy(context.getAssets().open(ASSET_PATH, AssetManager.ACCESS_STREAMING),
new FileOutputStream(dbFile));
try {
this.db = SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).getPath(),
null,
SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (SQLiteException e) {
throw new IOException(e);
}
}
private Apn getCustomApnParameters() {
String mmsc = TextSecurePreferences.getMmscUrl(context).trim();
if (!TextUtils.isEmpty(mmsc) && !mmsc.startsWith("http"))
mmsc = "http://" + mmsc;
String proxy = TextSecurePreferences.getMmscProxy(context);
String port = TextSecurePreferences.getMmscProxyPort(context);
String user = TextSecurePreferences.getMmscUsername(context);
String pass = TextSecurePreferences.getMmscPassword(context);
return new Apn(mmsc, proxy, port, user, pass);
}
public Apn getDefaultApnParameters(String mccmnc, String apn) {
if (mccmnc == null) {
Log.w(TAG, "mccmnc was null, returning null");
return Apn.EMPTY;
}
Cursor cursor = null;
try {
if (apn != null) {
Log.w(TAG, "Querying table for MCC+MNC " + mccmnc + " and APN name " + apn);
cursor = db.query(TABLE_NAME, null,
BASE_SELECTION + " AND " + APN_COLUMN + " = ?",
new String[] {mccmnc, apn},
null, null, null);
}
if (cursor == null || !cursor.moveToFirst()) {
if (cursor != null) cursor.close();
Log.w(TAG, "Querying table for MCC+MNC " + mccmnc + " without APN name");
cursor = db.query(TABLE_NAME, null,
BASE_SELECTION,
new String[] {mccmnc},
null, null, null);
}
if (cursor != null && cursor.moveToFirst()) {
Apn params = new Apn(cursor.getString(cursor.getColumnIndexOrThrow(MMSC_COLUMN)),
cursor.getString(cursor.getColumnIndexOrThrow(MMS_PROXY_COLUMN)),
cursor.getString(cursor.getColumnIndexOrThrow(MMS_PORT_COLUMN)),
cursor.getString(cursor.getColumnIndexOrThrow(USER_COLUMN)),
cursor.getString(cursor.getColumnIndexOrThrow(PASSWORD_COLUMN)));
Log.w(TAG, "Returning preferred APN " + params);
return params;
}
Log.w(TAG, "No matching APNs found, returning null");
return Apn.EMPTY;
} finally {
if (cursor != null) cursor.close();
}
}
public Optional<Apn> getMmsConnectionParameters(String mccmnc, String apn) {
Apn customApn = getCustomApnParameters();
Apn defaultApn = getDefaultApnParameters(mccmnc, apn);
Apn result = new Apn(customApn, defaultApn,
TextSecurePreferences.getUseCustomMmsc(context),
TextSecurePreferences.getUseCustomMmscProxy(context),
TextSecurePreferences.getUseCustomMmscProxyPort(context),
TextSecurePreferences.getUseCustomMmscUsername(context),
TextSecurePreferences.getUseCustomMmscPassword(context));
if (TextUtils.isEmpty(result.getMmsc())) return Optional.absent();
else return Optional.of(result);
}
}
| 7,360 | 41.062857 | 114 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/AttachmentDatabase.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.AttachmentId;
import org.thoughtcrime.securesms.attachments.DatabaseAttachment;
import org.thoughtcrime.securesms.crypto.DecryptingPartInputStream;
import org.thoughtcrime.securesms.crypto.EncryptingPartOutputStream;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.mms.PartAuthority;
import org.thoughtcrime.securesms.util.MediaUtil;
import org.thoughtcrime.securesms.util.MediaUtil.ThumbnailData;
import org.thoughtcrime.securesms.util.Util;
import org.thoughtcrime.securesms.util.VisibleForTesting;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import ws.com.google.android.mms.MmsException;
public class AttachmentDatabase extends Database {
private static final String TAG = AttachmentDatabase.class.getSimpleName();
static final String TABLE_NAME = "part";
static final String ROW_ID = "_id";
static final String ATTACHMENT_ID_ALIAS = "attachment_id";
static final String MMS_ID = "mid";
static final String CONTENT_TYPE = "ct";
static final String NAME = "name";
static final String CONTENT_DISPOSITION = "cd";
static final String CONTENT_LOCATION = "cl";
static final String DATA = "_data";
static final String TRANSFER_STATE = "pending_push";
static final String SIZE = "data_size";
private static final String THUMBNAIL = "thumbnail";
static final String THUMBNAIL_ASPECT_RATIO = "aspect_ratio";
static final String UNIQUE_ID = "unique_id";
public static final int TRANSFER_PROGRESS_DONE = 0;
public static final int TRANSFER_PROGRESS_STARTED = 1;
public static final int TRANSFER_PROGRESS_AUTO_PENDING = 2;
public static final int TRANSFER_PROGRESS_FAILED = 3;
private static final String PART_ID_WHERE = ROW_ID + " = ? AND " + UNIQUE_ID + " = ?";
private static final String[] PROJECTION = new String[] {ROW_ID + " AS " + ATTACHMENT_ID_ALIAS,
MMS_ID, CONTENT_TYPE, NAME, CONTENT_DISPOSITION,
CONTENT_LOCATION, DATA, TRANSFER_STATE,
SIZE, THUMBNAIL, THUMBNAIL_ASPECT_RATIO,
UNIQUE_ID};
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ROW_ID + " INTEGER PRIMARY KEY, " +
MMS_ID + " INTEGER, " + "seq" + " INTEGER DEFAULT 0, " +
CONTENT_TYPE + " TEXT, " + NAME + " TEXT, " + "chset" + " INTEGER, " +
CONTENT_DISPOSITION + " TEXT, " + "fn" + " TEXT, " + "cid" + " TEXT, " +
CONTENT_LOCATION + " TEXT, " + "ctt_s" + " INTEGER, " +
"ctt_t" + " TEXT, " + "encrypted" + " INTEGER, " +
TRANSFER_STATE + " INTEGER, "+ DATA + " TEXT, " + SIZE + " INTEGER, " +
THUMBNAIL + " TEXT, " + THUMBNAIL_ASPECT_RATIO + " REAL, " + UNIQUE_ID + " INTEGER NOT NULL);";
public static final String[] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS part_mms_id_index ON " + TABLE_NAME + " (" + MMS_ID + ");",
"CREATE INDEX IF NOT EXISTS pending_push_index ON " + TABLE_NAME + " (" + TRANSFER_STATE + ");",
};
private final ExecutorService thumbnailExecutor = Util.newSingleThreadedLifoExecutor();
public AttachmentDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public @NonNull InputStream getAttachmentStream(MasterSecret masterSecret, AttachmentId attachmentId)
throws IOException
{
InputStream dataStream = getDataStream(masterSecret, attachmentId, DATA);
if (dataStream == null) throw new IOException("No stream for: " + attachmentId);
else return dataStream;
}
public @NonNull InputStream getThumbnailStream(@NonNull MasterSecret masterSecret, @NonNull AttachmentId attachmentId)
throws IOException
{
Log.w(TAG, "getThumbnailStream(" + attachmentId + ")");
InputStream dataStream = getDataStream(masterSecret, attachmentId, THUMBNAIL);
if (dataStream != null) {
return dataStream;
}
try {
InputStream generatedStream = thumbnailExecutor.submit(new ThumbnailFetchCallable(masterSecret, attachmentId)).get();
if (generatedStream == null) throw new IOException("No thumbnail stream available: " + attachmentId);
else return generatedStream;
} catch (InterruptedException ie) {
throw new AssertionError("interrupted");
} catch (ExecutionException ee) {
Log.w(TAG, ee);
throw new IOException(ee);
}
}
public void setTransferProgressFailed(AttachmentId attachmentId, long mmsId)
throws MmsException
{
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRANSFER_STATE, TRANSFER_PROGRESS_FAILED);
database.update(TABLE_NAME, values, PART_ID_WHERE, attachmentId.toStrings());
notifyConversationListeners(DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(mmsId));
}
public @Nullable DatabaseAttachment getAttachment(AttachmentId attachmentId) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, PROJECTION, PART_ID_WHERE, attachmentId.toStrings(), null, null, null);
if (cursor != null && cursor.moveToFirst()) return getAttachment(cursor);
else return null;
} finally {
if (cursor != null)
cursor.close();
}
}
public @NonNull List<DatabaseAttachment> getAttachmentsForMessage(long mmsId) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
List<DatabaseAttachment> results = new LinkedList<>();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, PROJECTION, MMS_ID + " = ?", new String[] {mmsId+""},
null, null, null);
while (cursor != null && cursor.moveToNext()) {
results.add(getAttachment(cursor));
}
return results;
} finally {
if (cursor != null)
cursor.close();
}
}
public @NonNull List<DatabaseAttachment> getPendingAttachments() {
final SQLiteDatabase database = databaseHelper.getReadableDatabase();
final List<DatabaseAttachment> attachments = new LinkedList<>();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, PROJECTION, TRANSFER_STATE + " = ?", new String[] {String.valueOf(TRANSFER_PROGRESS_STARTED)}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
attachments.add(getAttachment(cursor));
}
} finally {
if (cursor != null) cursor.close();
}
return attachments;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void deleteAttachmentsForMessage(long mmsId) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, new String[] {DATA, THUMBNAIL}, MMS_ID + " = ?",
new String[] {mmsId+""}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
String data = cursor.getString(0);
String thumbnail = cursor.getString(1);
if (!TextUtils.isEmpty(data)) {
new File(data).delete();
}
if (!TextUtils.isEmpty(thumbnail)) {
new File(thumbnail).delete();
}
}
} finally {
if (cursor != null)
cursor.close();
}
database.delete(TABLE_NAME, MMS_ID + " = ?", new String[] {mmsId + ""});
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void deleteAllAttachments() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.delete(TABLE_NAME, null, null);
File attachmentsDirectory = context.getDir("parts", Context.MODE_PRIVATE);
File[] attachments = attachmentsDirectory.listFiles();
for (File attachment : attachments) {
attachment.delete();
}
}
public long insertAttachmentsForPlaceholder(@NonNull MasterSecret masterSecret, long mmsId,
@NonNull AttachmentId attachmentId,
@NonNull InputStream inputStream)
throws MmsException
{
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Pair<File, Long> partData = setAttachmentData(masterSecret, inputStream);
ContentValues values = new ContentValues();
values.put(DATA, partData.first.getAbsolutePath());
values.put(SIZE, partData.second);
values.put(TRANSFER_STATE, TRANSFER_PROGRESS_DONE);
values.put(CONTENT_LOCATION, (String)null);
values.put(CONTENT_DISPOSITION, (String)null);
values.put(NAME, (String) null);
if (database.update(TABLE_NAME, values, PART_ID_WHERE, attachmentId.toStrings()) == 0) {
//noinspection ResultOfMethodCallIgnored
partData.first.delete();
} else {
notifyConversationListeners(DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(mmsId));
notifyConversationListListeners();
}
thumbnailExecutor.submit(new ThumbnailFetchCallable(masterSecret, attachmentId));
return partData.second;
}
void insertAttachmentsForMessage(@NonNull MasterSecretUnion masterSecret,
long mmsId,
@NonNull List<Attachment> attachments)
throws MmsException
{
Log.w(TAG, "insertParts(" + attachments.size() + ")");
for (Attachment attachment : attachments) {
AttachmentId attachmentId = insertAttachment(masterSecret, mmsId, attachment);
Log.w(TAG, "Inserted attachment at ID: " + attachmentId);
}
}
public @NonNull Attachment updateAttachmentData(@NonNull MasterSecret masterSecret,
@NonNull Attachment attachment,
@NonNull InputStream inputStream)
throws MmsException
{
SQLiteDatabase database = databaseHelper.getWritableDatabase();
DatabaseAttachment databaseAttachment = (DatabaseAttachment) attachment;
File dataFile = getAttachmentDataFile(databaseAttachment.getAttachmentId(), DATA);
if (dataFile == null) {
throw new MmsException("No attachment data found!");
}
long dataSize = setAttachmentData(masterSecret, dataFile, inputStream);
ContentValues contentValues = new ContentValues();
contentValues.put(SIZE, dataSize);
database.update(TABLE_NAME, contentValues, PART_ID_WHERE, databaseAttachment.getAttachmentId().toStrings());
return new DatabaseAttachment(databaseAttachment.getAttachmentId(),
databaseAttachment.getMmsId(),
databaseAttachment.hasData(),
databaseAttachment.getContentType(),
databaseAttachment.getTransferState(),
dataSize, databaseAttachment.getLocation(),
databaseAttachment.getKey(),
databaseAttachment.getRelay());
}
public void markAttachmentUploaded(long messageId, Attachment attachment) {
ContentValues values = new ContentValues(1);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
values.put(TRANSFER_STATE, TRANSFER_PROGRESS_DONE);
database.update(TABLE_NAME, values, PART_ID_WHERE, ((DatabaseAttachment)attachment).getAttachmentId().toStrings());
notifyConversationListeners(DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(messageId));
}
public void setTransferState(long messageId, @NonNull Attachment attachment, int transferState) {
if (!(attachment instanceof DatabaseAttachment)) {
throw new AssertionError("Attempt to update attachment that doesn't belong to DB!");
}
setTransferState(messageId, ((DatabaseAttachment) attachment).getAttachmentId(), transferState);
}
public void setTransferState(long messageId, @NonNull AttachmentId attachmentId, int transferState) {
final ContentValues values = new ContentValues(1);
final SQLiteDatabase database = databaseHelper.getWritableDatabase();
values.put(TRANSFER_STATE, transferState);
database.update(TABLE_NAME, values, PART_ID_WHERE, attachmentId.toStrings());
notifyConversationListeners(DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(messageId));
ApplicationContext.getInstance(context).notifyMediaControlEvent();
}
@VisibleForTesting
@Nullable InputStream getDataStream(MasterSecret masterSecret, AttachmentId attachmentId, String dataType)
{
File dataFile = getAttachmentDataFile(attachmentId, dataType);
try {
if (dataFile != null) return new DecryptingPartInputStream(dataFile, masterSecret);
else return null;
} catch (FileNotFoundException e) {
Log.w(TAG, e);
return null;
}
}
private @Nullable File getAttachmentDataFile(@NonNull AttachmentId attachmentId,
@NonNull String dataType)
{
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, new String[]{dataType}, PART_ID_WHERE, attachmentId.toStrings(),
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
if (cursor.isNull(0)) {
return null;
}
return new File(cursor.getString(0));
} else {
return null;
}
} finally {
if (cursor != null)
cursor.close();
}
}
private @NonNull Pair<File, Long> setAttachmentData(@NonNull MasterSecret masterSecret,
@NonNull Uri uri)
throws MmsException
{
try {
InputStream inputStream = PartAuthority.getAttachmentStream(context, masterSecret, uri);
return setAttachmentData(masterSecret, inputStream);
} catch (IOException e) {
throw new MmsException(e);
}
}
private @NonNull Pair<File, Long> setAttachmentData(@NonNull MasterSecret masterSecret,
@NonNull InputStream in)
throws MmsException
{
try {
File partsDirectory = context.getDir("parts", Context.MODE_PRIVATE);
File dataFile = File.createTempFile("part", ".mms", partsDirectory);
return new Pair<>(dataFile, setAttachmentData(masterSecret, dataFile, in));
} catch (IOException e) {
throw new MmsException(e);
}
}
private long setAttachmentData(@NonNull MasterSecret masterSecret,
@NonNull File destination,
@NonNull InputStream in)
throws MmsException
{
try {
OutputStream out = new EncryptingPartOutputStream(destination, masterSecret);
return Util.copy(in, out);
} catch (IOException e) {
throw new MmsException(e);
}
}
DatabaseAttachment getAttachment(Cursor cursor) {
return new DatabaseAttachment(new AttachmentId(cursor.getLong(cursor.getColumnIndexOrThrow(ATTACHMENT_ID_ALIAS)),
cursor.getLong(cursor.getColumnIndexOrThrow(UNIQUE_ID))),
cursor.getLong(cursor.getColumnIndexOrThrow(MMS_ID)),
!cursor.isNull(cursor.getColumnIndexOrThrow(DATA)),
cursor.getString(cursor.getColumnIndexOrThrow(CONTENT_TYPE)),
cursor.getInt(cursor.getColumnIndexOrThrow(TRANSFER_STATE)),
cursor.getLong(cursor.getColumnIndexOrThrow(SIZE)),
cursor.getString(cursor.getColumnIndexOrThrow(CONTENT_LOCATION)),
cursor.getString(cursor.getColumnIndexOrThrow(CONTENT_DISPOSITION)),
cursor.getString(cursor.getColumnIndexOrThrow(NAME)));
}
private AttachmentId insertAttachment(MasterSecretUnion masterSecret, long mmsId, Attachment attachment)
throws MmsException
{
Log.w(TAG, "Inserting attachment for mms id: " + mmsId);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Pair<File, Long> partData = null;
long uniqueId = System.currentTimeMillis();
if (masterSecret.getMasterSecret().isPresent() && attachment.getDataUri() != null) {
partData = setAttachmentData(masterSecret.getMasterSecret().get(), attachment.getDataUri());
Log.w(TAG, "Wrote part to file: " + partData.first.getAbsolutePath());
}
ContentValues contentValues = new ContentValues();
contentValues.put(MMS_ID, mmsId);
contentValues.put(CONTENT_TYPE, attachment.getContentType());
contentValues.put(TRANSFER_STATE, attachment.getTransferState());
contentValues.put(UNIQUE_ID, uniqueId);
contentValues.put(CONTENT_LOCATION, attachment.getLocation());
contentValues.put(CONTENT_DISPOSITION, attachment.getKey());
contentValues.put(NAME, attachment.getRelay());
if (partData != null) {
contentValues.put(DATA, partData.first.getAbsolutePath());
contentValues.put(SIZE, partData.second);
}
long rowId = database.insert(TABLE_NAME, null, contentValues);
AttachmentId attachmentId = new AttachmentId(rowId, uniqueId);
if (attachment.getThumbnail() != null && masterSecret.getMasterSecret().isPresent()) {
Log.w(TAG, "inserting pre-generated thumbnail");
ThumbnailData data = new ThumbnailData(attachment.getThumbnail());
updateAttachmentThumbnail(masterSecret.getMasterSecret().get(), attachmentId, data.toDataStream(), data.getAspectRatio());
} else if (!attachment.isInProgress()) {
thumbnailExecutor.submit(new ThumbnailFetchCallable(masterSecret.getMasterSecret().get(), attachmentId));
}
return attachmentId;
}
@VisibleForTesting
void updateAttachmentThumbnail(MasterSecret masterSecret, AttachmentId attachmentId, InputStream in, float aspectRatio)
throws MmsException
{
Log.w(TAG, "updating part thumbnail for #" + attachmentId);
Pair<File, Long> thumbnailFile = setAttachmentData(masterSecret, in);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues(2);
values.put(THUMBNAIL, thumbnailFile.first.getAbsolutePath());
values.put(THUMBNAIL_ASPECT_RATIO, aspectRatio);
database.update(TABLE_NAME, values, PART_ID_WHERE, attachmentId.toStrings());
}
@VisibleForTesting
class ThumbnailFetchCallable implements Callable<InputStream> {
private final MasterSecret masterSecret;
private final AttachmentId attachmentId;
public ThumbnailFetchCallable(MasterSecret masterSecret, AttachmentId attachmentId) {
this.masterSecret = masterSecret;
this.attachmentId = attachmentId;
}
@Override
public @Nullable InputStream call() throws Exception {
final InputStream stream = getDataStream(masterSecret, attachmentId, THUMBNAIL);
if (stream != null) {
return stream;
}
DatabaseAttachment attachment = getAttachment(attachmentId);
if (attachment == null || !attachment.hasData()) {
return null;
}
ThumbnailData data = MediaUtil.generateThumbnail(context, masterSecret, attachment.getContentType(), attachment.getDataUri());
if (data == null) {
return null;
}
updateAttachmentThumbnail(masterSecret, attachmentId, data.toDataStream(), data.getAspectRatio());
return getDataStream(masterSecret, attachmentId, THUMBNAIL);
}
}
}
| 21,914 | 39.658627 | 155 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/CanonicalAddressDatabase.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.ShortNumberInfo;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.ShortCodeUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.VisibleForTesting;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class CanonicalAddressDatabase {
private static final String TAG = CanonicalAddressDatabase.class.getSimpleName();
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "canonical_address.db";
private static final String TABLE = "canonical_addresses";
private static final String ID_COLUMN = "_id";
private static final String ADDRESS_COLUMN = "address";
private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE + " (" + ID_COLUMN + " integer PRIMARY KEY, " + ADDRESS_COLUMN + " TEXT NOT NULL);";
private static final String SELECTION_NUMBER = "PHONE_NUMBERS_EQUAL(" + ADDRESS_COLUMN + ", ?)";
private static final String SELECTION_OTHER = ADDRESS_COLUMN + " = ? COLLATE NOCASE";
private static CanonicalAddressDatabase instance;
private DatabaseHelper databaseHelper;
private final Context context;
private final Map<String, Long> addressCache = new ConcurrentHashMap<>();
private final Map<Long, String> idCache = new ConcurrentHashMap<>();
public synchronized static CanonicalAddressDatabase getInstance(Context context) {
if (instance == null)
instance = new CanonicalAddressDatabase(context.getApplicationContext());
return instance;
}
private CanonicalAddressDatabase(Context context) {
this.context = context;
this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
fillCache();
}
public void reset(Context context) {
DatabaseHelper old = this.databaseHelper;
this.databaseHelper = new DatabaseHelper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);
old.close();
fillCache();
}
private void fillCache() {
Cursor cursor = null;
try {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
cursor = db.query(TABLE, null, null, null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(ID_COLUMN));
String address = cursor.getString(cursor.getColumnIndexOrThrow(ADDRESS_COLUMN));
if (address == null || address.trim().length() == 0)
address = "Anonymous";
idCache.put(id, address);
addressCache.put(address, id);
}
} finally {
if (cursor != null)
cursor.close();
}
}
public @NonNull String getAddressFromId(long id) {
String cachedAddress = idCache.get(id);
if (cachedAddress != null)
return cachedAddress;
Cursor cursor = null;
try {
Log.w(TAG, "Hitting DB on query [ID].");
SQLiteDatabase db = databaseHelper.getReadableDatabase();
cursor = db.query(TABLE, null, ID_COLUMN + " = ?", new String[] {id+""}, null, null, null);
if (!cursor.moveToFirst())
return "Anonymous";
String address = cursor.getString(cursor.getColumnIndexOrThrow(ADDRESS_COLUMN));
if (address == null || address.trim().equals("")) {
return "Anonymous";
} else {
idCache.put(id, address);
return address;
}
} finally {
if (cursor != null)
cursor.close();
}
}
public void close() {
databaseHelper.close();
instance = null;
}
public long getCanonicalAddressId(@NonNull String address) {
try {
long canonicalAddressId;
if (isNumberAddress(address) && TextSecurePreferences.isPushRegistered(context)) {
String localNumber = TextSecurePreferences.getLocalNumber(context);
if (!ShortCodeUtil.isShortCode(localNumber, address)) {
address = PhoneNumberFormatter.formatNumber(address, localNumber);
}
}
if ((canonicalAddressId = getCanonicalAddressFromCache(address)) != -1) {
return canonicalAddressId;
}
canonicalAddressId = getCanonicalAddressIdFromDatabase(address);
idCache.put(canonicalAddressId, address);
addressCache.put(address, canonicalAddressId);
return canonicalAddressId;
} catch (InvalidNumberException e) {
throw new AssertionError(e);
}
}
public @NonNull List<Long> getCanonicalAddressIds(@NonNull List<String> addresses) {
List<Long> addressList = new LinkedList<>();
for (String address : addresses) {
addressList.add(getCanonicalAddressId(address));
}
return addressList;
}
private long getCanonicalAddressFromCache(String address) {
Long cachedAddress = addressCache.get(address);
return cachedAddress == null ? -1L : cachedAddress;
}
private long getCanonicalAddressIdFromDatabase(@NonNull String address) {
Log.w(TAG, "Hitting DB on query [ADDRESS]");
Cursor cursor = null;
try {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String[] selectionArguments = new String[]{address};
boolean isNumber = isNumberAddress(address);
cursor = db.query(TABLE, null, isNumber ? SELECTION_NUMBER : SELECTION_OTHER,
selectionArguments, null, null, null);
if (cursor.getCount() == 0 || !cursor.moveToFirst()) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(ADDRESS_COLUMN, address);
return db.insert(TABLE, ADDRESS_COLUMN, contentValues);
} else {
long canonicalId = cursor.getLong(cursor.getColumnIndexOrThrow(ID_COLUMN));
String oldAddress = cursor.getString(cursor.getColumnIndexOrThrow(ADDRESS_COLUMN));
if (!address.equals(oldAddress)) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(ADDRESS_COLUMN, address);
db.update(TABLE, contentValues, ID_COLUMN + " = ?", new String[]{canonicalId+""});
addressCache.remove(oldAddress);
}
return canonicalId;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@VisibleForTesting
static boolean isNumberAddress(@NonNull String number) {
if (number.contains("@")) return false;
if (GroupUtil.isEncodedGroup(number)) return false;
final String networkNumber = PhoneNumberUtils.extractNetworkPortion(number);
if (TextUtils.isEmpty(networkNumber)) return false;
if (networkNumber.length() < 3) return false;
return PhoneNumberUtils.isWellFormedSmsAddress(number);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
| 8,741 | 32.883721 | 157 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/CanonicalSessionMigrator.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.Context;
import android.util.Log;
import java.io.File;
public class CanonicalSessionMigrator {
private static void migrateSession(File sessionFile, File sessionsDirectory, long canonicalAddress) {
File canonicalSessionFile = new File(sessionsDirectory.getAbsolutePath() + File.separatorChar + canonicalAddress);
sessionFile.renameTo(canonicalSessionFile);
Log.w("CanonicalSessionMigrator", "Moving: " + sessionFile.toString() + " to " + canonicalSessionFile.toString());
File canonicalSessionFileLocal = new File(sessionsDirectory.getAbsolutePath() + File.separatorChar + canonicalAddress + "-local");
File localFile = new File(sessionFile.getAbsolutePath() + "-local");
if (localFile.exists())
localFile.renameTo(canonicalSessionFileLocal);
Log.w("CanonicalSessionMigrator", "Moving " + localFile + " to " + canonicalSessionFileLocal);
File canonicalSessionFileRemote = new File(sessionsDirectory.getAbsolutePath() + File.separatorChar + canonicalAddress + "-remote");
File remoteFile = new File(sessionFile.getAbsolutePath() + "-remote");
if (remoteFile.exists())
remoteFile.renameTo(canonicalSessionFileRemote);
Log.w("CanonicalSessionMigrator", "Moving " + remoteFile + " to " + canonicalSessionFileRemote);
}
public static void migrateSessions(Context context) {
if (context.getSharedPreferences("SecureSMS", Context.MODE_PRIVATE).getBoolean("canonicalized", false))
return;
CanonicalAddressDatabase canonicalDb = CanonicalAddressDatabase.getInstance(context);
File rootDirectory = context.getFilesDir();
File sessionsDirectory = new File(rootDirectory.getAbsolutePath() + File.separatorChar + "sessions");
sessionsDirectory.mkdir();
String[] files = rootDirectory.list();
for (int i=0;i<files.length;i++) {
File item = new File(rootDirectory.getAbsolutePath() + File.separatorChar + files[i]);
if (!item.isDirectory() && files[i].matches("[0-9]+")) {
long canonicalAddress = canonicalDb.getCanonicalAddressId(files[i]);
migrateSession(item, sessionsDirectory, canonicalAddress);
}
}
context.getSharedPreferences("SecureSMS", Context.MODE_PRIVATE).edit().putBoolean("canonicalized", true).apply();
}
}
| 3,090 | 42.535211 | 136 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/ContentValuesBuilder.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.util.Log;
import org.thoughtcrime.securesms.util.Util;
import ws.com.google.android.mms.pdu.CharacterSets;
import ws.com.google.android.mms.pdu.EncodedStringValue;
import java.io.UnsupportedEncodingException;
public class ContentValuesBuilder {
private final ContentValues contentValues;
public ContentValuesBuilder(ContentValues contentValues) {
this.contentValues = contentValues;
}
public void add(String key, String charsetKey, EncodedStringValue value) {
if (value != null) {
contentValues.put(key, Util.toIsoString(value.getTextString()));
contentValues.put(charsetKey, value.getCharacterSet());
}
}
public void add(String contentKey, byte[] value) {
if (value != null) {
contentValues.put(contentKey, Util.toIsoString(value));
}
}
public void add(String contentKey, int b) {
if (b != 0)
contentValues.put(contentKey, b);
}
public void add(String contentKey, long value) {
if (value != -1L)
contentValues.put(contentKey, value);
}
public ContentValues getContentValues() {
return contentValues;
}
}
| 1,898 | 28.671875 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/CursorRecyclerViewAdapter.java | /**
* Copyright (C) 2015 Open Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.Context;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.View;
import android.view.ViewGroup;
import org.thoughtcrime.securesms.util.VisibleForTesting;
/**
* RecyclerView.Adapter that manages a Cursor, comparable to the CursorAdapter usable in ListView/GridView.
*/
public abstract class CursorRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context;
private final DataSetObserver observer = new AdapterDataSetObserver();
@VisibleForTesting final static int HEADER_TYPE = Integer.MIN_VALUE;
@VisibleForTesting final static int FOOTER_TYPE = Integer.MIN_VALUE + 1;
private Cursor cursor;
private boolean valid;
private @Nullable View header;
private @Nullable View footer;
private static class HeaderFooterViewHolder extends RecyclerView.ViewHolder {
public HeaderFooterViewHolder(View itemView) {
super(itemView);
}
}
protected CursorRecyclerViewAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
if (cursor != null) {
valid = true;
cursor.registerDataSetObserver(observer);
}
}
protected @NonNull Context getContext() {
return context;
}
public @Nullable Cursor getCursor() {
return cursor;
}
public void setHeaderView(@Nullable View header) {
this.header = header;
}
public void setFooterView(@Nullable View footer) {
this.footer = footer;
}
public boolean hasHeaderView() {
return header != null;
}
public boolean hasFooterView() {
return footer != null;
}
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close();
}
}
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == cursor) {
return null;
}
final Cursor oldCursor = cursor;
if (oldCursor != null) {
oldCursor.unregisterDataSetObserver(observer);
}
cursor = newCursor;
if (cursor != null) {
cursor.registerDataSetObserver(observer);
}
valid = cursor != null;
notifyDataSetChanged();
return oldCursor;
}
@Override
public int getItemCount() {
if (!isActiveCursor()) return 0;
return cursor.getCount()
+ (hasHeaderView() ? 1 : 0)
+ (hasFooterView() ? 1 : 0);
}
@SuppressWarnings("unchecked")
@Override
public final void onViewRecycled(ViewHolder holder) {
if (!(holder instanceof HeaderFooterViewHolder)) {
onItemViewRecycled((VH)holder);
}
}
public void onItemViewRecycled(VH holder) {}
@Override public final ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case HEADER_TYPE: return new HeaderFooterViewHolder(header);
case FOOTER_TYPE: return new HeaderFooterViewHolder(footer);
default: return onCreateItemViewHolder(parent, viewType);
}
}
public abstract VH onCreateItemViewHolder(ViewGroup parent, int viewType);
@SuppressWarnings("unchecked")
@Override
public final void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if (!isHeaderPosition(position) && !isFooterPosition(position)) {
moveToPositionOrThrow(getCursorPosition(position));
onBindItemViewHolder((VH)viewHolder, cursor);
}
}
public abstract void onBindItemViewHolder(VH viewHolder, @NonNull Cursor cursor);
@Override public int getItemViewType(int position) {
if (isHeaderPosition(position)) return HEADER_TYPE;
if (isFooterPosition(position)) return FOOTER_TYPE;
moveToPositionOrThrow(getCursorPosition(position));
return getItemViewType(cursor);
}
public int getItemViewType(@NonNull Cursor cursor) {
return 0;
}
private void assertActiveCursor() {
if (!isActiveCursor()) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
}
private void moveToPositionOrThrow(final int position) {
assertActiveCursor();
if (!cursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
}
private boolean isActiveCursor() {
return valid && cursor != null;
}
private boolean isFooterPosition(int position) {
return hasFooterView() && position == getItemCount() - 1;
}
private boolean isHeaderPosition(int position) {
return hasHeaderView() && position == 0;
}
private int getCursorPosition(int position) {
return hasHeaderView() ? position - 1 : position;
}
private class AdapterDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
super.onChanged();
valid = true;
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
valid = false;
notifyDataSetChanged();
}
}
}
| 5,928 | 27.504808 | 139 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/Database.java | /**
* Copyright (C) 2011 Whisper Systems
*
* 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 org.thoughtcrime.securesms.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.Set;
public abstract class Database {
protected static final String ID_WHERE = "_id = ?";
private static final String CONVERSATION_URI = "content://textsecure/thread/";
private static final String CONVERSATION_LIST_URI = "content://textsecure/conversation-list";
protected SQLiteOpenHelper databaseHelper;
protected final Context context;
public Database(Context context, SQLiteOpenHelper databaseHelper) {
this.context = context;
this.databaseHelper = databaseHelper;
}
protected void notifyConversationListeners(Set<Long> threadIds) {
for (long threadId : threadIds)
notifyConversationListeners(threadId);
}
protected void notifyConversationListeners(long threadId) {
context.getContentResolver().notifyChange(Uri.parse(CONVERSATION_URI + threadId), null);
}
protected void notifyConversationListListeners() {
context.getContentResolver().notifyChange(Uri.parse(CONVERSATION_LIST_URI), null);
}
protected void setNotifyConverationListeners(Cursor cursor, long threadId) {
cursor.setNotificationUri(context.getContentResolver(), Uri.parse(CONVERSATION_URI + threadId));
}
protected void setNotifyConverationListListeners(Cursor cursor) {
cursor.setNotificationUri(context.getContentResolver(), Uri.parse(CONVERSATION_LIST_URI));
}
public void reset(SQLiteOpenHelper databaseHelper) {
this.databaseHelper = databaseHelper;
}
}
| 2,345 | 34.545455 | 100 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.