Skip to content

Commit

Permalink
Refactoring: Moved saveAs... (with permissions) from BaseActivity to …
Browse files Browse the repository at this point in the history
…EditActivity
  • Loading branch information
k3b committed May 16, 2019
1 parent 24eacee commit 9b871a4
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,12 @@
abstract class CropAreasChooseBaseActivity extends BaseActivity {
private static int lastInstanceNo = 0;
private int instanceNo = 0;
private static final String TAG = "llCrop";
protected static final String TAG = "llCrop";
private static final int REQUEST_GET_PICTURE = 1;
protected static final int REQUEST_GET_PICTURE_PERMISSION = 101;

private static final int REQUEST_SAVE_PICTURE = 2;
private static final int REQUEST_SAVE_PICTURE_PERMISSION = 102;
private static final String CURRENT_CROP_AREA = "CURRENT_CROP_AREA";
private static final String IMAGE_JPEG_MIME = "image/jpeg";
protected static final String IMAGE_JPEG_MIME = "image/jpeg";

private CropImageView uCropView = null;
private ImageProcessor mSpectrum;
Expand Down Expand Up @@ -107,7 +105,7 @@ public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error)
}
}

private Rect getCropRect() {
protected Rect getCropRect() {
if (uCropView == null) {
Log.e(TAG, getInstanceNo() + "ups: no cropView");
return null;
Expand All @@ -116,7 +114,7 @@ private Rect getCropRect() {
return (cropRect != null) ? cropRect : mLastCropRect;
}

private String getInstanceNo() {
protected String getInstanceNo() {
return "#" + instanceNo + ":";
}

Expand Down Expand Up @@ -152,9 +150,7 @@ public boolean onCreateOptionsMenu(final Menu menu) {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
return saveAsPublicCroppedImage();
/*
/*
case R.id.menu_send: {
createSendIntend(true);
Expand Down Expand Up @@ -234,79 +230,7 @@ private void onGetPictureResult(int resultCode, Intent data) {
return;
}

private boolean saveAsPublicCroppedImage() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
getString(R.string.permission_write_storage_rationale),
REQUEST_SAVE_PICTURE_PERMISSION);
} else {
openPublicOutputUriPicker(REQUEST_SAVE_PICTURE);
}
return true;
}

private boolean openPublicOutputUriPicker(int folderpickerCode) {
Uri inUri = getIntent().getData();
String originalFileName = (inUri == null) ? "" : inUri.getLastPathSegment();
String proposedFileName = replaceExtension(originalFileName, "_llcrop.jpg");
// String proposedOutPath = inUri.getP new Uri() replaceExtension(originalFileName, "_llcrop.jpg");


// DocumentsContract#EXTRA_INITIAL_URI
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT)
.setType(IMAGE_JPEG_MIME)
.addCategory(Intent.CATEGORY_OPENABLE)
.putExtra(Intent.EXTRA_TITLE, proposedFileName)
.putExtra(DocumentsContract.EXTRA_PROMPT, getString(R.string.label_save_as))
.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
;

Log.d(TAG, getInstanceNo() + "openPublicOutputUriPicker '" + proposedFileName + "'");

startActivityForResult(intent, folderpickerCode);
return true;
}

private void onOpenPublicOutputUriPickerResult(int resultCode, Uri outUri) {
final Intent intent = getIntent();
final Uri inUri = ((resultCode == RESULT_OK) && (intent != null)) ? intent.getData() : null;

if (inUri != null) {
Rect rect = getCropRect();
InputStream inStream = null;
OutputStream outStream = null;

final String context_message = getInstanceNo() + "Cropping '" + inUri + "'(" + rect + ") => '"
+ outUri + "' ('" + toString(outUri) + "')";
Log.i(TAG, context_message);

try {
inStream = getContentResolver().openInputStream(inUri);
outStream = getContentResolver().openOutputStream(outUri, "w");
this.mSpectrum.crop(inStream, outStream, rect, 0);

String message = getString(R.string.toast_saved_as,
toString(outUri));
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

finish();
return;
} catch (Exception e) {
Log.e(TAG, "Error " + context_message + e.getMessage(), e);
} finally {
close(outStream, outStream);
close(inStream, inStream);
}
} else {
// uri==null or error
Log.i(TAG, getInstanceNo() + "onOpenPublicOutputUriPickerResult(null): No output url, not saved.");
}
}

private String toString(Uri outUri) {
protected String toString(Uri outUri) {
if (outUri == null) return "";
// may crash with "IllegalCharsetNameException" in https://github.com/k3b/LosslessJpgCrop/issues/7
try {
Expand All @@ -318,7 +242,7 @@ private String toString(Uri outUri) {
}
}

private void close(Closeable stream, Object source) {
protected void close(Closeable stream, Object source) {
if (stream != null) {
try {
stream.close();
Expand All @@ -328,13 +252,6 @@ private void close(Closeable stream, Object source) {
}
}

/** replaceExtension("/path/to/image.jpg", ".xmp") becomes "/path/to/image.xmp" */
private static String replaceExtension(String path, String extension) {
if (path == null) return null;
int ext = path.lastIndexOf(".");
return ((ext >= 0) ? path.substring(0, ext) : path) + extension;
}

/**
* Callback received when a permissions request has been completed.
*/
Expand All @@ -346,11 +263,6 @@ public void onRequestPermissionsResult(int requestCode, String[] permissions, in
pickFromGallery();
}
break;
case REQUEST_SAVE_PICTURE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveAsPublicCroppedImage();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
Expand All @@ -363,11 +275,6 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) {
onGetPictureResult(resultCode, data);
return;
}
if (requestCode == REQUEST_SAVE_PICTURE) {
final Uri outUri = (data == null) ? null : data.getData();
onOpenPublicOutputUriPickerResult(resultCode, outUri);
return;
}

super.onActivityResult(requestCode, resultCode, data);
}
Expand All @@ -388,7 +295,7 @@ private Uri __delete_saveAsPrivate() {
sharedFolder.mkdirs();
outStream = new FileOutputStream(sharedFile);
inStream = getContentResolver().openInputStream(inUri);
this.mSpectrum.crop(inStream, outStream, rect, 0);
crop(inStream, outStream, rect);

Uri sharedFileUri = FileProvider.getUriForFile(this, "de.k3b.llCrop", sharedFile);

Expand All @@ -403,6 +310,10 @@ private Uri __delete_saveAsPrivate() {

}

protected void crop(InputStream inStream, OutputStream outStream, Rect rect) {
this.mSpectrum.crop(inStream, outStream, rect, 0);
}

private Uri createPrivateOutUriOrNull() {
try {
final File sharedFolder = new File(getFilesDir(), "shared");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
package de.k3b.android.lossless_jpg_crop;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.io.InputStream;
import java.io.OutputStream;

public class CropAreasEditActivity extends CropAreasChooseBaseActivity {
private static final int REQUEST_SAVE_PICTURE = 2;
private static final int REQUEST_SAVE_PICTURE_PERMISSION = 102;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand All @@ -17,20 +32,15 @@ protected void onSaveInstanceState(Bundle outState) {

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
return super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_edit, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/*
case R.id.menu_send: {
createSendIntend(true);
}
reloadContext = false;
IntentUtil.cmdStartIntent("share", this, null, null, getCurrentFilePath(), Intent.ACTION_SEND, R.string.share_menu_title, R.string.share_err_not_found, 0);
break;
*/
case R.id.menu_save:
return saveAsPublicCroppedImage();
default:
return super.onOptionsItemSelected(item);
}
Expand All @@ -43,37 +53,104 @@ public boolean onOptionsItemSelected(MenuItem item) {
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
/*
case REQUEST_GET_PICTURE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
pickFromGallery();
}
break;
case REQUEST_SAVE_PICTURE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveAsPublicCroppedImage();
}
break;
*/

default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
/*
if (requestCode == REQUEST_GET_PICTURE) {
onGetPictureResult(resultCode, data);
return;
}
if (requestCode == REQUEST_SAVE_PICTURE) {
final Uri outUri = (data == null) ? null : data.getData();
onOpenPublicOutputUriPickerResult(resultCode, outUri);
return;
}
*/

super.onActivityResult(requestCode, resultCode, data);
}

private boolean saveAsPublicCroppedImage() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
getString(R.string.permission_write_storage_rationale),
REQUEST_SAVE_PICTURE_PERMISSION);
} else {
openPublicOutputUriPicker(REQUEST_SAVE_PICTURE);
}
return true;
}

private boolean openPublicOutputUriPicker(int folderpickerCode) {
Uri inUri = getIntent().getData();
String originalFileName = (inUri == null) ? "" : inUri.getLastPathSegment();
String proposedFileName = replaceExtension(originalFileName, "_llcrop.jpg");
// String proposedOutPath = inUri.getP new Uri() replaceExtension(originalFileName, "_llcrop.jpg");


// DocumentsContract#EXTRA_INITIAL_URI
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT)
.setType(IMAGE_JPEG_MIME)
.addCategory(Intent.CATEGORY_OPENABLE)
.putExtra(Intent.EXTRA_TITLE, proposedFileName)
.putExtra(DocumentsContract.EXTRA_PROMPT, getString(R.string.label_save_as))
.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
;

Log.d(TAG, getInstanceNo() + "openPublicOutputUriPicker '" + proposedFileName + "'");

startActivityForResult(intent, folderpickerCode);
return true;
}

private void onOpenPublicOutputUriPickerResult(int resultCode, Uri outUri) {
final Intent intent = getIntent();
final Uri inUri = ((resultCode == RESULT_OK) && (intent != null)) ? intent.getData() : null;

if (inUri != null) {
Rect rect = getCropRect();
InputStream inStream = null;
OutputStream outStream = null;

final String context_message = getInstanceNo() + "Cropping '" + inUri + "'(" + rect + ") => '"
+ outUri + "' ('" + toString(outUri) + "')";
Log.i(TAG, context_message);

try {
inStream = getContentResolver().openInputStream(inUri);
outStream = getContentResolver().openOutputStream(outUri, "w");
crop(inStream, outStream, rect);

String message = getString(R.string.toast_saved_as,
toString(outUri));
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

finish();
return;
} catch (Exception e) {
Log.e(TAG, "Error " + context_message + e.getMessage(), e);
} finally {
close(outStream, outStream);
close(inStream, inStream);
}
} else {
// uri==null or error
Log.i(TAG, getInstanceNo() + "onOpenPublicOutputUriPickerResult(null): No output url, not saved.");
}
}

/** replaceExtension("/path/to/image.jpg", ".xmp") becomes "/path/to/image.xmp" */
private static String replaceExtension(String path, String extension) {
if (path == null) return null;
int ext = path.lastIndexOf(".");
return ((ext >= 0) ? path.substring(0, ext) : path) + extension;
}
}

0 comments on commit 9b871a4

Please sign in to comment.