bytes = new ArrayList<>();
+ byte[] read = new byte[1];
+ while ((inputStream.read(read)) > 0) {
+ if (read[0] == 0x0A) { // newline \n character
+ break;
}
- } else {
- throw new IOException("Not valid file");
+ bytes.add(read[0]);
}
byte[] arr = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); i++) {
arr[i] = bytes.get(i);
}
- return new Streams(cipherInputStream, secretKey, new String(arr, StandardCharsets.UTF_8));
+ return arr;
+ }
+
+ private static Streams getCipherOutputStream(FragmentActivity context, Uri input, DocumentFile outputFile, char[] password, String sourceFileName, int version) throws GeneralSecurityException, IOException, JSONException {
+ if (version < 2) {
+ SecureRandom sr = SecureRandom.getInstanceStrong();
+ byte[] salt = new byte[SALT_LENGTH];
+ byte[] ivBytes = new byte[IV_LENGTH];
+ generateSecureRandom(sr, salt, ivBytes, null);
+
+ SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
+ KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION_COUNT_V1, KEY_LENGTH);
+ SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
+ IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
+
+ Cipher cipher = Cipher.getInstance(CIPHER);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
+
+ InputStream inputStream = context.getContentResolver().openInputStream(input);
+ OutputStream fos = new BufferedOutputStream(context.getContentResolver().openOutputStream(outputFile.getUri()), 1024 * 32);
+ writeSaltAndIV(null, salt, ivBytes, null, null, fos);
+ fos.flush();
+ CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, cipher);
+ cipherOutputStream.write(("\n" + sourceFileName + "\n").getBytes(StandardCharsets.UTF_8));
+ return new Streams(inputStream, cipherOutputStream, secretKey);
+ } else {
+ SecureRandom sr = SecureRandom.getInstanceStrong();
+ Settings settings = Settings.getInstance(context);
+ final int ITERATION_COUNT = settings.getIterationCount();
+ byte[] versionBytes = toByteArray(version);
+ byte[] salt = new byte[SALT_LENGTH];
+ byte[] ivBytes = new byte[IV_LENGTH];
+ byte[] iterationCount = toByteArray(ITERATION_COUNT);
+ byte[] checkBytes = new byte[CHECK_LENGTH];
+ generateSecureRandom(sr, salt, ivBytes, checkBytes);
+
+ SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
+ KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION_COUNT, KEY_LENGTH);
+ SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
+ IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
+
+ Cipher cipher = Cipher.getInstance(CIPHER);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
+
+ InputStream inputStream = context.getContentResolver().openInputStream(input);
+ OutputStream fos = new BufferedOutputStream(context.getContentResolver().openOutputStream(outputFile.getUri()), 1024 * 32);
+ writeSaltAndIV(versionBytes, salt, ivBytes, iterationCount, checkBytes, fos);
+ fos.flush();
+ CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, cipher);
+ cipherOutputStream.write(checkBytes);
+ JSONObject json = new JSONObject();
+ json.put(JSON_ORIGINAL_NAME, sourceFileName);
+ cipherOutputStream.write(("\n" + json + "\n").getBytes(StandardCharsets.UTF_8));
+ return new Streams(inputStream, cipherOutputStream, secretKey);
+ }
}
- private static Streams getCipherOutputStream(FragmentActivity context, Uri input, DocumentFile outputFile, char[] password, boolean isThumb, String sourceFileName) throws GeneralSecurityException, IOException {
- SecureRandom sr = SecureRandom.getInstanceStrong();
- byte[] salt = new byte[SALT_LENGTH];
- byte[] ivBytes = new byte[IV_LENGTH];
- byte[] checkBytes = new byte[CHECK_LENGTH];
- generateSecureRandom(sr, salt, ivBytes, isThumb ? checkBytes : null);
-
- SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
- KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION_COUNT, KEY_LENGTH);
- SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
- IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
-
- Cipher cipher = Cipher.getInstance(CIPHER);
- cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
-
- InputStream inputStream = context.getContentResolver().openInputStream(input);
- OutputStream fos = new BufferedOutputStream(context.getContentResolver().openOutputStream(outputFile.getUri()), 1024 * 32);
- writeSaltAndIV(isThumb, salt, ivBytes, checkBytes, fos);
- fos.flush();
- CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, cipher);
- if (isThumb) {
+ private static Streams getTextCipherOutputStream(FragmentActivity context, String input, DocumentFile outputFile, char[] password, String sourceFileName, int version) throws GeneralSecurityException, IOException, JSONException {
+ if (version < 2) {
+ SecureRandom sr = SecureRandom.getInstanceStrong();
+ byte[] salt = new byte[SALT_LENGTH];
+ byte[] ivBytes = new byte[IV_LENGTH];
+ generateSecureRandom(sr, salt, ivBytes, null);
+
+ SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
+ KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION_COUNT_V1, KEY_LENGTH);
+ SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
+ IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
+
+ Cipher cipher = Cipher.getInstance(CIPHER);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
+
+ OutputStream fos = new BufferedOutputStream(context.getContentResolver().openOutputStream(outputFile.getUri()), 1024 * 32);
+ writeSaltAndIV(null, salt, ivBytes, null, null, fos);
+ fos.flush();
+ CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, cipher);
+ cipherOutputStream.write(("\n" + sourceFileName + "\n").getBytes(StandardCharsets.UTF_8));
+ return new Streams(input, cipherOutputStream, secretKey);
+ } else {
+ SecureRandom sr = SecureRandom.getInstanceStrong();
+ Settings settings = Settings.getInstance(context);
+ final int ITERATION_COUNT = settings.getIterationCount();
+ byte[] versionBytes = toByteArray(version);
+ byte[] salt = new byte[SALT_LENGTH];
+ byte[] ivBytes = new byte[IV_LENGTH];
+ byte[] iterationCount = toByteArray(ITERATION_COUNT);
+ byte[] checkBytes = new byte[CHECK_LENGTH];
+ generateSecureRandom(sr, salt, ivBytes, checkBytes);
+
+ SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
+ KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION_COUNT, KEY_LENGTH);
+ SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
+ IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
+
+ Cipher cipher = Cipher.getInstance(CIPHER);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
+
+ OutputStream fos = new BufferedOutputStream(context.getContentResolver().openOutputStream(outputFile.getUri()), 1024 * 32);
+ writeSaltAndIV(versionBytes, salt, ivBytes, iterationCount, checkBytes, fos);
+ fos.flush();
+ CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, cipher);
cipherOutputStream.write(checkBytes);
+ JSONObject json = new JSONObject();
+ json.put(JSON_ORIGINAL_NAME, sourceFileName);
+ cipherOutputStream.write(("\n" + json + "\n").getBytes(StandardCharsets.UTF_8));
+ return new Streams(input, cipherOutputStream, secretKey);
}
- cipherOutputStream.write(("\n" + sourceFileName + "\n").getBytes(StandardCharsets.UTF_8));
- return new Streams(inputStream, cipherOutputStream, secretKey);
}
- private static Streams getTextCipherOutputStream(FragmentActivity context, String input, DocumentFile outputFile, char[] password, String sourceFileName) throws GeneralSecurityException, IOException {
- SecureRandom sr = SecureRandom.getInstanceStrong();
- byte[] salt = new byte[SALT_LENGTH];
- byte[] ivBytes = new byte[IV_LENGTH];
- generateSecureRandom(sr, salt, ivBytes, null);
-
- SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
- KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION_COUNT, KEY_LENGTH);
- SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
- IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
-
- Cipher cipher = Cipher.getInstance(CIPHER);
- cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
-
- OutputStream fos = new BufferedOutputStream(context.getContentResolver().openOutputStream(outputFile.getUri()), 1024 * 32);
- writeSaltAndIV(false, salt, ivBytes, null, fos);
- fos.flush();
- CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, cipher);
- cipherOutputStream.write(("\n" + sourceFileName + "\n").getBytes(StandardCharsets.UTF_8));
- return new Streams(input, cipherOutputStream, secretKey);
+ public static byte[] toByteArray(int value) {
+ return new byte[]{(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value};
+ }
+
+ public static int fromByteArray(byte[] bytes) {
+ return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}
@NonNull
- public static String getOriginalFilename(@NonNull InputStream inputStream, char[] password, boolean isThumb) {
+ public static String getOriginalFilename(@NonNull InputStream inputStream, char[] password, boolean isThumb, int version) {
String name = "";
try {
- Streams streams = getCipherInputStream(inputStream, password, isThumb);
+ Streams streams = getCipherInputStream(inputStream, password, isThumb, version);
name = streams.getOriginalFileName();
streams.close();
- } catch (IOException | GeneralSecurityException | InvalidPasswordException e) {
+ } catch (IOException | GeneralSecurityException | InvalidPasswordException |
+ JSONException e) {
e.printStackTrace();
}
return name;
@@ -387,23 +548,53 @@ private static void generateSecureRandom(SecureRandom sr, byte[] salt, byte[] iv
}
}
- private static void writeSaltAndIV(boolean isThumb, byte[] salt, byte[] ivBytes, byte[] checkBytes, OutputStream fos) throws IOException {
+ private static void writeSaltAndIV(@Nullable byte[] version, byte[] salt, byte[] ivBytes, @Nullable byte[] iterationCount, @Nullable byte[] checkBytes, OutputStream fos) throws IOException {
+ if (version != null) {
+ fos.write(version);
+ }
fos.write(salt);
fos.write(ivBytes);
- if (isThumb) {
+ if (iterationCount != null) {
+ fos.write(iterationCount);
+ }
+ if (checkBytes != null) {
fos.write(checkBytes);
}
}
- public static void decryptToCache(FragmentActivity context, Uri encryptedInput, @Nullable String extension, char[] password, IOnUriResult onUriResult) {
+ public static String readEncryptedTextFromUri(@NonNull Uri encryptedInput, Context context, int version, char[] password) {
+ try {
+ InputStream inputStream = context.getContentResolver().openInputStream(encryptedInput);
+ Streams cis = getCipherInputStream(inputStream, password, false, version);
+
+ BufferedReader br = new BufferedReader(new InputStreamReader(cis.inputStream, StandardCharsets.UTF_8));
+
+ StringBuilder sb = new StringBuilder();
+ int read;
+ char[] buffer = new char[8192];
+ while ((read = br.read(buffer)) != -1) {
+ sb.append(buffer, 0, read);
+ }
+
+ return sb.toString();
+ } catch (GeneralSecurityException | InvalidPasswordException | JSONException |
+ IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public static void decryptToCache(FragmentActivity context, Uri encryptedInput, @Nullable String extension, int version, char[] password, IOnUriResult onUriResult) {
new Thread(() -> {
try {
InputStream inputStream = new BufferedInputStream(context.getContentResolver().openInputStream(encryptedInput), 1024 * 32);
- Path file = Files.createTempFile("temp_", extension);
+ File cacheDir = context.getCacheDir();
+ cacheDir.mkdir();
+ Path file = Files.createTempFile(null, extension);
Uri fileUri = Uri.fromFile(file.toFile());
OutputStream fos = context.getContentResolver().openOutputStream(fileUri);
- Streams cis = getCipherInputStream(inputStream, password, false);
+ Streams cis = getCipherInputStream(inputStream, password, false, version);
int read;
byte[] buffer = new byte[2048];
@@ -415,7 +606,7 @@ public static void decryptToCache(FragmentActivity context, Uri encryptedInput,
inputStream.close();
context.runOnUiThread(() -> onUriResult.onUriResult(fileUri));
- } catch (GeneralSecurityException | IOException e) {
+ } catch (GeneralSecurityException | IOException | JSONException e) {
e.printStackTrace();
context.runOnUiThread(() -> onUriResult.onError(e));
} catch (InvalidPasswordException e) {
@@ -426,12 +617,12 @@ public static void decryptToCache(FragmentActivity context, Uri encryptedInput,
}).start();
}
- public static void decryptAndExport(FragmentActivity context, Uri encryptedInput, DocumentFile directory, GalleryFile galleryFile, char[] password, IOnUriResult onUriResult, boolean isVideo) {
+ public static void decryptAndExport(FragmentActivity context, Uri encryptedInput, DocumentFile directory, GalleryFile galleryFile, boolean isVideo, int version, char[] password, IOnUriResult onUriResult) {
DocumentFile documentFile = directory != null ? directory : DocumentFile.fromTreeUri(context, encryptedInput);
String originalFileName = galleryFile.getOriginalName();
if (originalFileName == null) {
try {
- originalFileName = Encryption.getOriginalFilename(context.getContentResolver().openInputStream(encryptedInput), password, false);
+ originalFileName = Encryption.getOriginalFilename(context.getContentResolver().openInputStream(encryptedInput), password, false, version);
galleryFile.setOriginalName(originalFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
@@ -443,7 +634,7 @@ public static void decryptAndExport(FragmentActivity context, Uri encryptedInput
InputStream inputStream = new BufferedInputStream(context.getContentResolver().openInputStream(encryptedInput), 1024 * 32);
OutputStream fos = context.getContentResolver().openOutputStream(file.getUri());
- Streams cis = getCipherInputStream(inputStream, password, false);
+ Streams cis = getCipherInputStream(inputStream, password, false, version);
int read;
byte[] buffer = new byte[2048];
@@ -455,7 +646,7 @@ public static void decryptAndExport(FragmentActivity context, Uri encryptedInput
inputStream.close();
onUriResult.onUriResult(file.getUri());
- } catch (GeneralSecurityException | IOException e) {
+ } catch (GeneralSecurityException | IOException | JSONException e) {
e.printStackTrace();
onUriResult.onError(e);
} catch (InvalidPasswordException e) {
diff --git a/app/src/main/java/se/arctosoft/vault/encryption/MyCipherInputStream.java b/app/src/main/java/se/arctosoft/vault/encryption/MyCipherInputStream.java
index d4d526f..8485b6a 100644
--- a/app/src/main/java/se/arctosoft/vault/encryption/MyCipherInputStream.java
+++ b/app/src/main/java/se/arctosoft/vault/encryption/MyCipherInputStream.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -30,23 +30,15 @@
public class MyCipherInputStream extends CipherInputStream {
- public MyCipherInputStream(InputStream is, Cipher c) throws IOException {
+ public MyCipherInputStream(InputStream is, Cipher c) {
super(is, c);
input = is;
cipher = c;
}
-
- // the cipher engine to use to process stream data
- private Cipher cipher;
-
- // the underlying input stream
- private InputStream input;
-
- /* the buffer holding data that have been read in from the
- underlying stream, but have not been processed by the cipher
- engine. the size 512 bytes is somewhat randomly chosen */
- private byte[] ibuffer = new byte[1024*8]; // Increased buffer size
+ private final Cipher cipher;
+ private final InputStream input;
+ private final byte[] ibuffer = new byte[1024 * 8];
// having reached the end of the underlying input stream
private boolean done = false;
@@ -61,27 +53,10 @@ public MyCipherInputStream(InputStream is, Cipher c) throws IOException {
// stream status
private boolean closed = false;
- /**
- * private convenience function.
- *
- * Entry condition: ostart = ofinish
- *
- * Exit condition: ostart <= ofinish
- *
- * return (ofinish-ostart) (we have this many bytes for you)
- * return 0 (no data now, but could have more later)
- * return -1 (absolutely no more data)
- *
- * Note: Exceptions are only thrown after the stream is completely read.
- * For AEAD ciphers a read() of any length will internally cause the
- * whole stream to be read fully and verify the authentication tag before
- * returning decrypted data or exceptions.
- */
private int getMoreData() throws IOException {
- // Android-changed: The method was creating a new object every time update(byte[], int, int)
- // or doFinal() was called resulting in the old object being GCed. With do(byte[], int) and
- // update(byte[], int, int, byte[], int), we use already initialized obuffer.
- if (done) return -1;
+ if (done) {
+ return -1;
+ }
ofinish = 0;
ostart = 0;
int expectedOutputSize = cipher.getOutputSize(ibuffer.length);
@@ -119,21 +94,7 @@ private int getMoreData() throws IOException {
return ofinish;
}
- /**
- * Reads the next byte of data from this input stream. The value
- * byte is returned as an int
in the range
- * 0
to 255
. If no byte is available
- * because the end of the stream has been reached, the value
- * -1
is returned. This method blocks until input data
- * is available, the end of the stream is detected, or an exception
- * is thrown.
- *
- *
- * @return the next byte of data, or -1
if the end of the
- * stream is reached.
- * @exception IOException if an I/O error occurs.
- * @since JCE1.2
- */
+ @Override
public int read() throws IOException {
if (ostart >= ofinish) {
// we loop for new data as the spec says we are blocking
@@ -142,46 +103,15 @@ public int read() throws IOException {
if (i == -1) return -1;
}
return ((int) obuffer[ostart++] & 0xff);
- };
+ }
- /**
- * Reads up to b.length
bytes of data from this input
- * stream into an array of bytes.
- *
- * The read
method of InputStream
calls
- * the read
method of three arguments with the arguments
- * b
, 0
, and b.length
.
- *
- * @param b the buffer into which the data is read.
- * @return the total number of bytes read into the buffer, or
- * -1
is there is no more data because the end of
- * the stream has been reached.
- * @exception IOException if an I/O error occurs.
- * @see java.io.InputStream#read(byte[], int, int)
- * @since JCE1.2
- */
- public int read(byte b[]) throws IOException {
+ @Override
+ public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
- /**
- * Reads up to len
bytes of data from this input stream
- * into an array of bytes. This method blocks until some input is
- * available. If the first argument is null,
up to
- * len
bytes are read and discarded.
- *
- * @param b the buffer into which the data is read.
- * @param off the start offset in the destination array
- * buf
- * @param len the maximum number of bytes read.
- * @return the total number of bytes read into the buffer, or
- * -1
if there is no more data because the end of
- * the stream has been reached.
- * @exception IOException if an I/O error occurs.
- * @see java.io.InputStream#read()
- * @since JCE1.2
- */
- public int read(byte b[], int off, int len) throws IOException {
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
if (ostart >= ofinish) {
// we loop for new data as the spec says we are blocking
int i = 0;
@@ -200,25 +130,8 @@ public int read(byte b[], int off, int len) throws IOException {
return available;
}
- /**
- * Skips n
bytes of input from the bytes that can be read
- * from this input stream without blocking.
- *
- *
Fewer bytes than requested might be skipped.
- * The actual number of bytes skipped is equal to n
or
- * the result of a call to
- * {@link #available() available},
- * whichever is smaller.
- * If n
is less than zero, no bytes are skipped.
- *
- *
The actual number of bytes skipped is returned.
- *
- * @param n the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @exception IOException if an I/O error occurs.
- * @since JCE1.2
- */
- public long skip(long n) throws IOException {
+ @Override
+ public long skip(long n) {
int available = ofinish - ostart;
if (n > available) {
n = available;
@@ -226,36 +139,16 @@ public long skip(long n) throws IOException {
if (n < 0) {
return 0;
}
- ostart += n;
+ ostart += (int) n;
return n;
}
- /**
- * Returns the number of bytes that can be read from this input
- * stream without blocking. The available
method of
- * InputStream
returns 0
. This method
- * should be overridden by subclasses.
- *
- * @return the number of bytes that can be read from this input stream
- * without blocking.
- * @exception IOException if an I/O error occurs.
- * @since JCE1.2
- */
- public int available() throws IOException {
+ @Override
+ public int available() {
return (ofinish - ostart);
}
- /**
- * Closes this input stream and releases any system resources
- * associated with the stream.
- *
- * The close
method of CipherInputStream
- * calls the close
method of its underlying input
- * stream.
- *
- * @exception IOException if an I/O error occurs.
- * @since JCE1.2
- */
+ @Override
public void close() throws IOException {
if (closed) {
return;
@@ -264,13 +157,10 @@ public void close() throws IOException {
closed = true;
input.close();
- // Android-removed: Removed a now-inaccurate comment
if (!done) {
try {
cipher.doFinal();
- }
- catch (BadPaddingException | IllegalBlockSizeException ex) {
- // Android-changed: Added throw if bad tag is seen. See b/31590622.
+ } catch (BadPaddingException | IllegalBlockSizeException ex) {
if (ex instanceof AEADBadTagException) {
throw new IOException(ex);
}
@@ -280,16 +170,7 @@ public void close() throws IOException {
ofinish = 0;
}
- /**
- * Tests if this input stream supports the mark
- * and reset
methods, which it does not.
- *
- * @return false
, since this class does not support the
- * mark
and reset
methods.
- * @see java.io.InputStream#mark(int)
- * @see java.io.InputStream#reset()
- * @since JCE1.2
- */
+ @Override
public boolean markSupported() {
return false;
}
diff --git a/app/src/main/java/se/arctosoft/vault/encryption/MyDataSource.java b/app/src/main/java/se/arctosoft/vault/encryption/MyDataSource.java
index 1efb825..6ec54d8 100644
--- a/app/src/main/java/se/arctosoft/vault/encryption/MyDataSource.java
+++ b/app/src/main/java/se/arctosoft/vault/encryption/MyDataSource.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -29,14 +29,16 @@
import androidx.media3.datasource.DataSpec;
import androidx.media3.datasource.TransferListener;
+import org.json.JSONException;
+
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import javax.crypto.CipherInputStream;
+import se.arctosoft.vault.data.Password;
import se.arctosoft.vault.exception.InvalidPasswordException;
-import se.arctosoft.vault.utils.Settings;
@OptIn(markerClass = androidx.media3.common.util.UnstableApi.class)
public class MyDataSource implements DataSource {
@@ -45,9 +47,13 @@ public class MyDataSource implements DataSource {
private Encryption.Streams streams;
private Uri uri;
+ private final Password password;
+ private final int version;
- public MyDataSource(@NonNull Context context) {
+ public MyDataSource(@NonNull Context context, int version, Password password) {
this.context = context.getApplicationContext();
+ this.version = version;
+ this.password = password;
}
@Override
@@ -55,8 +61,8 @@ public long open(@NonNull DataSpec dataSpec) throws IOException {
uri = dataSpec.uri;
try {
InputStream fileStream = context.getContentResolver().openInputStream(uri);
- streams = Encryption.getCipherInputStream(fileStream, Settings.getInstance(context).getTempPassword(), false);
- } catch (GeneralSecurityException | InvalidPasswordException e) {
+ streams = Encryption.getCipherInputStream(fileStream, password.getPassword(), false, version);
+ } catch (GeneralSecurityException | InvalidPasswordException | JSONException e) {
e.printStackTrace();
Log.e(TAG, "open error", e);
return 0;
diff --git a/app/src/main/java/se/arctosoft/vault/encryption/MyDataSourceFactory.java b/app/src/main/java/se/arctosoft/vault/encryption/MyDataSourceFactory.java
index 3666e3d..e3c29b1 100644
--- a/app/src/main/java/se/arctosoft/vault/encryption/MyDataSourceFactory.java
+++ b/app/src/main/java/se/arctosoft/vault/encryption/MyDataSourceFactory.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -24,17 +24,24 @@
import androidx.annotation.OptIn;
import androidx.media3.datasource.DataSource;
+import se.arctosoft.vault.data.Password;
+import se.arctosoft.vault.viewmodel.PasswordViewModel;
+
public class MyDataSourceFactory implements DataSource.Factory {
private final Context context;
+ private final int version;
+ private final Password password;
- public MyDataSourceFactory(Context context) {
+ public MyDataSourceFactory(Context context, int version, Password password) {
this.context = context;
+ this.version = version;
+ this.password = password;
}
@OptIn(markerClass = androidx.media3.common.util.UnstableApi.class)
@NonNull
@Override
public DataSource createDataSource() {
- return new MyDataSource(context);
+ return new MyDataSource(context, version, password);
}
}
diff --git a/app/src/main/java/se/arctosoft/vault/exception/InvalidPasswordException.java b/app/src/main/java/se/arctosoft/vault/exception/InvalidPasswordException.java
index c627ecb..cfa8b0d 100644
--- a/app/src/main/java/se/arctosoft/vault/exception/InvalidPasswordException.java
+++ b/app/src/main/java/se/arctosoft/vault/exception/InvalidPasswordException.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/fastscroll/views/FastScrollRecyclerView.java b/app/src/main/java/se/arctosoft/vault/fastscroll/views/FastScrollRecyclerView.java
index 37fcd27..cc3ea0a 100644
--- a/app/src/main/java/se/arctosoft/vault/fastscroll/views/FastScrollRecyclerView.java
+++ b/app/src/main/java/se/arctosoft/vault/fastscroll/views/FastScrollRecyclerView.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
* Copyright (c) 2016 Tim Malseed
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -303,7 +303,7 @@ public String scrollToPositionAtProgress(float touchFraction) {
scrollOffset = -(exactItemPos % mScrollPosState.rowHeight);
}
- RecyclerView.LayoutManager layoutManager = getLayoutManager();
+ LayoutManager layoutManager = getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(scrollPosition, scrollOffset);
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnAdapterItemChanged.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnAdapterItemChanged.java
new file mode 100644
index 0000000..753782f
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnAdapterItemChanged.java
@@ -0,0 +1,22 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.interfaces;
+
+public interface IOnAdapterItemChanged {
+ void onChanged(int pos);
+}
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnDirectoryAdded.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnDirectoryAdded.java
index 03fd59b..17bb2b7 100644
--- a/app/src/main/java/se/arctosoft/vault/interfaces/IOnDirectoryAdded.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnDirectoryAdded.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -18,14 +18,10 @@
package se.arctosoft.vault.interfaces;
-import android.net.Uri;
-
-import androidx.annotation.NonNull;
-
public interface IOnDirectoryAdded {
- void onAddedAsRoot();
+ void onAdded();
- void onAddedAsChildOf(@NonNull Uri parentUri);
+ void onAddedAsRoot();
- void onAlreadyExists(boolean isRootDir);
+ void onAlreadyExists();
}
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnDone.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnDone.java
new file mode 100644
index 0000000..30800cd
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnDone.java
@@ -0,0 +1,22 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.interfaces;
+
+public interface IOnDone {
+ void onDone();
+}
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnEdited.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnEdited.java
index 847926a..7f60b11 100644
--- a/app/src/main/java/se/arctosoft/vault/interfaces/IOnEdited.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnEdited.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileClicked.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileClicked.java
index 10991cb..cbd8f7c 100644
--- a/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileClicked.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileClicked.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileDeleted.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileDeleted.java
index e93af69..fa00621 100644
--- a/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileDeleted.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileDeleted.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/BaseActivity.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileOperationDone.java
similarity index 53%
rename from app/src/main/java/se/arctosoft/vault/BaseActivity.java
rename to app/src/main/java/se/arctosoft/vault/interfaces/IOnFileOperationDone.java
index 69db7fb..cff8624 100644
--- a/app/src/main/java/se/arctosoft/vault/BaseActivity.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnFileOperationDone.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (c) 2024 Arctosoft AB.
*
* 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
@@ -12,19 +12,15 @@
* 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 https://www.gnu.org/licenses/.
+ * You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.
*/
-package se.arctosoft.vault;
+package se.arctosoft.vault.interfaces;
-import android.content.Intent;
+import java.util.List;
-import androidx.activity.result.ActivityResult;
-import androidx.appcompat.app.AppCompatActivity;
+import se.arctosoft.vault.data.GalleryFile;
-import se.arctosoft.vault.utils.BetterActivityResult;
-
-public class BaseActivity extends AppCompatActivity {
- protected final BetterActivityResult activityLauncher = BetterActivityResult.registerActivityForResult(this);
+public interface IOnFileOperationDone {
+ void onDone(List processedFiles);
}
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnImportDone.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnImportDone.java
new file mode 100644
index 0000000..e958af4
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnImportDone.java
@@ -0,0 +1,24 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.interfaces;
+
+import android.net.Uri;
+
+public interface IOnImportDone {
+ void onDone(Uri destinationUri, boolean isSameDirectory, int importedCount, int failedCount, int thumbErrorCount);
+}
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnProgress.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnProgress.java
index 2ec556c..cb4096c 100644
--- a/app/src/main/java/se/arctosoft/vault/interfaces/IOnProgress.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnProgress.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/interfaces/IOnSelectionModeChanged.java b/app/src/main/java/se/arctosoft/vault/interfaces/IOnSelectionModeChanged.java
index 566336b..479c2a7 100644
--- a/app/src/main/java/se/arctosoft/vault/interfaces/IOnSelectionModeChanged.java
+++ b/app/src/main/java/se/arctosoft/vault/interfaces/IOnSelectionModeChanged.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/loader/CipherDataFetcher.java b/app/src/main/java/se/arctosoft/vault/loader/CipherDataFetcher.java
index 0b19801..09e3d76 100644
--- a/app/src/main/java/se/arctosoft/vault/loader/CipherDataFetcher.java
+++ b/app/src/main/java/se/arctosoft/vault/loader/CipherDataFetcher.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -27,34 +27,39 @@
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.data.DataFetcher;
+import org.json.JSONException;
+
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
+import se.arctosoft.vault.data.Password;
import se.arctosoft.vault.encryption.Encryption;
import se.arctosoft.vault.exception.InvalidPasswordException;
-import se.arctosoft.vault.utils.Settings;
public class CipherDataFetcher implements DataFetcher {
private static final String TAG = "CipherDataFetcher";
private Encryption.Streams streams;
private final Context context;
private final Uri uri;
- private final Settings settings;
+ private final int version;
+ private final Password password;
- public CipherDataFetcher(@NonNull Context context, Uri uri) {
+ public CipherDataFetcher(@NonNull Context context, Uri uri, int version) {
this.context = context.getApplicationContext();
this.uri = uri;
- this.settings = Settings.getInstance(context);
+ this.version = version;
+ this.password = Password.getInstance();
}
@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback super InputStream> callback) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
- streams = Encryption.getCipherInputStream(inputStream, settings.getTempPassword(), true);
+ streams = Encryption.getCipherInputStream(inputStream, password.getPassword(), true, version);
callback.onDataReady(streams.getInputStream());
- } catch (GeneralSecurityException | IOException | InvalidPasswordException e) {
+ } catch (GeneralSecurityException | IOException | InvalidPasswordException |
+ JSONException e) {
//e.printStackTrace();
callback.onLoadFailed(e);
}
diff --git a/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoader.java b/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoader.java
index cec642a..657fa1b 100644
--- a/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoader.java
+++ b/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoader.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -34,21 +34,27 @@
public class CipherModelLoader implements ModelLoader {
private final Context context;
+ private final int version;
- public CipherModelLoader(@NonNull Context context) {
+ public CipherModelLoader(@NonNull Context context, int version) {
this.context = context.getApplicationContext();
+ this.version = version;
}
@Nullable
@Override
public LoadData buildLoadData(@NonNull Uri uri, int width, int height, @NonNull Options options) {
- return new LoadData<>(new ObjectKey(uri), new CipherDataFetcher(context, uri));
+ return new LoadData<>(new ObjectKey(uri), new CipherDataFetcher(context, uri, version));
}
@Override
public boolean handles(@NonNull Uri uri) {
String lastSegment = uri.getLastPathSegment();
- return lastSegment != null && lastSegment.toLowerCase().contains("/" + Encryption.ENCRYPTED_PREFIX);
+ if (version < 2) {
+ return lastSegment != null && lastSegment.toLowerCase().contains("/" + Encryption.ENCRYPTED_PREFIX);
+ } else {
+ return lastSegment != null && lastSegment.toLowerCase().endsWith(Encryption.ENCRYPTED_SUFFIX);
+ }
}
}
diff --git a/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoaderFactory.java b/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoaderFactory.java
index 42ad4c6..72a2211 100644
--- a/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoaderFactory.java
+++ b/app/src/main/java/se/arctosoft/vault/loader/CipherModelLoaderFactory.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -29,19 +29,19 @@
import java.io.InputStream;
-import javax.crypto.CipherInputStream;
-
public class CipherModelLoaderFactory implements ModelLoaderFactory {
private final Context context;
+ private final int version;
- public CipherModelLoaderFactory(@NonNull Context context) {
+ public CipherModelLoaderFactory(@NonNull Context context, int version) {
this.context = context.getApplicationContext();
+ this.version = version;
}
@NonNull
@Override
public ModelLoader build(@NonNull MultiModelLoaderFactory multiFactory) {
- return new CipherModelLoader(context);
+ return new CipherModelLoader(context, version);
}
@Override
diff --git a/app/src/main/java/se/arctosoft/vault/loader/MyAppGlideModule.java b/app/src/main/java/se/arctosoft/vault/loader/MyAppGlideModule.java
index 1cc0efe..160111f 100644
--- a/app/src/main/java/se/arctosoft/vault/loader/MyAppGlideModule.java
+++ b/app/src/main/java/se/arctosoft/vault/loader/MyAppGlideModule.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -34,9 +34,11 @@
@GlideModule
public class MyAppGlideModule extends AppGlideModule {
+
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
- registry.prepend(Uri.class, InputStream.class, new CipherModelLoaderFactory(context));
+ registry.prepend(Uri.class, InputStream.class, new CipherModelLoaderFactory(context, 1));
+ registry.prepend(Uri.class, InputStream.class, new CipherModelLoaderFactory(context, 2));
}
@Override
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/ImageSource.java b/app/src/main/java/se/arctosoft/vault/subsampling/ImageSource.java
new file mode 100644
index 0000000..b50c1de
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/ImageSource.java
@@ -0,0 +1,174 @@
+package se.arctosoft.vault.subsampling;
+
+import android.graphics.Bitmap;
+import android.graphics.Rect;
+import android.net.Uri;
+
+import androidx.annotation.NonNull;
+
+/**
+ * Helper class used to set the source and additional attributes from a variety of sources. Supports
+ * use of a bitmap, asset, resource, external file or any other URI.
+ *
+ * When you are using a preview image, you must set the dimensions of the full size image on the
+ * ImageSource object for the full size image using the {@link #dimensions(int, int)} method.
+ */
+@SuppressWarnings({"unused", "WeakerAccess"})
+public final class ImageSource {
+
+ static final String FILE_SCHEME = "file:///";
+ static final String ASSET_SCHEME = "file:///android_asset/";
+
+ private final Uri uri;
+ private final Bitmap bitmap;
+ private final Integer resource;
+ private final char[] password;
+ private final int version;
+ private boolean tile;
+ private int sWidth;
+ private int sHeight;
+ private Rect sRegion;
+ private boolean cached;
+
+ private ImageSource(@NonNull Uri uri, char[] password, int version) {
+ this.bitmap = null;
+ this.uri = uri;
+ this.resource = null;
+ this.tile = true;
+ this.password = password;
+ this.version = version;
+ }
+
+ /**
+ * Create an instance from a URI.
+ *
+ * @param uri image URI.
+ * @param password
+ * @param version
+ * @return an {@link ImageSource} instance.
+ */
+ @NonNull
+ public static ImageSource uri(@NonNull Uri uri, char[] password, int version) {
+ //noinspection ConstantConditions
+ if (uri == null) {
+ throw new NullPointerException("Uri must not be null");
+ }
+ return new ImageSource(uri, password, version);
+ }
+
+ /**
+ * Enable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap.,
+ * and tiling cannot be disabled when displaying a region of the source image.
+ *
+ * @return this instance for chaining.
+ */
+ @NonNull
+ public ImageSource tilingEnabled() {
+ return tiling(true);
+ }
+
+ /**
+ * Disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap,
+ * and tiling cannot be disabled when displaying a region of the source image.
+ *
+ * @return this instance for chaining.
+ */
+ @NonNull
+ public ImageSource tilingDisabled() {
+ return tiling(false);
+ }
+
+ /**
+ * Enable or disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap,
+ * and tiling cannot be disabled when displaying a region of the source image.
+ *
+ * @param tile whether tiling should be enabled.
+ * @return this instance for chaining.
+ */
+ @NonNull
+ public ImageSource tiling(boolean tile) {
+ this.tile = tile;
+ return this;
+ }
+
+ /**
+ * Use a region of the source image. Region must be set independently for the full size image and the preview if
+ * you are using one.
+ *
+ * @param sRegion the region of the source image to be displayed.
+ * @return this instance for chaining.
+ */
+ @NonNull
+ public ImageSource region(Rect sRegion) {
+ this.sRegion = sRegion;
+ setInvariants();
+ return this;
+ }
+
+ /**
+ * Declare the dimensions of the image. This is only required for a full size image, when you are specifying a URI
+ * and also a preview image. When displaying a bitmap object, or not using a preview, you do not need to declare
+ * the image dimensions. Note if the declared dimensions are found to be incorrect, the view will reset.
+ *
+ * @param sWidth width of the source image.
+ * @param sHeight height of the source image.
+ * @return this instance for chaining.
+ */
+ @NonNull
+ public ImageSource dimensions(int sWidth, int sHeight) {
+ if (bitmap == null) {
+ this.sWidth = sWidth;
+ this.sHeight = sHeight;
+ }
+ setInvariants();
+ return this;
+ }
+
+ private void setInvariants() {
+ if (this.sRegion != null) {
+ this.tile = true;
+ this.sWidth = this.sRegion.width();
+ this.sHeight = this.sRegion.height();
+ }
+ }
+
+ public char[] getPassword() {
+ return password;
+ }
+
+ public int getVersion() {
+ return version;
+ }
+
+ protected final Uri getUri() {
+ return uri;
+ }
+
+ protected final Bitmap getBitmap() {
+ return bitmap;
+ }
+
+ protected final Integer getResource() {
+ return resource;
+ }
+
+ protected final boolean getTile() {
+ return tile;
+ }
+
+ protected final int getSWidth() {
+ return sWidth;
+ }
+
+ protected final int getSHeight() {
+ return sHeight;
+ }
+
+ protected final Rect getSRegion() {
+ return sRegion;
+ }
+
+ protected final boolean isCached() {
+ return cached;
+ }
+}
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/ImageViewState.java b/app/src/main/java/se/arctosoft/vault/subsampling/ImageViewState.java
new file mode 100644
index 0000000..ca67e37
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/ImageViewState.java
@@ -0,0 +1,42 @@
+package se.arctosoft.vault.subsampling;
+
+import android.graphics.PointF;
+
+import androidx.annotation.NonNull;
+
+import java.io.Serializable;
+
+/**
+ * Wraps the scale, center and orientation of a displayed image for easy restoration on screen rotate.
+ */
+public class ImageViewState implements Serializable {
+
+ private final float scale;
+
+ private final float centerX;
+
+ private final float centerY;
+
+ private final int orientation;
+
+ public ImageViewState(float scale, @NonNull PointF center, int orientation) {
+ this.scale = scale;
+ this.centerX = center.x;
+ this.centerY = center.y;
+ this.orientation = orientation;
+ }
+
+ public float getScale() {
+ return scale;
+ }
+
+ @NonNull
+ public PointF getCenter() {
+ return new PointF(centerX, centerY);
+ }
+
+ public int getOrientation() {
+ return orientation;
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/MySubsamplingScaleImageView.java b/app/src/main/java/se/arctosoft/vault/subsampling/MySubsamplingScaleImageView.java
new file mode 100644
index 0000000..a136938
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/MySubsamplingScaleImageView.java
@@ -0,0 +1,3418 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.subsampling;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.res.TypedArray;
+import android.database.Cursor;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.Paint.Style;
+import android.graphics.Point;
+import android.graphics.PointF;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.os.Message;
+import android.provider.MediaStore;
+import android.util.AttributeSet;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.util.TypedValue;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewParent;
+
+import androidx.annotation.AnyThread;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.exifinterface.media.ExifInterface;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.Executor;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import se.arctosoft.vault.R.styleable;
+import se.arctosoft.vault.subsampling.decoder.CompatDecoderFactory;
+import se.arctosoft.vault.subsampling.decoder.DecoderFactory;
+import se.arctosoft.vault.subsampling.decoder.ImageDecoder;
+import se.arctosoft.vault.subsampling.decoder.ImageRegionDecoder;
+import se.arctosoft.vault.subsampling.decoder.SkiaImageDecoder;
+import se.arctosoft.vault.subsampling.decoder.SkiaImageRegionDecoder;
+
+/**
+ *
+ * Displays an image subsampled as necessary to avoid loading too much image data into memory. After zooming in,
+ * a set of image tiles subsampled at higher resolution are loaded and displayed over the base layer. During pan and
+ * zoom, tiles off screen or higher/lower resolution than required are discarded from memory.
+ *
+ * Tiles are no larger than the max supported bitmap size, so with large images tiling may be used even when zoomed out.
+ *
+ * v prefixes - coordinates, translations and distances measured in screen (view) pixels
+ *
+ * s prefixes - coordinates, translations and distances measured in rotated and cropped source image pixels (scaled)
+ *
+ * f prefixes - coordinates, translations and distances measured in original unrotated, uncropped source file pixels
+ *
+ * View project on GitHub
+ *
+ */
+@SuppressWarnings("unused")
+public class MySubsamplingScaleImageView extends View {
+
+ private static final String TAG = MySubsamplingScaleImageView.class.getSimpleName();
+
+ /**
+ * Attempt to use EXIF information on the image to rotate it. Works for external files only.
+ */
+ public static final int ORIENTATION_USE_EXIF = -1;
+ /**
+ * Display the image file in its native orientation.
+ */
+ public static final int ORIENTATION_0 = 0;
+ /**
+ * Rotate the image 90 degrees clockwise.
+ */
+ public static final int ORIENTATION_90 = 90;
+ /**
+ * Rotate the image 180 degrees.
+ */
+ public static final int ORIENTATION_180 = 180;
+ /**
+ * Rotate the image 270 degrees clockwise.
+ */
+ public static final int ORIENTATION_270 = 270;
+
+ private static final List VALID_ORIENTATIONS = Arrays.asList(ORIENTATION_0, ORIENTATION_90, ORIENTATION_180, ORIENTATION_270, ORIENTATION_USE_EXIF);
+
+ /**
+ * During zoom animation, keep the point of the image that was tapped in the same place, and scale the image around it.
+ */
+ public static final int ZOOM_FOCUS_FIXED = 1;
+ /**
+ * During zoom animation, move the point of the image that was tapped to the center of the screen.
+ */
+ public static final int ZOOM_FOCUS_CENTER = 2;
+ /**
+ * Zoom in to and center the tapped point immediately without animating.
+ */
+ public static final int ZOOM_FOCUS_CENTER_IMMEDIATE = 3;
+
+ private static final List VALID_ZOOM_STYLES = Arrays.asList(ZOOM_FOCUS_FIXED, ZOOM_FOCUS_CENTER, ZOOM_FOCUS_CENTER_IMMEDIATE);
+
+ /**
+ * Quadratic ease out. Not recommended for scale animation, but good for panning.
+ */
+ public static final int EASE_OUT_QUAD = 1;
+ /**
+ * Quadratic ease in and out.
+ */
+ public static final int EASE_IN_OUT_QUAD = 2;
+
+ private static final List VALID_EASING_STYLES = Arrays.asList(EASE_IN_OUT_QUAD, EASE_OUT_QUAD);
+
+ /**
+ * Don't allow the image to be panned off screen. As much of the image as possible is always displayed, centered in the view when it is smaller. This is the best option for galleries.
+ */
+ public static final int PAN_LIMIT_INSIDE = 1;
+ /**
+ * Allows the image to be panned until it is just off screen, but no further. The edge of the image will stop when it is flush with the screen edge.
+ */
+ public static final int PAN_LIMIT_OUTSIDE = 2;
+ /**
+ * Allows the image to be panned until a corner reaches the center of the screen but no further. Useful when you want to pan any spot on the image to the exact center of the screen.
+ */
+ public static final int PAN_LIMIT_CENTER = 3;
+
+ private static final List VALID_PAN_LIMITS = Arrays.asList(PAN_LIMIT_INSIDE, PAN_LIMIT_OUTSIDE, PAN_LIMIT_CENTER);
+
+ /**
+ * Scale the image so that both dimensions of the image will be equal to or less than the corresponding dimension of the view. The image is then centered in the view. This is the default behaviour and best for galleries.
+ */
+ public static final int SCALE_TYPE_CENTER_INSIDE = 1;
+ /**
+ * Scale the image uniformly so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The image is then centered in the view.
+ */
+ public static final int SCALE_TYPE_CENTER_CROP = 2;
+ /**
+ * Scale the image so that both dimensions of the image will be equal to or less than the maxScale and equal to or larger than minScale. The image is then centered in the view.
+ */
+ public static final int SCALE_TYPE_CUSTOM = 3;
+ /**
+ * Scale the image so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The top left is shown.
+ */
+ public static final int SCALE_TYPE_START = 4;
+
+ private static final List VALID_SCALE_TYPES = Arrays.asList(SCALE_TYPE_CENTER_CROP, SCALE_TYPE_CENTER_INSIDE, SCALE_TYPE_CUSTOM, SCALE_TYPE_START);
+
+ /**
+ * State change originated from animation.
+ */
+ public static final int ORIGIN_ANIM = 1;
+ /**
+ * State change originated from touch gesture.
+ */
+ public static final int ORIGIN_TOUCH = 2;
+ /**
+ * State change originated from a fling momentum anim.
+ */
+ public static final int ORIGIN_FLING = 3;
+ /**
+ * State change originated from a double tap zoom anim.
+ */
+ public static final int ORIGIN_DOUBLE_TAP_ZOOM = 4;
+
+ // Bitmap (preview or full image)
+ private Bitmap bitmap;
+
+ // Whether the bitmap is a preview image
+ private boolean bitmapIsPreview;
+
+ // Specifies if a cache handler is also referencing the bitmap. Do not recycle if so.
+ private boolean bitmapIsCached;
+
+ // Uri of full size image
+ private Uri uri;
+
+ // Sample size used to display the whole image when fully zoomed out
+ private int fullImageSampleSize;
+
+ // Map of zoom level to tile grid
+ private Map> tileMap;
+
+ // Overlay tile boundaries and other info
+ private boolean debug;
+
+ // Image orientation setting
+ private int orientation = ORIENTATION_0;
+
+ // Max scale allowed (prevent infinite zoom)
+ private float maxScale = 2F;
+
+ // Min scale allowed (prevent infinite zoom)
+ private float minScale = minScale();
+
+ // Density to reach before loading higher resolution tiles
+ private int minimumTileDpi = -1;
+
+ // Pan limiting style
+ private int panLimit = PAN_LIMIT_INSIDE;
+
+ // Minimum scale type
+ private int minimumScaleType = SCALE_TYPE_CENTER_INSIDE;
+
+ // overrides for the dimensions of the generated tiles
+ public static final int TILE_SIZE_AUTO = Integer.MAX_VALUE;
+ private int maxTileWidth = TILE_SIZE_AUTO;
+ private int maxTileHeight = TILE_SIZE_AUTO;
+
+ // An executor service for loading of images
+ private Executor executor = AsyncTask.THREAD_POOL_EXECUTOR;
+
+ // Whether tiles should be loaded while gestures and animations are still in progress
+ private boolean eagerLoadingEnabled = true;
+
+ // Gesture detection settings
+ private boolean panEnabled = true;
+ private boolean zoomEnabled = true;
+ private boolean quickScaleEnabled = true;
+
+ // Double tap zoom behaviour
+ private float doubleTapZoomScale = 1F;
+ private int doubleTapZoomStyle = ZOOM_FOCUS_FIXED;
+ private int doubleTapZoomDuration = 500;
+
+ // Current scale and scale at start of zoom
+ private float scale;
+ private float scaleStart;
+
+ // Screen coordinate of top-left corner of source image
+ private PointF vTranslate;
+ private PointF vTranslateStart;
+ private PointF vTranslateBefore;
+
+ // Source coordinate to center on, used when new position is set externally before view is ready
+ private Float pendingScale;
+ private PointF sPendingCenter;
+ private PointF sRequestedCenter;
+
+ // Source image dimensions and orientation - dimensions relate to the unrotated image
+ private int sWidth;
+ private int sHeight;
+ private int sOrientation;
+ private Rect sRegion;
+ private Rect pRegion;
+
+ // Is two-finger zooming in progress
+ private boolean isZooming;
+ // Is one-finger panning in progress
+ private boolean isPanning;
+ // Is quick-scale gesture in progress
+ private boolean isQuickScaling;
+ // Max touches used in current gesture
+ private int maxTouchCount;
+
+ // Fling detector
+ private GestureDetector detector;
+ private GestureDetector singleDetector;
+
+ // Tile and image decoding
+ private ImageRegionDecoder decoder;
+ private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true);
+ private DecoderFactory extends ImageDecoder> bitmapDecoderFactory = new CompatDecoderFactory(SkiaImageDecoder.class);
+ private DecoderFactory extends ImageRegionDecoder> regionDecoderFactory = new CompatDecoderFactory(SkiaImageRegionDecoder.class);
+
+ // Debug values
+ private PointF vCenterStart;
+ private float vDistStart;
+
+ // Current quickscale state
+ private final float quickScaleThreshold;
+ private float quickScaleLastDistance;
+ private boolean quickScaleMoved;
+ private PointF quickScaleVLastPoint;
+ private PointF quickScaleSCenter;
+ private PointF quickScaleVStart;
+
+ // Scale and center animation tracking
+ private MySubsamplingScaleImageView.Anim anim;
+
+ // Whether a ready notification has been sent to subclasses
+ private boolean readySent;
+ // Whether a base layer loaded notification has been sent to subclasses
+ private boolean imageLoadedSent;
+
+ // Event listener
+ private MySubsamplingScaleImageView.OnImageEventListener onImageEventListener;
+
+ // Scale and center listener
+ private MySubsamplingScaleImageView.OnStateChangedListener onStateChangedListener;
+
+ // Long click listener
+ private OnLongClickListener onLongClickListener;
+
+ // Long click handler
+ private final Handler handler;
+ private static final int MESSAGE_LONG_CLICK = 1;
+
+ // Paint objects created once and reused for efficiency
+ private Paint bitmapPaint;
+ private Paint debugTextPaint;
+ private Paint debugLinePaint;
+ private Paint tileBgPaint;
+
+ // Volatile fields used to reduce object creation
+ private MySubsamplingScaleImageView.ScaleAndTranslate satTemp;
+ private Matrix matrix;
+ private RectF sRect;
+ private final float[] srcArray = new float[8];
+ private final float[] dstArray = new float[8];
+
+ //The logical density of the display
+ private final float density;
+
+ // A global preference for bitmap format, available to decoder classes that respect it
+ private static Bitmap.Config preferredBitmapConfig;
+
+ private ImageSource imageSource;
+
+ public MySubsamplingScaleImageView(Context context, AttributeSet attr) {
+ super(context, attr);
+ density = getResources().getDisplayMetrics().density;
+ setMinimumDpi(160);
+ setDoubleTapZoomDpi(160);
+ setMinimumTileDpi(320);
+ setGestureDetector(context);
+ this.handler = new Handler(new Handler.Callback() {
+ public boolean handleMessage(Message message) {
+ if (message.what == MESSAGE_LONG_CLICK && onLongClickListener != null) {
+ maxTouchCount = 0;
+ MySubsamplingScaleImageView.super.setOnLongClickListener(onLongClickListener);
+ performLongClick();
+ MySubsamplingScaleImageView.super.setOnLongClickListener(null);
+ }
+ return true;
+ }
+ });
+ // Handle XML attributes
+ if (attr != null) {
+ TypedArray typedAttr = getContext().obtainStyledAttributes(attr, styleable.SubsamplingScaleImageView);
+ /*if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_assetName)) {
+ String assetName = typedAttr.getString(styleable.SubsamplingScaleImageView_assetName);
+ if (assetName != null && assetName.length() > 0) {
+ setImage(ImageSource.asset(assetName).tilingEnabled());
+ }
+ }
+ if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_src)) {
+ int resId = typedAttr.getResourceId(styleable.SubsamplingScaleImageView_src, 0);
+ if (resId > 0) {
+ setImage(ImageSource.resource(resId).tilingEnabled());
+ }
+ }*/
+ if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_panEnabled)) {
+ setPanEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_panEnabled, true));
+ }
+ if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_zoomEnabled)) {
+ setZoomEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_zoomEnabled, true));
+ }
+ if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_quickScaleEnabled)) {
+ setQuickScaleEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_quickScaleEnabled, true));
+ }
+ if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_tileBackgroundColor)) {
+ setTileBackgroundColor(typedAttr.getColor(styleable.SubsamplingScaleImageView_tileBackgroundColor, Color.argb(0, 0, 0, 0)));
+ }
+ typedAttr.recycle();
+ }
+
+ quickScaleThreshold = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, context.getResources().getDisplayMetrics());
+ }
+
+ public MySubsamplingScaleImageView(Context context) {
+ this(context, null);
+ }
+
+ /**
+ * Get the current preferred configuration for decoding bitmaps. {@link ImageDecoder} and {@link ImageRegionDecoder}
+ * instances can read this and use it when decoding images.
+ *
+ * @return the preferred bitmap configuration, or null if none has been set.
+ */
+ public static Bitmap.Config getPreferredBitmapConfig() {
+ return preferredBitmapConfig;
+ }
+
+ /**
+ * Set a global preferred bitmap config shared by all view instances and applied to new instances
+ * initialised after the call is made. This is a hint only; the bundled {@link ImageDecoder} and
+ * {@link ImageRegionDecoder} classes all respect this (except when they were constructed with
+ * an instance-specific config) but custom decoder classes will not.
+ *
+ * @param preferredBitmapConfig the bitmap configuration to be used by future instances of the view. Pass null to restore the default.
+ */
+ public static void setPreferredBitmapConfig(Bitmap.Config preferredBitmapConfig) {
+ MySubsamplingScaleImageView.preferredBitmapConfig = preferredBitmapConfig;
+ }
+
+ /**
+ * Sets the image orientation. It's best to call this before setting the image file or asset, because it may waste
+ * loading of tiles. However, this can be freely called at any time.
+ *
+ * @param orientation orientation to be set. See ORIENTATION_ static fields for valid values.
+ */
+ public final void setOrientation(int orientation) {
+ if (!VALID_ORIENTATIONS.contains(orientation)) {
+ throw new IllegalArgumentException("Invalid orientation: " + orientation);
+ }
+ this.orientation = orientation;
+ reset(false);
+ invalidate();
+ requestLayout();
+ }
+
+ /**
+ * Set the image source from a bitmap, resource, asset, file or other URI.
+ *
+ * @param imageSource Image source.
+ */
+ public final void setImage(@NonNull ImageSource imageSource) {
+ this.imageSource = imageSource;
+ setImage(imageSource, null, null);
+ }
+
+ /**
+ * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be
+ * displayed until the full size image is loaded, starting with a given orientation setting, scale and center.
+ * This is the best method to use when you want scale and center to be restored after screen orientation change;
+ * it avoids any redundant loading of tiles in the wrong orientation.
+ *
+ * You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)}
+ * on the imageSource object. The preview source will be ignored if you don't provide dimensions,
+ * and if you provide a bitmap for the full size image.
+ *
+ * @param imageSource Image source. Dimensions must be declared.
+ * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads.
+ * @param state State to be restored. Nullable.
+ */
+ public final void setImage(@NonNull ImageSource imageSource, ImageSource previewSource, ImageViewState state) {
+ //noinspection ConstantConditions
+ if (imageSource == null) {
+ throw new NullPointerException("imageSource must not be null");
+ }
+
+ reset(true);
+ if (state != null) {
+ restoreState(state);
+ }
+
+ if (previewSource != null) {
+ if (imageSource.getBitmap() != null) {
+ throw new IllegalArgumentException("Preview image cannot be used when a bitmap is provided for the main image");
+ }
+ if (imageSource.getSWidth() <= 0 || imageSource.getSHeight() <= 0) {
+ throw new IllegalArgumentException("Preview image cannot be used unless dimensions are provided for the main image");
+ }
+ this.sWidth = imageSource.getSWidth();
+ this.sHeight = imageSource.getSHeight();
+ this.pRegion = previewSource.getSRegion();
+ if (previewSource.getBitmap() != null) {
+ this.bitmapIsCached = previewSource.isCached();
+ onPreviewLoaded(previewSource.getBitmap());
+ } else {
+ Uri uri = previewSource.getUri();
+ if (uri == null && previewSource.getResource() != null) {
+ uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + previewSource.getResource());
+ }
+ MySubsamplingScaleImageView.BitmapLoadTask task = new MySubsamplingScaleImageView.BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, true, imageSource.getPassword(), imageSource.getVersion());
+ execute(task);
+ }
+ }
+
+ if (imageSource.getBitmap() != null && imageSource.getSRegion() != null) {
+ onImageLoaded(Bitmap.createBitmap(imageSource.getBitmap(), imageSource.getSRegion().left, imageSource.getSRegion().top, imageSource.getSRegion().width(), imageSource.getSRegion().height()), ORIENTATION_0, false);
+ } else if (imageSource.getBitmap() != null) {
+ onImageLoaded(imageSource.getBitmap(), ORIENTATION_0, imageSource.isCached());
+ } else {
+ sRegion = imageSource.getSRegion();
+ uri = imageSource.getUri();
+ if (uri == null && imageSource.getResource() != null) {
+ uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + imageSource.getResource());
+ }
+ //if (imageSource.getTile() || sRegion != null) {
+ Log.e(TAG, "setImage: 1 tile");
+ // Load the bitmap using tile decoding.
+ MySubsamplingScaleImageView.TilesInitTask task = new MySubsamplingScaleImageView.TilesInitTask(this, getContext(), regionDecoderFactory, uri, imageSource.getPassword(), imageSource.getVersion());
+ execute(task);
+ /*} else {
+ Log.e(TAG, "setImage: 2 bitmap");
+ // Load the bitmap as a single image.
+ MySubsamplingScaleImageView.BitmapLoadTask task = new MySubsamplingScaleImageView.BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false);
+ execute(task);
+ }*/
+ }
+ }
+
+ /**
+ * Reset all state before setting/changing image or setting new rotation.
+ */
+ private void reset(boolean newImage) {
+ debug("reset newImage=" + newImage);
+ scale = 0f;
+ scaleStart = 0f;
+ vTranslate = null;
+ vTranslateStart = null;
+ vTranslateBefore = null;
+ pendingScale = 0f;
+ sPendingCenter = null;
+ sRequestedCenter = null;
+ isZooming = false;
+ isPanning = false;
+ isQuickScaling = false;
+ maxTouchCount = 0;
+ fullImageSampleSize = 0;
+ vCenterStart = null;
+ vDistStart = 0;
+ quickScaleLastDistance = 0f;
+ quickScaleMoved = false;
+ quickScaleSCenter = null;
+ quickScaleVLastPoint = null;
+ quickScaleVStart = null;
+ anim = null;
+ satTemp = null;
+ matrix = null;
+ sRect = null;
+ if (newImage) {
+ uri = null;
+ decoderLock.writeLock().lock();
+ try {
+ if (decoder != null) {
+ decoder.recycle();
+ decoder = null;
+ }
+ } finally {
+ decoderLock.writeLock().unlock();
+ }
+ if (bitmap != null && !bitmapIsCached) {
+ bitmap.recycle();
+ }
+ if (bitmap != null && bitmapIsCached && onImageEventListener != null) {
+ onImageEventListener.onPreviewReleased();
+ }
+ sWidth = 0;
+ sHeight = 0;
+ sOrientation = 0;
+ sRegion = null;
+ pRegion = null;
+ readySent = false;
+ imageLoadedSent = false;
+ bitmap = null;
+ bitmapIsPreview = false;
+ bitmapIsCached = false;
+ }
+ if (tileMap != null) {
+ for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
+ for (MySubsamplingScaleImageView.Tile tile : tileMapEntry.getValue()) {
+ tile.visible = false;
+ if (tile.bitmap != null) {
+ tile.bitmap.recycle();
+ tile.bitmap = null;
+ }
+ }
+ }
+ tileMap = null;
+ }
+ setGestureDetector(getContext());
+ }
+
+ private void setGestureDetector(final Context context) {
+ this.detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
+
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
+ if (panEnabled && readySent && vTranslate != null && e1 != null && e2 != null && (Math.abs(e1.getX() - e2.getX()) > 50 || Math.abs(e1.getY() - e2.getY()) > 50) && (Math.abs(velocityX) > 500 || Math.abs(velocityY) > 500) && !isZooming) {
+ PointF vTranslateEnd = new PointF(vTranslate.x + (velocityX * 0.25f), vTranslate.y + (velocityY * 0.25f));
+ float sCenterXEnd = ((getWidth() / 2) - vTranslateEnd.x) / scale;
+ float sCenterYEnd = ((getHeight() / 2) - vTranslateEnd.y) / scale;
+ new MySubsamplingScaleImageView.AnimationBuilder(new PointF(sCenterXEnd, sCenterYEnd)).withEasing(EASE_OUT_QUAD).withPanLimited(false).withOrigin(ORIGIN_FLING).start();
+ return true;
+ }
+ return super.onFling(e1, e2, velocityX, velocityY);
+ }
+
+ @Override
+ public boolean onSingleTapConfirmed(MotionEvent e) {
+ performClick();
+ return true;
+ }
+
+ @Override
+ public boolean onDoubleTap(MotionEvent e) {
+ if (zoomEnabled && readySent && vTranslate != null) {
+ // Hacky solution for #15 - after a double tap the GestureDetector gets in a state
+ // where the next fling is ignored, so here we replace it with a new one.
+ setGestureDetector(context);
+ if (quickScaleEnabled) {
+ // Store quick scale params. This will become either a double tap zoom or a
+ // quick scale depending on whether the user swipes.
+ vCenterStart = new PointF(e.getX(), e.getY());
+ vTranslateStart = new PointF(vTranslate.x, vTranslate.y);
+ scaleStart = scale;
+ isQuickScaling = true;
+ isZooming = true;
+ quickScaleLastDistance = -1F;
+ quickScaleSCenter = viewToSourceCoord(vCenterStart);
+ quickScaleVStart = new PointF(e.getX(), e.getY());
+ quickScaleVLastPoint = new PointF(quickScaleSCenter.x, quickScaleSCenter.y);
+ quickScaleMoved = false;
+ // We need to get events in onTouchEvent after this.
+ return false;
+ } else {
+ // Start double tap zoom animation.
+ doubleTapZoom(viewToSourceCoord(new PointF(e.getX(), e.getY())), new PointF(e.getX(), e.getY()));
+ return true;
+ }
+ }
+ return super.onDoubleTapEvent(e);
+ }
+ });
+
+ singleDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
+ @Override
+ public boolean onSingleTapConfirmed(MotionEvent e) {
+ performClick();
+ return true;
+ }
+ });
+ }
+
+ /**
+ * On resize, preserve center and scale. Various behaviours are possible, override this method to use another.
+ */
+ @Override
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+ debug("onSizeChanged %dx%d -> %dx%d", oldw, oldh, w, h);
+ PointF sCenter = getCenter();
+ if (readySent && sCenter != null) {
+ this.anim = null;
+ this.pendingScale = scale;
+ this.sPendingCenter = sCenter;
+ }
+ }
+
+ /**
+ * Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is
+ * used. The image will scale within this box, not resizing the view as it is zoomed.
+ */
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
+ int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
+ int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
+ int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
+ boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY;
+ boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY;
+ int width = parentWidth;
+ int height = parentHeight;
+ if (sWidth > 0 && sHeight > 0) {
+ if (resizeWidth && resizeHeight) {
+ width = sWidth();
+ height = sHeight();
+ } else if (resizeHeight) {
+ height = (int) ((((double) sHeight() / (double) sWidth()) * width));
+ } else if (resizeWidth) {
+ width = (int) ((((double) sWidth() / (double) sHeight()) * height));
+ }
+ }
+ width = Math.max(width, getSuggestedMinimumWidth());
+ height = Math.max(height, getSuggestedMinimumHeight());
+ setMeasuredDimension(width, height);
+ }
+
+ /**
+ * Handle touch events. One finger pans, and two finger pinch and zoom plus panning.
+ */
+ @Override
+ public boolean onTouchEvent(@NonNull MotionEvent event) {
+ // During non-interruptible anims, ignore all touch events
+ if (anim != null && !anim.interruptible) {
+ requestDisallowInterceptTouchEvent(true);
+ return true;
+ } else {
+ if (anim != null && anim.listener != null) {
+ try {
+ anim.listener.onInterruptedByUser();
+ } catch (Exception e) {
+ Log.w(TAG, "Error thrown by animation listener", e);
+ }
+ }
+ anim = null;
+ }
+
+ // Abort if not ready
+ if (vTranslate == null) {
+ if (singleDetector != null) {
+ singleDetector.onTouchEvent(event);
+ }
+ return true;
+ }
+ // Detect flings, taps and double taps
+ if (!isQuickScaling && (detector == null || detector.onTouchEvent(event))) {
+ isZooming = false;
+ isPanning = false;
+ maxTouchCount = 0;
+ return true;
+ }
+
+ if (vTranslateStart == null) {
+ vTranslateStart = new PointF(0, 0);
+ }
+ if (vTranslateBefore == null) {
+ vTranslateBefore = new PointF(0, 0);
+ }
+ if (vCenterStart == null) {
+ vCenterStart = new PointF(0, 0);
+ }
+
+ // Store current values so we can send an event if they change
+ float scaleBefore = scale;
+ vTranslateBefore.set(vTranslate);
+
+ boolean handled = onTouchEventInternal(event);
+ sendStateChanged(scaleBefore, vTranslateBefore, ORIGIN_TOUCH);
+ return handled || super.onTouchEvent(event);
+ }
+
+ @SuppressWarnings("deprecation")
+ private boolean onTouchEventInternal(@NonNull MotionEvent event) {
+ int touchCount = event.getPointerCount();
+ switch (event.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ case MotionEvent.ACTION_POINTER_1_DOWN:
+ case MotionEvent.ACTION_POINTER_2_DOWN:
+ anim = null;
+ requestDisallowInterceptTouchEvent(true);
+ maxTouchCount = Math.max(maxTouchCount, touchCount);
+ if (touchCount >= 2) {
+ if (zoomEnabled) {
+ // Start pinch to zoom. Calculate distance between touch points and center point of the pinch.
+ float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1));
+ scaleStart = scale;
+ vDistStart = distance;
+ vTranslateStart.set(vTranslate.x, vTranslate.y);
+ vCenterStart.set((event.getX(0) + event.getX(1)) / 2, (event.getY(0) + event.getY(1)) / 2);
+ } else {
+ // Abort all gestures on second touch
+ maxTouchCount = 0;
+ }
+ // Cancel long click timer
+ handler.removeMessages(MESSAGE_LONG_CLICK);
+ } else if (!isQuickScaling) {
+ // Start one-finger pan
+ vTranslateStart.set(vTranslate.x, vTranslate.y);
+ vCenterStart.set(event.getX(), event.getY());
+
+ // Start long click timer
+ handler.sendEmptyMessageDelayed(MESSAGE_LONG_CLICK, 600);
+ }
+ return true;
+ case MotionEvent.ACTION_MOVE:
+ boolean consumed = false;
+ if (maxTouchCount > 0) {
+ if (touchCount >= 2) {
+ // Calculate new distance between touch points, to scale and pan relative to start values.
+ float vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1));
+ float vCenterEndX = (event.getX(0) + event.getX(1)) / 2;
+ float vCenterEndY = (event.getY(0) + event.getY(1)) / 2;
+
+ if (zoomEnabled && (distance(vCenterStart.x, vCenterEndX, vCenterStart.y, vCenterEndY) > 5 || Math.abs(vDistEnd - vDistStart) > 5 || isPanning)) {
+ isZooming = true;
+ isPanning = true;
+ consumed = true;
+
+ double previousScale = scale;
+ scale = Math.min(maxScale, (vDistEnd / vDistStart) * scaleStart);
+
+ if (scale <= minScale()) {
+ // Minimum scale reached so don't pan. Adjust start settings so any expand will zoom in.
+ vDistStart = vDistEnd;
+ scaleStart = minScale();
+ vCenterStart.set(vCenterEndX, vCenterEndY);
+ vTranslateStart.set(vTranslate);
+ } else if (panEnabled) {
+ // Translate to place the source image coordinate that was at the center of the pinch at the start
+ // at the center of the pinch now, to give simultaneous pan + zoom.
+ float vLeftStart = vCenterStart.x - vTranslateStart.x;
+ float vTopStart = vCenterStart.y - vTranslateStart.y;
+ float vLeftNow = vLeftStart * (scale / scaleStart);
+ float vTopNow = vTopStart * (scale / scaleStart);
+ vTranslate.x = vCenterEndX - vLeftNow;
+ vTranslate.y = vCenterEndY - vTopNow;
+ if ((previousScale * sHeight() < getHeight() && scale * sHeight() >= getHeight()) || (previousScale * sWidth() < getWidth() && scale * sWidth() >= getWidth())) {
+ fitToBounds(true);
+ vCenterStart.set(vCenterEndX, vCenterEndY);
+ vTranslateStart.set(vTranslate);
+ scaleStart = scale;
+ vDistStart = vDistEnd;
+ }
+ } else if (sRequestedCenter != null) {
+ // With a center specified from code, zoom around that point.
+ vTranslate.x = (getWidth() / 2) - (scale * sRequestedCenter.x);
+ vTranslate.y = (getHeight() / 2) - (scale * sRequestedCenter.y);
+ } else {
+ // With no requested center, scale around the image center.
+ vTranslate.x = (getWidth() / 2) - (scale * (sWidth() / 2));
+ vTranslate.y = (getHeight() / 2) - (scale * (sHeight() / 2));
+ }
+
+ fitToBounds(true);
+ refreshRequiredTiles(eagerLoadingEnabled);
+ }
+ } else if (isQuickScaling) {
+ // One finger zoom
+ // Stole Google's Magical Formula™ to make sure it feels the exact same
+ float dist = Math.abs(quickScaleVStart.y - event.getY()) * 2 + quickScaleThreshold;
+
+ if (quickScaleLastDistance == -1f) {
+ quickScaleLastDistance = dist;
+ }
+ boolean isUpwards = event.getY() > quickScaleVLastPoint.y;
+ quickScaleVLastPoint.set(0, event.getY());
+
+ float spanDiff = Math.abs(1 - (dist / quickScaleLastDistance)) * 0.5f;
+
+ if (spanDiff > 0.03f || quickScaleMoved) {
+ quickScaleMoved = true;
+
+ float multiplier = 1;
+ if (quickScaleLastDistance > 0) {
+ multiplier = isUpwards ? (1 + spanDiff) : (1 - spanDiff);
+ }
+
+ double previousScale = scale;
+ scale = Math.max(minScale(), Math.min(maxScale, scale * multiplier));
+
+ if (panEnabled) {
+ float vLeftStart = vCenterStart.x - vTranslateStart.x;
+ float vTopStart = vCenterStart.y - vTranslateStart.y;
+ float vLeftNow = vLeftStart * (scale / scaleStart);
+ float vTopNow = vTopStart * (scale / scaleStart);
+ vTranslate.x = vCenterStart.x - vLeftNow;
+ vTranslate.y = vCenterStart.y - vTopNow;
+ if ((previousScale * sHeight() < getHeight() && scale * sHeight() >= getHeight()) || (previousScale * sWidth() < getWidth() && scale * sWidth() >= getWidth())) {
+ fitToBounds(true);
+ vCenterStart.set(sourceToViewCoord(quickScaleSCenter));
+ vTranslateStart.set(vTranslate);
+ scaleStart = scale;
+ dist = 0;
+ }
+ } else if (sRequestedCenter != null) {
+ // With a center specified from code, zoom around that point.
+ vTranslate.x = (getWidth() / 2) - (scale * sRequestedCenter.x);
+ vTranslate.y = (getHeight() / 2) - (scale * sRequestedCenter.y);
+ } else {
+ // With no requested center, scale around the image center.
+ vTranslate.x = (getWidth() / 2) - (scale * (sWidth() / 2));
+ vTranslate.y = (getHeight() / 2) - (scale * (sHeight() / 2));
+ }
+ }
+
+ quickScaleLastDistance = dist;
+
+ fitToBounds(true);
+ refreshRequiredTiles(eagerLoadingEnabled);
+
+ consumed = true;
+ } else if (!isZooming) {
+ // One finger pan - translate the image. We do this calculation even with pan disabled so click
+ // and long click behaviour is preserved.
+ float dx = Math.abs(event.getX() - vCenterStart.x);
+ float dy = Math.abs(event.getY() - vCenterStart.y);
+
+ //On the Samsung S6 long click event does not work, because the dx > 5 usually true
+ float offset = density * 5;
+ if (dx > offset || dy > offset || isPanning) {
+ consumed = true;
+ vTranslate.x = vTranslateStart.x + (event.getX() - vCenterStart.x);
+ vTranslate.y = vTranslateStart.y + (event.getY() - vCenterStart.y);
+
+ float lastX = vTranslate.x;
+ float lastY = vTranslate.y;
+ fitToBounds(true);
+ boolean atXEdge = lastX != vTranslate.x;
+ boolean atYEdge = lastY != vTranslate.y;
+ boolean edgeXSwipe = atXEdge && dx > dy && !isPanning;
+ boolean edgeYSwipe = atYEdge && dy > dx && !isPanning;
+ boolean yPan = lastY == vTranslate.y && dy > offset * 3;
+ if (!edgeXSwipe && !edgeYSwipe && (!atXEdge || !atYEdge || yPan || isPanning)) {
+ isPanning = true;
+ } else if (dx > offset || dy > offset) {
+ // Haven't panned the image, and we're at the left or right edge. Switch to page swipe.
+ maxTouchCount = 0;
+ handler.removeMessages(MESSAGE_LONG_CLICK);
+ requestDisallowInterceptTouchEvent(false);
+ }
+ if (!panEnabled) {
+ vTranslate.x = vTranslateStart.x;
+ vTranslate.y = vTranslateStart.y;
+ requestDisallowInterceptTouchEvent(false);
+ }
+
+ refreshRequiredTiles(eagerLoadingEnabled);
+ }
+ }
+ }
+ if (consumed) {
+ handler.removeMessages(MESSAGE_LONG_CLICK);
+ invalidate();
+ return true;
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_POINTER_UP:
+ case MotionEvent.ACTION_POINTER_2_UP:
+ handler.removeMessages(MESSAGE_LONG_CLICK);
+ if (isQuickScaling) {
+ isQuickScaling = false;
+ if (!quickScaleMoved) {
+ doubleTapZoom(quickScaleSCenter, vCenterStart);
+ }
+ }
+ if (maxTouchCount > 0 && (isZooming || isPanning)) {
+ if (isZooming && touchCount == 2) {
+ // Convert from zoom to pan with remaining touch
+ isPanning = true;
+ vTranslateStart.set(vTranslate.x, vTranslate.y);
+ if (event.getActionIndex() == 1) {
+ vCenterStart.set(event.getX(0), event.getY(0));
+ } else {
+ vCenterStart.set(event.getX(1), event.getY(1));
+ }
+ }
+ if (touchCount < 3) {
+ // End zooming when only one touch point
+ isZooming = false;
+ }
+ if (touchCount < 2) {
+ // End panning when no touch points
+ isPanning = false;
+ maxTouchCount = 0;
+ }
+ // Trigger load of tiles now required
+ refreshRequiredTiles(true);
+ return true;
+ }
+ if (touchCount == 1) {
+ isZooming = false;
+ isPanning = false;
+ maxTouchCount = 0;
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
+ ViewParent parent = getParent();
+ if (parent != null) {
+ parent.requestDisallowInterceptTouchEvent(disallowIntercept);
+ }
+ }
+
+ /**
+ * Double tap zoom handler triggered from gesture detector or on touch, depending on whether
+ * quick scale is enabled.
+ */
+ private void doubleTapZoom(PointF sCenter, PointF vFocus) {
+ if (!panEnabled) {
+ if (sRequestedCenter != null) {
+ // With a center specified from code, zoom around that point.
+ sCenter.x = sRequestedCenter.x;
+ sCenter.y = sRequestedCenter.y;
+ } else {
+ // With no requested center, scale around the image center.
+ sCenter.x = sWidth() / 2;
+ sCenter.y = sHeight() / 2;
+ }
+ }
+ float doubleTapZoomScale = Math.min(maxScale, MySubsamplingScaleImageView.this.doubleTapZoomScale);
+ boolean zoomIn = (scale <= doubleTapZoomScale * 0.9) || scale == minScale;
+ float targetScale = zoomIn ? doubleTapZoomScale : minScale();
+ if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER_IMMEDIATE) {
+ setScaleAndCenter(targetScale, sCenter);
+ } else if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER || !zoomIn || !panEnabled) {
+ new MySubsamplingScaleImageView.AnimationBuilder(targetScale, sCenter).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start();
+ } else if (doubleTapZoomStyle == ZOOM_FOCUS_FIXED) {
+ new MySubsamplingScaleImageView.AnimationBuilder(targetScale, sCenter, vFocus).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start();
+ }
+ invalidate();
+ }
+
+ /**
+ * Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate
+ * the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded.
+ */
+ @Override
+ protected void onDraw(Canvas canvas) {
+ super.onDraw(canvas);
+ createPaints();
+
+ // If image or view dimensions are not known yet, abort.
+ if (sWidth == 0 || sHeight == 0 || getWidth() == 0 || getHeight() == 0) {
+ return;
+ }
+
+ // When using tiles, on first render with no tile map ready, initialise it and kick off async base image loading.
+ if (tileMap == null && decoder != null) {
+ initialiseBaseLayer(getMaxBitmapDimensions(canvas));
+ }
+
+ // If image has been loaded or supplied as a bitmap, onDraw may be the first time the view has
+ // dimensions and therefore the first opportunity to set scale and translate. If this call returns
+ // false there is nothing to be drawn so return immediately.
+ if (!checkReady()) {
+ return;
+ }
+
+ // Set scale and translate before draw.
+ preDraw();
+
+ // If animating scale, calculate current scale and center with easing equations
+ if (anim != null && anim.vFocusStart != null) {
+ // Store current values so we can send an event if they change
+ float scaleBefore = scale;
+ if (vTranslateBefore == null) {
+ vTranslateBefore = new PointF(0, 0);
+ }
+ vTranslateBefore.set(vTranslate);
+
+ long scaleElapsed = System.currentTimeMillis() - anim.time;
+ boolean finished = scaleElapsed > anim.duration;
+ scaleElapsed = Math.min(scaleElapsed, anim.duration);
+ scale = ease(anim.easing, scaleElapsed, anim.scaleStart, anim.scaleEnd - anim.scaleStart, anim.duration);
+
+ // Apply required animation to the focal point
+ float vFocusNowX = ease(anim.easing, scaleElapsed, anim.vFocusStart.x, anim.vFocusEnd.x - anim.vFocusStart.x, anim.duration);
+ float vFocusNowY = ease(anim.easing, scaleElapsed, anim.vFocusStart.y, anim.vFocusEnd.y - anim.vFocusStart.y, anim.duration);
+ // Find out where the focal point is at this scale and adjust its position to follow the animation path
+ vTranslate.x -= sourceToViewX(anim.sCenterEnd.x) - vFocusNowX;
+ vTranslate.y -= sourceToViewY(anim.sCenterEnd.y) - vFocusNowY;
+
+ // For translate anims, showing the image non-centered is never allowed, for scaling anims it is during the animation.
+ fitToBounds(finished || (anim.scaleStart == anim.scaleEnd));
+ sendStateChanged(scaleBefore, vTranslateBefore, anim.origin);
+ refreshRequiredTiles(finished);
+ if (finished) {
+ if (anim.listener != null) {
+ try {
+ anim.listener.onComplete();
+ } catch (Exception e) {
+ Log.w(TAG, "Error thrown by animation listener", e);
+ }
+ }
+ anim = null;
+ }
+ invalidate();
+ }
+
+ if (tileMap != null && isBaseLayerReady()) {
+
+ // Optimum sample size for current scale
+ int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale));
+
+ // First check for missing tiles - if there are any we need the base layer underneath to avoid gaps
+ boolean hasMissingTiles = false;
+ for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
+ if (tileMapEntry.getKey() == sampleSize) {
+ for (MySubsamplingScaleImageView.Tile tile : tileMapEntry.getValue()) {
+ if (tile.visible && (tile.loading || tile.bitmap == null)) {
+ hasMissingTiles = true;
+ }
+ }
+ }
+ }
+
+ // Render all loaded tiles. LinkedHashMap used for bottom up rendering - lower res tiles underneath.
+ for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
+ if (tileMapEntry.getKey() == sampleSize || hasMissingTiles) {
+ for (MySubsamplingScaleImageView.Tile tile : tileMapEntry.getValue()) {
+ sourceToViewRect(tile.sRect, tile.vRect);
+ if (!tile.loading && tile.bitmap != null) {
+ if (tileBgPaint != null) {
+ canvas.drawRect(tile.vRect, tileBgPaint);
+ }
+ if (matrix == null) {
+ matrix = new Matrix();
+ }
+ matrix.reset();
+ setMatrixArray(srcArray, 0, 0, tile.bitmap.getWidth(), 0, tile.bitmap.getWidth(), tile.bitmap.getHeight(), 0, tile.bitmap.getHeight());
+ if (getRequiredRotation() == ORIENTATION_0) {
+ setMatrixArray(dstArray, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom);
+ } else if (getRequiredRotation() == ORIENTATION_90) {
+ setMatrixArray(dstArray, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top);
+ } else if (getRequiredRotation() == ORIENTATION_180) {
+ setMatrixArray(dstArray, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top);
+ } else if (getRequiredRotation() == ORIENTATION_270) {
+ setMatrixArray(dstArray, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom);
+ }
+ matrix.setPolyToPoly(srcArray, 0, dstArray, 0, 4);
+ canvas.drawBitmap(tile.bitmap, matrix, bitmapPaint);
+ if (debug) {
+ canvas.drawRect(tile.vRect, debugLinePaint);
+ }
+ } else if (tile.loading && debug) {
+ canvas.drawText("LOADING", tile.vRect.left + px(5), tile.vRect.top + px(35), debugTextPaint);
+ }
+ if (tile.visible && debug) {
+ canvas.drawText("ISS " + tile.sampleSize + " RECT " + tile.sRect.top + "," + tile.sRect.left + "," + tile.sRect.bottom + "," + tile.sRect.right, tile.vRect.left + px(5), tile.vRect.top + px(15), debugTextPaint);
+ }
+ }
+ }
+ }
+
+ } else if (bitmap != null) {
+
+ float xScale = scale, yScale = scale;
+ if (bitmapIsPreview) {
+ xScale = scale * ((float) sWidth / bitmap.getWidth());
+ yScale = scale * ((float) sHeight / bitmap.getHeight());
+ }
+
+ if (matrix == null) {
+ matrix = new Matrix();
+ }
+ matrix.reset();
+ matrix.postScale(xScale, yScale);
+ matrix.postRotate(getRequiredRotation());
+ matrix.postTranslate(vTranslate.x, vTranslate.y);
+
+ if (getRequiredRotation() == ORIENTATION_180) {
+ matrix.postTranslate(scale * sWidth, scale * sHeight);
+ } else if (getRequiredRotation() == ORIENTATION_90) {
+ matrix.postTranslate(scale * sHeight, 0);
+ } else if (getRequiredRotation() == ORIENTATION_270) {
+ matrix.postTranslate(0, scale * sWidth);
+ }
+
+ if (tileBgPaint != null) {
+ if (sRect == null) {
+ sRect = new RectF();
+ }
+ sRect.set(0f, 0f, bitmapIsPreview ? bitmap.getWidth() : sWidth, bitmapIsPreview ? bitmap.getHeight() : sHeight);
+ matrix.mapRect(sRect);
+ canvas.drawRect(sRect, tileBgPaint);
+ }
+ canvas.drawBitmap(bitmap, matrix, bitmapPaint);
+
+ }
+
+ if (debug) {
+ canvas.drawText("Scale: " + String.format(Locale.ENGLISH, "%.2f", scale) + " (" + String.format(Locale.ENGLISH, "%.2f", minScale()) + " - " + String.format(Locale.ENGLISH, "%.2f", maxScale) + ")", px(5), px(15), debugTextPaint);
+ canvas.drawText("Translate: " + String.format(Locale.ENGLISH, "%.2f", vTranslate.x) + ":" + String.format(Locale.ENGLISH, "%.2f", vTranslate.y), px(5), px(30), debugTextPaint);
+ PointF center = getCenter();
+ //noinspection ConstantConditions
+ canvas.drawText("Source center: " + String.format(Locale.ENGLISH, "%.2f", center.x) + ":" + String.format(Locale.ENGLISH, "%.2f", center.y), px(5), px(45), debugTextPaint);
+ if (anim != null) {
+ PointF vCenterStart = sourceToViewCoord(anim.sCenterStart);
+ PointF vCenterEndRequested = sourceToViewCoord(anim.sCenterEndRequested);
+ PointF vCenterEnd = sourceToViewCoord(anim.sCenterEnd);
+ //noinspection ConstantConditions
+ canvas.drawCircle(vCenterStart.x, vCenterStart.y, px(10), debugLinePaint);
+ debugLinePaint.setColor(Color.RED);
+ //noinspection ConstantConditions
+ canvas.drawCircle(vCenterEndRequested.x, vCenterEndRequested.y, px(20), debugLinePaint);
+ debugLinePaint.setColor(Color.BLUE);
+ //noinspection ConstantConditions
+ canvas.drawCircle(vCenterEnd.x, vCenterEnd.y, px(25), debugLinePaint);
+ debugLinePaint.setColor(Color.CYAN);
+ canvas.drawCircle(getWidth() / 2, getHeight() / 2, px(30), debugLinePaint);
+ }
+ if (vCenterStart != null) {
+ debugLinePaint.setColor(Color.RED);
+ canvas.drawCircle(vCenterStart.x, vCenterStart.y, px(20), debugLinePaint);
+ }
+ if (quickScaleSCenter != null) {
+ debugLinePaint.setColor(Color.BLUE);
+ canvas.drawCircle(sourceToViewX(quickScaleSCenter.x), sourceToViewY(quickScaleSCenter.y), px(35), debugLinePaint);
+ }
+ if (quickScaleVStart != null && isQuickScaling) {
+ debugLinePaint.setColor(Color.CYAN);
+ canvas.drawCircle(quickScaleVStart.x, quickScaleVStart.y, px(30), debugLinePaint);
+ }
+ debugLinePaint.setColor(Color.MAGENTA);
+ }
+ }
+
+ /**
+ * Helper method for setting the values of a tile matrix array.
+ */
+ private void setMatrixArray(float[] array, float f0, float f1, float f2, float f3, float f4, float f5, float f6, float f7) {
+ array[0] = f0;
+ array[1] = f1;
+ array[2] = f2;
+ array[3] = f3;
+ array[4] = f4;
+ array[5] = f5;
+ array[6] = f6;
+ array[7] = f7;
+ }
+
+ /**
+ * Checks whether the base layer of tiles or full size bitmap is ready.
+ */
+ private boolean isBaseLayerReady() {
+ if (bitmap != null && !bitmapIsPreview) {
+ return true;
+ } else if (tileMap != null) {
+ boolean baseLayerReady = true;
+ for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
+ if (tileMapEntry.getKey() == fullImageSampleSize) {
+ for (MySubsamplingScaleImageView.Tile tile : tileMapEntry.getValue()) {
+ if (tile.loading || tile.bitmap == null) {
+ baseLayerReady = false;
+ }
+ }
+ }
+ }
+ return baseLayerReady;
+ }
+ return false;
+ }
+
+ /**
+ * Check whether view and image dimensions are known and either a preview, full size image or
+ * base layer tiles are loaded. First time, send ready event to listener. The next draw will
+ * display an image.
+ */
+ private boolean checkReady() {
+ boolean ready = getWidth() > 0 && getHeight() > 0 && sWidth > 0 && sHeight > 0 && (bitmap != null || isBaseLayerReady());
+ if (!readySent && ready) {
+ preDraw();
+ readySent = true;
+ onReady();
+ if (onImageEventListener != null) {
+ onImageEventListener.onReady();
+ }
+ }
+ return ready;
+ }
+
+ /**
+ * Check whether either the full size bitmap or base layer tiles are loaded. First time, send image
+ * loaded event to listener.
+ */
+ private boolean checkImageLoaded() {
+ boolean imageLoaded = isBaseLayerReady();
+ if (!imageLoadedSent && imageLoaded) {
+ preDraw();
+ imageLoadedSent = true;
+ onImageLoaded();
+ if (onImageEventListener != null) {
+ onImageEventListener.onImageLoaded();
+ }
+ }
+ return imageLoaded;
+ }
+
+ /**
+ * Creates Paint objects once when first needed.
+ */
+ private void createPaints() {
+ if (bitmapPaint == null) {
+ bitmapPaint = new Paint();
+ bitmapPaint.setAntiAlias(true);
+ bitmapPaint.setFilterBitmap(true);
+ bitmapPaint.setDither(true);
+ }
+ if ((debugTextPaint == null || debugLinePaint == null) && debug) {
+ debugTextPaint = new Paint();
+ debugTextPaint.setTextSize(px(12));
+ debugTextPaint.setColor(Color.MAGENTA);
+ debugTextPaint.setStyle(Style.FILL);
+ debugLinePaint = new Paint();
+ debugLinePaint.setColor(Color.MAGENTA);
+ debugLinePaint.setStyle(Style.STROKE);
+ debugLinePaint.setStrokeWidth(px(1));
+ }
+ }
+
+ /**
+ * Called on first draw when the view has dimensions. Calculates the initial sample size and starts async loading of
+ * the base layer image - the whole source subsampled as necessary.
+ */
+ private synchronized void initialiseBaseLayer(@NonNull Point maxTileDimensions) {
+ debug("initialiseBaseLayer maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y);
+
+ satTemp = new MySubsamplingScaleImageView.ScaleAndTranslate(0f, new PointF(0, 0));
+ fitToBounds(true, satTemp);
+
+ // Load double resolution - next level will be split into four tiles and at the center all four are required,
+ // so don't bother with tiling until the next level 16 tiles are needed.
+ fullImageSampleSize = calculateInSampleSize(satTemp.scale);
+ if (fullImageSampleSize > 1) {
+ fullImageSampleSize /= 2;
+ }
+
+ if (fullImageSampleSize == 1 && sRegion == null && sWidth() < maxTileDimensions.x && sHeight() < maxTileDimensions.y) {
+
+ // Whole image is required at native resolution, and is smaller than the canvas max bitmap size.
+ // Use BitmapDecoder for better image support.
+ decoder.recycle();
+ decoder = null;
+ MySubsamplingScaleImageView.BitmapLoadTask task = new MySubsamplingScaleImageView.BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false, imageSource.getPassword(), imageSource.getVersion());
+ execute(task);
+
+ } else {
+
+ initialiseTileMap(maxTileDimensions);
+
+ List baseGrid = tileMap.get(fullImageSampleSize);
+ for (MySubsamplingScaleImageView.Tile baseTile : baseGrid) {
+ MySubsamplingScaleImageView.TileLoadTask task = new MySubsamplingScaleImageView.TileLoadTask(this, decoder, baseTile);
+ execute(task);
+ }
+ refreshRequiredTiles(true);
+
+ }
+
+ }
+
+ /**
+ * Loads the optimum tiles for display at the current scale and translate, so the screen can be filled with tiles
+ * that are at least as high resolution as the screen. Frees up bitmaps that are now off the screen.
+ *
+ * @param load Whether to load the new tiles needed. Use false while scrolling/panning for performance.
+ */
+ private void refreshRequiredTiles(boolean load) {
+ if (decoder == null || tileMap == null) {
+ return;
+ }
+
+ int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale));
+
+ // Load tiles of the correct sample size that are on screen. Discard tiles off screen, and those that are higher
+ // resolution than required, or lower res than required but not the base layer, so the base layer is always present.
+ for (Map.Entry> tileMapEntry : tileMap.entrySet()) {
+ for (MySubsamplingScaleImageView.Tile tile : tileMapEntry.getValue()) {
+ if (tile.sampleSize < sampleSize || (tile.sampleSize > sampleSize && tile.sampleSize != fullImageSampleSize)) {
+ tile.visible = false;
+ if (tile.bitmap != null) {
+ tile.bitmap.recycle();
+ tile.bitmap = null;
+ }
+ }
+ if (tile.sampleSize == sampleSize) {
+ if (tileVisible(tile)) {
+ tile.visible = true;
+ if (!tile.loading && tile.bitmap == null && load) {
+ MySubsamplingScaleImageView.TileLoadTask task = new MySubsamplingScaleImageView.TileLoadTask(this, decoder, tile);
+ execute(task);
+ }
+ } else if (tile.sampleSize != fullImageSampleSize) {
+ tile.visible = false;
+ if (tile.bitmap != null) {
+ tile.bitmap.recycle();
+ tile.bitmap = null;
+ }
+ }
+ } else if (tile.sampleSize == fullImageSampleSize) {
+ tile.visible = true;
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Determine whether tile is visible.
+ */
+ private boolean tileVisible(MySubsamplingScaleImageView.Tile tile) {
+ float sVisLeft = viewToSourceX(0),
+ sVisRight = viewToSourceX(getWidth()),
+ sVisTop = viewToSourceY(0),
+ sVisBottom = viewToSourceY(getHeight());
+ return !(sVisLeft > tile.sRect.right || tile.sRect.left > sVisRight || sVisTop > tile.sRect.bottom || tile.sRect.top > sVisBottom);
+ }
+
+ /**
+ * Sets scale and translate ready for the next draw.
+ */
+ private void preDraw() {
+ if (getWidth() == 0 || getHeight() == 0 || sWidth <= 0 || sHeight <= 0) {
+ return;
+ }
+
+ // If waiting to translate to new center position, set translate now
+ if (sPendingCenter != null && pendingScale != null) {
+ scale = pendingScale;
+ if (vTranslate == null) {
+ vTranslate = new PointF();
+ }
+ vTranslate.x = (getWidth() / 2) - (scale * sPendingCenter.x);
+ vTranslate.y = (getHeight() / 2) - (scale * sPendingCenter.y);
+ sPendingCenter = null;
+ pendingScale = null;
+ fitToBounds(true);
+ refreshRequiredTiles(true);
+ }
+
+ // On first display of base image set up position, and in other cases make sure scale is correct.
+ fitToBounds(false);
+ }
+
+ /**
+ * Calculates sample size to fit the source image in given bounds.
+ */
+ private int calculateInSampleSize(float scale) {
+ if (minimumTileDpi > 0) {
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ float averageDpi = (metrics.xdpi + metrics.ydpi) / 2;
+ scale = (minimumTileDpi / averageDpi) * scale;
+ }
+
+ int reqWidth = (int) (sWidth() * scale);
+ int reqHeight = (int) (sHeight() * scale);
+
+ // Raw height and width of image
+ int inSampleSize = 1;
+ if (reqWidth == 0 || reqHeight == 0) {
+ return 32;
+ }
+
+ if (sHeight() > reqHeight || sWidth() > reqWidth) {
+
+ // Calculate ratios of height and width to requested height and width
+ final int heightRatio = Math.round((float) sHeight() / (float) reqHeight);
+ final int widthRatio = Math.round((float) sWidth() / (float) reqWidth);
+
+ // Choose the smallest ratio as inSampleSize value, this will guarantee
+ // a final image with both dimensions larger than or equal to the
+ // requested height and width.
+ inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
+ }
+
+ // We want the actual sample size that will be used, so round down to nearest power of 2.
+ int power = 1;
+ while (power * 2 < inSampleSize) {
+ power = power * 2;
+ }
+
+ return power;
+ }
+
+ /**
+ * Adjusts hypothetical future scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale
+ * is set so one dimension fills the view and the image is centered on the other dimension. Used to calculate what the target of an
+ * animation should be.
+ *
+ * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached.
+ * @param sat The scale we want and the translation we're aiming for. The values are adjusted to be valid.
+ */
+ private void fitToBounds(boolean center, MySubsamplingScaleImageView.ScaleAndTranslate sat) {
+ if (panLimit == PAN_LIMIT_OUTSIDE && isReady()) {
+ center = false;
+ }
+
+ PointF vTranslate = sat.vTranslate;
+ float scale = limitedScale(sat.scale);
+ float scaleWidth = scale * sWidth();
+ float scaleHeight = scale * sHeight();
+
+ if (panLimit == PAN_LIMIT_CENTER && isReady()) {
+ vTranslate.x = Math.max(vTranslate.x, getWidth() / 2 - scaleWidth);
+ vTranslate.y = Math.max(vTranslate.y, getHeight() / 2 - scaleHeight);
+ } else if (center) {
+ vTranslate.x = Math.max(vTranslate.x, getWidth() - scaleWidth);
+ vTranslate.y = Math.max(vTranslate.y, getHeight() - scaleHeight);
+ } else {
+ vTranslate.x = Math.max(vTranslate.x, -scaleWidth);
+ vTranslate.y = Math.max(vTranslate.y, -scaleHeight);
+ }
+
+ // Asymmetric padding adjustments
+ float xPaddingRatio = getPaddingLeft() > 0 || getPaddingRight() > 0 ? getPaddingLeft() / (float) (getPaddingLeft() + getPaddingRight()) : 0.5f;
+ float yPaddingRatio = getPaddingTop() > 0 || getPaddingBottom() > 0 ? getPaddingTop() / (float) (getPaddingTop() + getPaddingBottom()) : 0.5f;
+
+ float maxTx;
+ float maxTy;
+ if (panLimit == PAN_LIMIT_CENTER && isReady()) {
+ maxTx = Math.max(0, getWidth() / 2);
+ maxTy = Math.max(0, getHeight() / 2);
+ } else if (center) {
+ maxTx = Math.max(0, (getWidth() - scaleWidth) * xPaddingRatio);
+ maxTy = Math.max(0, (getHeight() - scaleHeight) * yPaddingRatio);
+ } else {
+ maxTx = Math.max(0, getWidth());
+ maxTy = Math.max(0, getHeight());
+ }
+
+ vTranslate.x = Math.min(vTranslate.x, maxTx);
+ vTranslate.y = Math.min(vTranslate.y, maxTy);
+
+ sat.scale = scale;
+ }
+
+ /**
+ * Adjusts current scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale
+ * is set so one dimension fills the view and the image is centered on the other dimension.
+ *
+ * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached.
+ */
+ private void fitToBounds(boolean center) {
+ boolean init = false;
+ if (vTranslate == null) {
+ init = true;
+ vTranslate = new PointF(0, 0);
+ }
+ if (satTemp == null) {
+ satTemp = new MySubsamplingScaleImageView.ScaleAndTranslate(0, new PointF(0, 0));
+ }
+ satTemp.scale = scale;
+ satTemp.vTranslate.set(vTranslate);
+ fitToBounds(center, satTemp);
+ scale = satTemp.scale;
+ vTranslate.set(satTemp.vTranslate);
+ if (init && minimumScaleType != SCALE_TYPE_START) {
+ vTranslate.set(vTranslateForSCenter(sWidth() / 2, sHeight() / 2, scale));
+ }
+ }
+
+ /**
+ * Once source image and view dimensions are known, creates a map of sample size to tile grid.
+ */
+ private void initialiseTileMap(Point maxTileDimensions) {
+ debug("initialiseTileMap maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y);
+ this.tileMap = new LinkedHashMap<>();
+ int sampleSize = fullImageSampleSize;
+ int xTiles = 1;
+ int yTiles = 1;
+ while (true) {
+ int sTileWidth = sWidth() / xTiles;
+ int sTileHeight = sHeight() / yTiles;
+ int subTileWidth = sTileWidth / sampleSize;
+ int subTileHeight = sTileHeight / sampleSize;
+ while (subTileWidth + xTiles + 1 > maxTileDimensions.x || (subTileWidth > getWidth() * 1.25 && sampleSize < fullImageSampleSize)) {
+ xTiles += 1;
+ sTileWidth = sWidth() / xTiles;
+ subTileWidth = sTileWidth / sampleSize;
+ }
+ while (subTileHeight + yTiles + 1 > maxTileDimensions.y || (subTileHeight > getHeight() * 1.25 && sampleSize < fullImageSampleSize)) {
+ yTiles += 1;
+ sTileHeight = sHeight() / yTiles;
+ subTileHeight = sTileHeight / sampleSize;
+ }
+ List tileGrid = new ArrayList<>(xTiles * yTiles);
+ for (int x = 0; x < xTiles; x++) {
+ for (int y = 0; y < yTiles; y++) {
+ MySubsamplingScaleImageView.Tile tile = new MySubsamplingScaleImageView.Tile();
+ tile.sampleSize = sampleSize;
+ tile.visible = sampleSize == fullImageSampleSize;
+ tile.sRect = new Rect(
+ x * sTileWidth,
+ y * sTileHeight,
+ x == xTiles - 1 ? sWidth() : (x + 1) * sTileWidth,
+ y == yTiles - 1 ? sHeight() : (y + 1) * sTileHeight
+ );
+ tile.vRect = new Rect(0, 0, 0, 0);
+ tile.fileSRect = new Rect(tile.sRect);
+ tileGrid.add(tile);
+ }
+ }
+ tileMap.put(sampleSize, tileGrid);
+ if (sampleSize == 1) {
+ break;
+ } else {
+ sampleSize /= 2;
+ }
+ }
+ }
+
+ /**
+ * Async task used to get image details without blocking the UI thread.
+ */
+ private static class TilesInitTask extends AsyncTask {
+ private final WeakReference viewRef;
+ private final WeakReference contextRef;
+ private final WeakReference> decoderFactoryRef;
+ private final Uri source;
+ private final char[] password;
+ private final int version;
+ private ImageRegionDecoder decoder;
+ private Exception exception;
+
+ TilesInitTask(MySubsamplingScaleImageView view, Context context, DecoderFactory extends ImageRegionDecoder> decoderFactory, Uri source, char[] password, int version) {
+ this.viewRef = new WeakReference<>(view);
+ this.contextRef = new WeakReference<>(context);
+ this.decoderFactoryRef = new WeakReference<>(decoderFactory);
+ this.source = source;
+ this.password = password;
+ this.version = version;
+ }
+
+ @Override
+ protected int[] doInBackground(Void... params) {
+ try {
+ String sourceUri = source.toString();
+ Context context = contextRef.get();
+ DecoderFactory extends ImageRegionDecoder> decoderFactory = decoderFactoryRef.get();
+ MySubsamplingScaleImageView view = viewRef.get();
+ if (context != null && decoderFactory != null && view != null) {
+ view.debug("TilesInitTask.doInBackground");
+ decoder = decoderFactory.make();
+ Point dimensions = decoder.init(context, source, password, version);
+ int sWidth = dimensions.x;
+ int sHeight = dimensions.y;
+ int exifOrientation = view.getExifOrientation(context, sourceUri);
+ if (view.sRegion != null) {
+ view.sRegion.left = Math.max(0, view.sRegion.left);
+ view.sRegion.top = Math.max(0, view.sRegion.top);
+ view.sRegion.right = Math.min(sWidth, view.sRegion.right);
+ view.sRegion.bottom = Math.min(sHeight, view.sRegion.bottom);
+ sWidth = view.sRegion.width();
+ sHeight = view.sRegion.height();
+ }
+ return new int[]{sWidth, sHeight, exifOrientation};
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to initialise bitmap decoder", e);
+ this.exception = e;
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(int[] xyo) {
+ final MySubsamplingScaleImageView view = viewRef.get();
+ if (view != null) {
+ if (decoder != null && xyo != null && xyo.length == 3) {
+ view.onTilesInited(decoder, xyo[0], xyo[1], xyo[2]);
+ } else if (exception != null && view.onImageEventListener != null) {
+ view.onImageEventListener.onImageLoadError(exception);
+ }
+ }
+ }
+ }
+
+ /**
+ * Called by worker task when decoder is ready and image size and EXIF orientation is known.
+ */
+ private synchronized void onTilesInited(ImageRegionDecoder decoder, int sWidth, int sHeight, int sOrientation) {
+ debug("onTilesInited sWidth=%d, sHeight=%d, sOrientation=%d", sWidth, sHeight, orientation);
+ // If actual dimensions don't match the declared size, reset everything.
+ if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != sWidth || this.sHeight != sHeight)) {
+ reset(false);
+ if (bitmap != null) {
+ if (!bitmapIsCached) {
+ bitmap.recycle();
+ }
+ bitmap = null;
+ if (onImageEventListener != null && bitmapIsCached) {
+ onImageEventListener.onPreviewReleased();
+ }
+ bitmapIsPreview = false;
+ bitmapIsCached = false;
+ }
+ }
+ this.decoder = decoder;
+ this.sWidth = sWidth;
+ this.sHeight = sHeight;
+ this.sOrientation = sOrientation;
+ checkReady();
+ if (!checkImageLoaded() && maxTileWidth > 0 && maxTileWidth != TILE_SIZE_AUTO && maxTileHeight > 0 && maxTileHeight != TILE_SIZE_AUTO && getWidth() > 0 && getHeight() > 0) {
+ initialiseBaseLayer(new Point(maxTileWidth, maxTileHeight));
+ }
+ invalidate();
+ requestLayout();
+ }
+
+ /**
+ * Async task used to load images without blocking the UI thread.
+ */
+ private static class TileLoadTask extends AsyncTask {
+ private final WeakReference viewRef;
+ private final WeakReference decoderRef;
+ private final WeakReference tileRef;
+ private Exception exception;
+
+ TileLoadTask(MySubsamplingScaleImageView view, ImageRegionDecoder decoder, MySubsamplingScaleImageView.Tile tile) {
+ this.viewRef = new WeakReference<>(view);
+ this.decoderRef = new WeakReference<>(decoder);
+ this.tileRef = new WeakReference<>(tile);
+ tile.loading = true;
+ }
+
+ @Override
+ protected Bitmap doInBackground(Void... params) {
+ try {
+ MySubsamplingScaleImageView view = viewRef.get();
+ ImageRegionDecoder decoder = decoderRef.get();
+ MySubsamplingScaleImageView.Tile tile = tileRef.get();
+ if (decoder != null && tile != null && view != null && decoder.isReady() && tile.visible) {
+ view.debug("TileLoadTask.doInBackground, tile.sRect=%s, tile.sampleSize=%d", tile.sRect, tile.sampleSize);
+ view.decoderLock.readLock().lock();
+ try {
+ if (decoder.isReady()) {
+ // Update tile's file sRect according to rotation
+ view.fileSRect(tile.sRect, tile.fileSRect);
+ if (view.sRegion != null) {
+ tile.fileSRect.offset(view.sRegion.left, view.sRegion.top);
+ }
+ return decoder.decodeRegion(tile.fileSRect, tile.sampleSize);
+ } else {
+ tile.loading = false;
+ }
+ } finally {
+ view.decoderLock.readLock().unlock();
+ }
+ } else if (tile != null) {
+ tile.loading = false;
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to decode tile", e);
+ this.exception = e;
+ } catch (OutOfMemoryError e) {
+ Log.e(TAG, "Failed to decode tile - OutOfMemoryError", e);
+ this.exception = new RuntimeException(e);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Bitmap bitmap) {
+ final MySubsamplingScaleImageView subsamplingScaleImageView = viewRef.get();
+ final MySubsamplingScaleImageView.Tile tile = tileRef.get();
+ if (subsamplingScaleImageView != null && tile != null) {
+ if (bitmap != null) {
+ tile.bitmap = bitmap;
+ tile.loading = false;
+ subsamplingScaleImageView.onTileLoaded();
+ } else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) {
+ subsamplingScaleImageView.onImageEventListener.onTileLoadError(exception);
+ }
+ }
+ }
+ }
+
+ /**
+ * Called by worker task when a tile has loaded. Redraws the view.
+ */
+ private synchronized void onTileLoaded() {
+ debug("onTileLoaded");
+ checkReady();
+ checkImageLoaded();
+ if (isBaseLayerReady() && bitmap != null) {
+ if (!bitmapIsCached) {
+ bitmap.recycle();
+ }
+ bitmap = null;
+ if (onImageEventListener != null && bitmapIsCached) {
+ onImageEventListener.onPreviewReleased();
+ }
+ bitmapIsPreview = false;
+ bitmapIsCached = false;
+ }
+ invalidate();
+ }
+
+ /**
+ * Async task used to load bitmap without blocking the UI thread.
+ */
+ private static class BitmapLoadTask extends AsyncTask {
+ private final WeakReference viewRef;
+ private final WeakReference contextRef;
+ private final WeakReference> decoderFactoryRef;
+ private final Uri source;
+ private final boolean preview;
+ private final char[] password;
+ private final int version;
+ private Bitmap bitmap;
+ private Exception exception;
+
+ BitmapLoadTask(MySubsamplingScaleImageView view, Context context, DecoderFactory extends ImageDecoder> decoderFactory, Uri source, boolean preview, char[] password, int version) {
+ this.viewRef = new WeakReference<>(view);
+ this.contextRef = new WeakReference<>(context);
+ this.decoderFactoryRef = new WeakReference<>(decoderFactory);
+ this.source = source;
+ this.preview = preview;
+ this.password = password;
+ this.version = version;
+ }
+
+ @Override
+ protected Integer doInBackground(Void... params) {
+ try {
+ String sourceUri = source.toString();
+ Context context = contextRef.get();
+ DecoderFactory extends ImageDecoder> decoderFactory = decoderFactoryRef.get();
+ MySubsamplingScaleImageView view = viewRef.get();
+ if (context != null && decoderFactory != null && view != null) {
+ view.debug("BitmapLoadTask.doInBackground");
+ bitmap = decoderFactory.make().decode(context, source, password, version);
+ return view.getExifOrientation(context, sourceUri);
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "Failed to load bitmap", e);
+ this.exception = e;
+ } catch (OutOfMemoryError e) {
+ Log.e(TAG, "Failed to load bitmap - OutOfMemoryError", e);
+ this.exception = new RuntimeException(e);
+ }
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Integer orientation) {
+ MySubsamplingScaleImageView subsamplingScaleImageView = viewRef.get();
+ if (subsamplingScaleImageView != null) {
+ if (bitmap != null && orientation != null) {
+ if (preview) {
+ subsamplingScaleImageView.onPreviewLoaded(bitmap);
+ } else {
+ subsamplingScaleImageView.onImageLoaded(bitmap, orientation, false);
+ }
+ } else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) {
+ if (preview) {
+ subsamplingScaleImageView.onImageEventListener.onPreviewLoadError(exception);
+ } else {
+ subsamplingScaleImageView.onImageEventListener.onImageLoadError(exception);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Called by worker task when preview image is loaded.
+ */
+ private synchronized void onPreviewLoaded(Bitmap previewBitmap) {
+ debug("onPreviewLoaded");
+ if (bitmap != null || imageLoadedSent) {
+ previewBitmap.recycle();
+ return;
+ }
+ if (pRegion != null) {
+ bitmap = Bitmap.createBitmap(previewBitmap, pRegion.left, pRegion.top, pRegion.width(), pRegion.height());
+ } else {
+ bitmap = previewBitmap;
+ }
+ bitmapIsPreview = true;
+ if (checkReady()) {
+ invalidate();
+ requestLayout();
+ }
+ }
+
+ /**
+ * Called by worker task when full size image bitmap is ready (tiling is disabled).
+ */
+ private synchronized void onImageLoaded(Bitmap bitmap, int sOrientation, boolean bitmapIsCached) {
+ debug("onImageLoaded");
+ // If actual dimensions don't match the declared size, reset everything.
+ if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != bitmap.getWidth() || this.sHeight != bitmap.getHeight())) {
+ reset(false);
+ }
+ if (this.bitmap != null && !this.bitmapIsCached) {
+ this.bitmap.recycle();
+ }
+
+ if (this.bitmap != null && this.bitmapIsCached && onImageEventListener != null) {
+ onImageEventListener.onPreviewReleased();
+ }
+
+ this.bitmapIsPreview = false;
+ this.bitmapIsCached = bitmapIsCached;
+ this.bitmap = bitmap;
+ this.sWidth = bitmap.getWidth();
+ this.sHeight = bitmap.getHeight();
+ this.sOrientation = sOrientation;
+ boolean ready = checkReady();
+ boolean imageLoaded = checkImageLoaded();
+ if (ready || imageLoaded) {
+ invalidate();
+ requestLayout();
+ }
+ }
+
+ /**
+ * Helper method for load tasks. Examines the EXIF info on the image file to determine the orientation.
+ * This will only work for external files, not assets, resources or other URIs.
+ */
+ @AnyThread
+ private int getExifOrientation(Context context, String sourceUri) {
+ int exifOrientation = ORIENTATION_0;
+ if (sourceUri.startsWith(ContentResolver.SCHEME_CONTENT)) {
+ Cursor cursor = null;
+ try {
+ String[] columns = {MediaStore.Images.Media.ORIENTATION};
+ cursor = context.getContentResolver().query(Uri.parse(sourceUri), columns, null, null, null);
+ if (cursor != null) {
+ if (cursor.moveToFirst()) {
+ int orientation = cursor.getInt(0);
+ if (VALID_ORIENTATIONS.contains(orientation) && orientation != ORIENTATION_USE_EXIF) {
+ exifOrientation = orientation;
+ } else {
+ Log.w(TAG, "Unsupported orientation: " + orientation);
+ }
+ }
+ }
+ } catch (Exception e) {
+ Log.w(TAG, "Could not get orientation of image from media store");
+ } finally {
+ if (cursor != null) {
+ cursor.close();
+ }
+ }
+ } else if (sourceUri.startsWith(ImageSource.FILE_SCHEME) && !sourceUri.startsWith(ImageSource.ASSET_SCHEME)) {
+ try {
+ ExifInterface exifInterface = new ExifInterface(sourceUri.substring(ImageSource.FILE_SCHEME.length() - 1));
+ int orientationAttr = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
+ if (orientationAttr == ExifInterface.ORIENTATION_NORMAL || orientationAttr == ExifInterface.ORIENTATION_UNDEFINED) {
+ exifOrientation = ORIENTATION_0;
+ } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_90) {
+ exifOrientation = ORIENTATION_90;
+ } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_180) {
+ exifOrientation = ORIENTATION_180;
+ } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_270) {
+ exifOrientation = ORIENTATION_270;
+ } else {
+ Log.w(TAG, "Unsupported EXIF orientation: " + orientationAttr);
+ }
+ } catch (Exception e) {
+ Log.w(TAG, "Could not get EXIF orientation of image");
+ }
+ }
+ return exifOrientation;
+ }
+
+ private void execute(AsyncTask asyncTask) {
+ asyncTask.executeOnExecutor(executor);
+ }
+
+ private static class Tile {
+
+ private Rect sRect;
+ private int sampleSize;
+ private Bitmap bitmap;
+ private boolean loading;
+ private boolean visible;
+
+ // Volatile fields instantiated once then updated before use to reduce GC.
+ private Rect vRect;
+ private Rect fileSRect;
+
+ }
+
+ private static class Anim {
+
+ private float scaleStart; // Scale at start of anim
+ private float scaleEnd; // Scale at end of anim (target)
+ private PointF sCenterStart; // Source center point at start
+ private PointF sCenterEnd; // Source center point at end, adjusted for pan limits
+ private PointF sCenterEndRequested; // Source center point that was requested, without adjustment
+ private PointF vFocusStart; // View point that was double tapped
+ private PointF vFocusEnd; // Where the view focal point should be moved to during the anim
+ private long duration = 500; // How long the anim takes
+ private boolean interruptible = true; // Whether the anim can be interrupted by a touch
+ private int easing = EASE_IN_OUT_QUAD; // Easing style
+ private int origin = ORIGIN_ANIM; // Animation origin (API, double tap or fling)
+ private long time = System.currentTimeMillis(); // Start time
+ private MySubsamplingScaleImageView.OnAnimationEventListener listener; // Event listener
+
+ }
+
+ private static class ScaleAndTranslate {
+ private ScaleAndTranslate(float scale, PointF vTranslate) {
+ this.scale = scale;
+ this.vTranslate = vTranslate;
+ }
+
+ private float scale;
+ private final PointF vTranslate;
+ }
+
+ /**
+ * Set scale, center and orientation from saved state.
+ */
+ private void restoreState(ImageViewState state) {
+ if (state != null && VALID_ORIENTATIONS.contains(state.getOrientation())) {
+ this.orientation = state.getOrientation();
+ this.pendingScale = state.getScale();
+ this.sPendingCenter = state.getCenter();
+ invalidate();
+ }
+ }
+
+ /**
+ * By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour.
+ *
+ * @param maxPixels Maximum tile size X and Y in pixels.
+ */
+ public void setMaxTileSize(int maxPixels) {
+ this.maxTileWidth = maxPixels;
+ this.maxTileHeight = maxPixels;
+ }
+
+ /**
+ * By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour.
+ *
+ * @param maxPixelsX Maximum tile width.
+ * @param maxPixelsY Maximum tile height.
+ */
+ public void setMaxTileSize(int maxPixelsX, int maxPixelsY) {
+ this.maxTileWidth = maxPixelsX;
+ this.maxTileHeight = maxPixelsY;
+ }
+
+ /**
+ * Use canvas max bitmap width and height instead of the default 2048, to avoid redundant tiling.
+ */
+ @NonNull
+ private Point getMaxBitmapDimensions(Canvas canvas) {
+ return new Point(Math.min(canvas.getMaximumBitmapWidth(), maxTileWidth), Math.min(canvas.getMaximumBitmapHeight(), maxTileHeight));
+ }
+
+ /**
+ * Get source width taking rotation into account.
+ */
+ @SuppressWarnings("SuspiciousNameCombination")
+ private int sWidth() {
+ int rotation = getRequiredRotation();
+ if (rotation == 90 || rotation == 270) {
+ return sHeight;
+ } else {
+ return sWidth;
+ }
+ }
+
+ /**
+ * Get source height taking rotation into account.
+ */
+ @SuppressWarnings("SuspiciousNameCombination")
+ private int sHeight() {
+ int rotation = getRequiredRotation();
+ if (rotation == 90 || rotation == 270) {
+ return sWidth;
+ } else {
+ return sHeight;
+ }
+ }
+
+ /**
+ * Converts source rectangle from tile, which treats the image file as if it were in the correct orientation already,
+ * to the rectangle of the image that needs to be loaded.
+ */
+ @SuppressWarnings("SuspiciousNameCombination")
+ @AnyThread
+ private void fileSRect(Rect sRect, Rect target) {
+ if (getRequiredRotation() == 0) {
+ target.set(sRect);
+ } else if (getRequiredRotation() == 90) {
+ target.set(sRect.top, sHeight - sRect.right, sRect.bottom, sHeight - sRect.left);
+ } else if (getRequiredRotation() == 180) {
+ target.set(sWidth - sRect.right, sHeight - sRect.bottom, sWidth - sRect.left, sHeight - sRect.top);
+ } else {
+ target.set(sWidth - sRect.bottom, sRect.left, sWidth - sRect.top, sRect.right);
+ }
+ }
+
+ /**
+ * Determines the rotation to be applied to tiles, based on EXIF orientation or chosen setting.
+ */
+ @AnyThread
+ private int getRequiredRotation() {
+ if (orientation == ORIENTATION_USE_EXIF) {
+ return sOrientation;
+ } else {
+ return orientation;
+ }
+ }
+
+ /**
+ * Pythagoras distance between two points.
+ */
+ private float distance(float x0, float x1, float y0, float y1) {
+ float x = x0 - x1;
+ float y = y0 - y1;
+ return (float) Math.sqrt(x * x + y * y);
+ }
+
+ /**
+ * Releases all resources the view is using and resets the state, nulling any fields that use significant memory.
+ * After you have called this method, the view can be re-used by setting a new image. Settings are remembered
+ * but state (scale and center) is forgotten. You can restore these yourself if required.
+ */
+ public void recycle() {
+ reset(true);
+ bitmapPaint = null;
+ debugTextPaint = null;
+ debugLinePaint = null;
+ tileBgPaint = null;
+ }
+
+ /**
+ * Convert screen to source x coordinate.
+ */
+ private float viewToSourceX(float vx) {
+ if (vTranslate == null) {
+ return Float.NaN;
+ }
+ return (vx - vTranslate.x) / scale;
+ }
+
+ /**
+ * Convert screen to source y coordinate.
+ */
+ private float viewToSourceY(float vy) {
+ if (vTranslate == null) {
+ return Float.NaN;
+ }
+ return (vy - vTranslate.y) / scale;
+ }
+
+ /**
+ * Converts a rectangle within the view to the corresponding rectangle from the source file, taking
+ * into account the current scale, translation, orientation and clipped region. This can be used
+ * to decode a bitmap from the source file.
+ *
+ * This method will only work when the image has fully initialised, after {@link #isReady()} returns
+ * true. It is not guaranteed to work with preloaded bitmaps.
+ *
+ * The result is written to the fRect argument. Re-use a single instance for efficiency.
+ *
+ * @param vRect rectangle representing the view area to interpret.
+ * @param fRect rectangle instance to which the result will be written. Re-use for efficiency.
+ */
+ public void viewToFileRect(Rect vRect, Rect fRect) {
+ if (vTranslate == null || !readySent) {
+ return;
+ }
+ fRect.set(
+ (int) viewToSourceX(vRect.left),
+ (int) viewToSourceY(vRect.top),
+ (int) viewToSourceX(vRect.right),
+ (int) viewToSourceY(vRect.bottom));
+ fileSRect(fRect, fRect);
+ fRect.set(
+ Math.max(0, fRect.left),
+ Math.max(0, fRect.top),
+ Math.min(sWidth, fRect.right),
+ Math.min(sHeight, fRect.bottom)
+ );
+ if (sRegion != null) {
+ fRect.offset(sRegion.left, sRegion.top);
+ }
+ }
+
+ /**
+ * Find the area of the source file that is currently visible on screen, taking into account the
+ * current scale, translation, orientation and clipped region. This is a convenience method; see
+ * {@link #viewToFileRect(Rect, Rect)}.
+ *
+ * @param fRect rectangle instance to which the result will be written. Re-use for efficiency.
+ */
+ public void visibleFileRect(Rect fRect) {
+ if (vTranslate == null || !readySent) {
+ return;
+ }
+ fRect.set(0, 0, getWidth(), getHeight());
+ viewToFileRect(fRect, fRect);
+ }
+
+ /**
+ * Convert screen coordinate to source coordinate.
+ *
+ * @param vxy view X/Y coordinate.
+ * @return a coordinate representing the corresponding source coordinate.
+ */
+ @Nullable
+ public final PointF viewToSourceCoord(PointF vxy) {
+ return viewToSourceCoord(vxy.x, vxy.y, new PointF());
+ }
+
+ /**
+ * Convert screen coordinate to source coordinate.
+ *
+ * @param vx view X coordinate.
+ * @param vy view Y coordinate.
+ * @return a coordinate representing the corresponding source coordinate.
+ */
+ @Nullable
+ public final PointF viewToSourceCoord(float vx, float vy) {
+ return viewToSourceCoord(vx, vy, new PointF());
+ }
+
+ /**
+ * Convert screen coordinate to source coordinate.
+ *
+ * @param vxy view coordinates to convert.
+ * @param sTarget target object for result. The same instance is also returned.
+ * @return source coordinates. This is the same instance passed to the sTarget param.
+ */
+ @Nullable
+ public final PointF viewToSourceCoord(PointF vxy, @NonNull PointF sTarget) {
+ return viewToSourceCoord(vxy.x, vxy.y, sTarget);
+ }
+
+ /**
+ * Convert screen coordinate to source coordinate.
+ *
+ * @param vx view X coordinate.
+ * @param vy view Y coordinate.
+ * @param sTarget target object for result. The same instance is also returned.
+ * @return source coordinates. This is the same instance passed to the sTarget param.
+ */
+ @Nullable
+ public final PointF viewToSourceCoord(float vx, float vy, @NonNull PointF sTarget) {
+ if (vTranslate == null) {
+ return null;
+ }
+ sTarget.set(viewToSourceX(vx), viewToSourceY(vy));
+ return sTarget;
+ }
+
+ /**
+ * Convert source to view x coordinate.
+ */
+ private float sourceToViewX(float sx) {
+ if (vTranslate == null) {
+ return Float.NaN;
+ }
+ return (sx * scale) + vTranslate.x;
+ }
+
+ /**
+ * Convert source to view y coordinate.
+ */
+ private float sourceToViewY(float sy) {
+ if (vTranslate == null) {
+ return Float.NaN;
+ }
+ return (sy * scale) + vTranslate.y;
+ }
+
+ /**
+ * Convert source coordinate to view coordinate.
+ *
+ * @param sxy source coordinates to convert.
+ * @return view coordinates.
+ */
+ @Nullable
+ public final PointF sourceToViewCoord(PointF sxy) {
+ return sourceToViewCoord(sxy.x, sxy.y, new PointF());
+ }
+
+ /**
+ * Convert source coordinate to view coordinate.
+ *
+ * @param sx source X coordinate.
+ * @param sy source Y coordinate.
+ * @return view coordinates.
+ */
+ @Nullable
+ public final PointF sourceToViewCoord(float sx, float sy) {
+ return sourceToViewCoord(sx, sy, new PointF());
+ }
+
+ /**
+ * Convert source coordinate to view coordinate.
+ *
+ * @param sxy source coordinates to convert.
+ * @param vTarget target object for result. The same instance is also returned.
+ * @return view coordinates. This is the same instance passed to the vTarget param.
+ */
+ @SuppressWarnings("UnusedReturnValue")
+ @Nullable
+ public final PointF sourceToViewCoord(PointF sxy, @NonNull PointF vTarget) {
+ return sourceToViewCoord(sxy.x, sxy.y, vTarget);
+ }
+
+ /**
+ * Convert source coordinate to view coordinate.
+ *
+ * @param sx source X coordinate.
+ * @param sy source Y coordinate.
+ * @param vTarget target object for result. The same instance is also returned.
+ * @return view coordinates. This is the same instance passed to the vTarget param.
+ */
+ @Nullable
+ public final PointF sourceToViewCoord(float sx, float sy, @NonNull PointF vTarget) {
+ if (vTranslate == null) {
+ return null;
+ }
+ vTarget.set(sourceToViewX(sx), sourceToViewY(sy));
+ return vTarget;
+ }
+
+ /**
+ * Convert source rect to screen rect, integer values.
+ */
+ private void sourceToViewRect(@NonNull Rect sRect, @NonNull Rect vTarget) {
+ vTarget.set(
+ (int) sourceToViewX(sRect.left),
+ (int) sourceToViewY(sRect.top),
+ (int) sourceToViewX(sRect.right),
+ (int) sourceToViewY(sRect.bottom)
+ );
+ }
+
+ /**
+ * Get the translation required to place a given source coordinate at the center of the screen, with the center
+ * adjusted for asymmetric padding. Accepts the desired scale as an argument, so this is independent of current
+ * translate and scale. The result is fitted to bounds, putting the image point as near to the screen center as permitted.
+ */
+ @NonNull
+ private PointF vTranslateForSCenter(float sCenterX, float sCenterY, float scale) {
+ int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft()) / 2;
+ int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop()) / 2;
+ if (satTemp == null) {
+ satTemp = new MySubsamplingScaleImageView.ScaleAndTranslate(0, new PointF(0, 0));
+ }
+ satTemp.scale = scale;
+ satTemp.vTranslate.set(vxCenter - (sCenterX * scale), vyCenter - (sCenterY * scale));
+ fitToBounds(true, satTemp);
+ return satTemp.vTranslate;
+ }
+
+ /**
+ * Given a requested source center and scale, calculate what the actual center will have to be to keep the image in
+ * pan limits, keeping the requested center as near to the middle of the screen as allowed.
+ */
+ @NonNull
+ private PointF limitedSCenter(float sCenterX, float sCenterY, float scale, @NonNull PointF sTarget) {
+ PointF vTranslate = vTranslateForSCenter(sCenterX, sCenterY, scale);
+ int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft()) / 2;
+ int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop()) / 2;
+ float sx = (vxCenter - vTranslate.x) / scale;
+ float sy = (vyCenter - vTranslate.y) / scale;
+ sTarget.set(sx, sy);
+ return sTarget;
+ }
+
+ /**
+ * Returns the minimum allowed scale.
+ */
+ private float minScale() {
+ int vPadding = getPaddingBottom() + getPaddingTop();
+ int hPadding = getPaddingLeft() + getPaddingRight();
+ if (minimumScaleType == SCALE_TYPE_CENTER_CROP || minimumScaleType == SCALE_TYPE_START) {
+ return Math.max((getWidth() - hPadding) / (float) sWidth(), (getHeight() - vPadding) / (float) sHeight());
+ } else if (minimumScaleType == SCALE_TYPE_CUSTOM && minScale > 0) {
+ return minScale;
+ } else {
+ return Math.min((getWidth() - hPadding) / (float) sWidth(), (getHeight() - vPadding) / (float) sHeight());
+ }
+ }
+
+ /**
+ * Adjust a requested scale to be within the allowed limits.
+ */
+ private float limitedScale(float targetScale) {
+ targetScale = Math.max(minScale(), targetScale);
+ targetScale = Math.min(maxScale, targetScale);
+ return targetScale;
+ }
+
+ /**
+ * Apply a selected type of easing.
+ *
+ * @param type Easing type, from static fields
+ * @param time Elapsed time
+ * @param from Start value
+ * @param change Target value
+ * @param duration Anm duration
+ * @return Current value
+ */
+ private float ease(int type, long time, float from, float change, long duration) {
+ switch (type) {
+ case EASE_IN_OUT_QUAD:
+ return easeInOutQuad(time, from, change, duration);
+ case EASE_OUT_QUAD:
+ return easeOutQuad(time, from, change, duration);
+ default:
+ throw new IllegalStateException("Unexpected easing type: " + type);
+ }
+ }
+
+ /**
+ * Quadratic easing for fling. With thanks to Robert Penner - http://gizma.com/easing/
+ *
+ * @param time Elapsed time
+ * @param from Start value
+ * @param change Target value
+ * @param duration Anm duration
+ * @return Current value
+ */
+ private float easeOutQuad(long time, float from, float change, long duration) {
+ float progress = (float) time / (float) duration;
+ return -change * progress * (progress - 2) + from;
+ }
+
+ /**
+ * Quadratic easing for scale and center animations. With thanks to Robert Penner - http://gizma.com/easing/
+ *
+ * @param time Elapsed time
+ * @param from Start value
+ * @param change Target value
+ * @param duration Anm duration
+ * @return Current value
+ */
+ private float easeInOutQuad(long time, float from, float change, long duration) {
+ float timeF = time / (duration / 2f);
+ if (timeF < 1) {
+ return (change / 2f * timeF * timeF) + from;
+ } else {
+ timeF--;
+ return (-change / 2f) * (timeF * (timeF - 2) - 1) + from;
+ }
+ }
+
+ /**
+ * Debug logger
+ */
+ @AnyThread
+ private void debug(String message, Object... args) {
+ if (debug) {
+ Log.d(TAG, String.format(message, args));
+ }
+ }
+
+ /**
+ * For debug overlays. Scale pixel value according to screen density.
+ */
+ private int px(int px) {
+ return (int) (density * px);
+ }
+
+ /**
+ * Swap the default region decoder implementation for one of your own. You must do this before setting the image file or
+ * asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a
+ * public default constructor.
+ *
+ * @param regionDecoderClass The {@link ImageRegionDecoder} implementation to use.
+ */
+ public final void setRegionDecoderClass(@NonNull Class extends ImageRegionDecoder> regionDecoderClass) {
+ //noinspection ConstantConditions
+ if (regionDecoderClass == null) {
+ throw new IllegalArgumentException("Decoder class cannot be set to null");
+ }
+ this.regionDecoderFactory = new CompatDecoderFactory<>(regionDecoderClass);
+ }
+
+ /**
+ * Swap the default region decoder implementation for one of your own. You must do this before setting the image file or
+ * asset, and you cannot use a custom decoder when using layout XML to set an asset name.
+ *
+ * @param regionDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageRegionDecoder}
+ * instances.
+ */
+ public final void setRegionDecoderFactory(@NonNull DecoderFactory extends ImageRegionDecoder> regionDecoderFactory) {
+ //noinspection ConstantConditions
+ if (regionDecoderFactory == null) {
+ throw new IllegalArgumentException("Decoder factory cannot be set to null");
+ }
+ this.regionDecoderFactory = regionDecoderFactory;
+ }
+
+ /**
+ * Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or
+ * asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a
+ * public default constructor.
+ *
+ * @param bitmapDecoderClass The {@link ImageDecoder} implementation to use.
+ */
+ public final void setBitmapDecoderClass(@NonNull Class extends ImageDecoder> bitmapDecoderClass) {
+ //noinspection ConstantConditions
+ if (bitmapDecoderClass == null) {
+ throw new IllegalArgumentException("Decoder class cannot be set to null");
+ }
+ this.bitmapDecoderFactory = new CompatDecoderFactory<>(bitmapDecoderClass);
+ }
+
+ /**
+ * Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or
+ * asset, and you cannot use a custom decoder when using layout XML to set an asset name.
+ *
+ * @param bitmapDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageDecoder} instances.
+ */
+ public final void setBitmapDecoderFactory(@NonNull DecoderFactory extends ImageDecoder> bitmapDecoderFactory) {
+ //noinspection ConstantConditions
+ if (bitmapDecoderFactory == null) {
+ throw new IllegalArgumentException("Decoder factory cannot be set to null");
+ }
+ this.bitmapDecoderFactory = bitmapDecoderFactory;
+ }
+
+ /**
+ * Calculate how much further the image can be panned in each direction. The results are set on
+ * the supplied {@link RectF} and expressed as screen pixels. For example, if the image cannot be
+ * panned any further towards the left, the value of {@link RectF#left} will be set to 0.
+ *
+ * @param vTarget target object for results. Re-use for efficiency.
+ */
+ public final void getPanRemaining(RectF vTarget) {
+ if (!isReady()) {
+ return;
+ }
+
+ float scaleWidth = scale * sWidth();
+ float scaleHeight = scale * sHeight();
+
+ if (panLimit == PAN_LIMIT_CENTER) {
+ vTarget.top = Math.max(0, -(vTranslate.y - (getHeight() / 2)));
+ vTarget.left = Math.max(0, -(vTranslate.x - (getWidth() / 2)));
+ vTarget.bottom = Math.max(0, vTranslate.y - ((getHeight() / 2) - scaleHeight));
+ vTarget.right = Math.max(0, vTranslate.x - ((getWidth() / 2) - scaleWidth));
+ } else if (panLimit == PAN_LIMIT_OUTSIDE) {
+ vTarget.top = Math.max(0, -(vTranslate.y - getHeight()));
+ vTarget.left = Math.max(0, -(vTranslate.x - getWidth()));
+ vTarget.bottom = Math.max(0, vTranslate.y + scaleHeight);
+ vTarget.right = Math.max(0, vTranslate.x + scaleWidth);
+ } else {
+ vTarget.top = Math.max(0, -vTranslate.y);
+ vTarget.left = Math.max(0, -vTranslate.x);
+ vTarget.bottom = Math.max(0, (scaleHeight + vTranslate.y) - getHeight());
+ vTarget.right = Math.max(0, (scaleWidth + vTranslate.x) - getWidth());
+ }
+ }
+
+ /**
+ * Set the pan limiting style. See static fields. Normally {@link #PAN_LIMIT_INSIDE} is best, for image galleries.
+ *
+ * @param panLimit a pan limit constant. See static fields.
+ */
+ public final void setPanLimit(int panLimit) {
+ if (!VALID_PAN_LIMITS.contains(panLimit)) {
+ throw new IllegalArgumentException("Invalid pan limit: " + panLimit);
+ }
+ this.panLimit = panLimit;
+ if (isReady()) {
+ fitToBounds(true);
+ invalidate();
+ }
+ }
+
+ /**
+ * Set the minimum scale type. See static fields. Normally {@link #SCALE_TYPE_CENTER_INSIDE} is best, for image galleries.
+ *
+ * @param scaleType a scale type constant. See static fields.
+ */
+ public final void setMinimumScaleType(int scaleType) {
+ if (!VALID_SCALE_TYPES.contains(scaleType)) {
+ throw new IllegalArgumentException("Invalid scale type: " + scaleType);
+ }
+ this.minimumScaleType = scaleType;
+ if (isReady()) {
+ fitToBounds(true);
+ invalidate();
+ }
+ }
+
+ /**
+ * Set the maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according
+ * to screen density - on a retina screen, 1:1 may still be too small. Consider using {@link #setMinimumDpi(int)},
+ * which is density aware.
+ *
+ * @param maxScale maximum scale expressed as a source/view pixels ratio.
+ */
+ public final void setMaxScale(float maxScale) {
+ this.maxScale = maxScale;
+ }
+
+ /**
+ * Set the minimum scale allowed. A value of 1 means 1:1 pixels at minimum scale. You may wish to set this according
+ * to screen density. Consider using {@link #setMaximumDpi(int)}, which is density aware.
+ *
+ * @param minScale minimum scale expressed as a source/view pixels ratio.
+ */
+ public final void setMinScale(float minScale) {
+ this.minScale = minScale;
+ }
+
+ /**
+ * This is a screen density aware alternative to {@link #setMaxScale(float)}; it allows you to express the maximum
+ * allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being
+ * too small on a high density screen. A sensible starting point is 160 - the default used by this view.
+ *
+ * @param dpi Source image pixel density at maximum zoom.
+ */
+ public final void setMinimumDpi(int dpi) {
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ float averageDpi = (metrics.xdpi + metrics.ydpi) / 2;
+ setMaxScale(averageDpi / dpi);
+ }
+
+ /**
+ * This is a screen density aware alternative to {@link #setMinScale(float)}; it allows you to express the minimum
+ * allowed scale in terms of the maximum pixel density.
+ *
+ * @param dpi Source image pixel density at minimum zoom.
+ */
+ public final void setMaximumDpi(int dpi) {
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ float averageDpi = (metrics.xdpi + metrics.ydpi) / 2;
+ setMinScale(averageDpi / dpi);
+ }
+
+ /**
+ * Returns the maximum allowed scale.
+ *
+ * @return the maximum scale as a source/view pixels ratio.
+ */
+ public float getMaxScale() {
+ return maxScale;
+ }
+
+ /**
+ * Returns the minimum allowed scale.
+ *
+ * @return the minimum scale as a source/view pixels ratio.
+ */
+ public final float getMinScale() {
+ return minScale();
+ }
+
+ /**
+ * By default, image tiles are at least as high resolution as the screen. For a retina screen this may not be
+ * necessary, and may increase the likelihood of an OutOfMemoryError. This method sets a DPI at which higher
+ * resolution tiles should be loaded. Using a lower number will on average use less memory but result in a lower
+ * quality image. 160-240dpi will usually be enough. This should be called before setting the image source,
+ * because it affects which tiles get loaded. When using an untiled source image this method has no effect.
+ *
+ * @param minimumTileDpi Tile loading threshold.
+ */
+ public void setMinimumTileDpi(int minimumTileDpi) {
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ float averageDpi = (metrics.xdpi + metrics.ydpi) / 2;
+ this.minimumTileDpi = (int) Math.min(averageDpi, minimumTileDpi);
+ if (isReady()) {
+ reset(false);
+ invalidate();
+ }
+ }
+
+ /**
+ * Returns the source point at the center of the view.
+ *
+ * @return the source coordinates current at the center of the view.
+ */
+ @Nullable
+ public final PointF getCenter() {
+ int mX = getWidth() / 2;
+ int mY = getHeight() / 2;
+ return viewToSourceCoord(mX, mY);
+ }
+
+ /**
+ * Returns the current scale value.
+ *
+ * @return the current scale as a source/view pixels ratio.
+ */
+ public final float getScale() {
+ return scale;
+ }
+
+ /**
+ * Externally change the scale and translation of the source image. This may be used with getCenter() and getScale()
+ * to restore the scale and zoom after a screen rotate.
+ *
+ * @param scale New scale to set.
+ * @param sCenter New source image coordinate to center on the screen, subject to boundaries.
+ */
+ public final void setScaleAndCenter(float scale, @Nullable PointF sCenter) {
+ this.anim = null;
+ this.pendingScale = scale;
+ this.sPendingCenter = sCenter;
+ this.sRequestedCenter = sCenter;
+ invalidate();
+ }
+
+ /**
+ * Fully zoom out and return the image to the middle of the screen. This might be useful if you have a view pager
+ * and want images to be reset when the user has moved to another page.
+ */
+ public final void resetScaleAndCenter() {
+ this.anim = null;
+ this.pendingScale = limitedScale(0);
+ if (isReady()) {
+ this.sPendingCenter = new PointF(sWidth() / 2, sHeight() / 2);
+ } else {
+ this.sPendingCenter = new PointF(0, 0);
+ }
+ invalidate();
+ }
+
+ /**
+ * Call to find whether the view is initialised, has dimensions, and will display an image on
+ * the next draw. If a preview has been provided, it may be the preview that will be displayed
+ * and the full size image may still be loading. If no preview was provided, this is called once
+ * the base layer tiles of the full size image are loaded.
+ *
+ * @return true if the view is ready to display an image and accept touch gestures.
+ */
+ public final boolean isReady() {
+ return readySent;
+ }
+
+ /**
+ * Called once when the view is initialised, has dimensions, and will display an image on the
+ * next draw. This is triggered at the same time as {@link MySubsamplingScaleImageView.OnImageEventListener#onReady()} but
+ * allows a subclass to receive this event without using a listener.
+ */
+ @SuppressWarnings("EmptyMethod")
+ protected void onReady() {
+
+ }
+
+ /**
+ * Call to find whether the main image (base layer tiles where relevant) have been loaded. Before
+ * this event the view is blank unless a preview was provided.
+ *
+ * @return true if the main image (not the preview) has been loaded and is ready to display.
+ */
+ public final boolean isImageLoaded() {
+ return imageLoadedSent;
+ }
+
+ /**
+ * Called once when the full size image or its base layer tiles have been loaded.
+ */
+ @SuppressWarnings("EmptyMethod")
+ protected void onImageLoaded() {
+
+ }
+
+ /**
+ * Get source width, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSHeight()}
+ * for the apparent width.
+ *
+ * @return the source image width in pixels.
+ */
+ public final int getSWidth() {
+ return sWidth;
+ }
+
+ /**
+ * Get source height, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSWidth()}
+ * for the apparent height.
+ *
+ * @return the source image height in pixels.
+ */
+ public final int getSHeight() {
+ return sHeight;
+ }
+
+ /**
+ * Returns the orientation setting. This can return {@link #ORIENTATION_USE_EXIF}, in which case it doesn't tell you
+ * the applied orientation of the image. For that, use {@link #getAppliedOrientation()}.
+ *
+ * @return the orientation setting. See static fields.
+ */
+ public final int getOrientation() {
+ return orientation;
+ }
+
+ /**
+ * Returns the actual orientation of the image relative to the source file. This will be based on the source file's
+ * EXIF orientation if you're using ORIENTATION_USE_EXIF. Values are 0, 90, 180, 270.
+ *
+ * @return the orientation applied after EXIF information has been extracted. See static fields.
+ */
+ public final int getAppliedOrientation() {
+ return getRequiredRotation();
+ }
+
+ /**
+ * Get the current state of the view (scale, center, orientation) for restoration after rotate. Will return null if
+ * the view is not ready.
+ *
+ * @return an {@link ImageViewState} instance representing the current position of the image. null if the view isn't ready.
+ */
+ @Nullable
+ public final ImageViewState getState() {
+ if (vTranslate != null && sWidth > 0 && sHeight > 0) {
+ //noinspection ConstantConditions
+ return new ImageViewState(getScale(), getCenter(), getOrientation());
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if zoom gesture detection is enabled.
+ *
+ * @return true if zoom gesture detection is enabled.
+ */
+ public final boolean isZoomEnabled() {
+ return zoomEnabled;
+ }
+
+ /**
+ * Enable or disable zoom gesture detection. Disabling zoom locks the the current scale.
+ *
+ * @param zoomEnabled true to enable zoom gestures, false to disable.
+ */
+ public final void setZoomEnabled(boolean zoomEnabled) {
+ this.zoomEnabled = zoomEnabled;
+ }
+
+ /**
+ * Returns true if double tap & swipe to zoom is enabled.
+ *
+ * @return true if double tap & swipe to zoom is enabled.
+ */
+ public final boolean isQuickScaleEnabled() {
+ return quickScaleEnabled;
+ }
+
+ /**
+ * Enable or disable double tap & swipe to zoom.
+ *
+ * @param quickScaleEnabled true to enable quick scale, false to disable.
+ */
+ public final void setQuickScaleEnabled(boolean quickScaleEnabled) {
+ this.quickScaleEnabled = quickScaleEnabled;
+ }
+
+ /**
+ * Returns true if pan gesture detection is enabled.
+ *
+ * @return true if pan gesture detection is enabled.
+ */
+ public final boolean isPanEnabled() {
+ return panEnabled;
+ }
+
+ /**
+ * Enable or disable pan gesture detection. Disabling pan causes the image to be centered. Pan
+ * can still be changed from code.
+ *
+ * @param panEnabled true to enable panning, false to disable.
+ */
+ public final void setPanEnabled(boolean panEnabled) {
+ this.panEnabled = panEnabled;
+ if (!panEnabled && vTranslate != null) {
+ vTranslate.x = (getWidth() / 2) - (scale * (sWidth() / 2));
+ vTranslate.y = (getHeight() / 2) - (scale * (sHeight() / 2));
+ if (isReady()) {
+ refreshRequiredTiles(true);
+ invalidate();
+ }
+ }
+ }
+
+ /**
+ * Set a solid color to render behind tiles, useful for displaying transparent PNGs.
+ *
+ * @param tileBgColor Background color for tiles.
+ */
+ public final void setTileBackgroundColor(int tileBgColor) {
+ if (Color.alpha(tileBgColor) == 0) {
+ tileBgPaint = null;
+ } else {
+ tileBgPaint = new Paint();
+ tileBgPaint.setStyle(Style.FILL);
+ tileBgPaint.setColor(tileBgColor);
+ }
+ invalidate();
+ }
+
+ /**
+ * Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted
+ * as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values
+ * greater than the max zoom.
+ *
+ * @param doubleTapZoomScale New value for double tap gesture zoom scale.
+ */
+ public final void setDoubleTapZoomScale(float doubleTapZoomScale) {
+ this.doubleTapZoomScale = doubleTapZoomScale;
+ }
+
+ /**
+ * A density aware alternative to {@link #setDoubleTapZoomScale(float)}; this allows you to express the scale the
+ * image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will
+ * be ignored. A sensible starting point is 160 - the default used by this view.
+ *
+ * @param dpi New value for double tap gesture zoom scale.
+ */
+ public final void setDoubleTapZoomDpi(int dpi) {
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ float averageDpi = (metrics.xdpi + metrics.ydpi) / 2;
+ setDoubleTapZoomScale(averageDpi / dpi);
+ }
+
+ /**
+ * Set the type of zoom animation to be used for double taps. See static fields.
+ *
+ * @param doubleTapZoomStyle New value for zoom style.
+ */
+ public final void setDoubleTapZoomStyle(int doubleTapZoomStyle) {
+ if (!VALID_ZOOM_STYLES.contains(doubleTapZoomStyle)) {
+ throw new IllegalArgumentException("Invalid zoom style: " + doubleTapZoomStyle);
+ }
+ this.doubleTapZoomStyle = doubleTapZoomStyle;
+ }
+
+ /**
+ * Set the duration of the double tap zoom animation.
+ *
+ * @param durationMs Duration in milliseconds.
+ */
+ public final void setDoubleTapZoomDuration(int durationMs) {
+ this.doubleTapZoomDuration = Math.max(0, durationMs);
+ }
+
+ /**
+ *
+ * Provide an {@link Executor} to be used for loading images. By default, {@link AsyncTask#THREAD_POOL_EXECUTOR}
+ * is used to minimise contention with other background work the app is doing. You can also choose
+ * to use {@link AsyncTask#SERIAL_EXECUTOR} if you want to limit concurrent background tasks.
+ * Alternatively you can supply an {@link Executor} of your own to avoid any contention. It is
+ * strongly recommended to use a single executor instance for the life of your application, not
+ * one per view instance.
+ *
+ * Warning: If you are using a custom implementation of {@link ImageRegionDecoder}, and you
+ * supply an executor with more than one thread, you must make sure your implementation supports
+ * multi-threaded bitmap decoding or has appropriate internal synchronization. From SDK 21, Android's
+ * {@link android.graphics.BitmapRegionDecoder} uses an internal lock so it is thread safe but
+ * there is no advantage to using multiple threads.
+ *
+ *
+ * @param executor an {@link Executor} for image loading.
+ */
+ public void setExecutor(@NonNull Executor executor) {
+ //noinspection ConstantConditions
+ if (executor == null) {
+ throw new NullPointerException("Executor must not be null");
+ }
+ this.executor = executor;
+ }
+
+ /**
+ * Enable or disable eager loading of tiles that appear on screen during gestures or animations,
+ * while the gesture or animation is still in progress. By default this is enabled to improve
+ * responsiveness, but it can result in tiles being loaded and discarded more rapidly than
+ * necessary and reduce the animation frame rate on old/cheap devices. Disable this on older
+ * devices if you see poor performance. Tiles will then be loaded only when gestures and animations
+ * are completed.
+ *
+ * @param eagerLoadingEnabled true to enable loading during gestures, false to delay loading until gestures end
+ */
+ public void setEagerLoadingEnabled(boolean eagerLoadingEnabled) {
+ this.eagerLoadingEnabled = eagerLoadingEnabled;
+ }
+
+ /**
+ * Enables visual debugging, showing tile boundaries and sizes.
+ *
+ * @param debug true to enable debugging, false to disable.
+ */
+ public final void setDebug(boolean debug) {
+ this.debug = debug;
+ }
+
+ /**
+ * Check if an image has been set. The image may not have been loaded and displayed yet.
+ *
+ * @return If an image is currently set.
+ */
+ public boolean hasImage() {
+ return uri != null || bitmap != null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setOnLongClickListener(OnLongClickListener onLongClickListener) {
+ this.onLongClickListener = onLongClickListener;
+ }
+
+ /**
+ * Add a listener allowing notification of load and error events. Extend {@link MySubsamplingScaleImageView.DefaultOnImageEventListener}
+ * to simplify implementation.
+ *
+ * @param onImageEventListener an {@link MySubsamplingScaleImageView.OnImageEventListener} instance.
+ */
+ public void setOnImageEventListener(MySubsamplingScaleImageView.OnImageEventListener onImageEventListener) {
+ this.onImageEventListener = onImageEventListener;
+ }
+
+ /**
+ * Add a listener for pan and zoom events. Extend {@link MySubsamplingScaleImageView.DefaultOnStateChangedListener} to simplify
+ * implementation.
+ *
+ * @param onStateChangedListener an {@link MySubsamplingScaleImageView.OnStateChangedListener} instance.
+ */
+ public void setOnStateChangedListener(MySubsamplingScaleImageView.OnStateChangedListener onStateChangedListener) {
+ this.onStateChangedListener = onStateChangedListener;
+ }
+
+ private void sendStateChanged(float oldScale, PointF oldVTranslate, int origin) {
+ if (onStateChangedListener != null && scale != oldScale) {
+ onStateChangedListener.onScaleChanged(scale, origin);
+ }
+ if (onStateChangedListener != null && !vTranslate.equals(oldVTranslate)) {
+ onStateChangedListener.onCenterChanged(getCenter(), origin);
+ }
+ }
+
+ /**
+ * Creates a panning animation builder, that when started will animate the image to place the given coordinates of
+ * the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the
+ * image is instead animated to move the center point as near to the center of the screen as is allowed - it's
+ * guaranteed to be on screen.
+ *
+ * @param sCenter Target center point
+ * @return {@link MySubsamplingScaleImageView.AnimationBuilder} instance. Call {@link MySubsamplingScaleImageView.AnimationBuilder#start()} to start the anim.
+ */
+ @Nullable
+ public MySubsamplingScaleImageView.AnimationBuilder animateCenter(PointF sCenter) {
+ if (!isReady()) {
+ return null;
+ }
+ return new MySubsamplingScaleImageView.AnimationBuilder(sCenter);
+ }
+
+ /**
+ * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image
+ * beyond the panning limits, the image is automatically panned during the animation.
+ *
+ * @param scale Target scale.
+ * @return {@link MySubsamplingScaleImageView.AnimationBuilder} instance. Call {@link MySubsamplingScaleImageView.AnimationBuilder#start()} to start the anim.
+ */
+ @Nullable
+ public MySubsamplingScaleImageView.AnimationBuilder animateScale(float scale) {
+ if (!isReady()) {
+ return null;
+ }
+ return new MySubsamplingScaleImageView.AnimationBuilder(scale);
+ }
+
+ /**
+ * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image
+ * beyond the panning limits, the image is automatically panned during the animation.
+ *
+ * @param scale Target scale.
+ * @param sCenter Target source center.
+ * @return {@link MySubsamplingScaleImageView.AnimationBuilder} instance. Call {@link MySubsamplingScaleImageView.AnimationBuilder#start()} to start the anim.
+ */
+ @Nullable
+ public MySubsamplingScaleImageView.AnimationBuilder animateScaleAndCenter(float scale, PointF sCenter) {
+ if (!isReady()) {
+ return null;
+ }
+ return new MySubsamplingScaleImageView.AnimationBuilder(scale, sCenter);
+ }
+
+ /**
+ * Builder class used to set additional options for a scale animation. Create an instance using {@link #animateScale(float)},
+ * then set your options and call {@link #start()}.
+ */
+ public final class AnimationBuilder {
+
+ private final float targetScale;
+ private final PointF targetSCenter;
+ private final PointF vFocus;
+ private long duration = 500;
+ private int easing = EASE_IN_OUT_QUAD;
+ private int origin = ORIGIN_ANIM;
+ private boolean interruptible = true;
+ private boolean panLimited = true;
+ private MySubsamplingScaleImageView.OnAnimationEventListener listener;
+
+ private AnimationBuilder(PointF sCenter) {
+ this.targetScale = scale;
+ this.targetSCenter = sCenter;
+ this.vFocus = null;
+ }
+
+ private AnimationBuilder(float scale) {
+ this.targetScale = scale;
+ this.targetSCenter = getCenter();
+ this.vFocus = null;
+ }
+
+ private AnimationBuilder(float scale, PointF sCenter) {
+ this.targetScale = scale;
+ this.targetSCenter = sCenter;
+ this.vFocus = null;
+ }
+
+ private AnimationBuilder(float scale, PointF sCenter, PointF vFocus) {
+ this.targetScale = scale;
+ this.targetSCenter = sCenter;
+ this.vFocus = vFocus;
+ }
+
+ /**
+ * Desired duration of the anim in milliseconds. Default is 500.
+ *
+ * @param duration duration in milliseconds.
+ * @return this builder for method chaining.
+ */
+ @NonNull
+ public MySubsamplingScaleImageView.AnimationBuilder withDuration(long duration) {
+ this.duration = duration;
+ return this;
+ }
+
+ /**
+ * Whether the animation can be interrupted with a touch. Default is true.
+ *
+ * @param interruptible interruptible flag.
+ * @return this builder for method chaining.
+ */
+ @NonNull
+ public MySubsamplingScaleImageView.AnimationBuilder withInterruptible(boolean interruptible) {
+ this.interruptible = interruptible;
+ return this;
+ }
+
+ /**
+ * Set the easing style. See static fields. {@link #EASE_IN_OUT_QUAD} is recommended, and the default.
+ *
+ * @param easing easing style.
+ * @return this builder for method chaining.
+ */
+ @NonNull
+ public MySubsamplingScaleImageView.AnimationBuilder withEasing(int easing) {
+ if (!VALID_EASING_STYLES.contains(easing)) {
+ throw new IllegalArgumentException("Unknown easing type: " + easing);
+ }
+ this.easing = easing;
+ return this;
+ }
+
+ /**
+ * Add an animation event listener.
+ *
+ * @param listener The listener.
+ * @return this builder for method chaining.
+ */
+ @NonNull
+ public MySubsamplingScaleImageView.AnimationBuilder withOnAnimationEventListener(MySubsamplingScaleImageView.OnAnimationEventListener listener) {
+ this.listener = listener;
+ return this;
+ }
+
+ /**
+ * Only for internal use. When set to true, the animation proceeds towards the actual end point - the nearest
+ * point to the center allowed by pan limits. When false, animation is in the direction of the requested end
+ * point and is stopped when the limit for each axis is reached. The latter behaviour is used for flings but
+ * nothing else.
+ */
+ @NonNull
+ private MySubsamplingScaleImageView.AnimationBuilder withPanLimited(boolean panLimited) {
+ this.panLimited = panLimited;
+ return this;
+ }
+
+ /**
+ * Only for internal use. Indicates what caused the animation.
+ */
+ @NonNull
+ private MySubsamplingScaleImageView.AnimationBuilder withOrigin(int origin) {
+ this.origin = origin;
+ return this;
+ }
+
+ /**
+ * Starts the animation.
+ */
+ public void start() {
+ if (anim != null && anim.listener != null) {
+ try {
+ anim.listener.onInterruptedByNewAnim();
+ } catch (Exception e) {
+ Log.w(TAG, "Error thrown by animation listener", e);
+ }
+ }
+
+ int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft()) / 2;
+ int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop()) / 2;
+ float targetScale = limitedScale(this.targetScale);
+ PointF targetSCenter = panLimited ? limitedSCenter(this.targetSCenter.x, this.targetSCenter.y, targetScale, new PointF()) : this.targetSCenter;
+ anim = new MySubsamplingScaleImageView.Anim();
+ anim.scaleStart = scale;
+ anim.scaleEnd = targetScale;
+ anim.time = System.currentTimeMillis();
+ anim.sCenterEndRequested = targetSCenter;
+ anim.sCenterStart = getCenter();
+ anim.sCenterEnd = targetSCenter;
+ anim.vFocusStart = sourceToViewCoord(targetSCenter);
+ anim.vFocusEnd = new PointF(
+ vxCenter,
+ vyCenter
+ );
+ anim.duration = duration;
+ anim.interruptible = interruptible;
+ anim.easing = easing;
+ anim.origin = origin;
+ anim.time = System.currentTimeMillis();
+ anim.listener = listener;
+
+ if (vFocus != null) {
+ // Calculate where translation will be at the end of the anim
+ float vTranslateXEnd = vFocus.x - (targetScale * anim.sCenterStart.x);
+ float vTranslateYEnd = vFocus.y - (targetScale * anim.sCenterStart.y);
+ MySubsamplingScaleImageView.ScaleAndTranslate satEnd = new MySubsamplingScaleImageView.ScaleAndTranslate(targetScale, new PointF(vTranslateXEnd, vTranslateYEnd));
+ // Fit the end translation into bounds
+ fitToBounds(true, satEnd);
+ // Adjust the position of the focus point at end so image will be in bounds
+ anim.vFocusEnd = new PointF(
+ vFocus.x + (satEnd.vTranslate.x - vTranslateXEnd),
+ vFocus.y + (satEnd.vTranslate.y - vTranslateYEnd)
+ );
+ }
+
+ invalidate();
+ }
+
+ }
+
+ /**
+ * An event listener for animations, allows events to be triggered when an animation completes,
+ * is aborted by another animation starting, or is aborted by a touch event. Note that none of
+ * these events are triggered if the activity is paused, the image is swapped, or in other cases
+ * where the view's internal state gets wiped or draw events stop.
+ */
+ @SuppressWarnings("EmptyMethod")
+ public interface OnAnimationEventListener {
+
+ /**
+ * The animation has completed, having reached its endpoint.
+ */
+ void onComplete();
+
+ /**
+ * The animation has been aborted before reaching its endpoint because the user touched the screen.
+ */
+ void onInterruptedByUser();
+
+ /**
+ * The animation has been aborted before reaching its endpoint because a new animation has been started.
+ */
+ void onInterruptedByNewAnim();
+
+ }
+
+ /**
+ * Default implementation of {@link MySubsamplingScaleImageView.OnAnimationEventListener} for extension. This does nothing in any method.
+ */
+ public static class DefaultOnAnimationEventListener implements MySubsamplingScaleImageView.OnAnimationEventListener {
+
+ @Override
+ public void onComplete() {
+ }
+
+ @Override
+ public void onInterruptedByUser() {
+ }
+
+ @Override
+ public void onInterruptedByNewAnim() {
+ }
+
+ }
+
+ /**
+ * An event listener, allowing subclasses and activities to be notified of significant events.
+ */
+ @SuppressWarnings("EmptyMethod")
+ public interface OnImageEventListener {
+
+ /**
+ * Called when the dimensions of the image and view are known, and either a preview image,
+ * the full size image, or base layer tiles are loaded. This indicates the scale and translate
+ * are known and the next draw will display an image. This event can be used to hide a loading
+ * graphic, or inform a subclass that it is safe to draw overlays.
+ */
+ void onReady();
+
+ /**
+ * Called when the full size image is ready. When using tiling, this means the lowest resolution
+ * base layer of tiles are loaded, and when tiling is disabled, the image bitmap is loaded.
+ * This event could be used as a trigger to enable gestures if you wanted interaction disabled
+ * while only a preview is displayed, otherwise for most cases {@link #onReady()} is the best
+ * event to listen to.
+ */
+ void onImageLoaded();
+
+ /**
+ * Called when a preview image could not be loaded. This method cannot be relied upon; certain
+ * encoding types of supported image formats can result in corrupt or blank images being loaded
+ * and displayed with no detectable error. The view will continue to load the full size image.
+ *
+ * @param e The exception thrown. This error is logged by the view.
+ */
+ void onPreviewLoadError(Exception e);
+
+ /**
+ * Indicates an error initiliasing the decoder when using a tiling, or when loading the full
+ * size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding
+ * types of supported image formats can result in corrupt or blank images being loaded and
+ * displayed with no detectable error.
+ *
+ * @param e The exception thrown. This error is also logged by the view.
+ */
+ void onImageLoadError(Exception e);
+
+ /**
+ * Called when an image tile could not be loaded. This method cannot be relied upon; certain
+ * encoding types of supported image formats can result in corrupt or blank images being loaded
+ * and displayed with no detectable error. Most cases where an unsupported file is used will
+ * result in an error caught by {@link #onImageLoadError(Exception)}.
+ *
+ * @param e The exception thrown. This error is logged by the view.
+ */
+ void onTileLoadError(Exception e);
+
+ /**
+ * Called when a bitmap set using ImageSource.cachedBitmap is no longer being used by the View.
+ * This is useful if you wish to manage the bitmap after the preview is shown
+ */
+ void onPreviewReleased();
+ }
+
+ /**
+ * Default implementation of {@link MySubsamplingScaleImageView.OnImageEventListener} for extension. This does nothing in any method.
+ */
+ public static class DefaultOnImageEventListener implements MySubsamplingScaleImageView.OnImageEventListener {
+
+ @Override
+ public void onReady() {
+ }
+
+ @Override
+ public void onImageLoaded() {
+ }
+
+ @Override
+ public void onPreviewLoadError(Exception e) {
+ }
+
+ @Override
+ public void onImageLoadError(Exception e) {
+ }
+
+ @Override
+ public void onTileLoadError(Exception e) {
+ }
+
+ @Override
+ public void onPreviewReleased() {
+ }
+
+ }
+
+ /**
+ * An event listener, allowing activities to be notified of pan and zoom events. Initialisation
+ * and calls made by your code do not trigger events; touch events and animations do. Methods in
+ * this listener will be called on the UI thread and may be called very frequently - your
+ * implementation should return quickly.
+ */
+ @SuppressWarnings("EmptyMethod")
+ public interface OnStateChangedListener {
+
+ /**
+ * The scale has changed. Use with {@link #getMaxScale()} and {@link #getMinScale()} to determine
+ * whether the image is fully zoomed in or out.
+ *
+ * @param newScale The new scale.
+ * @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}.
+ */
+ void onScaleChanged(float newScale, int origin);
+
+ /**
+ * The source center has been changed. This can be a result of panning or zooming.
+ *
+ * @param newCenter The new source center point.
+ * @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}.
+ */
+ void onCenterChanged(PointF newCenter, int origin);
+
+ }
+
+ /**
+ * Default implementation of {@link MySubsamplingScaleImageView.OnStateChangedListener}. This does nothing in any method.
+ */
+ public static class DefaultOnStateChangedListener implements MySubsamplingScaleImageView.OnStateChangedListener {
+
+ @Override
+ public void onCenterChanged(PointF newCenter, int origin) {
+ }
+
+ @Override
+ public void onScaleChanged(float newScale, int origin) {
+ }
+
+ }
+
+}
+
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/CompatDecoderFactory.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/CompatDecoderFactory.java
new file mode 100644
index 0000000..7cad0c0
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/CompatDecoderFactory.java
@@ -0,0 +1,48 @@
+package se.arctosoft.vault.subsampling.decoder;
+
+import android.graphics.Bitmap;
+import androidx.annotation.NonNull;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * Compatibility factory to instantiate decoders with empty public constructors.
+ * @param The base type of the decoder this factory will produce.
+ */
+@SuppressWarnings("WeakerAccess")
+public class CompatDecoderFactory implements DecoderFactory {
+
+ private final Class extends T> clazz;
+ private final Bitmap.Config bitmapConfig;
+
+ /**
+ * Construct a factory for the given class. This must have a default constructor.
+ * @param clazz a class that implements {@link ImageDecoder} or {@link com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder}.
+ */
+ public CompatDecoderFactory(@NonNull Class extends T> clazz) {
+ this(clazz, null);
+ }
+
+ /**
+ * Construct a factory for the given class. This must have a constructor that accepts a {@link Bitmap.Config} instance.
+ * @param clazz a class that implements {@link ImageDecoder} or {@link ImageRegionDecoder}.
+ * @param bitmapConfig bitmap configuration to be used when loading images.
+ */
+ public CompatDecoderFactory(@NonNull Class extends T> clazz, Bitmap.Config bitmapConfig) {
+ this.clazz = clazz;
+ this.bitmapConfig = bitmapConfig;
+ }
+
+ @Override
+ @NonNull
+ public T make() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
+ if (bitmapConfig == null) {
+ return clazz.newInstance();
+ } else {
+ Constructor extends T> ctor = clazz.getConstructor(Bitmap.Config.class);
+ return ctor.newInstance(bitmapConfig);
+ }
+ }
+
+}
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/DecoderFactory.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/DecoderFactory.java
new file mode 100644
index 0000000..f8ca244
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/DecoderFactory.java
@@ -0,0 +1,24 @@
+package se.arctosoft.vault.subsampling.decoder;
+
+import androidx.annotation.NonNull;
+
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * Interface for {@link ImageDecoder} and {@link ImageRegionDecoder} factories.
+ * @param the class of decoder that will be produced.
+ */
+public interface DecoderFactory {
+
+ /**
+ * Produce a new instance of a decoder with type {@link T}.
+ * @return a new instance of your decoder.
+ * @throws IllegalAccessException if the factory class cannot be instantiated.
+ * @throws InstantiationException if the factory class cannot be instantiated.
+ * @throws NoSuchMethodException if the factory class cannot be instantiated.
+ * @throws InvocationTargetException if the factory class cannot be instantiated.
+ */
+ @NonNull
+ T make() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException;
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/ImageDecoder.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/ImageDecoder.java
new file mode 100644
index 0000000..9ab915b
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/ImageDecoder.java
@@ -0,0 +1,51 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.subsampling.decoder;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.net.Uri;
+
+import androidx.annotation.NonNull;
+
+/**
+ * Interface for image decoding classes, allowing the default {@link android.graphics.BitmapFactory}
+ * based on the Skia library to be replaced with a custom class.
+ */
+public interface ImageDecoder {
+
+ /**
+ * Decode an image. The URI can be in one of the following formats:
+ *
+ * File: file:///scard/picture.jpg
+ *
+ * Asset: file:///android_asset/picture.png
+ *
+ * Resource: android.resource://com.example.app/drawable/picture
+ *
+ * @param context Application context
+ * @param uri URI of the image
+ * @param password
+ * @param version
+ * @return the decoded bitmap
+ * @throws Exception if decoding fails.
+ */
+ @NonNull
+ Bitmap decode(Context context, @NonNull Uri uri, char[] password, int version) throws Exception;
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/ImageRegionDecoder.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/ImageRegionDecoder.java
new file mode 100644
index 0000000..798f93d
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/ImageRegionDecoder.java
@@ -0,0 +1,86 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.subsampling.decoder;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.net.Uri;
+
+import androidx.annotation.NonNull;
+
+/**
+ * Interface for image decoding classes, allowing the default {@link android.graphics.BitmapRegionDecoder}
+ * based on the Skia library to be replaced with a custom class.
+ */
+public interface ImageRegionDecoder {
+
+ /**
+ * Initialise the decoder. When possible, perform initial setup work once in this method. The
+ * dimensions of the image must be returned. The URI can be in one of the following formats:
+ *
+ * File: file:///scard/picture.jpg
+ *
+ * Asset: file:///android_asset/picture.png
+ *
+ * Resource: android.resource://com.example.app/drawable/picture
+ *
+ * @param context Application context. A reference may be held, but must be cleared on recycle.
+ * @param uri URI of the image.
+ * @param password
+ * @param version
+ * @return Dimensions of the image.
+ * @throws Exception if initialisation fails.
+ */
+ @NonNull
+ Point init(Context context, @NonNull Uri uri, char[] password, int version) throws Exception;
+
+ /**
+ *
+ * Decode a region of the image with the given sample size. This method is called off the UI
+ * thread so it can safely load the image on the current thread. It is called from
+ * {@link android.os.AsyncTask}s running in an executor that may have multiple threads, so
+ * implementations must be thread safe. Adding synchronized
to the method signature
+ * is the simplest way to achieve this, but bear in mind the {@link #recycle()} method can be
+ * called concurrently.
+ *
+ * See {@link SkiaImageRegionDecoder} and {@link SkiaPooledImageRegionDecoder} for examples of
+ * internal locking and synchronization.
+ *
+ *
+ * @param sRect Source image rectangle to decode.
+ * @param sampleSize Sample size.
+ * @return The decoded region. It is safe to return null if decoding fails.
+ */
+ @NonNull
+ Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize);
+
+ /**
+ * Status check. Should return false before initialisation and after recycle.
+ *
+ * @return true if the decoder is ready to be used.
+ */
+ boolean isReady();
+
+ /**
+ * This method will be called when the decoder is no longer required. It should clean up any resources still in use.
+ */
+ void recycle();
+
+}
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaImageDecoder.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaImageDecoder.java
new file mode 100644
index 0000000..0b05f44
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaImageDecoder.java
@@ -0,0 +1,81 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.subsampling.decoder;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+
+import androidx.annotation.Keep;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import se.arctosoft.vault.encryption.Encryption;
+import se.arctosoft.vault.subsampling.MySubsamplingScaleImageView;
+
+/**
+ * Default implementation of {@link com.davemorrissey.labs.subscaleview.decoder.ImageDecoder}
+ * using Android's {@link android.graphics.BitmapFactory}, based on the Skia library. This
+ * works well in most circumstances and has reasonable performance, however it has some problems
+ * with grayscale, indexed and CMYK images.
+ */
+public class SkiaImageDecoder implements ImageDecoder {
+ private final Bitmap.Config bitmapConfig;
+
+ @Keep
+ @SuppressWarnings("unused")
+ public SkiaImageDecoder() {
+ this(null);
+ }
+
+ @SuppressWarnings({"WeakerAccess", "SameParameterValue"})
+ public SkiaImageDecoder(@Nullable Bitmap.Config bitmapConfig) {
+ Bitmap.Config globalBitmapConfig = MySubsamplingScaleImageView.getPreferredBitmapConfig();
+ if (bitmapConfig != null) {
+ this.bitmapConfig = bitmapConfig;
+ } else if (globalBitmapConfig != null) {
+ this.bitmapConfig = globalBitmapConfig;
+ } else {
+ this.bitmapConfig = Bitmap.Config.RGB_565;
+ }
+ }
+
+ @Override
+ @NonNull
+ public Bitmap decode(Context context, @NonNull Uri uri, char[] password, int version) throws Exception {
+ BitmapFactory.Options options = new BitmapFactory.Options();
+ Bitmap bitmap;
+ options.inPreferredConfig = bitmapConfig;
+ Encryption.Streams streams = null;
+ try {
+ ContentResolver contentResolver = context.getContentResolver();
+ streams = Encryption.getCipherInputStream(contentResolver.openInputStream(uri), password, false, version);
+ bitmap = BitmapFactory.decodeStream(streams.getInputStream(), null, options);
+ } finally {
+ if (streams != null) {
+ streams.close();
+ }
+ }
+ if (bitmap == null) {
+ throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
+ }
+ return bitmap;
+ }
+}
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaImageRegionDecoder.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaImageRegionDecoder.java
new file mode 100644
index 0000000..a24259f
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaImageRegionDecoder.java
@@ -0,0 +1,138 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.subsampling.decoder;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.BitmapRegionDecoder;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.net.Uri;
+
+import androidx.annotation.Keep;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import se.arctosoft.vault.encryption.Encryption;
+import se.arctosoft.vault.subsampling.MySubsamplingScaleImageView;
+
+/**
+ * Default implementation of {@link com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder}
+ * using Android's {@link android.graphics.BitmapRegionDecoder}, based on the Skia library. This
+ * works well in most circumstances and has reasonable performance due to the cached decoder instance,
+ * however it has some problems with grayscale, indexed and CMYK images.
+ *
+ * A {@link ReadWriteLock} is used to delegate responsibility for multi threading behaviour to the
+ * {@link BitmapRegionDecoder} instance on SDK >= 21, whilst allowing this class to block until no
+ * tiles are being loaded before recycling the decoder. In practice, {@link BitmapRegionDecoder} is
+ * synchronized internally so this has no real impact on performance.
+ */
+public class SkiaImageRegionDecoder implements ImageRegionDecoder {
+
+ private BitmapRegionDecoder decoder;
+ private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true);
+
+ private final Bitmap.Config bitmapConfig;
+
+ @Keep
+ @SuppressWarnings("unused")
+ public SkiaImageRegionDecoder() {
+ this(null);
+ }
+
+ @SuppressWarnings({"WeakerAccess", "SameParameterValue"})
+ public SkiaImageRegionDecoder(@Nullable Bitmap.Config bitmapConfig) {
+ Bitmap.Config globalBitmapConfig = MySubsamplingScaleImageView.getPreferredBitmapConfig();
+ if (bitmapConfig != null) {
+ this.bitmapConfig = bitmapConfig;
+ } else if (globalBitmapConfig != null) {
+ this.bitmapConfig = globalBitmapConfig;
+ } else {
+ this.bitmapConfig = Bitmap.Config.RGB_565;
+ }
+ }
+
+ @Override
+ @NonNull
+ public Point init(Context context, @NonNull Uri uri, char[] password, int version) throws Exception {
+ Encryption.Streams streams = null;
+ try {
+ ContentResolver contentResolver = context.getContentResolver();
+ streams = Encryption.getCipherInputStream(contentResolver.openInputStream(uri), password, false, version);
+ decoder = BitmapRegionDecoder.newInstance(streams.getInputStream(), false);
+ } finally {
+ if (streams != null) {
+ streams.close();
+ }
+ }
+ return new Point(decoder.getWidth(), decoder.getHeight());
+ }
+
+ @Override
+ @NonNull
+ public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
+ getDecodeLock().lock();
+ try {
+ if (decoder != null && !decoder.isRecycled()) {
+ BitmapFactory.Options options = new BitmapFactory.Options();
+ options.inSampleSize = sampleSize;
+ options.inPreferredConfig = bitmapConfig;
+ Bitmap bitmap = decoder.decodeRegion(sRect, options);
+ if (bitmap == null) {
+ throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
+ }
+ return bitmap;
+ } else {
+ throw new IllegalStateException("Cannot decode region after decoder has been recycled");
+ }
+ } finally {
+ getDecodeLock().unlock();
+ }
+ }
+
+ @Override
+ public synchronized boolean isReady() {
+ return decoder != null && !decoder.isRecycled();
+ }
+
+ @Override
+ public synchronized void recycle() {
+ decoderLock.writeLock().lock();
+ try {
+ decoder.recycle();
+ decoder = null;
+ } finally {
+ decoderLock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Before SDK 21, BitmapRegionDecoder was not synchronized internally. Any attempt to decode
+ * regions from multiple threads with one decoder instance causes a segfault. For old versions
+ * use the write lock to enforce single threaded decoding.
+ */
+ private Lock getDecodeLock() {
+ return decoderLock.readLock();
+ }
+}
diff --git a/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaPooledImageRegionDecoder.java b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaPooledImageRegionDecoder.java
new file mode 100644
index 0000000..b26e6b7
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/subsampling/decoder/SkiaPooledImageRegionDecoder.java
@@ -0,0 +1,401 @@
+/*
+ * Valv-Android
+ * Copyright (c) 2024 Arctosoft AB.
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.subsampling.decoder;
+
+import static android.content.Context.ACTIVITY_SERVICE;
+
+import android.app.ActivityManager;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.BitmapRegionDecoder;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.net.Uri;
+import android.util.Log;
+
+import androidx.annotation.Keep;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import se.arctosoft.vault.encryption.Encryption;
+import se.arctosoft.vault.subsampling.MySubsamplingScaleImageView;
+
+/**
+ *
+ * An implementation of {@link ImageRegionDecoder} using a pool of {@link BitmapRegionDecoder}s,
+ * to provide true parallel loading of tiles. This is only effective if parallel loading has been
+ * enabled in the view by calling {@link com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView#setExecutor(Executor)}
+ * with a multi-threaded {@link Executor} instance.
+ *
+ * One decoder is initialised when the class is initialised. This is enough to decode base layer tiles.
+ * Additional decoders are initialised when a subregion of the image is first requested, which indicates
+ * interaction with the view. Creation of additional encoders stops when {@link #allowAdditionalDecoder(int, long)}
+ * returns false. The default implementation takes into account the file size, number of CPU cores,
+ * low memory status and a hard limit of 4. Extend this class to customise this.
+ *
+ * WARNING: This class is highly experimental and not proven to be stable on a wide range of
+ * devices. You are advised to test it thoroughly on all available devices, and code your app to use
+ * {@link SkiaImageRegionDecoder} on old or low powered devices you could not test.
+ *
+ */
+public class SkiaPooledImageRegionDecoder implements ImageRegionDecoder {
+
+ private static final String TAG = SkiaPooledImageRegionDecoder.class.getSimpleName();
+
+ private static boolean debug = false;
+
+ private SkiaPooledImageRegionDecoder.DecoderPool decoderPool = new SkiaPooledImageRegionDecoder.DecoderPool();
+ private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true);
+
+ private static final String FILE_PREFIX = "file://";
+ private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/";
+ private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
+
+ private final Bitmap.Config bitmapConfig;
+
+ private Context context;
+ private Uri uri;
+ private char[] password;
+ private int version;
+
+ private long fileLength = Long.MAX_VALUE;
+ private final Point imageDimensions = new Point(0, 0);
+ private final AtomicBoolean lazyInited = new AtomicBoolean(false);
+
+ @Keep
+ @SuppressWarnings("unused")
+ public SkiaPooledImageRegionDecoder() {
+ this(null);
+ }
+
+ @SuppressWarnings({"WeakerAccess", "SameParameterValue"})
+ public SkiaPooledImageRegionDecoder(@Nullable Bitmap.Config bitmapConfig) {
+ Bitmap.Config globalBitmapConfig = MySubsamplingScaleImageView.getPreferredBitmapConfig();
+ if (bitmapConfig != null) {
+ this.bitmapConfig = bitmapConfig;
+ } else if (globalBitmapConfig != null) {
+ this.bitmapConfig = globalBitmapConfig;
+ } else {
+ this.bitmapConfig = Bitmap.Config.RGB_565;
+ }
+ }
+
+ /**
+ * Controls logging of debug messages. All instances are affected.
+ *
+ * @param debug true to enable debug logging, false to disable.
+ */
+ @Keep
+ @SuppressWarnings("unused")
+ public static void setDebug(boolean debug) {
+ SkiaPooledImageRegionDecoder.debug = debug;
+ }
+
+ /**
+ * Initialises the decoder pool. This method creates one decoder on the current thread and uses
+ * it to decode the bounds, then spawns an independent thread to populate the pool with an
+ * additional three decoders. The thread will abort if {@link #recycle()} is called.
+ */
+ @Override
+ @NonNull
+ public Point init(final Context context, @NonNull final Uri uri, char[] password, int version) throws Exception {
+ this.context = context;
+ this.uri = uri;
+ this.password = password;
+ this.version = version;
+ initialiseDecoder();
+ return this.imageDimensions;
+ }
+
+ /**
+ * Initialises extra decoders for as long as {@link #allowAdditionalDecoder(int, long)} returns
+ * true and the pool has not been recycled.
+ */
+ private void lazyInit() {
+ if (lazyInited.compareAndSet(false, true) && fileLength < Long.MAX_VALUE) {
+ debug("Starting lazy init of additional decoders");
+ Thread thread = new Thread() {
+ @Override
+ public void run() {
+ while (decoderPool != null && allowAdditionalDecoder(decoderPool.size(), fileLength)) {
+ // New decoders can be created while reading tiles but this read lock prevents
+ // them being initialised while the pool is being recycled.
+ try {
+ if (decoderPool != null) {
+ long start = System.currentTimeMillis();
+ debug("Starting decoder");
+ initialiseDecoder();
+ long end = System.currentTimeMillis();
+ debug("Started decoder, took " + (end - start) + "ms");
+ }
+ } catch (Exception e) {
+ // A decoder has already been successfully created so we can ignore this
+ debug("Failed to start decoder: " + e.getMessage());
+ }
+ }
+ }
+ };
+ thread.start();
+ }
+ }
+
+ /**
+ * Initialises a new {@link BitmapRegionDecoder} and adds it to the pool, unless the pool has
+ * been recycled while it was created.
+ */
+ private void initialiseDecoder() throws Exception {
+ BitmapRegionDecoder decoder;
+ Encryption.Streams streams = null;
+ try {
+ ContentResolver contentResolver = context.getContentResolver();
+ streams = Encryption.getCipherInputStream(contentResolver.openInputStream(uri), password, false, version);
+ decoder = BitmapRegionDecoder.newInstance(streams.getInputStream(), false);
+ } finally {
+ if (streams != null) {
+ streams.close();
+ }
+ }
+ this.imageDimensions.set(decoder.getWidth(), decoder.getHeight());
+ decoderLock.writeLock().lock();
+ try {
+ if (decoderPool != null) {
+ decoderPool.add(decoder);
+ }
+ } finally {
+ decoderLock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still
+ * exists and acquire a decoder to load the requested region. There is no check whether the pool
+ * currently has decoders, because it's guaranteed to have one decoder after {@link ImageRegionDecoder#init(Context, Uri, char[], int)}
+ * is called and be null once {@link #recycle()} is called. In practice the view can't call this
+ * method until after {@link ImageRegionDecoder#init(Context, Uri, char[], int)}, so there will be no blocking on an empty pool.
+ */
+ @Override
+ @NonNull
+ public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) {
+ debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName());
+ if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) {
+ lazyInit();
+ }
+ decoderLock.readLock().lock();
+ try {
+ if (decoderPool != null) {
+ BitmapRegionDecoder decoder = decoderPool.acquire();
+ try {
+ // Decoder can't be null or recycled in practice
+ if (decoder != null && !decoder.isRecycled()) {
+ BitmapFactory.Options options = new BitmapFactory.Options();
+ options.inSampleSize = sampleSize;
+ options.inPreferredConfig = bitmapConfig;
+ Bitmap bitmap = decoder.decodeRegion(sRect, options);
+ if (bitmap == null) {
+ throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported");
+ }
+ return bitmap;
+ }
+ } finally {
+ if (decoder != null) {
+ decoderPool.release(decoder);
+ }
+ }
+ }
+ throw new IllegalStateException("Cannot decode region after decoder has been recycled");
+ } finally {
+ decoderLock.readLock().unlock();
+ }
+ }
+
+ /**
+ * Holding a read lock to avoid returning true while the pool is being recycled, this returns
+ * true if the pool has at least one decoder available.
+ */
+ @Override
+ public synchronized boolean isReady() {
+ return decoderPool != null && !decoderPool.isEmpty();
+ }
+
+ /**
+ * Wait until all read locks held by {@link #decodeRegion(Rect, int)} are released, then recycle
+ * and destroy the pool. Elsewhere, when a read lock is acquired, we must check the pool is not null.
+ */
+ @Override
+ public synchronized void recycle() {
+ decoderLock.writeLock().lock();
+ try {
+ if (decoderPool != null) {
+ decoderPool.recycle();
+ decoderPool = null;
+ context = null;
+ uri = null;
+ }
+ } finally {
+ decoderLock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Called before creating a new decoder. Based on number of CPU cores, available memory, and the
+ * size of the image file, determines whether another decoder can be created. Subclasses can
+ * override and customise this.
+ *
+ * @param numberOfDecoders the number of decoders that have been created so far
+ * @param fileLength the size of the image file in bytes. Creating another decoder will use approximately this much native memory.
+ * @return true if another decoder can be created.
+ */
+ @SuppressWarnings("WeakerAccess")
+ protected boolean allowAdditionalDecoder(int numberOfDecoders, long fileLength) {
+ if (numberOfDecoders >= 4) {
+ debug("No additional decoders allowed, reached hard limit (4)");
+ return false;
+ } else if (numberOfDecoders * fileLength > 20 * 1024 * 1024) {
+ debug("No additional encoders allowed, reached hard memory limit (20Mb)");
+ return false;
+ } else if (numberOfDecoders >= getNumberOfCores()) {
+ debug("No additional encoders allowed, limited by CPU cores (" + getNumberOfCores() + ")");
+ return false;
+ } else if (isLowMemory()) {
+ debug("No additional encoders allowed, memory is low");
+ return false;
+ }
+ debug("Additional decoder allowed, current count is " + numberOfDecoders + ", estimated native memory " + ((fileLength * numberOfDecoders) / (1024 * 1024)) + "Mb");
+ return true;
+ }
+
+
+ /**
+ * A simple pool of {@link BitmapRegionDecoder} instances, all loading from the same source.
+ */
+ private static class DecoderPool {
+ private final Semaphore available = new Semaphore(0, true);
+ private final Map decoders = new ConcurrentHashMap<>();
+
+ /**
+ * Returns false if there is at least one decoder in the pool.
+ */
+ private synchronized boolean isEmpty() {
+ return decoders.isEmpty();
+ }
+
+ /**
+ * Returns number of encoders.
+ */
+ private synchronized int size() {
+ return decoders.size();
+ }
+
+ /**
+ * Acquire a decoder. Blocks until one is available.
+ */
+ private BitmapRegionDecoder acquire() {
+ available.acquireUninterruptibly();
+ return getNextAvailable();
+ }
+
+ /**
+ * Release a decoder back to the pool.
+ */
+ private void release(BitmapRegionDecoder decoder) {
+ if (markAsUnused(decoder)) {
+ available.release();
+ }
+ }
+
+ /**
+ * Adds a newly created decoder to the pool, releasing an additional permit.
+ */
+ private synchronized void add(BitmapRegionDecoder decoder) {
+ decoders.put(decoder, false);
+ available.release();
+ }
+
+ /**
+ * While there are decoders in the map, wait until each is available before acquiring,
+ * recycling and removing it. After this is called, any call to {@link #acquire()} will
+ * block forever, so this call should happen within a write lock, and all calls to
+ * {@link #acquire()} should be made within a read lock so they cannot end up blocking on
+ * the semaphore when it has no permits.
+ */
+ private synchronized void recycle() {
+ while (!decoders.isEmpty()) {
+ BitmapRegionDecoder decoder = acquire();
+ decoder.recycle();
+ decoders.remove(decoder);
+ }
+ }
+
+ private synchronized BitmapRegionDecoder getNextAvailable() {
+ for (Map.Entry entry : decoders.entrySet()) {
+ if (!entry.getValue()) {
+ entry.setValue(true);
+ return entry.getKey();
+ }
+ }
+ return null;
+ }
+
+ private synchronized boolean markAsUnused(BitmapRegionDecoder decoder) {
+ for (Map.Entry entry : decoders.entrySet()) {
+ if (decoder == entry.getKey()) {
+ if (entry.getValue()) {
+ entry.setValue(false);
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+ return false;
+ }
+
+ }
+
+ private int getNumberOfCores() {
+ return Runtime.getRuntime().availableProcessors();
+ }
+
+ private boolean isLowMemory() {
+ ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
+ if (activityManager != null) {
+ ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
+ activityManager.getMemoryInfo(memoryInfo);
+ return memoryInfo.lowMemory;
+ } else {
+ return true;
+ }
+ }
+
+ private void debug(String message) {
+ if (debug) {
+ Log.d(TAG, message);
+ }
+ }
+
+}
diff --git a/app/src/main/java/se/arctosoft/vault/utils/BetterActivityResult.java b/app/src/main/java/se/arctosoft/vault/utils/BetterActivityResult.java
deleted file mode 100644
index 5f7757d..0000000
--- a/app/src/main/java/se/arctosoft/vault/utils/BetterActivityResult.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package se.arctosoft.vault.utils;
-
-import android.content.Intent;
-
-import androidx.activity.result.ActivityResult;
-import androidx.activity.result.ActivityResultCaller;
-import androidx.activity.result.ActivityResultLauncher;
-import androidx.activity.result.contract.ActivityResultContract;
-import androidx.activity.result.contract.ActivityResultContracts;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
-public class BetterActivityResult {
-
- @NonNull
- public static BetterActivityResult registerActivityForResult(@NonNull ActivityResultCaller caller) {
- return new BetterActivityResult<>(caller, new ActivityResultContracts.StartActivityForResult(), null);
- }
-
- public interface OnActivityResult {
- void onActivityResult(O result);
- }
-
- private final ActivityResultLauncher launcher;
- @Nullable
- private OnActivityResult onActivityResult;
-
- private BetterActivityResult(@NonNull ActivityResultCaller caller, @NonNull ActivityResultContract contract, @Nullable OnActivityResult onActivityResult) {
- this.onActivityResult = onActivityResult;
- this.launcher = caller.registerForActivityResult(contract, this::callOnActivityResult);
- }
-
- public void launch(Input input, @Nullable OnActivityResult onActivityResult) {
- if (onActivityResult != null) {
- this.onActivityResult = onActivityResult;
- }
- launcher.launch(input);
- }
-
- private void callOnActivityResult(Result result) {
- if (onActivityResult != null) {
- onActivityResult.onActivityResult(result);
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/se/arctosoft/vault/utils/CacheDataSourceFactory.java b/app/src/main/java/se/arctosoft/vault/utils/CacheDataSourceFactory.java
deleted file mode 100644
index 0a37ea1..0000000
--- a/app/src/main/java/se/arctosoft/vault/utils/CacheDataSourceFactory.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Valv-Android
- * Copyright (C) 2023 Arctosoft AB
- *
- * 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 https://www.gnu.org/licenses/.
- */
-
-package se.arctosoft.vault.utils;
-
-import android.content.Context;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.OptIn;
-import androidx.media3.database.StandaloneDatabaseProvider;
-import androidx.media3.datasource.ContentDataSource;
-import androidx.media3.datasource.DataSource;
-import androidx.media3.datasource.FileDataSource;
-import androidx.media3.datasource.cache.CacheDataSink;
-import androidx.media3.datasource.cache.CacheDataSource;
-import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor;
-import androidx.media3.datasource.cache.SimpleCache;
-
-import java.io.File;
-
-@OptIn(markerClass = androidx.media3.common.util.UnstableApi.class)
-public class CacheDataSourceFactory implements DataSource.Factory {
- private final Context context;
- private final ContentDataSource dataSource;
- private final long maxFileSize, maxCacheSize;
-
- private static SimpleCache simpleCache = null;
-
- public CacheDataSourceFactory(Context context, long maxCacheSize, long maxFileSize) {
- super();
- this.context = context;
- this.maxCacheSize = maxCacheSize;
- this.maxFileSize = maxFileSize;
- dataSource = new ContentDataSource(this.context);
- }
-
- @NonNull
- @Override
- public DataSource createDataSource() {
- LeastRecentlyUsedCacheEvictor evictor = new LeastRecentlyUsedCacheEvictor(maxCacheSize);
- if (simpleCache == null) {
- simpleCache = new SimpleCache(new File(context.getCacheDir(), "media"), evictor, new StandaloneDatabaseProvider(context));
- }
- return new CacheDataSource(simpleCache, dataSource,
- new FileDataSource(), new CacheDataSink(simpleCache, maxFileSize),
- CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null);
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/se/arctosoft/vault/utils/Constants.java b/app/src/main/java/se/arctosoft/vault/utils/Constants.java
index f91707c..e77d43d 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/Constants.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/Constants.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
diff --git a/app/src/main/java/se/arctosoft/vault/utils/Dialogs.java b/app/src/main/java/se/arctosoft/vault/utils/Dialogs.java
index 7aebbfa..ab19dd1 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/Dialogs.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/Dialogs.java
@@ -21,34 +21,31 @@
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
-import android.view.View;
+import android.text.Editable;
+import android.text.TextWatcher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import androidx.appcompat.app.AlertDialog;
import androidx.documentfile.provider.DocumentFile;
import androidx.fragment.app.FragmentActivity;
-import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.mikepenz.aboutlibraries.LibsBuilder;
-import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import se.arctosoft.vault.BuildConfig;
import se.arctosoft.vault.R;
-import se.arctosoft.vault.adapters.ImportListAdapter;
import se.arctosoft.vault.databinding.DialogEditNoteBinding;
-import se.arctosoft.vault.databinding.DialogImportBinding;
import se.arctosoft.vault.databinding.DialogImportTextBinding;
+import se.arctosoft.vault.databinding.DialogSetIterationCountBinding;
import se.arctosoft.vault.interfaces.IOnEdited;
public class Dialogs {
private static final String TAG = "Dialogs";
- public static void showImportGalleryChooseDestinationDialog(FragmentActivity context, Settings settings, int fileCount, IOnDirectorySelected onDirectorySelected) {
+ /*public static void showImportGalleryChooseDestinationDialog(FragmentActivity context, Settings settings, int fileCount, IOnDirectorySelected onDirectorySelected) {
List directories = settings.getGalleryDirectoriesAsUri(false);
List names = new ArrayList<>(directories.size());
for (int i = 0; i < directories.size(); i++) {
@@ -112,7 +109,7 @@ public static void showImportTextChooseDestinationDialog(FragmentActivity contex
binding.checkbox.setVisibility(View.GONE);
binding.recycler.setLayoutManager(new LinearLayoutManager(context));
binding.recycler.setAdapter(adapter);
- }
+ }*/
public static void showCopyMoveChooseDestinationDialog(FragmentActivity context, Settings settings, int fileCount, IOnDirectorySelected onDirectorySelected) {
List directories = settings.getGalleryDirectoriesAsUri(false);
@@ -211,6 +208,42 @@ public static void showImportTextDialog(FragmentActivity context, @Nullable Stri
.show();
}
+ public static void showSetIterationCountDialog(FragmentActivity context, @Nullable String editTextBody, IOnEdited onEdited) {
+ DialogSetIterationCountBinding binding = DialogSetIterationCountBinding.inflate(context.getLayoutInflater(), null, false);
+ if (editTextBody != null) {
+ binding.text.setText(editTextBody);
+ }
+ binding.text.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) {
+ try {
+ int ic = Integer.parseInt(s.toString());
+ if (ic > 500000) {
+ binding.text.setText(String.valueOf(500000));
+ }
+ } catch (NumberFormatException ignored) {
+ }
+ }
+ });
+
+ new MaterialAlertDialogBuilder(context)
+ .setTitle(context.getString(R.string.settings_iteration_count_title))
+ .setView(binding.getRoot())
+ .setPositiveButton(R.string.save, (dialog, which) -> onEdited.onEdited(binding.text.getText().toString()))
+ .setNegativeButton(android.R.string.cancel, null)
+ .show();
+ }
+
public static void showEditIncludedFolders(Context context, @NonNull Settings settings, @NonNull IOnEditedIncludedFolders onEditedIncludedFolders) {
List directories = settings.getGalleryDirectoriesAsUri(false);
String[] names = new String[directories.size()];
diff --git a/app/src/main/java/se/arctosoft/vault/utils/FileStuff.java b/app/src/main/java/se/arctosoft/vault/utils/FileStuff.java
index 4fb0681..03f1bde 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/FileStuff.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/FileStuff.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -26,20 +26,16 @@
import android.provider.DocumentsContract;
import android.util.Log;
-import androidx.activity.result.ActivityResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
-import java.io.InputStreamReader;
import java.io.OutputStream;
-import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -53,11 +49,13 @@ public class FileStuff {
@NonNull
public static List getFilesInFolder(Context context, Uri pickedDir) {
+ //Log.e(TAG, "getFilesInFolder: " + pickedDir);
Uri realUri = DocumentsContract.buildChildDocumentsUriUsingTree(pickedDir, DocumentsContract.getDocumentId(pickedDir));
List files = new ArrayList<>();
Cursor c = context.getContentResolver().query(
realUri,
- new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_LAST_MODIFIED, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE},
+ new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_LAST_MODIFIED,
+ DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE},
null,
null,
null);
@@ -89,13 +87,15 @@ private static List getEncryptedFilesInFolder(@NonNull List documentNote = new ArrayList<>();
List galleryFiles = new ArrayList<>();
for (CursorFile file : files) {
- if (!file.getName().startsWith(Encryption.ENCRYPTED_PREFIX) && !file.isDirectory()) {
+ String name = file.getName();
+ if (!name.startsWith(Encryption.ENCRYPTED_PREFIX) && !name.endsWith(Encryption.ENCRYPTED_SUFFIX) && !file.isDirectory()) {
continue;
}
+ //Log.e(TAG, "getEncryptedFilesInFolder: found " + name);
- if (file.getName().startsWith(Encryption.PREFIX_THUMB)) {
+ if (name.endsWith(Encryption.SUFFIX_THUMB) || name.startsWith(Encryption.PREFIX_THUMB)) {
documentThumbs.add(file);
- } else if (file.getName().startsWith(Encryption.PREFIX_NOTE_FILE)) {
+ } else if (name.endsWith(Encryption.SUFFIX_NOTE_FILE) || name.startsWith(Encryption.PREFIX_NOTE_FILE)) {
documentNote.add(file);
} else {
documentFiles.add(file);
@@ -104,7 +104,7 @@ private static List getEncryptedFilesInFolder(@NonNull List list, String
return null;
}
- public static void pickImageFiles(@NonNull BetterActivityResult activityLauncher, BetterActivityResult.OnActivityResult onActivityResult) {
- pickFiles(activityLauncher, "image/*", onActivityResult);
- }
-
- public static void pickVideoFiles(@NonNull BetterActivityResult activityLauncher, BetterActivityResult.OnActivityResult onActivityResult) {
- pickFiles(activityLauncher, "video/*", onActivityResult);
- }
-
- private static void pickFiles(BetterActivityResult activityLauncher, String mimeType, BetterActivityResult.OnActivityResult onActivityResult) {
+ public static Intent getPickFilesIntent(String mimeType) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
-
- activityLauncher.launch(intent, onActivityResult);
+ return intent;
}
@NonNull
@@ -163,43 +154,33 @@ public static String getFilenameFromUri(@NonNull Uri uri, boolean withoutPrefix)
String[] split = uri.getLastPathSegment().split("/");
String s = split[split.length - 1];
if (withoutPrefix) {
- return s.split("-", 2)[1];
+ if (s.startsWith(Encryption.ENCRYPTED_PREFIX)) {
+ return s.substring(s.indexOf("-") + 1);
+ } else {
+ return s.substring(0, s.lastIndexOf("-"));
+ }
}
return s;
}
- public static String getNameWithoutPrefix(@NonNull String s) {
- return s.split("-", 2)[1];
- }
-
- public static String readTextFromUri(@NonNull Uri uri, Context context) throws IOException {
- InputStream in = context.getContentResolver().openInputStream(uri);
- BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
-
- StringBuilder sb = new StringBuilder();
- int read;
- char[] buffer = new char[8192];
- while ((read = br.read(buffer)) != -1) {
- sb.append(buffer, 0, read);
+ public static String getNameWithoutPrefix(@NonNull String encryptedName) {
+ if (encryptedName.startsWith(Encryption.ENCRYPTED_PREFIX)) {
+ return encryptedName.substring(encryptedName.indexOf("-") + 1);
+ } else {
+ return encryptedName.substring(0, encryptedName.lastIndexOf("-"));
}
-
- return sb.toString();
}
@NonNull
- public static List getDocumentsFromDirectoryResult(Context context, @NonNull Intent data) {
- ClipData clipData = data.getClipData();
- List uris = FileStuff.uriListFromClipData(clipData);
- if (uris.isEmpty()) {
- Uri dataUri = data.getData();
- if (dataUri != null) {
- uris.add(dataUri);
- }
- }
+ public static List getDocumentsFromDirectoryResult(Context context, List uris) {
List documentFiles = new ArrayList<>();
+ if (context == null) {
+ return documentFiles;
+ }
for (Uri uri : uris) {
DocumentFile pickedFile = DocumentFile.fromSingleUri(context, uri);
- if (pickedFile != null && pickedFile.getType() != null && (pickedFile.getType().startsWith("image/") || pickedFile.getType().startsWith("video/")) && !pickedFile.getName().startsWith(Encryption.ENCRYPTED_PREFIX)) {
+ if (pickedFile != null && pickedFile.getType() != null && (pickedFile.getType().startsWith("image/") || pickedFile.getType().startsWith("video/")) &&
+ (!pickedFile.getName().endsWith(Encryption.ENCRYPTED_SUFFIX) || !pickedFile.getName().startsWith(Encryption.ENCRYPTED_PREFIX))) {
documentFiles.add(pickedFile);
}
}
@@ -209,9 +190,13 @@ public static List getDocumentsFromDirectoryResult(Context context
@NonNull
public static List getDocumentsFromShareIntent(Context context, @NonNull List uris) {
List documentFiles = new ArrayList<>();
+ if (context == null) {
+ return documentFiles;
+ }
for (Uri uri : uris) {
DocumentFile pickedFile = DocumentFile.fromSingleUri(context, uri);
- if (pickedFile != null && pickedFile.getType() != null && (pickedFile.getType().startsWith("image/") || pickedFile.getType().startsWith("video/")) && !pickedFile.getName().startsWith(Encryption.ENCRYPTED_PREFIX)) {
+ if (pickedFile != null && pickedFile.getType() != null && (pickedFile.getType().startsWith("image/") || pickedFile.getType().startsWith("video/")) &&
+ (!pickedFile.getName().endsWith(Encryption.ENCRYPTED_SUFFIX) || !pickedFile.getName().startsWith(Encryption.ENCRYPTED_PREFIX))) {
documentFiles.add(pickedFile);
}
}
@@ -276,9 +261,10 @@ public static boolean copyTo(Context context, GalleryFile sourceFile, DocumentFi
return false;
}
String generatedName = StringStuff.getRandomFileName();
- DocumentFile file = directory.createFile("", sourceFile.getFileType().encryptionPrefix + generatedName);
- DocumentFile thumbFile = sourceFile.getThumbUri() == null ? null : directory.createFile("", Encryption.PREFIX_THUMB + generatedName);
- DocumentFile noteFile = sourceFile.getNoteUri() == null ? null : directory.createFile("", Encryption.PREFIX_NOTE_FILE + generatedName);
+ int version = sourceFile.getVersion();
+ DocumentFile file = directory.createFile("", version < 2 ? sourceFile.getFileType().suffixPrefix + generatedName : generatedName + sourceFile.getFileType().suffixPrefix);
+ DocumentFile thumbFile = sourceFile.getThumbUri() == null ? null : directory.createFile("", version < 2 ? Encryption.PREFIX_THUMB + generatedName : generatedName + Encryption.SUFFIX_THUMB);
+ DocumentFile noteFile = sourceFile.getNoteUri() == null ? null : directory.createFile("", version < 2 ? Encryption.PREFIX_NOTE_FILE + generatedName : generatedName + Encryption.SUFFIX_NOTE_FILE);
if (file == null) {
Log.e(TAG, "copyTo: could not create file from " + sourceFile.getUri());
@@ -298,9 +284,11 @@ public static boolean moveTo(Context context, GalleryFile sourceFile, DocumentFi
Log.e(TAG, "moveTo: can't move " + sourceFile.getUri().getLastPathSegment() + " to the same folder");
return false;
}
- DocumentFile file = directory.createFile("", sourceFile.getEncryptedName());
- DocumentFile thumbFile = sourceFile.getThumbUri() == null ? null : directory.createFile("", Encryption.PREFIX_THUMB + sourceFile.getEncryptedName().split("-", 2)[1]);
- DocumentFile noteFile = sourceFile.getNoteUri() == null ? null : directory.createFile("", Encryption.PREFIX_NOTE_FILE + sourceFile.getEncryptedName().split("-", 2)[1]);
+ String nameWithoutPrefix = getNameWithoutPrefix(sourceFile.getEncryptedName());
+ int version = sourceFile.getVersion();
+ DocumentFile file = directory.createFile("", version < 2 ? sourceFile.getFileType().suffixPrefix + nameWithoutPrefix : nameWithoutPrefix + sourceFile.getFileType().suffixPrefix);
+ DocumentFile thumbFile = sourceFile.getThumbUri() == null ? null : directory.createFile("", version < 2 ? Encryption.PREFIX_THUMB + nameWithoutPrefix : nameWithoutPrefix + Encryption.SUFFIX_THUMB);
+ DocumentFile noteFile = sourceFile.getNoteUri() == null ? null : directory.createFile("", version < 2 ? Encryption.PREFIX_NOTE_FILE + nameWithoutPrefix : nameWithoutPrefix + Encryption.SUFFIX_NOTE_FILE);
if (file == null) {
Log.e(TAG, "moveTo: could not create file from " + sourceFile.getUri());
@@ -315,7 +303,7 @@ public static boolean moveTo(Context context, GalleryFile sourceFile, DocumentFi
return writeTo(context, sourceFile.getUri(), file.getUri());
}
- private static boolean writeTo(Context context, Uri src, Uri dest) {
+ public static boolean writeTo(Context context, Uri src, Uri dest) {
try {
InputStream inputStream = new BufferedInputStream(context.getContentResolver().openInputStream(src), 1024 * 32);
OutputStream outputStream = new BufferedOutputStream(context.getContentResolver().openOutputStream(dest));
diff --git a/app/src/main/java/se/arctosoft/vault/utils/GlideStuff.java b/app/src/main/java/se/arctosoft/vault/utils/GlideStuff.java
index 7b675f1..1f57e53 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/GlideStuff.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/GlideStuff.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -20,17 +20,19 @@
import androidx.annotation.NonNull;
+import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
-import se.arctosoft.vault.LaunchActivity;
+import se.arctosoft.vault.MainActivity;
public class GlideStuff {
@NonNull
- public static RequestOptions getRequestOptions() {
+ public static RequestOptions getRequestOptions(boolean useDiskCache) {
return new RequestOptions()
- .signature(new ObjectKey(LaunchActivity.GLIDE_KEY));
+ .diskCacheStrategy(useDiskCache ? DiskCacheStrategy.AUTOMATIC : DiskCacheStrategy.NONE)
+ .signature(new ObjectKey(MainActivity.GLIDE_KEY));
}
}
diff --git a/app/src/main/java/se/arctosoft/vault/utils/Settings.java b/app/src/main/java/se/arctosoft/vault/utils/Settings.java
index 8895803..82be3a2 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/Settings.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/Settings.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -27,12 +27,10 @@
import androidx.annotation.Nullable;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import se.arctosoft.vault.data.StoredDirectory;
-import se.arctosoft.vault.encryption.Password;
import se.arctosoft.vault.interfaces.IOnDirectoryAdded;
public class Settings {
@@ -40,12 +38,14 @@ public class Settings {
private static final String SHARED_PREFERENCES_NAME = "prefs";
private static final String PREF_DIRECTORIES = "p.gallery.dirs";
private static final String PREF_SHOW_FILENAMES_IN_GRID = "p.gallery.fn";
+ public static final String PREF_ENCRYPTION_ITERATION_COUNT = "encryption_iteration_count";
+ public static final String PREF_ENCRYPTION_USE_DISK_CACHE = "encryption_use_disk_cache";
+ public static final String PREF_APP_SECURE = "app_secure";
+ public static final String PREF_APP_EDIT_FOLDERS = "app_edit_folders";
private final Context context;
private static Settings settings;
- private char[] password = null;
-
public static Settings getInstance(@NonNull Context context) {
if (settings == null) {
settings = new Settings(context);
@@ -65,50 +65,29 @@ private SharedPreferences.Editor getSharedPrefsEditor() {
return context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).edit();
}
- @Override
- protected void finalize() throws Throwable {
- Log.d(TAG, "finalize: ");
- Password.lock(context, this);
- super.finalize();
+ public int getIterationCount() {
+ return getSharedPrefs().getInt(PREF_ENCRYPTION_ITERATION_COUNT, 50000);
}
- @Nullable
- public char[] getTempPassword() {
- return password;
+ public void setIterationCount(int iterationCount) {
+ getSharedPrefsEditor().putInt(PREF_ENCRYPTION_ITERATION_COUNT, iterationCount).apply();
}
- public boolean isLocked() {
- return password == null || password.length == 0;
+ public boolean useDiskCache() {
+ return getSharedPrefs().getBoolean(PREF_ENCRYPTION_USE_DISK_CACHE, true);
}
- public void setTempPassword(@NonNull char[] password) {
- this.password = password;
+ public void setUseDiskCache(boolean useDiskCache) {
+ getSharedPrefsEditor().putBoolean(PREF_ENCRYPTION_USE_DISK_CACHE, useDiskCache).apply();
}
- public void clearTempPassword() {
- if (password != null) {
- Arrays.fill(password, (char) 0);
- password = null;
- }
+ public boolean isSecureFlag() {
+ return getSharedPrefs().getBoolean(PREF_APP_SECURE, true);
}
- public void addGalleryDirectory(@NonNull Uri uri, @Nullable IOnDirectoryAdded onDirectoryAdded) {
+ public void addGalleryDirectory(@NonNull Uri uri, boolean asRootDir, @Nullable IOnDirectoryAdded onDirectoryAdded) {
List directories = getGalleryDirectories(false);
- boolean isRootDir = true;
- Uri parentFolder = null;
- final String newLast = uri.getLastPathSegment() + "/";
- for (StoredDirectory storedDirectory : directories) {
- if (!storedDirectory.isRootDir()) {
- continue;
- }
- if (!uri.equals(storedDirectory.getUri()) && newLast.startsWith(storedDirectory.getUri().getLastPathSegment() + "/")) { // prevent adding a child of an already added folder
- isRootDir = false;
- parentFolder = storedDirectory.getUri();
- break;
- }
- }
- String uriString = uri.toString();
- StoredDirectory newDir = new StoredDirectory(uriString, isRootDir);
+ StoredDirectory newDir = new StoredDirectory(uri, asRootDir);
boolean reordered = false;
if (directories.contains(newDir)) {
Log.d(TAG, "addGalleryDirectory: uri already saved");
@@ -122,25 +101,27 @@ public void addGalleryDirectory(@NonNull Uri uri, @Nullable IOnDirectoryAdded on
getSharedPrefsEditor().putString(PREF_DIRECTORIES, stringListAsString(directories)).apply();
if (onDirectoryAdded != null) {
if (reordered) {
- onDirectoryAdded.onAlreadyExists(isRootDir);
- } else if (isRootDir) {
+ onDirectoryAdded.onAlreadyExists();
+ } else if (asRootDir) {
onDirectoryAdded.onAddedAsRoot();
} else {
- onDirectoryAdded.onAddedAsChildOf(parentFolder);
+ onDirectoryAdded.onAdded();
}
}
}
public void removeGalleryDirectory(@NonNull Uri uri) {
List directories = getGalleryDirectories(false);
- directories.remove(new StoredDirectory(uri.toString(), false));
+ String[] split = uri.toString().split("/document/");
+ directories.remove(new StoredDirectory(split[0], false));
+ directories.remove(new StoredDirectory(uri, false));
getSharedPrefsEditor().putString(PREF_DIRECTORIES, stringListAsString(directories)).apply();
}
public void removeGalleryDirectories(@NonNull List uris) {
List directories = getGalleryDirectories(false);
for (Uri u : uris) {
- directories.remove(new StoredDirectory(u.toString(), false));
+ directories.remove(new StoredDirectory(u, false));
}
getSharedPrefsEditor().putString(PREF_DIRECTORIES, stringListAsString(directories)).apply();
}
@@ -177,6 +158,7 @@ public List getGalleryDirectoriesAsUri(boolean rootDirsOnly) {
private List getGalleryDirectories(boolean rootDirsOnly) {
String s = getSharedPrefs().getString(PREF_DIRECTORIES, null);
List storedDirectories = new ArrayList<>();
+ Log.e(TAG, "getGalleryDirectories: " + s);
if (s != null && !s.isEmpty()) {
String[] split = s.split("\n");
for (String value : split) {
diff --git a/app/src/main/java/se/arctosoft/vault/utils/StringStuff.java b/app/src/main/java/se/arctosoft/vault/utils/StringStuff.java
index 24eab2e..6943205 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/StringStuff.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/StringStuff.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -25,7 +25,7 @@
import java.util.Random;
public class StringStuff {
- private static final String ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
+ private static final String ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int NAME_LENGTH = 32;
public static String getRandomFileName() {
diff --git a/app/src/main/java/se/arctosoft/vault/utils/Toaster.java b/app/src/main/java/se/arctosoft/vault/utils/Toaster.java
index 4ee3a9a..981f485 100644
--- a/app/src/main/java/se/arctosoft/vault/utils/Toaster.java
+++ b/app/src/main/java/se/arctosoft/vault/utils/Toaster.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -27,7 +27,7 @@
public class Toaster {
private static Toaster toaster;
- private static android.widget.Toast toast;
+ private static Toast toast;
private final WeakReference weakReference;
private Toaster(@NonNull Context context) {
diff --git a/app/src/main/java/se/arctosoft/vault/viewmodel/CopyViewModel.java b/app/src/main/java/se/arctosoft/vault/viewmodel/CopyViewModel.java
new file mode 100644
index 0000000..e6b03f6
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/viewmodel/CopyViewModel.java
@@ -0,0 +1,174 @@
+/*
+ * Valv-Android
+ * Copyright (C) 2024 Arctosoft AB
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.viewmodel;
+
+import android.net.Uri;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.documentfile.provider.DocumentFile;
+import androidx.fragment.app.FragmentActivity;
+import androidx.lifecycle.MutableLiveData;
+import androidx.lifecycle.ViewModel;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import se.arctosoft.vault.data.GalleryFile;
+import se.arctosoft.vault.data.ProgressData;
+import se.arctosoft.vault.interfaces.IOnFileOperationDone;
+import se.arctosoft.vault.interfaces.IOnProgress;
+import se.arctosoft.vault.utils.FileStuff;
+
+public class CopyViewModel extends ViewModel {
+ private static final String TAG = "CopyViewModel";
+
+ private final List files = new LinkedList<>();
+
+ private boolean running;
+ private long totalBytes;
+ private String destinationFolderName;
+ final AtomicBoolean interrupted = new AtomicBoolean(false);
+
+ private MutableLiveData progressData;
+
+ private Thread thread;
+ private IOnFileOperationDone onDoneBottomSheet, onDoneFragment;
+ private DocumentFile destinationDirectory;
+ private Uri currentDirectoryUri, destinationUri;
+
+ public MutableLiveData getProgressData() {
+ if (progressData == null) {
+ progressData = new MutableLiveData<>(null);
+ }
+ return progressData;
+ }
+
+ public void setDestinationFolderName(String destinationFolderName) {
+ this.destinationFolderName = destinationFolderName;
+ }
+
+ public String getDestinationFolderName() {
+ return destinationFolderName;
+ }
+
+ public void setDestinationDirectory(DocumentFile destinationDirectory) {
+ this.destinationDirectory = destinationDirectory;
+ }
+
+ public DocumentFile getDestinationDirectory() {
+ return destinationDirectory;
+ }
+
+ public void setCurrentDirectoryUri(Uri currentDirectoryUri) {
+ this.currentDirectoryUri = currentDirectoryUri;
+ }
+
+ public Uri getCurrentDirectoryUri() {
+ return currentDirectoryUri;
+ }
+
+ public void setDestinationUri(Uri destinationUri) {
+ this.destinationUri = destinationUri;
+ }
+
+ public Uri getDestinationUri() {
+ return destinationUri;
+ }
+
+ @NonNull
+ public List getFiles() {
+ return files;
+ }
+
+ public boolean isRunning() {
+ return running;
+ }
+
+ public void setRunning(boolean running) {
+ this.running = running;
+ }
+
+ public void setOnDoneBottomSheet(IOnFileOperationDone onFileOperationDone) {
+ this.onDoneBottomSheet = onFileOperationDone;
+ }
+
+ public void setOnDoneFragment(IOnFileOperationDone onFileOperationDone) {
+ this.onDoneFragment = onFileOperationDone;
+ }
+
+ public void setTotalBytes(long totalBytes) {
+ this.totalBytes = totalBytes;
+ }
+
+ public long getTotalBytes() {
+ return totalBytes;
+ }
+
+ public void cancel() {
+ Log.e(TAG, "cancel: ");
+ interrupted.set(true);
+ setRunning(false);
+ if (thread != null) {
+ thread.interrupt();
+ }
+ }
+
+ public void start(FragmentActivity activity) {
+ Log.e(TAG, "start: ");
+ if (thread != null) {
+ thread.interrupt();
+ }
+ interrupted.set(false);
+ thread = new Thread(() -> {
+ final int fileCount = files.size();
+ final List doneFiles = Collections.synchronizedList(new ArrayList<>(fileCount));
+ final long[] lastPublish = {0};
+ final IOnProgress onProgress = currentBytesDeleted -> {
+ if (System.currentTimeMillis() - lastPublish[0] > 20) {
+ lastPublish[0] = System.currentTimeMillis();
+ getProgressData().postValue(new ProgressData(fileCount, doneFiles.size() + 1, (int) Math.round((doneFiles.size() + 0.0) / fileCount * 100.0), null, null));
+ }
+ };
+
+ Log.e(TAG, "start: " + destinationUri);
+ DocumentFile destinationDocument = DocumentFile.fromTreeUri(activity, destinationUri);
+ for (GalleryFile f : files) {
+ boolean success = FileStuff.copyTo(activity, f, destinationDocument);
+ if (success) {
+ doneFiles.add(f);
+ onProgress.onProgress(doneFiles.size());
+ }
+ }
+
+ if (onDoneBottomSheet != null) {
+ onDoneBottomSheet.onDone(doneFiles);
+ }
+ if (onDoneFragment != null) {
+ onDoneFragment.onDone(doneFiles);
+ }
+ interrupted.set(false);
+ });
+ thread.start();
+ }
+
+}
diff --git a/app/src/main/java/se/arctosoft/vault/viewmodel/DeleteViewModel.java b/app/src/main/java/se/arctosoft/vault/viewmodel/DeleteViewModel.java
new file mode 100644
index 0000000..9552ee8
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/viewmodel/DeleteViewModel.java
@@ -0,0 +1,159 @@
+/*
+ * Valv-Android
+ * Copyright (C) 2024 Arctosoft AB
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.viewmodel;
+
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.fragment.app.FragmentActivity;
+import androidx.lifecycle.MutableLiveData;
+import androidx.lifecycle.ViewModel;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import se.arctosoft.vault.data.GalleryFile;
+import se.arctosoft.vault.data.ProgressData;
+import se.arctosoft.vault.interfaces.IOnFileOperationDone;
+import se.arctosoft.vault.interfaces.IOnProgress;
+import se.arctosoft.vault.utils.FileStuff;
+
+public class DeleteViewModel extends ViewModel {
+ private static final String TAG = "DeleteViewModel";
+
+ private final List filesToDelete = new LinkedList<>();
+
+ private boolean deleting;
+ private long totalBytes;
+ final AtomicBoolean interrupted = new AtomicBoolean(false);
+
+ private MutableLiveData progressData;
+
+ private Thread thread;
+ private IOnFileOperationDone onDeleteDoneBottomSheet, onDeleteDoneFragment;
+
+ public MutableLiveData getProgressData() {
+ if (progressData == null) {
+ progressData = new MutableLiveData<>(null);
+ }
+ return progressData;
+ }
+
+ @NonNull
+ public List getFilesToDelete() {
+ return filesToDelete;
+ }
+
+ public boolean isDeleting() {
+ return deleting;
+ }
+
+ public void setDeleting(boolean deleting) {
+ this.deleting = deleting;
+ }
+
+ public void setOnDeleteDoneBottomSheet(IOnFileOperationDone onImportDone) {
+ this.onDeleteDoneBottomSheet = onImportDone;
+ }
+
+ public void setOnDeleteDoneFragment(IOnFileOperationDone onDeleteDoneFragment) {
+ this.onDeleteDoneFragment = onDeleteDoneFragment;
+ }
+
+ public void setTotalBytes(long totalBytes) {
+ this.totalBytes = totalBytes;
+ }
+
+ public long getTotalBytes() {
+ return totalBytes;
+ }
+
+ public void cancelDelete() {
+ Log.e(TAG, "cancelDelete: ");
+ interrupted.set(true);
+ setDeleting(false);
+ if (thread != null) {
+ thread.interrupt();
+ }
+ }
+
+ public void startDelete(FragmentActivity activity) {
+ Log.e(TAG, "startDelete: ");
+ if (thread != null) {
+ thread.interrupt();
+ }
+ interrupted.set(false);
+ thread = new Thread(() -> {
+ final List deletedFiles = Collections.synchronizedList(new ArrayList<>(filesToDelete.size()));
+ final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(filesToDelete);
+ final AtomicLong bytesDeleted = new AtomicLong(0);
+ final int fileCount = filesToDelete.size();
+ final int threadCount = fileCount < 4 ? 1 : 4;
+
+ final long[] lastPublish = {0};
+ final IOnProgress onProgress = currentBytesDeleted -> {
+ if (System.currentTimeMillis() - lastPublish[0] > 20) {
+ lastPublish[0] = System.currentTimeMillis();
+ getProgressData().postValue(new ProgressData(filesToDelete.size(), deletedFiles.size() + 1, (int) Math.round((bytesDeleted.get() + 0.0) / totalBytes * 100.0), null, null));
+ }
+ };
+
+ List threads = new ArrayList<>(threadCount);
+ for (int i = 0; i < threadCount; i++) {
+ Thread t = new Thread(() -> {
+ GalleryFile galleryFile;
+ while (!interrupted.get() && (galleryFile = queue.poll()) != null) {
+ boolean deletedFile = FileStuff.deleteFile(activity, galleryFile.getUri());
+ if (deletedFile) {
+ deletedFiles.add(galleryFile);
+ boolean deletedThumb = FileStuff.deleteFile(activity, galleryFile.getThumbUri());
+ boolean deletedNote = FileStuff.deleteFile(activity, galleryFile.getNoteUri());
+ onProgress.onProgress(bytesDeleted.addAndGet(galleryFile.getSize()));
+ }
+ }
+ });
+ threads.add(t);
+ t.start();
+ }
+
+ for (Thread thread : threads) {
+ try {
+ thread.join();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ if (onDeleteDoneBottomSheet != null) {
+ onDeleteDoneBottomSheet.onDone(deletedFiles);
+ }
+ if (onDeleteDoneFragment != null) {
+ onDeleteDoneFragment.onDone(deletedFiles);
+ }
+ interrupted.set(false);
+ });
+ thread.start();
+ }
+
+}
diff --git a/app/src/main/java/se/arctosoft/vault/viewmodel/ExportViewModel.java b/app/src/main/java/se/arctosoft/vault/viewmodel/ExportViewModel.java
new file mode 100644
index 0000000..2fecca9
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/viewmodel/ExportViewModel.java
@@ -0,0 +1,158 @@
+/*
+ * Valv-Android
+ * Copyright (C) 2024 Arctosoft AB
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.viewmodel;
+
+import android.net.Uri;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.documentfile.provider.DocumentFile;
+import androidx.fragment.app.FragmentActivity;
+import androidx.lifecycle.MutableLiveData;
+import androidx.lifecycle.ViewModel;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import se.arctosoft.vault.data.GalleryFile;
+import se.arctosoft.vault.data.Password;
+import se.arctosoft.vault.data.ProgressData;
+import se.arctosoft.vault.encryption.Encryption;
+import se.arctosoft.vault.exception.InvalidPasswordException;
+import se.arctosoft.vault.interfaces.IOnFileOperationDone;
+import se.arctosoft.vault.interfaces.IOnProgress;
+
+public class ExportViewModel extends ViewModel {
+ private static final String TAG = "ExportViewModel";
+
+ private final List filesToExport = new LinkedList<>();
+
+ private boolean running;
+ private long totalBytes;
+ final AtomicBoolean interrupted = new AtomicBoolean(false);
+
+ private MutableLiveData progressData;
+
+ private Thread thread;
+ private IOnFileOperationDone onDoneBottomSheet, onDoneFragment;
+ private DocumentFile currentDocumentDirectory;
+
+ public MutableLiveData getProgressData() {
+ if (progressData == null) {
+ progressData = new MutableLiveData<>(null);
+ }
+ return progressData;
+ }
+
+ public void setCurrentDocumentDirectory(DocumentFile currentDocumentDirectory) {
+ this.currentDocumentDirectory = currentDocumentDirectory;
+ }
+
+ public DocumentFile getCurrentDocumentDirectory() {
+ return currentDocumentDirectory;
+ }
+
+ @NonNull
+ public List getFilesToExport() {
+ return filesToExport;
+ }
+
+ public boolean isRunning() {
+ return running;
+ }
+
+ public void setRunning(boolean running) {
+ this.running = running;
+ }
+
+ public void setOnDoneBottomSheet(IOnFileOperationDone onFileOperationDone) {
+ this.onDoneBottomSheet = onFileOperationDone;
+ }
+
+ public void setOnDoneFragment(IOnFileOperationDone onFileOperationDone) {
+ this.onDoneFragment = onFileOperationDone;
+ }
+
+ public void setTotalBytes(long totalBytes) {
+ this.totalBytes = totalBytes;
+ }
+
+ public long getTotalBytes() {
+ return totalBytes;
+ }
+
+ public void cancel() {
+ Log.e(TAG, "cancel: ");
+ interrupted.set(true);
+ setRunning(false);
+ if (thread != null) {
+ thread.interrupt();
+ }
+ }
+
+ public void start(FragmentActivity activity) {
+ Log.e(TAG, "start: ");
+ if (thread != null) {
+ thread.interrupt();
+ }
+ interrupted.set(false);
+ thread = new Thread(() -> {
+ Password password = Password.getInstance();
+ final int fileCount = filesToExport.size();
+ final List doneFiles = Collections.synchronizedList(new ArrayList<>(fileCount));
+ final long[] lastPublish = {0};
+ final IOnProgress onProgress = currentBytesDeleted -> {
+ if (System.currentTimeMillis() - lastPublish[0] > 20) {
+ lastPublish[0] = System.currentTimeMillis();
+ getProgressData().postValue(new ProgressData(fileCount, doneFiles.size() + 1, (int) Math.round((doneFiles.size() + 0.0) / fileCount * 100.0), null, null));
+ }
+ };
+ for (GalleryFile f : filesToExport) {
+ Encryption.IOnUriResult result = new Encryption.IOnUriResult() {
+ @Override
+ public void onUriResult(Uri outputUri) {
+ doneFiles.add(f);
+ onProgress.onProgress(doneFiles.size());
+ }
+
+ @Override
+ public void onError(Exception e) {
+ }
+
+ @Override
+ public void onInvalidPassword(InvalidPasswordException e) {
+ }
+ };
+ Encryption.decryptAndExport(activity, f.getUri(), currentDocumentDirectory, f, f.isVideo(), f.getVersion(), password.getPassword(), result);
+ }
+ if (onDoneBottomSheet != null) {
+ onDoneBottomSheet.onDone(doneFiles);
+ }
+ if (onDoneFragment != null) {
+ onDoneFragment.onDone(doneFiles);
+ }
+ interrupted.set(false);
+ });
+ thread.start();
+ }
+
+}
diff --git a/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryDirectoryViewModel.java b/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryDirectoryViewModel.java
deleted file mode 100644
index 4e4f802..0000000
--- a/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryDirectoryViewModel.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Valv-Android
- * Copyright (C) 2023 Arctosoft AB
- *
- * 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 https://www.gnu.org/licenses/.
- */
-
-package se.arctosoft.vault.viewmodel;
-
-import androidx.annotation.NonNull;
-import androidx.lifecycle.ViewModel;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import se.arctosoft.vault.data.GalleryFile;
-
-public class GalleryDirectoryViewModel extends ViewModel {
- private static final String TAG = "GalleryDirectoryViewMod";
-
- private final List galleryFiles = new LinkedList<>();
- private final List hiddenFiles = new LinkedList<>();
- private int currentPosition = 0;
- private boolean viewPagerVisible = false;
- private boolean initialised = false;
-
- public boolean isInitialised() {
- return initialised;
- }
-
- @NonNull
- public List getGalleryFiles() {
- return galleryFiles;
- }
-
- @NonNull
- public List getHiddenFiles() {
- return hiddenFiles;
- }
-
- public void setInitialised(List galleryFiles) {
- //Log.e(TAG, "setInitialised: " + galleryFiles.size());
- if (initialised) {
- return;
- }
- this.initialised = true;
- this.galleryFiles.addAll(galleryFiles);
- this.hiddenFiles.clear();
- }
-
- public int getCurrentPosition() {
- return currentPosition;
- }
-
- public void setCurrentPosition(int currentPosition) {
- this.currentPosition = currentPosition;
- }
-
- public boolean isViewpagerVisible() {
- return viewPagerVisible;
- }
-
- public void setViewpagerVisible(boolean fullscreen) {
- viewPagerVisible = fullscreen;
- }
-}
diff --git a/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryViewModel.java b/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryViewModel.java
index 2b181e2..fbe2ac9 100644
--- a/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryViewModel.java
+++ b/app/src/main/java/se/arctosoft/vault/viewmodel/GalleryViewModel.java
@@ -1,6 +1,6 @@
/*
* Valv-Android
- * Copyright (C) 2023 Arctosoft AB
+ * Copyright (C) 2024 Arctosoft AB
*
* 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
@@ -18,31 +18,155 @@
package se.arctosoft.vault.viewmodel;
-import androidx.annotation.Nullable;
+import android.content.Context;
+import android.net.Uri;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
import androidx.documentfile.provider.DocumentFile;
import androidx.lifecycle.ViewModel;
+import java.util.LinkedList;
import java.util.List;
+import se.arctosoft.vault.data.GalleryFile;
+import se.arctosoft.vault.interfaces.IOnAdapterItemChanged;
+
public class GalleryViewModel extends ViewModel {
- private List filesToAdd;
- private String textToImport;
+ private static final String TAG = "GalleryDirectoryViewMod";
+
+ private final List galleryFiles = new LinkedList<>();
+ private final List hiddenFiles = new LinkedList<>();
+
+ private DocumentFile currentDocumentDirectory;
+ private Uri currentDirectoryUri;
+ private String directory, nestedPath = "";
+ private int currentPosition = 0;
+ private boolean viewPagerVisible = false;
+ private boolean initialised = false;
+ private boolean inSelectionMode = false;
+ private boolean isRootDir = false;
+ private boolean isAllFolder = false;
+ private IOnAdapterItemChanged onAdapterItemChanged;
+
+ public boolean isInitialised() {
+ return initialised;
+ }
+
+ public void setInitialised(boolean initialised) {
+ this.initialised = initialised;
+ }
+
+ public void setOnAdapterItemChanged(IOnAdapterItemChanged onAdapterItemChanged) {
+ this.onAdapterItemChanged = onAdapterItemChanged;
+ }
+
+ public IOnAdapterItemChanged getOnAdapterItemChanged() {
+ return onAdapterItemChanged;
+ }
+
+ @NonNull
+ public List getGalleryFiles() {
+ return galleryFiles;
+ }
+
+ public void addGalleryFiles(List galleryFiles) {
+ this.galleryFiles.addAll(galleryFiles);
+ }
+
+ @NonNull
+ public List getHiddenFiles() {
+ return hiddenFiles;
+ }
+
+ public void setDirectory(String directory, Context context) {
+ this.directory = directory;
+ if (directory != null) {
+ currentDirectoryUri = Uri.parse(directory);
+ currentDocumentDirectory = DocumentFile.fromTreeUri(context, currentDirectoryUri);
+ if (!currentDocumentDirectory.getUri().toString().equals(currentDirectoryUri.toString())) {
+ String[] paths = nestedPath.split("/");
+ for (String s : paths) {
+ if (currentDocumentDirectory != null && s != null && !s.isEmpty()) {
+ DocumentFile found = currentDocumentDirectory.findFile(s);
+ if (found != null) {
+ currentDocumentDirectory = found;
+ }
+ }
+ }
+ }
+ } else {
+ currentDirectoryUri = null;
+ currentDocumentDirectory = null;
+ }
+ Log.e(TAG, "currentDocumentDirectory: " + currentDocumentDirectory);
+ }
+
+ public void setRootDir(boolean rootDir) {
+ isRootDir = rootDir;
+ }
+
+ public boolean isRootDir() {
+ return isRootDir;
+ }
+
+ public String getDirectory() {
+ return directory;
+ }
+
+ public void setNestedPath(String nestedPath) {
+ this.nestedPath = nestedPath;
+ }
+
+ public String getNestedPath() {
+ return nestedPath;
+ }
+
+ public void setCurrentDirectoryUri(Uri currentDirectoryUri) {
+ this.currentDirectoryUri = currentDirectoryUri;
+ }
+
+ public Uri getCurrentDirectoryUri() {
+ return currentDirectoryUri;
+ }
+
+ public void setCurrentDocumentDirectory(DocumentFile currentDocumentDirectory) {
+ this.currentDocumentDirectory = currentDocumentDirectory;
+ }
+
+ public DocumentFile getCurrentDocumentDirectory() {
+ return currentDocumentDirectory;
+ }
+
+ public int getCurrentPosition() {
+ return currentPosition;
+ }
+
+ public void setCurrentPosition(int currentPosition) {
+ this.currentPosition = currentPosition;
+ }
+
+ public boolean isViewpagerVisible() {
+ return viewPagerVisible;
+ }
+
+ public void setViewpagerVisible(boolean fullscreen) {
+ viewPagerVisible = fullscreen;
+ }
- public void setFilesToAdd(@Nullable List filesToAdd) {
- this.filesToAdd = filesToAdd;
+ public boolean isInSelectionMode() {
+ return inSelectionMode;
}
- @Nullable
- public List getFilesToAdd() {
- return filesToAdd;
+ public void setInSelectionMode(boolean inSelectionMode) {
+ this.inSelectionMode = inSelectionMode;
}
- public void setTextToImport(String textToImport) {
- this.textToImport = textToImport;
+ public void setAllFolder(boolean allFolder) {
+ isAllFolder = allFolder;
}
- @Nullable
- public String getTextToImport() {
- return textToImport;
+ public boolean isAllFolder() {
+ return isAllFolder;
}
}
diff --git a/app/src/main/java/se/arctosoft/vault/viewmodel/ImportViewModel.java b/app/src/main/java/se/arctosoft/vault/viewmodel/ImportViewModel.java
new file mode 100644
index 0000000..832f420
--- /dev/null
+++ b/app/src/main/java/se/arctosoft/vault/viewmodel/ImportViewModel.java
@@ -0,0 +1,257 @@
+/*
+ * Valv-Android
+ * Copyright (C) 2024 Arctosoft AB
+ *
+ * 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 https://www.gnu.org/licenses/.
+ */
+
+package se.arctosoft.vault.viewmodel;
+
+import android.icu.text.DecimalFormat;
+import android.net.Uri;
+import android.util.Log;
+import android.util.Pair;
+
+import androidx.annotation.NonNull;
+import androidx.documentfile.provider.DocumentFile;
+import androidx.fragment.app.FragmentActivity;
+import androidx.lifecycle.MutableLiveData;
+import androidx.lifecycle.ViewModel;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import se.arctosoft.vault.data.GalleryFile;
+import se.arctosoft.vault.data.Password;
+import se.arctosoft.vault.data.ProgressData;
+import se.arctosoft.vault.encryption.Encryption;
+import se.arctosoft.vault.interfaces.IOnImportDone;
+import se.arctosoft.vault.interfaces.IOnProgress;
+
+public class ImportViewModel extends ViewModel {
+ private static final String TAG = "ImportViewModel";
+
+ private final List filesToImport = new LinkedList<>();
+ private final List textToImport = new LinkedList<>();
+
+ private boolean importing, deleteAfterImport, sameDirectory, fromShare;
+ private long totalBytes;
+ private String destinationFolderName;
+ private Uri currentDirectoryUri, importToUri;
+ private DocumentFile destinationDirectory;
+ private final AtomicBoolean interrupted = new AtomicBoolean(false);
+
+ private MutableLiveData progressData;
+
+ private Thread importThread;
+ private IOnImportDone onImportDoneBottomSheet, onImportDoneFragment;
+
+ public MutableLiveData getProgressData() {
+ if (progressData == null) {
+ progressData = new MutableLiveData<>(null);
+ }
+ return progressData;
+ }
+
+ @NonNull
+ public List getFilesToImport() {
+ return filesToImport;
+ }
+
+ public List getTextToImport() {
+ return textToImport;
+ }
+
+ public boolean isImporting() {
+ return importing;
+ }
+
+ public void setImporting(boolean importing) {
+ this.importing = importing;
+ }
+
+ public void setOnImportDoneBottomSheet(IOnImportDone onImportDone) {
+ this.onImportDoneBottomSheet = onImportDone;
+ }
+
+ public void setOnImportDoneFragment(IOnImportDone onImportDoneFragment) {
+ this.onImportDoneFragment = onImportDoneFragment;
+ }
+
+ public void setDestinationDirectory(DocumentFile destinationDirectory) {
+ this.destinationDirectory = destinationDirectory;
+ }
+
+ public DocumentFile getDestinationDirectory() {
+ return destinationDirectory;
+ }
+
+ public void setSameDirectory(boolean sameDirectory) {
+ this.sameDirectory = sameDirectory;
+ }
+
+ public boolean isSameDirectory() {
+ return sameDirectory;
+ }
+
+ public boolean isFromShare() {
+ return fromShare;
+ }
+
+ public void setFromShare(boolean fromShare) {
+ this.fromShare = fromShare;
+ }
+
+ public boolean isDeleteAfterImport() {
+ return deleteAfterImport;
+ }
+
+ public void setDeleteAfterImport(boolean deleteAfterImport) {
+ this.deleteAfterImport = deleteAfterImport;
+ }
+
+ public void setTotalBytes(long totalBytes) {
+ this.totalBytes = totalBytes;
+ }
+
+ public long getTotalBytes() {
+ return totalBytes;
+ }
+
+ public Uri getImportToUri() {
+ return importToUri;
+ }
+
+ public void setImportToUri(Uri importToUri) {
+ this.importToUri = importToUri;
+ }
+
+ public void setCurrentDirectoryUri(Uri currentDirectoryUri) {
+ this.currentDirectoryUri = currentDirectoryUri;
+ }
+
+ public Uri getCurrentDirectoryUri() {
+ return currentDirectoryUri;
+ }
+
+ public void setDestinationFolderName(String destinationFolderName) {
+ this.destinationFolderName = destinationFolderName;
+ }
+
+ public String getDestinationFolderName() {
+ return destinationFolderName;
+ }
+
+ public void cancelImport() {
+ Log.e(TAG, "cancelImport: ");
+ interrupted.set(true);
+ setImporting(false);
+ setImportToUri(null);
+ if (importThread != null) {
+ importThread.interrupt();
+ }
+ }
+
+ public void startImport(FragmentActivity activity) {
+ Log.e(TAG, "startImport: ");
+ if (importThread != null) {
+ importThread.interrupt();
+ }
+ interrupted.set(false);
+ importThread = new Thread(() -> {
+ Password password = Password.getInstance();
+ final DecimalFormat decimalFormat = new DecimalFormat("0.00");
+ final String totalMB = decimalFormat.format(totalBytes / 1000000.0);
+ final int[] progress = new int[]{1};
+ int errors = 0;
+ int thumbErrors = 0;
+ final double[] bytesDone = new double[]{0};
+ final long[] lastPublish = {0};
+ final int totalSize = filesToImport.size() + textToImport.size();
+ final IOnProgress onProgress = progress1 -> {
+ if (System.currentTimeMillis() - lastPublish[0] > 20) {
+ lastPublish[0] = System.currentTimeMillis();
+ getProgressData().postValue(new ProgressData(totalSize, progress[0], (int) Math.round((bytesDone[0] + progress1) / totalBytes * 100.0),
+ decimalFormat.format((bytesDone[0] + progress1) / 1000000.0), totalMB));
+ }
+ };
+ onProgress.onProgress(0);
+ for (DocumentFile file : filesToImport) {
+ if (Thread.currentThread().isInterrupted() || interrupted.get()) {
+ if (onImportDoneFragment != null) {
+ onImportDoneFragment.onDone(importToUri, sameDirectory, progress[0] - 1, errors, thumbErrors);
+ }
+ Log.e(TAG, "startImport: interrupted, stop");
+ break;
+ }
+ Pair