Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83e9791b77 | ||
|
|
a58d1f5d96 | ||
|
|
894a1f7b12 | ||
|
|
38f7da4194 | ||
|
|
5b188bf555 | ||
|
|
0cb99758d4 | ||
|
|
ef5d5c028c | ||
|
|
e7bc8479b5 | ||
|
|
e9e017215f | ||
|
|
bc1b14e4f4 | ||
|
|
7c86d1786a | ||
|
|
9ff2cdb502 | ||
|
|
0843aa3701 | ||
|
|
f9dcb530f9 | ||
|
|
e708cbbdaa | ||
|
|
0b8f55501a |
No files matched your search
@@ -13,8 +13,12 @@ import kotlinx.parcelize.IgnoredOnParcel
|
||||
import kotlinx.parcelize.Parcelize
|
||||
import java.util.Random
|
||||
|
||||
/** Which way the image data flows for a job. */
|
||||
enum class JobOperation { WRITE, BACKUP }
|
||||
|
||||
object Intents {
|
||||
const val START_JOB = "eu.depau.etchdroid.action.START_JOB"
|
||||
const val START_BACKUP = "eu.depau.etchdroid.action.START_BACKUP"
|
||||
const val USB_PERMISSION = "eu.depau.etchdroid.action.USB_PERMISSION"
|
||||
const val SKIP_VERIFY = "eu.depau.etchdroid.action.CANCEL_VERIFY"
|
||||
const val JOB_PROGRESS = "eu.depau.etchdroid.broadcast.JOB_PROGRESS"
|
||||
@@ -32,6 +36,8 @@ data class JobStatusInfo(
|
||||
val jobId: Int,
|
||||
val isVerifying: Boolean = false,
|
||||
val exception: EtchDroidException? = null,
|
||||
val isBackup: Boolean = false,
|
||||
val sha256: String? = null,
|
||||
) : Parcelable {
|
||||
@IgnoredOnParcel
|
||||
val percent =
|
||||
@@ -48,11 +54,13 @@ fun getConfirmOperationActivityIntent(
|
||||
destDevice: UsbMassStorageDeviceDescriptor,
|
||||
packageContext: Context? = null,
|
||||
cls: Class<*>? = null,
|
||||
operation: JobOperation = JobOperation.WRITE,
|
||||
): Intent {
|
||||
return mkIntent(packageContext, cls).apply {
|
||||
data = sourceUri
|
||||
putExtra("sourceUri", sourceUri)
|
||||
putExtra("destDevice", destDevice)
|
||||
putExtra("operation", operation.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +91,32 @@ fun getStartJobIntent(
|
||||
}
|
||||
}
|
||||
|
||||
fun getStartBackupJobIntent(
|
||||
destinationUri: Uri,
|
||||
sourceDevice: UsbMassStorageDeviceDescriptor,
|
||||
jobId: Int,
|
||||
packageContext: Context? = null,
|
||||
cls: Class<*>? = null,
|
||||
): Intent {
|
||||
return mkIntent(packageContext, cls).apply {
|
||||
action = Intents.START_BACKUP
|
||||
data = destinationUri
|
||||
// Same rationale as getStartJobIntent: hand the URI grants to the service so they outlive
|
||||
// the activity. A backup writes the image and may read it back to verify, so request both
|
||||
// grants, but only when we actually hold them (granting a lost permission throws).
|
||||
if (packageContext?.checkCallingOrSelfUriPermission(
|
||||
destinationUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
if (packageContext?.checkCallingOrSelfUriPermission(
|
||||
destinationUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
) addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
|
||||
putExtra("destDevice", sourceDevice)
|
||||
putExtra("jobId", jobId)
|
||||
}
|
||||
}
|
||||
|
||||
fun getProgressUpdateIntent(
|
||||
sourceUri: Uri,
|
||||
destDevice: UsbMassStorageDeviceDescriptor,
|
||||
@@ -93,13 +127,14 @@ fun getProgressUpdateIntent(
|
||||
isVerifying: Boolean = false,
|
||||
packageContext: Context? = null,
|
||||
cls: Class<*>? = null,
|
||||
isBackup: Boolean = false,
|
||||
) = mkIntent(packageContext, cls).apply {
|
||||
action = Intents.JOB_PROGRESS
|
||||
putExtra("sourceUri", sourceUri)
|
||||
putExtra(
|
||||
"status", JobStatusInfo(
|
||||
sourceUri, destDevice, processedBytes, totalBytes, speed, jobId,
|
||||
isVerifying = isVerifying
|
||||
isVerifying = isVerifying, isBackup = isBackup
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -113,6 +148,7 @@ fun getErrorIntent(
|
||||
exception: EtchDroidException,
|
||||
packageContext: Context? = null,
|
||||
cls: Class<*>? = null,
|
||||
isBackup: Boolean = false,
|
||||
) = mkIntent(packageContext, cls).apply {
|
||||
action = Intents.ERROR
|
||||
putExtra("sourceUri", sourceUri)
|
||||
@@ -120,7 +156,7 @@ fun getErrorIntent(
|
||||
"status",
|
||||
JobStatusInfo(
|
||||
sourceUri, destDevice, processedBytes, totalBytes,
|
||||
jobId = jobId, exception = exception
|
||||
jobId = jobId, exception = exception, isBackup = isBackup
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -131,10 +167,18 @@ fun getFinishedIntent(
|
||||
totalBytes: Long,
|
||||
packageContext: Context? = null,
|
||||
cls: Class<*>? = null,
|
||||
isBackup: Boolean = false,
|
||||
sha256: String? = null,
|
||||
) = mkIntent(packageContext, cls).apply {
|
||||
action = Intents.FINISHED
|
||||
putExtra("sourceUri", sourceUri)
|
||||
putExtra("status", JobStatusInfo(sourceUri, destDevice, totalBytes, totalBytes, jobId = -1))
|
||||
putExtra(
|
||||
"status",
|
||||
JobStatusInfo(
|
||||
sourceUri, destDevice, totalBytes, totalBytes, jobId = -1,
|
||||
isBackup = isBackup, sha256 = sha256
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fun Intent.getProgressActivityPendingIntent(
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package eu.depau.etchdroid.service
|
||||
|
||||
import eu.depau.etchdroid.massstorage.BlockDeviceInputStream
|
||||
import eu.depau.etchdroid.utils.TimeoutBump
|
||||
import eu.depau.etchdroid.utils.exception.CouldNotWriteBackupException
|
||||
import eu.depau.etchdroid.utils.timeoutWatchdog
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import me.jahnen.libaums.core.driver.BlockDeviceDriver
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Streams a block device into a destination stream, hashing the whole destination as it goes.
|
||||
*
|
||||
* The destination may already contain a prefix of the device (an interrupted backup): the caller
|
||||
* passes it as [existing] together with the number of bytes it holds in [resumeOffset]. Those bytes
|
||||
* are fed to the digest first, then the device is read from that offset onwards. Neither [output]
|
||||
* nor [existing] is closed here: the service that opened them owns them.
|
||||
*/
|
||||
object BackupFlow {
|
||||
private const val DIGEST_ALGORITHM = "SHA-256"
|
||||
|
||||
/**
|
||||
* Appends the contents of [blockDev] to [output], starting at [resumeOffset].
|
||||
*
|
||||
* @param blockDev The device to back up.
|
||||
* @param output The destination stream, positioned at its end.
|
||||
* @param existing The destination bytes from 0 to [resumeOffset], or null when [resumeOffset]
|
||||
* is 0.
|
||||
* @param resumeOffset The number of device bytes already present in the destination; the
|
||||
* device is read from here.
|
||||
* @param deviceSize The total number of bytes to back up.
|
||||
* @param bufferSize The chunk size in bytes.
|
||||
* @param notifyCurrentOffset Called with the number of bytes processed after every device
|
||||
* chunk.
|
||||
* @param coroScope The coroutine scope for the prefetching I/O worker.
|
||||
* @param grabWakeLock Called periodically to keep the device awake.
|
||||
* @param sendProgressUpdate Reports progress through both the prefix-hash and device phases.
|
||||
* @return The lowercase hex SHA-256 of the whole destination file.
|
||||
* @throws CouldNotWriteBackupException If the existing prefix cannot be read in full or the
|
||||
* destination cannot be written.
|
||||
*/
|
||||
suspend fun backupImage(
|
||||
blockDev: BlockDeviceDriver,
|
||||
output: OutputStream,
|
||||
existing: InputStream?,
|
||||
resumeOffset: Long,
|
||||
deviceSize: Long,
|
||||
bufferSize: Long,
|
||||
notifyCurrentOffset: (offset: Long) -> Unit,
|
||||
coroScope: CoroutineScope,
|
||||
grabWakeLock: () -> Unit,
|
||||
sendProgressUpdate: (
|
||||
lastReadBytes: Int,
|
||||
processedBytes: Long,
|
||||
totalBytes: Long,
|
||||
isVerifying: Boolean,
|
||||
) -> Unit,
|
||||
): String {
|
||||
require(bufferSize > 0) { "bufferSize must be positive" }
|
||||
if (resumeOffset > deviceSize) throw CouldNotWriteBackupException(
|
||||
"Existing backup is larger than the device", null
|
||||
)
|
||||
|
||||
val digest = MessageDigest.getInstance(DIGEST_ALGORITHM)
|
||||
val buffer = ByteArray(bufferSize.toInt())
|
||||
val src = BlockDeviceInputStream(
|
||||
blockDev, coroScope, BUFFER_BLOCKS / QUEUE_SIZE, QUEUE_SIZE
|
||||
)
|
||||
var processedBytes = 0L
|
||||
|
||||
try {
|
||||
timeoutWatchdog(IO_TIMEOUT) { watchdog ->
|
||||
Thread.currentThread().name = "backupImage coroutine scope"
|
||||
|
||||
// Re-hash what a previous run already wrote so the final digest covers the whole
|
||||
// file, and report it as progress: a long prefix must not look like a stalled job.
|
||||
if (resumeOffset > 0) {
|
||||
processedBytes = hashExistingPrefix(
|
||||
existing, resumeOffset, buffer, digest, deviceSize,
|
||||
grabWakeLock, watchdog, sendProgressUpdate,
|
||||
)
|
||||
}
|
||||
|
||||
// The stream is freshly created and still at offset 0, so seekAsync's relative
|
||||
// skip is the absolute resume position here.
|
||||
src.seekAsync(resumeOffset)
|
||||
|
||||
while (processedBytes < deviceSize) {
|
||||
grabWakeLock()
|
||||
watchdog.bump()
|
||||
|
||||
val toRead =
|
||||
minOf(buffer.size.toLong(), deviceSize - processedBytes).toInt()
|
||||
val read = src.readAsync(buffer, 0, toRead)
|
||||
if (read < 0) throw CouldNotWriteBackupException(
|
||||
"Device ended before the expected size: " +
|
||||
"expected $deviceSize bytes, got $processedBytes", null
|
||||
)
|
||||
|
||||
watchdog.bump()
|
||||
digest.update(buffer, 0, read)
|
||||
|
||||
try {
|
||||
output.write(buffer, 0, read)
|
||||
output.flush()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
throw CouldNotWriteBackupException("Failed to write backup file", e)
|
||||
}
|
||||
watchdog.bump()
|
||||
|
||||
processedBytes += read
|
||||
notifyCurrentOffset(processedBytes)
|
||||
sendProgressUpdate(read, processedBytes, deviceSize, false)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
src.closeAsync()
|
||||
}
|
||||
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads exactly [resumeOffset] bytes from [existing] into [digest], reporting progress as it
|
||||
* goes, and returns the number of bytes consumed. The watchdog is bumped per chunk: hashing a
|
||||
* large prefix takes longer than one I/O timeout on its own.
|
||||
*/
|
||||
private fun hashExistingPrefix(
|
||||
existing: InputStream?,
|
||||
resumeOffset: Long,
|
||||
buffer: ByteArray,
|
||||
digest: MessageDigest,
|
||||
totalBytes: Long,
|
||||
grabWakeLock: () -> Unit,
|
||||
watchdog: TimeoutBump,
|
||||
sendProgressUpdate: (
|
||||
lastReadBytes: Int,
|
||||
processedBytes: Long,
|
||||
totalBytes: Long,
|
||||
isVerifying: Boolean,
|
||||
) -> Unit,
|
||||
): Long {
|
||||
val stream = existing ?: throw CouldNotWriteBackupException(
|
||||
"Cannot resume: the existing backup data is missing", null
|
||||
)
|
||||
var consumed = 0L
|
||||
|
||||
while (consumed < resumeOffset) {
|
||||
grabWakeLock()
|
||||
watchdog.bump()
|
||||
|
||||
val toRead = minOf(buffer.size.toLong(), resumeOffset - consumed).toInt()
|
||||
val read = try {
|
||||
stream.read(buffer, 0, toRead)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
throw CouldNotWriteBackupException("Failed to read existing backup data", e)
|
||||
}
|
||||
watchdog.bump()
|
||||
if (read <= 0) throw CouldNotWriteBackupException(
|
||||
"Existing backup data ends before the resume offset", null
|
||||
)
|
||||
|
||||
digest.update(buffer, 0, read)
|
||||
consumed += read
|
||||
// The prefix is not device I/O, but marking it as the backup's "verifying" phase is
|
||||
// how the UI and the notification tell it apart from the copy phase.
|
||||
sendProgressUpdate(read, consumed, totalBytes, true)
|
||||
}
|
||||
|
||||
return consumed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package eu.depau.etchdroid.service
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.storage.StorageManager
|
||||
import android.os.storage.StorageVolume
|
||||
import android.provider.DocumentsContract
|
||||
import java.util.UUID
|
||||
|
||||
private const val EXTERNAL_STORAGE_AUTHORITY = "com.android.externalstorage.documents"
|
||||
private const val PRIMARY_VOLUME_ID = "primary"
|
||||
|
||||
/**
|
||||
* Extracts the storage volume ID (`primary`, `1234-ABCD`, ...) from an ExternalStorageProvider
|
||||
* document URI. Returns null for URIs belonging to other providers.
|
||||
*/
|
||||
fun documentVolumeId(uri: Uri): String? {
|
||||
if (uri.authority != EXTERNAL_STORAGE_AUTHORITY) return null
|
||||
val documentId = try {
|
||||
DocumentsContract.getDocumentId(uri)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
return null
|
||||
}
|
||||
return documentId.substringBefore(':').takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort lookup of the bytes that can still be allocated on the volume holding [uri].
|
||||
* Returns null on API levels below 26 and whenever the volume cannot be resolved.
|
||||
*/
|
||||
fun availableBytesFor(context: Context, uri: Uri): Long? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return null
|
||||
return try {
|
||||
val volumeId = documentVolumeId(uri) ?: return null
|
||||
val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
|
||||
?: return null
|
||||
val volume = storageManager.storageVolumes.firstOrNull { volume ->
|
||||
if (volumeId == PRIMARY_VOLUME_ID) volume.isPrimary else volume.uuid == volumeId
|
||||
} ?: return null
|
||||
val storageUuid = storageUuidFor(volume) ?: return null
|
||||
storageManager.getAllocatableBytes(storageUuid)
|
||||
} catch (e: Throwable) {
|
||||
// Best effort: a hidden or unsupported framework API must never crash the backup flow.
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the UUID expected by [StorageManager.getAllocatableBytes] without touching
|
||||
* hidden framework APIs on older releases.
|
||||
*/
|
||||
@SuppressLint("NewApi") // public in the SDK only since API 31
|
||||
private fun storageUuidFor(volume: StorageVolume): UUID? =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
volume.storageUuid
|
||||
} else {
|
||||
// getStorageUuid() is a hidden API below API 31. The public volume UUID is the best
|
||||
// available substitute; a null (primary volume) or non-UUID value means "unknown".
|
||||
volume.uuid?.let { uuid -> runCatching { UUID.fromString(uuid) }.getOrNull() }
|
||||
}
|
||||
@@ -8,13 +8,16 @@ import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.PowerManager
|
||||
import android.provider.DocumentsContract
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
import eu.depau.etchdroid.Intents
|
||||
import eu.depau.etchdroid.JobOperation
|
||||
import eu.depau.etchdroid.JobStatusInfo
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.getErrorIntent
|
||||
@@ -32,10 +35,12 @@ import eu.depau.etchdroid.service.WorkerServiceFlowImpl.writeImage
|
||||
import eu.depau.etchdroid.ui.ProgressActivity
|
||||
import eu.depau.etchdroid.utils.TimeoutExpiredException
|
||||
import eu.depau.etchdroid.utils.broadcastReceiver
|
||||
import eu.depau.etchdroid.utils.exception.CouldNotWriteBackupException
|
||||
import eu.depau.etchdroid.utils.exception.InitException
|
||||
import eu.depau.etchdroid.utils.exception.MissingDeviceException
|
||||
import eu.depau.etchdroid.utils.exception.NoMediumException
|
||||
import eu.depau.etchdroid.utils.exception.NotEnoughSpaceException
|
||||
import eu.depau.etchdroid.utils.exception.NotEnoughSpaceForBackupException
|
||||
import eu.depau.etchdroid.utils.exception.OpenFileException
|
||||
import eu.depau.etchdroid.utils.exception.UnknownException
|
||||
import eu.depau.etchdroid.utils.exception.UsbCommunicationException
|
||||
@@ -44,6 +49,7 @@ import eu.depau.etchdroid.utils.exception.UsbDriveTooLargeException
|
||||
import eu.depau.etchdroid.utils.exception.VerificationFailedException
|
||||
import eu.depau.etchdroid.utils.exception.base.EtchDroidException
|
||||
import eu.depau.etchdroid.utils.exception.base.FatalException
|
||||
import eu.depau.etchdroid.utils.isIncompleteBackupName
|
||||
import eu.depau.etchdroid.utils.ktexts.broadcastLocally
|
||||
import eu.depau.etchdroid.utils.ktexts.broadcastLocallySync
|
||||
import eu.depau.etchdroid.utils.ktexts.getDisplayName
|
||||
@@ -55,6 +61,7 @@ import eu.depau.etchdroid.utils.ktexts.threadIdCompat
|
||||
import eu.depau.etchdroid.utils.ktexts.toHRSize
|
||||
import eu.depau.etchdroid.utils.lateInit
|
||||
import eu.depau.etchdroid.utils.timeoutWatchdog
|
||||
import eu.depau.etchdroid.utils.withoutPartSuffix
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -69,6 +76,8 @@ import me.jahnen.libaums.core.driver.scsi.commands.sense.SenseException
|
||||
import me.jahnen.libaums.core.usb.PipeException
|
||||
import me.jahnen.libaums.libusbcommunication.ErrNoIOException
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.BufferedOutputStream
|
||||
import java.io.FileNotFoundException
|
||||
import java.io.InputStream
|
||||
import java.util.Random
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
@@ -90,6 +99,7 @@ class WorkerService : LifecycleService() {
|
||||
private var mLoggedNotificationWarning = false
|
||||
private var mNotificationsSetUp = false
|
||||
private val mProgressNotificationId = Random().nextInt()
|
||||
private var mOperation = JobOperation.WRITE
|
||||
private lateinit var mSourceUri: Uri
|
||||
private lateinit var mDestDevice: UsbMassStorageDeviceDescriptor
|
||||
private var mJobId by lateInit<Int>(mutable = true)
|
||||
@@ -164,21 +174,36 @@ class WorkerService : LifecycleService() {
|
||||
.setSmallIcon(R.drawable.ic_write_to_usb_anim)
|
||||
.setContentTitle(
|
||||
getString(
|
||||
if (status.isVerifying) R.string.notification_verify_progress_title
|
||||
else R.string.notification_write_progress_title
|
||||
when {
|
||||
status.isBackup && status.isVerifying ->
|
||||
R.string.notification_backup_prefix_progress_title
|
||||
|
||||
status.isBackup -> R.string.notification_backup_progress_title
|
||||
status.isVerifying -> R.string.notification_verify_progress_title
|
||||
else -> R.string.notification_write_progress_title
|
||||
}
|
||||
)
|
||||
)
|
||||
.setContentText(
|
||||
if (status.isVerifying) getString(
|
||||
R.string.notification_verify_progress_content,
|
||||
mDestDevice.name,
|
||||
filenameStr
|
||||
)
|
||||
else getString(
|
||||
R.string.notification_write_progress_content,
|
||||
filenameStr,
|
||||
mDestDevice.name
|
||||
)
|
||||
when {
|
||||
status.isBackup -> getString(
|
||||
R.string.notification_backup_progress_content,
|
||||
mDestDevice.name,
|
||||
filenameStr
|
||||
)
|
||||
|
||||
status.isVerifying -> getString(
|
||||
R.string.notification_verify_progress_content,
|
||||
mDestDevice.name,
|
||||
filenameStr
|
||||
)
|
||||
|
||||
else -> getString(
|
||||
R.string.notification_write_progress_content,
|
||||
filenameStr,
|
||||
mDestDevice.name
|
||||
)
|
||||
}
|
||||
)
|
||||
.setContentIntent(
|
||||
getProgressUpdateIntent(
|
||||
@@ -190,7 +215,8 @@ class WorkerService : LifecycleService() {
|
||||
status.totalBytes,
|
||||
isVerifying = status.isVerifying,
|
||||
packageContext = this@WorkerService,
|
||||
cls = ProgressActivity::class.java
|
||||
cls = ProgressActivity::class.java,
|
||||
isBackup = status.isBackup
|
||||
).getProgressActivityPendingIntent(this@WorkerService)
|
||||
)
|
||||
.setSubText(
|
||||
@@ -215,8 +241,13 @@ class WorkerService : LifecycleService() {
|
||||
.setSmallIcon(R.drawable.ic_write_to_usb_failed)
|
||||
.setContentTitle(
|
||||
getString(
|
||||
if (status.exception is FatalException) R.string.write_failed
|
||||
else R.string.action_required
|
||||
when {
|
||||
status.exception is FatalException && status.isBackup ->
|
||||
R.string.backup_failed
|
||||
|
||||
status.exception is FatalException -> R.string.write_failed
|
||||
else -> R.string.action_required
|
||||
}
|
||||
)
|
||||
)
|
||||
.setContentText(status.exception.getUiMessage(this@WorkerService))
|
||||
@@ -229,7 +260,8 @@ class WorkerService : LifecycleService() {
|
||||
status.totalBytes,
|
||||
status.exception,
|
||||
packageContext = this@WorkerService,
|
||||
cls = ProgressActivity::class.java
|
||||
cls = ProgressActivity::class.java,
|
||||
isBackup = status.isBackup
|
||||
).getProgressActivityPendingIntent(this@WorkerService)
|
||||
)
|
||||
.setOngoing(false)
|
||||
@@ -246,9 +278,19 @@ class WorkerService : LifecycleService() {
|
||||
mJobId, NotificationCompat
|
||||
.Builder(this@WorkerService, JOB_RESULT_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_written_to_usb)
|
||||
.setContentTitle(getString(R.string.write_finished))
|
||||
.setContentText(
|
||||
.setContentTitle(
|
||||
getString(
|
||||
if (status.isBackup) R.string.backup_finished
|
||||
else R.string.write_finished
|
||||
)
|
||||
)
|
||||
.setContentText(
|
||||
if (status.isBackup) getString(
|
||||
R.string.backup_success_notif_content_text,
|
||||
mDestDevice.name,
|
||||
filenameStr.withoutPartSuffix()
|
||||
)
|
||||
else getString(
|
||||
R.string.success_notif_content_text, filenameStr, mDestDevice.name
|
||||
)
|
||||
)
|
||||
@@ -258,7 +300,9 @@ class WorkerService : LifecycleService() {
|
||||
mDestDevice,
|
||||
status.totalBytes,
|
||||
packageContext = this@WorkerService,
|
||||
cls = ProgressActivity::class.java
|
||||
cls = ProgressActivity::class.java,
|
||||
isBackup = status.isBackup,
|
||||
sha256 = status.sha256
|
||||
).getProgressActivityPendingIntent(this@WorkerService)
|
||||
)
|
||||
.setOngoing(false)
|
||||
@@ -294,7 +338,7 @@ class WorkerService : LifecycleService() {
|
||||
val verifyOnly: Boolean
|
||||
|
||||
try {
|
||||
if (intent?.action != Intents.START_JOB) {
|
||||
if (intent?.action != Intents.START_JOB && intent?.action != Intents.START_BACKUP) {
|
||||
Telemetry.captureMessage("Received invalid intent action: ${intent?.action}")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
@@ -304,21 +348,30 @@ class WorkerService : LifecycleService() {
|
||||
// interface claim from each other, killing each other's in-flight transfers.
|
||||
// Also guards mJobId/mSourceUri/mDestDevice from being overwritten mid-job.
|
||||
if (!mJobActive.compareAndSet(false, true)) {
|
||||
Telemetry.captureMessage("Ignoring START_JOB: a job is already running")
|
||||
Telemetry.captureMessage("Ignoring ${intent.action}: a job is already running")
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
mOperation =
|
||||
if (intent.action == Intents.START_BACKUP) JobOperation.BACKUP
|
||||
else JobOperation.WRITE
|
||||
|
||||
mSourceUri = intent.data!!
|
||||
mDestDevice = intent.safeParcelableExtra<UsbMassStorageDeviceDescriptor>("destDevice")
|
||||
?: throw MissingDeviceException()
|
||||
mJobId = intent.getIntExtra("jobId", -1)
|
||||
offset = intent.getLongExtra("offset", 0L)
|
||||
verifyOnly = intent.getBooleanExtra("verifyOnly", false)
|
||||
// Backups always append to whatever the destination already holds.
|
||||
offset =
|
||||
if (mOperation == JobOperation.BACKUP) 0L
|
||||
else intent.getLongExtra("offset", 0L)
|
||||
verifyOnly =
|
||||
mOperation != JobOperation.BACKUP && intent.getBooleanExtra("verifyOnly", false)
|
||||
|
||||
val fileName = mSourceUri.getFileName(this@WorkerService) ?: "Unknown file"
|
||||
Telemetry.configureScope {
|
||||
setTag("intent", intent.toString())
|
||||
setTag("job.id", mJobId.toString())
|
||||
setTag("job.type", mOperation.name.lowercase())
|
||||
setTag("job.offset", offset.toString())
|
||||
setTag("job.verifyOnly", verifyOnly.toString())
|
||||
setTag("image.filename", fileName)
|
||||
@@ -355,7 +408,13 @@ class WorkerService : LifecycleService() {
|
||||
val downstreamException =
|
||||
exception as? EtchDroidException ?: UnknownException(exception)
|
||||
getErrorIntent(
|
||||
mSourceUri, mDestDevice, mJobId, 0, 0, exception = downstreamException
|
||||
mSourceUri,
|
||||
mDestDevice,
|
||||
mJobId,
|
||||
0,
|
||||
0,
|
||||
exception = downstreamException,
|
||||
isBackup = mOperation == JobOperation.BACKUP
|
||||
).broadcastLocallySync(this@WorkerService)
|
||||
}
|
||||
mJobActive.set(false)
|
||||
@@ -421,85 +480,134 @@ class WorkerService : LifecycleService() {
|
||||
throw UsbDriveTooLargeException()
|
||||
}
|
||||
|
||||
imageSize = mSourceUri.getFileSize(this@WorkerService)
|
||||
if (mOperation == JobOperation.BACKUP) {
|
||||
// The destination already holds the bytes written by an interrupted run:
|
||||
// the flow resumes from its size and appends, so the total is the device.
|
||||
imageSize = devSize
|
||||
|
||||
if (devSize < imageSize) {
|
||||
Telemetry.captureMessage(
|
||||
"Device size is smaller than image size: " +
|
||||
"device: ${devSize.toHRSize(false)}, " +
|
||||
"image: ${imageSize.toHRSize(false)}"
|
||||
)
|
||||
throw NotEnoughSpaceException(sourceSize = imageSize, destSize = devSize)
|
||||
}
|
||||
// Fail early when we can tell the destination cannot hold the rest. Both
|
||||
// values are best-effort: an unknown size must not abort a resumable job.
|
||||
val existingSize: Long? = try {
|
||||
mSourceUri.getFileSize(this@WorkerService)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
val available = availableBytesFor(this@WorkerService, mSourceUri)
|
||||
if (existingSize != null && available != null &&
|
||||
available < devSize - existingSize
|
||||
) {
|
||||
throw NotEnoughSpaceForBackupException(devSize - existingSize, available)
|
||||
}
|
||||
|
||||
getProgressUpdateIntent(
|
||||
mSourceUri,
|
||||
mDestDevice,
|
||||
mJobId,
|
||||
0f,
|
||||
currentOffset,
|
||||
imageSize,
|
||||
isVerifying = verifyOnly
|
||||
).broadcastLocallySync(this@WorkerService)
|
||||
// The prefix-hash phase advances the bar to the resume offset, so start at 0
|
||||
// rather than at the resume offset: progress must never move backwards.
|
||||
getProgressUpdateIntent(
|
||||
mSourceUri,
|
||||
mDestDevice,
|
||||
mJobId,
|
||||
0f,
|
||||
0L,
|
||||
devSize,
|
||||
isBackup = true
|
||||
).broadcastLocallySync(this@WorkerService)
|
||||
|
||||
val bufferSize = BUFFER_BLOCKS * blockDev.blockSize
|
||||
Telemetry.info("Backing up USB drive", "worker")
|
||||
|
||||
// Write image
|
||||
if (!verifyOnly) {
|
||||
val sha256 = runBackup(blockDev, devSize, coroScope) { currentOffset = it }
|
||||
|
||||
// Best-effort: the data is already complete, a rename failure is not fatal.
|
||||
renameToFinalName(mSourceUri)
|
||||
|
||||
getFinishedIntent(
|
||||
mSourceUri,
|
||||
mDestDevice,
|
||||
devSize,
|
||||
isBackup = true,
|
||||
sha256 = sha256
|
||||
).broadcastLocallySync(this@WorkerService)
|
||||
} else {
|
||||
imageSize = mSourceUri.getFileSize(this@WorkerService)
|
||||
|
||||
if (devSize < imageSize) {
|
||||
Telemetry.captureMessage(
|
||||
"Device size is smaller than image size: " +
|
||||
"device: ${devSize.toHRSize(false)}, " +
|
||||
"image: ${imageSize.toHRSize(false)}"
|
||||
)
|
||||
throw NotEnoughSpaceException(sourceSize = imageSize, destSize = devSize)
|
||||
}
|
||||
|
||||
getProgressUpdateIntent(
|
||||
mSourceUri,
|
||||
mDestDevice,
|
||||
mJobId,
|
||||
0f,
|
||||
currentOffset,
|
||||
imageSize,
|
||||
isVerifying = verifyOnly
|
||||
).broadcastLocallySync(this@WorkerService)
|
||||
|
||||
val bufferSize = BUFFER_BLOCKS * blockDev.blockSize
|
||||
|
||||
// Write image
|
||||
if (!verifyOnly) {
|
||||
try {
|
||||
rawSourceStream = contentResolver.openInputStream(mSourceUri)!!
|
||||
} catch (e: Exception) {
|
||||
Telemetry.warning("Failed to open image file: ${e.message}")
|
||||
throw OpenFileException("Failed to open image file", e)
|
||||
}
|
||||
|
||||
Telemetry.info("Writing image to USB drive", "worker")
|
||||
|
||||
writeImage(
|
||||
rawSourceStream,
|
||||
blockDev,
|
||||
imageSize,
|
||||
bufferSize,
|
||||
currentOffset,
|
||||
{ currentOffset = it },
|
||||
coroScope,
|
||||
::ensureWakelock,
|
||||
::sendProgressUpdate
|
||||
)
|
||||
} else {
|
||||
Telemetry.info(
|
||||
"Skipping write, only verifying image on USB drive", "worker"
|
||||
)
|
||||
}
|
||||
|
||||
// Verify written image
|
||||
try {
|
||||
rawSourceStream = contentResolver.openInputStream(mSourceUri)!!
|
||||
} catch (e: Exception) {
|
||||
Telemetry.warning("Failed to open image file: ${e.message}")
|
||||
Log.e(TAG, "Failed to open image file", e)
|
||||
throw OpenFileException("Failed to open image file", e)
|
||||
}
|
||||
|
||||
Telemetry.info("Writing image to USB drive", "worker")
|
||||
// Always verify the whole image, not just the part that was written
|
||||
currentOffset = 0
|
||||
mLast10Speeds.clear()
|
||||
|
||||
writeImage(
|
||||
Telemetry.info("Verifying image on USB drive", "worker")
|
||||
|
||||
verifyImage(
|
||||
rawSourceStream,
|
||||
blockDev,
|
||||
imageSize,
|
||||
bufferSize,
|
||||
currentOffset,
|
||||
{ currentOffset = it },
|
||||
coroScope,
|
||||
::ensureWakelock,
|
||||
::sendProgressUpdate
|
||||
::sendProgressUpdate,
|
||||
{ mVerificationCancelled },
|
||||
::ensureWakelock
|
||||
)
|
||||
|
||||
getFinishedIntent(mSourceUri, mDestDevice, imageSize).broadcastLocallySync(
|
||||
this@WorkerService
|
||||
)
|
||||
} else {
|
||||
Telemetry.info("Skipping write, only verifying image on USB drive", "worker")
|
||||
}
|
||||
|
||||
// Verify written image
|
||||
try {
|
||||
rawSourceStream = contentResolver.openInputStream(mSourceUri)!!
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open image file", e)
|
||||
throw OpenFileException("Failed to open image file", e)
|
||||
}
|
||||
|
||||
// Always verify the whole image, not just the part that was written
|
||||
currentOffset = 0
|
||||
mLast10Speeds.clear()
|
||||
|
||||
Telemetry.info("Verifying image on USB drive", "worker")
|
||||
|
||||
verifyImage(
|
||||
rawSourceStream,
|
||||
blockDev,
|
||||
imageSize,
|
||||
bufferSize,
|
||||
{ currentOffset = it },
|
||||
coroScope,
|
||||
::sendProgressUpdate,
|
||||
{ mVerificationCancelled },
|
||||
::ensureWakelock
|
||||
)
|
||||
|
||||
getFinishedIntent(mSourceUri, mDestDevice, imageSize).broadcastLocallySync(
|
||||
this@WorkerService
|
||||
)
|
||||
|
||||
} catch (exception: Exception) {
|
||||
// A cancelled job (service destroyed) is not a failure: rethrow instead of
|
||||
// reporting it or broadcasting an error.
|
||||
@@ -546,7 +654,8 @@ class WorkerService : LifecycleService() {
|
||||
mJobId,
|
||||
currentOffset,
|
||||
imageSize,
|
||||
exception = it
|
||||
exception = it,
|
||||
isBackup = mOperation == JobOperation.BACKUP
|
||||
).broadcastLocallySync(this@WorkerService)
|
||||
}
|
||||
stopSelf()
|
||||
@@ -565,11 +674,12 @@ class WorkerService : LifecycleService() {
|
||||
processedBytes: Long,
|
||||
imageSize: Long,
|
||||
isVerifying: Boolean = false,
|
||||
force: Boolean = false,
|
||||
) {
|
||||
mBytesSinceLastUpdate += lastWrittenBytes
|
||||
val newTime = System.currentTimeMillis()
|
||||
|
||||
if (mLastProgressUpdate + PROGRESS_UPDATE_INTERVAL > newTime) return
|
||||
if (!force && mLastProgressUpdate + PROGRESS_UPDATE_INTERVAL > newTime) return
|
||||
|
||||
val interval = newTime - mLastProgressUpdate
|
||||
val speed =
|
||||
@@ -588,33 +698,149 @@ class WorkerService : LifecycleService() {
|
||||
newSpeed,
|
||||
processedBytes,
|
||||
imageSize,
|
||||
isVerifying = isVerifying
|
||||
isVerifying = isVerifying,
|
||||
isBackup = mOperation == JobOperation.BACKUP
|
||||
).broadcastLocally(this@WorkerService)
|
||||
|
||||
mLastProgressUpdate = newTime
|
||||
mBytesSinceLastUpdate = 0.0
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the device to the destination document, resuming from whatever it already holds,
|
||||
* and returns the SHA-256 of the resulting file. The document is opened in append mode and
|
||||
* never truncated: an interrupted backup keeps its prefix for the next attempt.
|
||||
*/
|
||||
private suspend fun runBackup(
|
||||
blockDev: BlockDeviceDriver,
|
||||
devSize: Long,
|
||||
coroScope: CoroutineScope,
|
||||
notifyCurrentOffset: (offset: Long) -> Unit,
|
||||
): String {
|
||||
val pfd = openBackupFile()
|
||||
var existing: InputStream? = null
|
||||
var out: BufferedOutputStream? = null
|
||||
|
||||
try {
|
||||
val resumeOffset = pfd.statSize
|
||||
if (resumeOffset < 0) throw CouldNotWriteBackupException(
|
||||
"Could not determine the size of the backup file", null
|
||||
)
|
||||
|
||||
if (resumeOffset > 0) {
|
||||
existing = try {
|
||||
contentResolver.openInputStream(mSourceUri)
|
||||
} catch (e: SecurityException) {
|
||||
throw CouldNotWriteBackupException("Failed to reopen the backup file", e)
|
||||
} catch (e: FileNotFoundException) {
|
||||
throw CouldNotWriteBackupException("Failed to reopen the backup file", e)
|
||||
} ?: throw CouldNotWriteBackupException("Failed to reopen the backup file", null)
|
||||
}
|
||||
|
||||
// Closing this also closes the descriptor: it owns pfd from here on.
|
||||
out = BufferedOutputStream(
|
||||
ParcelFileDescriptor.AutoCloseOutputStream(pfd), 1 shl 20
|
||||
)
|
||||
|
||||
val sha256 = BackupFlow.backupImage(
|
||||
blockDev,
|
||||
out,
|
||||
existing,
|
||||
resumeOffset,
|
||||
devSize,
|
||||
BUFFER_BLOCKS * blockDev.blockSize,
|
||||
notifyCurrentOffset,
|
||||
coroScope,
|
||||
::ensureWakelock,
|
||||
::sendProgressUpdate,
|
||||
)
|
||||
|
||||
// Make the whole file durable before renaming it to its final name. Announce the
|
||||
// finished copy first: fsync on a slow provider can take a while, and the UI treats
|
||||
// ~11 s without a progress update as a stalled job.
|
||||
sendProgressUpdate(0, devSize, devSize, false, force = true)
|
||||
try {
|
||||
out.flush()
|
||||
pfd.fileDescriptor.sync()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
throw CouldNotWriteBackupException("Failed to sync the backup file", e)
|
||||
}
|
||||
|
||||
return sha256
|
||||
} finally {
|
||||
val stream = out
|
||||
try {
|
||||
if (stream != null) stream.close() else pfd.close()
|
||||
} catch (e: Exception) {
|
||||
Telemetry.warning("Failed to close the backup file: ${e.message}")
|
||||
}
|
||||
try {
|
||||
existing?.close()
|
||||
} catch (e: Exception) {
|
||||
Telemetry.warning("Failed to close the existing backup data: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openBackupFile(): ParcelFileDescriptor = try {
|
||||
contentResolver.openFileDescriptor(mSourceUri, "wa")
|
||||
} catch (e: SecurityException) {
|
||||
throw CouldNotWriteBackupException("Failed to open the backup file", e)
|
||||
} catch (e: FileNotFoundException) {
|
||||
throw CouldNotWriteBackupException("Failed to open the backup file", e)
|
||||
} ?: throw CouldNotWriteBackupException("Failed to open the backup file", null)
|
||||
|
||||
/**
|
||||
* Drops the `.part` suffix from a finished backup. Best-effort: the file already holds the
|
||||
* complete data, so neither a provider that does not support renaming nor a failure may turn
|
||||
* a successful backup into a failed one.
|
||||
*/
|
||||
private fun renameToFinalName(uri: Uri) {
|
||||
try {
|
||||
val name = uri.getDisplayName(this) ?: return
|
||||
if (!name.isIncompleteBackupName()) return
|
||||
DocumentsContract.renameDocument(contentResolver, uri, name.withoutPartSuffix())
|
||||
} catch (e: Exception) {
|
||||
Telemetry.warning("Failed to rename the backup file: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private val filenameStr: String by lazy {
|
||||
mSourceUri.getDisplayName(this) ?: getString(R.string.unknown_filename)
|
||||
}
|
||||
|
||||
private val basicForegroundNotification: Notification
|
||||
get() = NotificationCompat
|
||||
.Builder(this, JOB_PROGRESS_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_write_to_usb_anim)
|
||||
.setContentTitle(getString(R.string.notification_write_progress_title))
|
||||
.setContentText(
|
||||
getString(
|
||||
if (notificationsAllowed) R.string.notification_write_tap_for_progress_text
|
||||
else R.string.notification_write_no_notifications_text,
|
||||
filenameStr,
|
||||
mDestDevice.name
|
||||
get() {
|
||||
val isBackup = mOperation == JobOperation.BACKUP
|
||||
return NotificationCompat
|
||||
.Builder(this, JOB_PROGRESS_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_write_to_usb_anim)
|
||||
.setContentTitle(
|
||||
getString(
|
||||
if (isBackup) R.string.notification_backup_progress_title
|
||||
else R.string.notification_write_progress_title
|
||||
)
|
||||
)
|
||||
)
|
||||
.setProgress(100, 0, true)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
.setContentText(
|
||||
if (isBackup) getString(
|
||||
if (notificationsAllowed) R.string.notification_backup_tap_for_progress_text
|
||||
else R.string.notification_backup_no_notifications_text,
|
||||
mDestDevice.name,
|
||||
filenameStr
|
||||
)
|
||||
else getString(
|
||||
if (notificationsAllowed) R.string.notification_write_tap_for_progress_text
|
||||
else R.string.notification_write_no_notifications_text,
|
||||
filenameStr,
|
||||
mDestDevice.name
|
||||
)
|
||||
)
|
||||
.setProgress(100, 0, true)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun trySetupNotifications() {
|
||||
if (mNotificationsSetUp || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
|
||||
@@ -88,8 +88,10 @@ import com.airbnb.lottie.compose.rememberLottieDynamicProperties
|
||||
import com.airbnb.lottie.compose.rememberLottieDynamicProperty
|
||||
import eu.depau.etchdroid.AppSettings
|
||||
import eu.depau.etchdroid.Intents
|
||||
import eu.depau.etchdroid.JobOperation
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.getProgressUpdateIntent
|
||||
import eu.depau.etchdroid.getStartBackupJobIntent
|
||||
import eu.depau.etchdroid.getStartJobIntent
|
||||
import eu.depau.etchdroid.massstorage.PreviewUsbDevice
|
||||
import eu.depau.etchdroid.massstorage.UsbMassStorageDeviceDescriptor
|
||||
@@ -110,6 +112,7 @@ import eu.depau.etchdroid.utils.ktexts.startForegroundServiceCompat
|
||||
import eu.depau.etchdroid.utils.ktexts.toHRSize
|
||||
import eu.depau.etchdroid.utils.ktexts.toast
|
||||
import eu.depau.etchdroid.utils.ktexts.usbDevice
|
||||
import eu.depau.etchdroid.utils.withoutPartSuffix
|
||||
import kotlin.random.Random
|
||||
|
||||
private const val TAG = "ConfirmOperationActivit"
|
||||
@@ -211,11 +214,17 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
unregisterUsbReceiver()
|
||||
}
|
||||
|
||||
private fun writeImage(uri: Uri, device: UsbMassStorageDeviceDescriptor) {
|
||||
println("writeImage $uri, $device")
|
||||
private fun startJob(
|
||||
uri: Uri, device: UsbMassStorageDeviceDescriptor, operation: JobOperation
|
||||
) {
|
||||
println("startJob $operation $uri, $device")
|
||||
val jobId = Random.nextInt()
|
||||
val intent =
|
||||
val isBackup = operation == JobOperation.BACKUP
|
||||
val intent = if (isBackup) {
|
||||
getStartBackupJobIntent(uri, device, jobId, this, WorkerService::class.java)
|
||||
} else {
|
||||
getStartJobIntent(uri, device, jobId, 0, false, this, WorkerService::class.java)
|
||||
}
|
||||
Telemetry.addBreadcrumb {
|
||||
category = "flow"
|
||||
message = "Starting worker service; job ID: $jobId"
|
||||
@@ -225,7 +234,8 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
startForegroundServiceCompat(intent)
|
||||
startActivity(
|
||||
getProgressUpdateIntent(
|
||||
uri, device, jobId, 0f, 0, 0, false, this, ProgressActivity::class.java
|
||||
uri, device, jobId, 0f, 0, 0, false, this, ProgressActivity::class.java,
|
||||
isBackup = isBackup,
|
||||
)
|
||||
)
|
||||
finish()
|
||||
@@ -234,6 +244,17 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
val operation = try {
|
||||
JobOperation.valueOf(
|
||||
intent.getStringExtra("operation") ?: JobOperation.WRITE.name
|
||||
)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
Log.w(TAG, "Unknown operation in intent, falling back to write")
|
||||
JobOperation.WRITE
|
||||
}
|
||||
val isBackup = operation == JobOperation.BACKUP
|
||||
|
||||
// In backup mode this is the destination file, in write mode the source image.
|
||||
val openedImage = intent.safeParcelableExtra<Uri>("sourceUri") ?: run {
|
||||
Log.e(TAG, "No source image URI provided")
|
||||
toast(getString(R.string.no_image_uri_provided))
|
||||
@@ -241,8 +262,13 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
return
|
||||
}
|
||||
if (!openedImage.isAccessible(this)) {
|
||||
Log.e(TAG, "Source image is no longer accessible: $openedImage")
|
||||
toast(getString(R.string.could_not_open_the_source_file))
|
||||
Log.e(TAG, "Job file is no longer accessible: $openedImage")
|
||||
toast(
|
||||
getString(
|
||||
if (isBackup) R.string.could_not_write_backup_file
|
||||
else R.string.could_not_open_the_source_file
|
||||
)
|
||||
)
|
||||
finish()
|
||||
return
|
||||
}
|
||||
@@ -253,13 +279,16 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
mViewModel.init(openedImage, selectedDevice)
|
||||
mViewModel.init(openedImage, selectedDevice, operation)
|
||||
|
||||
val imageFileName = openedImage.getFileName(this) ?: "unknown"
|
||||
Telemetry.addBreadcrumb {
|
||||
category = "flow"
|
||||
message = "Image opened"
|
||||
message = if (isBackup) "Backup destination opened" else "Image opened"
|
||||
data["image.filename"] = imageFileName
|
||||
if (isBackup) {
|
||||
data["job.type"] = "backup"
|
||||
}
|
||||
}
|
||||
|
||||
Telemetry.configureScope {
|
||||
@@ -268,13 +297,19 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
setTag("usb.vidpid", selectedDevice.vidpid)
|
||||
setTag("usb.name", selectedDevice.name)
|
||||
setTag("image.filename", imageFileName)
|
||||
try {
|
||||
setTag(
|
||||
"image.size",
|
||||
openedImage.getFileSize(this@ConfirmOperationActivity).toString()
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
if (isBackup) {
|
||||
setTag("job.type", "backup")
|
||||
// The destination file is created empty: its size says nothing about the job.
|
||||
setTag("image.size", "unknown")
|
||||
} else {
|
||||
try {
|
||||
setTag(
|
||||
"image.size",
|
||||
openedImage.getFileSize(this@ConfirmOperationActivity).toString()
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
setTag("image.size", "unknown")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,8 +365,8 @@ class ConfirmOperationActivity : ActivityBase() {
|
||||
LayFlatOnTableBottomSheet(
|
||||
onReady = {
|
||||
println("onReady")
|
||||
writeImage(
|
||||
uiState.openedImage!!, uiState.selectedDevice!!
|
||||
startJob(
|
||||
uiState.openedImage!!, uiState.selectedDevice!!, uiState.operation
|
||||
)
|
||||
},
|
||||
onDismissRequest = { showLayFlatDialog = false },
|
||||
@@ -509,146 +544,239 @@ fun ConfirmationView(
|
||||
askUsbPermission: () -> Unit,
|
||||
) {
|
||||
val uiState by viewModel.state.collectAsState()
|
||||
val isBackup = uiState.operation == JobOperation.BACKUP
|
||||
|
||||
ConfirmationViewLayout(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
title = {
|
||||
Text(
|
||||
text = stringResource(R.string.confirm_operation),
|
||||
text = stringResource(
|
||||
if (isBackup) R.string.back_up_usb_drive else R.string.confirm_operation
|
||||
),
|
||||
style = MaterialTheme.typography.titleLarge.copy(fontSize = 28.sp),
|
||||
)
|
||||
},
|
||||
sourceCard = { modifier, fillMaxSize ->
|
||||
Card(modifier) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterHorizontally)
|
||||
.then(if (fillMaxSize) Modifier.fillMaxSize() else Modifier),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start
|
||||
) {
|
||||
Icon(
|
||||
if (isBackup) {
|
||||
Card(modifier) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.padding(16.dp, 16.dp, 0.dp, 16.dp),
|
||||
imageVector = ImageVector.vectorResource(
|
||||
id = R.drawable.ic_disk_image_large
|
||||
), contentDescription = stringResource(R.string.disk_image)
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(
|
||||
8.dp,
|
||||
Alignment.CenterVertically
|
||||
)
|
||||
.align(Alignment.CenterHorizontally)
|
||||
.then(if (fillMaxSize) Modifier.fillMaxSize() else Modifier),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start
|
||||
) {
|
||||
val sourceUri = uiState.openedImage
|
||||
val context = LocalContext.current
|
||||
val sourceFileName by remember {
|
||||
derivedStateOf {
|
||||
sourceUri?.getFileName(context)
|
||||
?: context.getString(R.string.unknown_filename)
|
||||
Icon(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.padding(16.dp, 16.dp, 0.dp, 16.dp),
|
||||
imageVector = ImageVector.vectorResource(
|
||||
id = R.drawable.ic_usb_stick_large
|
||||
), contentDescription = stringResource(R.string.usb_drive)
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(
|
||||
8.dp,
|
||||
Alignment.CenterVertically
|
||||
)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.source_usb_device),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Column {
|
||||
Text(
|
||||
text = uiState.selectedDevice?.name ?: stringResource(
|
||||
R.string.unknown_device
|
||||
),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
softWrap = true,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = uiState.selectedDevice?.vidpid ?: "Unknown VID:PID",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
softWrap = true,
|
||||
fontStyle = FontStyle.Italic, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
GrantAccessButton(
|
||||
hasUsbPermission = uiState.hasUsbPermission,
|
||||
askUsbPermission = askUsbPermission,
|
||||
)
|
||||
}
|
||||
val sourceFileSize by remember {
|
||||
derivedStateOf {
|
||||
try {
|
||||
sourceUri!!.getFileSize(context).toHRSize()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to get file size", e)
|
||||
"Unknown file size"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Card(modifier) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterHorizontally)
|
||||
.then(if (fillMaxSize) Modifier.fillMaxSize() else Modifier),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start
|
||||
) {
|
||||
Icon(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.padding(16.dp, 16.dp, 0.dp, 16.dp),
|
||||
imageVector = ImageVector.vectorResource(
|
||||
id = R.drawable.ic_disk_image_large
|
||||
), contentDescription = stringResource(R.string.disk_image)
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(
|
||||
8.dp,
|
||||
Alignment.CenterVertically
|
||||
)
|
||||
) {
|
||||
val sourceUri = uiState.openedImage
|
||||
val context = LocalContext.current
|
||||
val sourceFileName by remember {
|
||||
derivedStateOf {
|
||||
sourceUri?.getFileName(context)
|
||||
?: context.getString(R.string.unknown_filename)
|
||||
}
|
||||
}
|
||||
val sourceFileSize by remember {
|
||||
derivedStateOf {
|
||||
try {
|
||||
sourceUri!!.getFileSize(context).toHRSize()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to get file size", e)
|
||||
"Unknown file size"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.image_to_write),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.padding(0.dp, 0.dp, 0.dp, 8.dp)
|
||||
)
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = sourceFileName,
|
||||
text = stringResource(R.string.image_to_write),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 2,
|
||||
softWrap = true,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = sourceFileSize,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontStyle = FontStyle.Italic,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.padding(0.dp, 0.dp, 0.dp, 8.dp)
|
||||
)
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = sourceFileName,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 2,
|
||||
softWrap = true,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = sourceFileSize,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontStyle = FontStyle.Italic,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
destinationCard = { modifier ->
|
||||
Card(modifier) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start
|
||||
) {
|
||||
Icon(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.padding(16.dp, 16.dp, 0.dp, 16.dp),
|
||||
imageVector = ImageVector.vectorResource(
|
||||
id = R.drawable.ic_usb_stick_large
|
||||
), contentDescription = stringResource(R.string.usb_drive)
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(
|
||||
8.dp,
|
||||
Alignment.CenterVertically
|
||||
)
|
||||
if (isBackup) {
|
||||
Card(modifier) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.destination_usb_device),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
Icon(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.padding(16.dp, 16.dp, 0.dp, 16.dp),
|
||||
imageVector = ImageVector.vectorResource(
|
||||
id = R.drawable.ic_disk_image_large
|
||||
), contentDescription = stringResource(R.string.disk_image)
|
||||
)
|
||||
Column {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(
|
||||
8.dp,
|
||||
Alignment.CenterVertically
|
||||
)
|
||||
) {
|
||||
val destinationUri = uiState.openedImage
|
||||
val context = LocalContext.current
|
||||
val unknownFileName = stringResource(R.string.unknown_filename)
|
||||
val destinationFileName by remember {
|
||||
derivedStateOf {
|
||||
destinationUri?.getFileName(context)?.withoutPartSuffix()
|
||||
?: unknownFileName
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = uiState.selectedDevice?.name ?: stringResource(
|
||||
R.string.unknown_device
|
||||
),
|
||||
text = stringResource(R.string.destination_file),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
softWrap = true,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Text(
|
||||
text = uiState.selectedDevice?.vidpid ?: "Unknown VID:PID",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
text = destinationFileName,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 2,
|
||||
softWrap = true,
|
||||
fontStyle = FontStyle.Italic, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Button(
|
||||
modifier = Modifier.appiumTag("grantUsbPermissionButton"),
|
||||
onClick = askUsbPermission,
|
||||
enabled = !uiState.hasUsbPermission,
|
||||
contentPadding = if (!uiState.hasUsbPermission) PaddingValues(
|
||||
24.dp, 8.dp
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Card(modifier) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start
|
||||
) {
|
||||
Icon(
|
||||
modifier = Modifier
|
||||
.size(128.dp)
|
||||
.padding(16.dp, 16.dp, 0.dp, 16.dp),
|
||||
imageVector = ImageVector.vectorResource(
|
||||
id = R.drawable.ic_usb_stick_large
|
||||
), contentDescription = stringResource(R.string.usb_drive)
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(
|
||||
8.dp,
|
||||
Alignment.CenterVertically
|
||||
)
|
||||
else PaddingValues(24.dp, 8.dp, 16.dp, 8.dp),
|
||||
) {
|
||||
Text(text = stringResource(R.string.grant_access))
|
||||
if (uiState.hasUsbPermission) {
|
||||
Icon(
|
||||
modifier = Modifier.padding(8.dp, 0.dp, 0.dp, 0.dp),
|
||||
imageVector = Icons.TwoTone.Check,
|
||||
contentDescription = stringResource(R.string.permission_granted)
|
||||
Text(
|
||||
text = stringResource(R.string.destination_usb_device),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Column {
|
||||
Text(
|
||||
text = uiState.selectedDevice?.name ?: stringResource(
|
||||
R.string.unknown_device
|
||||
),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
softWrap = true,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = uiState.selectedDevice?.vidpid ?: "Unknown VID:PID",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
softWrap = true,
|
||||
fontStyle = FontStyle.Italic, maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
GrantAccessButton(
|
||||
hasUsbPermission = uiState.hasUsbPermission,
|
||||
askUsbPermission = askUsbPermission,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -684,7 +812,8 @@ fun ConfirmationView(
|
||||
)
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.writing_the_image_will_erase
|
||||
if (isBackup) R.string.backup_warning
|
||||
else R.string.writing_the_image_will_erase
|
||||
), style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
@@ -703,12 +832,41 @@ fun ConfirmationView(
|
||||
onClick = onConfirm,
|
||||
enabled = uiState.selectedDevice != null && uiState.hasUsbPermission
|
||||
) {
|
||||
Text(text = stringResource(R.string.write_image))
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (isBackup) R.string.start_backup else R.string.write_image
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GrantAccessButton(
|
||||
hasUsbPermission: Boolean,
|
||||
askUsbPermission: () -> Unit,
|
||||
) {
|
||||
Button(
|
||||
modifier = Modifier.appiumTag("grantUsbPermissionButton"),
|
||||
onClick = askUsbPermission,
|
||||
enabled = !hasUsbPermission,
|
||||
contentPadding = if (!hasUsbPermission) PaddingValues(
|
||||
24.dp, 8.dp
|
||||
)
|
||||
else PaddingValues(24.dp, 8.dp, 16.dp, 8.dp),
|
||||
) {
|
||||
Text(text = stringResource(R.string.grant_access))
|
||||
if (hasUsbPermission) {
|
||||
Icon(
|
||||
modifier = Modifier.padding(8.dp, 0.dp, 0.dp, 0.dp),
|
||||
imageVector = Icons.TwoTone.Check,
|
||||
contentDescription = stringResource(R.string.permission_granted)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LayFlatOnTableBottomSheet(
|
||||
@@ -878,18 +1036,31 @@ fun LayFlatOnTableBottomSheet(
|
||||
|
||||
@PreviewScreenSizes
|
||||
@Composable
|
||||
fun ConfirmationViewPreview() {
|
||||
fun ConfirmationViewPreview() = ConfirmationViewPreviewContent(JobOperation.WRITE)
|
||||
|
||||
@PreviewScreenSizes
|
||||
@Composable
|
||||
fun ConfirmationViewBackupPreview() = ConfirmationViewPreviewContent(JobOperation.BACKUP)
|
||||
|
||||
@Composable
|
||||
private fun ConfirmationViewPreviewContent(operation: JobOperation) {
|
||||
val isBackup = operation == JobOperation.BACKUP
|
||||
val viewModel = remember {
|
||||
ConfirmOperationActivityViewModel().apply {
|
||||
setState(
|
||||
state.value.copy(
|
||||
operation = operation,
|
||||
selectedDevice = UsbMassStorageDeviceDescriptor(
|
||||
previewUsbDevice = PreviewUsbDevice(
|
||||
name = "Kingston DataTraveler 3.0",
|
||||
vidpid = "dead:beef",
|
||||
)
|
||||
),
|
||||
openedImage = "file:///storage/emulated/0/Download/etchdroid-test-image-very-long-name-lol-rip-ive-never-seen-a-filename-this-long-its-absolutely-crazy.img".toUri(),
|
||||
openedImage = if (isBackup) {
|
||||
"file:///storage/emulated/0/Download/backup-kingston-datatraveler-3-0-20261117-1200.img.part".toUri()
|
||||
} else {
|
||||
"file:///storage/emulated/0/Download/etchdroid-test-image-very-long-name-lol-rip-ive-never-seen-a-filename-this-long-its-absolutely-crazy.img".toUri()
|
||||
},
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.HelpCenter
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.twotone.Archive
|
||||
import androidx.compose.material.icons.twotone.Check
|
||||
import androidx.compose.material.icons.twotone.Clear
|
||||
import androidx.compose.material.icons.twotone.Info
|
||||
@@ -97,6 +98,7 @@ import androidx.compose.ui.unit.sp
|
||||
import androidx.constraintlayout.compose.ConstraintLayout
|
||||
import androidx.core.net.toUri
|
||||
import eu.depau.etchdroid.AppSettings
|
||||
import eu.depau.etchdroid.JobOperation
|
||||
import eu.depau.etchdroid.PRIVACY_URL
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.ThemeMode
|
||||
@@ -113,11 +115,13 @@ import eu.depau.etchdroid.ui.theme.notSupportedRed
|
||||
import eu.depau.etchdroid.ui.theme.partiallySupportedYellow
|
||||
import eu.depau.etchdroid.ui.theme.supportedGreen
|
||||
import eu.depau.etchdroid.utils.broadcastReceiver
|
||||
import eu.depau.etchdroid.utils.isIncompleteBackupName
|
||||
import eu.depau.etchdroid.utils.ktexts.getFileName
|
||||
import eu.depau.etchdroid.utils.ktexts.isAccessible
|
||||
import eu.depau.etchdroid.utils.ktexts.registerExportedReceiver
|
||||
import eu.depau.etchdroid.utils.ktexts.toast
|
||||
import eu.depau.etchdroid.utils.ktexts.usbDevice
|
||||
import eu.depau.etchdroid.utils.suggestedBackupFileName
|
||||
|
||||
private const val TAG = "MainActivity"
|
||||
|
||||
@@ -155,6 +159,52 @@ class MainActivity : ActivityBase() {
|
||||
}
|
||||
}
|
||||
|
||||
private val mCreateDocumentLauncher =
|
||||
registerForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
|
||||
onBackupDestinationPicked(uri)
|
||||
}
|
||||
|
||||
private fun onBackupDestinationPicked(uri: Uri?) {
|
||||
val device = mViewModel.state.value.pendingBackupDevice
|
||||
if (uri == null) {
|
||||
// The user backed out of the system file picker: start nothing.
|
||||
mViewModel.setPendingBackupDevice(null)
|
||||
return
|
||||
}
|
||||
if (device == null) {
|
||||
Log.w(TAG, "Backup destination picked with no pending device, ignoring")
|
||||
return
|
||||
}
|
||||
Telemetry.addBreadcrumb {
|
||||
val filename = uri.getFileName(this@MainActivity) ?: "null"
|
||||
message = "User selected backup destination: $filename"
|
||||
category = "flow"
|
||||
level = TelemetryLevel.INFO
|
||||
data["backup.filename"] = filename
|
||||
data["usb.name"] = device.name
|
||||
}
|
||||
// Keep read and write access after this activity is gone: the worker service writes the
|
||||
// backup to this URI. Never released, same policy as the source-image grant in openUri.
|
||||
try {
|
||||
contentResolver.takePersistableUriPermission(
|
||||
uri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
// Some providers only grant one of the two flags: persisting both then fails
|
||||
// without persisting anything, so settle for write access, which is what the
|
||||
// running job actually needs.
|
||||
try {
|
||||
contentResolver.takePersistableUriPermission(
|
||||
uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
launchConfirmationActivity(device, uri, JobOperation.BACKUP)
|
||||
mViewModel.setPendingBackupDevice(null)
|
||||
}
|
||||
|
||||
private val mUsbDevicesReceiver = broadcastReceiver { intent ->
|
||||
|
||||
if (intent.usbDevice == null) {
|
||||
@@ -200,13 +250,15 @@ class MainActivity : ActivityBase() {
|
||||
private fun launchConfirmationActivity(
|
||||
selectedDevice: UsbMassStorageDeviceDescriptor,
|
||||
openedImage: Uri,
|
||||
operation: JobOperation = JobOperation.WRITE,
|
||||
) {
|
||||
startActivity(
|
||||
getConfirmOperationActivityIntent(
|
||||
openedImage,
|
||||
selectedDevice,
|
||||
this,
|
||||
ConfirmOperationActivity::class.java
|
||||
ConfirmOperationActivity::class.java,
|
||||
operation,
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -235,6 +287,17 @@ class MainActivity : ActivityBase() {
|
||||
}
|
||||
|
||||
if (!userSaysYolo) {
|
||||
if (filename?.isIncompleteBackupName() == true) {
|
||||
Telemetry.addBreadcrumb {
|
||||
message = "Incomplete backup file detected"
|
||||
category = "flow"
|
||||
level = TelemetryLevel.DEBUG
|
||||
data["image.filename"] = filename ?: "null"
|
||||
}
|
||||
|
||||
mViewModel.setIncompleteBackupAlertUri(uri)
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Check if it's a Windows image and alert the user; fail-open
|
||||
filename?.let {
|
||||
@@ -312,6 +375,14 @@ class MainActivity : ActivityBase() {
|
||||
}
|
||||
launchFilePicker()
|
||||
},
|
||||
onBackupCTAClick = {
|
||||
Telemetry.addBreadcrumb {
|
||||
message = "User clicked on Back up a drive"
|
||||
category = "flow"
|
||||
level = TelemetryLevel.DEBUG
|
||||
}
|
||||
mViewModel.setBackupDevicePickerOpen(true)
|
||||
},
|
||||
openAboutView = {
|
||||
startActivity(Intent(this, AboutActivity::class.java))
|
||||
},
|
||||
@@ -329,10 +400,20 @@ class MainActivity : ActivityBase() {
|
||||
onDismissRequest = { mViewModel.setShowWindowsAlertUri(null) },
|
||||
onConfirm = { openUri(uiState.showWindowsAlertForUri!!, true) })
|
||||
}
|
||||
if (uiState.openedImage != null) {
|
||||
if (uiState.showIncompleteBackupAlertForUri != null) {
|
||||
IncompleteBackupAlertDialog(
|
||||
onDismissRequest = { mViewModel.setIncompleteBackupAlertUri(null) },
|
||||
onConfirm = { openUri(uiState.showIncompleteBackupAlertForUri!!, true) })
|
||||
}
|
||||
if (uiState.openedImage != null || uiState.backupDevicePickerOpen) {
|
||||
UsbDevicePickerBottomSheet(
|
||||
onDismissRequest = {
|
||||
mViewModel.setOpenedImage(null)
|
||||
if (mViewModel.state.value.backupDevicePickerOpen) {
|
||||
mViewModel.setBackupDevicePickerOpen(false)
|
||||
mViewModel.setPendingBackupDevice(null)
|
||||
} else {
|
||||
mViewModel.setOpenedImage(null)
|
||||
}
|
||||
},
|
||||
selectDevice = {
|
||||
Telemetry.addBreadcrumb {
|
||||
@@ -345,10 +426,29 @@ class MainActivity : ActivityBase() {
|
||||
data["usb.vidpid"] = it.vidpid
|
||||
}
|
||||
|
||||
launchConfirmationActivity(
|
||||
it as UsbMassStorageDeviceDescriptor,
|
||||
mViewModel.state.value.openedImage!!,
|
||||
)
|
||||
val device = it as UsbMassStorageDeviceDescriptor
|
||||
if (mViewModel.state.value.backupDevicePickerOpen) {
|
||||
// The backup flow always asks which drive to back up, even
|
||||
// when only one is connected.
|
||||
mViewModel.setPendingBackupDevice(device)
|
||||
mViewModel.setBackupDevicePickerOpen(false)
|
||||
try {
|
||||
mCreateDocumentLauncher.launch(
|
||||
suggestedBackupFileName(device.name)
|
||||
)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
mViewModel.setPendingBackupDevice(null)
|
||||
toast(
|
||||
getString(R.string.no_file_picker),
|
||||
Toast.LENGTH_LONG
|
||||
)
|
||||
}
|
||||
} else {
|
||||
launchConfirmationActivity(
|
||||
device,
|
||||
mViewModel.state.value.openedImage!!,
|
||||
)
|
||||
}
|
||||
},
|
||||
availableDevices = { uiState.massStorageDevices }
|
||||
)
|
||||
@@ -397,6 +497,7 @@ fun StartViewLayout(
|
||||
title: @Composable () -> Unit,
|
||||
logo: @Composable () -> Unit,
|
||||
mainButton: @Composable () -> Unit,
|
||||
secondaryButton: @Composable () -> Unit,
|
||||
bottomButton: @Composable () -> Unit,
|
||||
menuButton: @Composable () -> Unit,
|
||||
dropdownMenu: @Composable () -> Unit,
|
||||
@@ -433,7 +534,10 @@ fun StartViewLayout(
|
||||
verticalArrangement = Arrangement.spacedBy(64.dp)
|
||||
) {
|
||||
logo()
|
||||
mainButton()
|
||||
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
mainButton()
|
||||
secondaryButton()
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.constrainAs(bottomButtonRef) {
|
||||
@@ -481,6 +585,7 @@ fun StartViewLayout(
|
||||
) {
|
||||
title()
|
||||
mainButton()
|
||||
secondaryButton()
|
||||
bottomButton()
|
||||
}
|
||||
}
|
||||
@@ -507,6 +612,7 @@ fun StartView(
|
||||
setThemeMode: (ThemeMode) -> Unit = {},
|
||||
setDynamicTheme: (Boolean) -> Unit = {},
|
||||
onCTAClick: () -> Unit = {},
|
||||
onBackupCTAClick: () -> Unit = {},
|
||||
openAboutView: () -> Unit = {},
|
||||
toggleTelemetry: () -> Unit = {},
|
||||
) {
|
||||
@@ -580,6 +686,21 @@ fun StartView(
|
||||
},
|
||||
)
|
||||
},
|
||||
secondaryButton = {
|
||||
val label = stringResource(R.string.backup_a_drive)
|
||||
OutlinedButton(
|
||||
onClick = onBackupCTAClick,
|
||||
modifier = Modifier.appiumTag("backupDriveCTA"),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.TwoTone.Archive,
|
||||
// button isn't focusable without this for some reason
|
||||
contentDescription = label
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(label)
|
||||
}
|
||||
},
|
||||
bottomButton = {
|
||||
OutlinedButton(onClick = { whatCanIWriteOpen = true }) {
|
||||
Text(stringResource(R.string.whats_supported))
|
||||
@@ -752,6 +873,49 @@ fun WindowsImageAlertDialog(
|
||||
}
|
||||
})
|
||||
|
||||
@Composable
|
||||
fun IncompleteBackupAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
onConfirm: () -> Unit,
|
||||
onCancel: () -> Unit = {},
|
||||
) = AlertDialog(
|
||||
modifier = Modifier.appiumTag("incomplete_backup_alert"),
|
||||
onDismissRequest = onDismissRequest, title = {
|
||||
Text(
|
||||
modifier = Modifier.appiumTag("incomplete_backup_alert_title"),
|
||||
text = stringResource(R.string.incomplete_backup_title),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}, text = {
|
||||
Text(
|
||||
text = stringResource(R.string.incomplete_backup_message)
|
||||
)
|
||||
}, icon = {
|
||||
Icon(
|
||||
imageVector = Icons.TwoTone.Archive,
|
||||
contentDescription = null
|
||||
)
|
||||
}, confirmButton = {
|
||||
TextButton(
|
||||
modifier = Modifier.appiumTag("confirmIncompleteBackupAlert"),
|
||||
onClick = {
|
||||
onConfirm()
|
||||
onDismissRequest()
|
||||
}
|
||||
) {
|
||||
Text(stringResource(R.string.continue_anyway))
|
||||
}
|
||||
}, dismissButton = {
|
||||
TextButton(
|
||||
modifier = Modifier.appiumTag("cancelIncompleteBackupAlert"),
|
||||
onClick = {
|
||||
onCancel()
|
||||
onDismissRequest()
|
||||
}) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
})
|
||||
|
||||
@Composable
|
||||
fun TelemetryAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
|
||||
@@ -50,6 +50,7 @@ import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.wrapContentSize
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
@@ -85,6 +86,7 @@ import androidx.compose.ui.res.vectorResource
|
||||
import androidx.compose.ui.text.LinkAnnotation
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
@@ -111,6 +113,7 @@ import eu.depau.etchdroid.AppSettings
|
||||
import eu.depau.etchdroid.BuildConfig
|
||||
import eu.depau.etchdroid.Intents
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.getStartBackupJobIntent
|
||||
import eu.depau.etchdroid.getStartJobIntent
|
||||
import eu.depau.etchdroid.massstorage.EtchDroidUsbMassStorageDevice.Companion.isMassStorageDevice
|
||||
import eu.depau.etchdroid.massstorage.UsbMassStorageDeviceDescriptor
|
||||
@@ -130,9 +133,11 @@ import eu.depau.etchdroid.ui.composables.ScreenSizeLayoutSelector
|
||||
import eu.depau.etchdroid.ui.composables.appiumTag
|
||||
import eu.depau.etchdroid.ui.utils.rtlMirror
|
||||
import eu.depau.etchdroid.utils.broadcastReceiver
|
||||
import eu.depau.etchdroid.utils.exception.CouldNotWriteBackupException
|
||||
import eu.depau.etchdroid.utils.exception.InitException
|
||||
import eu.depau.etchdroid.utils.exception.MissingPermissionException
|
||||
import eu.depau.etchdroid.utils.exception.NotEnoughSpaceException
|
||||
import eu.depau.etchdroid.utils.exception.NotEnoughSpaceForBackupException
|
||||
import eu.depau.etchdroid.utils.exception.UsbCommunicationException
|
||||
import eu.depau.etchdroid.utils.exception.VerificationFailedException
|
||||
import eu.depau.etchdroid.utils.exception.base.FatalException
|
||||
@@ -146,6 +151,7 @@ import eu.depau.etchdroid.utils.ktexts.startForegroundServiceCompat
|
||||
import eu.depau.etchdroid.utils.ktexts.toHRSize
|
||||
import eu.depau.etchdroid.utils.ktexts.toast
|
||||
import eu.depau.etchdroid.utils.ktexts.usbDevice
|
||||
import eu.depau.etchdroid.utils.withoutPartSuffix
|
||||
import eu.depau.etchdroid.websiteUrl
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -290,7 +296,7 @@ class ProgressActivity : ActivityBase() {
|
||||
JobState.SUCCESS -> {
|
||||
BackHandler { finish() }
|
||||
TelemetryTraced("success_screen") {
|
||||
SuccessView()
|
||||
SuccessView(appState)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,7 +306,8 @@ class ProgressActivity : ActivityBase() {
|
||||
exception = appState.exception!! as FatalException,
|
||||
imageUri = appState.sourceUri!!,
|
||||
jobId = appState.jobId,
|
||||
device = appState.destDevice!!
|
||||
device = appState.destDevice!!,
|
||||
isBackup = appState.isBackup,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -448,6 +455,9 @@ fun JobInProgressView(
|
||||
cancelVerification: () -> Unit = {},
|
||||
) {
|
||||
val uiState by viewModel.state.collectAsState()
|
||||
// Verification and backup both read from the drive towards the disk images; a write
|
||||
// pushes the images the other way, into the drive.
|
||||
val isReadingDrive = uiState.isVerifying || uiState.isBackup
|
||||
|
||||
KeepScreenOn()
|
||||
JobInProgressViewLayout(
|
||||
@@ -455,16 +465,20 @@ fun JobInProgressView(
|
||||
title = {
|
||||
Text(
|
||||
modifier = Modifier.appiumTag(
|
||||
if (uiState.isVerifying)
|
||||
"verify_progress_title"
|
||||
else
|
||||
"write_progress_title"
|
||||
),
|
||||
text = if (uiState.isVerifying) stringResource(
|
||||
R.string.verifying_image
|
||||
) else stringResource(
|
||||
R.string.writing_image
|
||||
when {
|
||||
uiState.isBackup -> "backup_progress_title"
|
||||
uiState.isVerifying -> "verify_progress_title"
|
||||
else -> "write_progress_title"
|
||||
}
|
||||
),
|
||||
text = when {
|
||||
uiState.isBackup && uiState.isVerifying ->
|
||||
stringResource(R.string.backup_checking_existing_data)
|
||||
|
||||
uiState.isBackup -> stringResource(R.string.backup_progress_title)
|
||||
uiState.isVerifying -> stringResource(R.string.verifying_image)
|
||||
else -> stringResource(R.string.writing_image)
|
||||
},
|
||||
style = MaterialTheme.typography.titleLarge.copy(fontSize = 28.sp),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
@@ -536,8 +550,8 @@ fun JobInProgressView(
|
||||
val anchorTransition =
|
||||
rememberInfiniteTransition(label = "anchorTransition")
|
||||
val anchor by anchorTransition.animateValue(
|
||||
initialValue = if (uiState.isVerifying) 100.dp else (100 + repeatWidth).dp,
|
||||
targetValue = if (uiState.isVerifying) (100 + repeatWidth).dp else 100.dp,
|
||||
initialValue = if (isReadingDrive) 100.dp else (100 + repeatWidth).dp,
|
||||
targetValue = if (isReadingDrive) (100 + repeatWidth).dp else 100.dp,
|
||||
typeConverter = TwoWayConverter(
|
||||
convertToVector = {
|
||||
AnimationVector1D(
|
||||
@@ -556,7 +570,7 @@ fun JobInProgressView(
|
||||
modifier = Modifier
|
||||
.constrainAs(imagesRow) {
|
||||
centerVerticallyTo(usbDrive)
|
||||
if (uiState.isVerifying) {
|
||||
if (isReadingDrive) {
|
||||
absoluteLeft.linkTo(usbDrive.absoluteLeft, anchor)
|
||||
} else {
|
||||
absoluteRight.linkTo(usbDrive.absoluteRight, anchor)
|
||||
@@ -587,9 +601,9 @@ fun JobInProgressView(
|
||||
centerTo(parent)
|
||||
}
|
||||
.padding(
|
||||
// If we are verifying, the USB drive should be on the left
|
||||
// When reading from the drive, the USB drive should be on the left
|
||||
// Invert if we're in RTL mode
|
||||
if (!(uiState.isVerifying xor (LocalLayoutDirection.current == LayoutDirection.Ltr)))
|
||||
if (!(isReadingDrive xor (LocalLayoutDirection.current == LayoutDirection.Ltr)))
|
||||
PaddingValues(end = 128.dp)
|
||||
else
|
||||
PaddingValues(start = 128.dp)
|
||||
@@ -686,19 +700,24 @@ fun JobInProgressView(
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
// Queried once per URI: recomposing on every progress update would spam the provider
|
||||
val sourceName = remember(uiState.sourceUri) {
|
||||
uiState.sourceUri?.getDisplayName(context)
|
||||
val sourceName = remember(uiState.sourceUri, uiState.isBackup) {
|
||||
uiState.sourceUri?.getDisplayName(context)?.let {
|
||||
// For a backup this is the destination file, still carrying .part.
|
||||
if (uiState.isBackup) it.withoutPartSuffix() else it
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center
|
||||
) {
|
||||
Text(
|
||||
text = if (uiState.isVerifying) stringResource(R.string.verifying) else stringResource(
|
||||
R.string.copying
|
||||
)
|
||||
text = when {
|
||||
uiState.isBackup -> stringResource(R.string.backup_copying)
|
||||
uiState.isVerifying -> stringResource(R.string.verifying)
|
||||
else -> stringResource(R.string.copying)
|
||||
}
|
||||
)
|
||||
Text(
|
||||
text = " " + if (uiState.isVerifying) uiState.destDevice?.name
|
||||
text = " " + if (uiState.isVerifying || uiState.isBackup) uiState.destDevice?.name
|
||||
else sourceName,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
@@ -709,12 +728,12 @@ fun JobInProgressView(
|
||||
modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center
|
||||
) {
|
||||
Text(
|
||||
text = if (uiState.isVerifying) stringResource(
|
||||
text = if (uiState.isVerifying && !uiState.isBackup) stringResource(
|
||||
R.string.against
|
||||
) else stringResource(R.string.to)
|
||||
)
|
||||
Text(
|
||||
text = " " + if (uiState.isVerifying) sourceName
|
||||
text = " " + if (uiState.isVerifying || uiState.isBackup) sourceName
|
||||
else uiState.destDevice?.name,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
@@ -726,8 +745,21 @@ fun JobInProgressView(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 8.dp),
|
||||
text = if (uiState.percent >= 0) "${uiState.processedBytes.toHRSize()} / ${uiState.totalBytes.toHRSize()}" + " ${if (uiState.isVerifying) "verified" else "written"}, ${uiState.speed.toHRSize()}/s"
|
||||
else stringResource(R.string.getting_ready),
|
||||
text = when {
|
||||
uiState.percent < 0 -> stringResource(R.string.getting_ready)
|
||||
uiState.isBackup && uiState.isVerifying -> stringResource(
|
||||
R.string.backup_prefix_progress_summary,
|
||||
uiState.processedBytes.toHRSize(),
|
||||
uiState.totalBytes.toHRSize(),
|
||||
)
|
||||
uiState.isBackup -> stringResource(
|
||||
R.string.backup_progress_summary,
|
||||
uiState.processedBytes.toHRSize(),
|
||||
uiState.totalBytes.toHRSize(),
|
||||
uiState.speed.toHRSize()
|
||||
)
|
||||
else -> "${uiState.processedBytes.toHRSize()} / ${uiState.totalBytes.toHRSize()}" + " ${if (uiState.isVerifying) "verified" else "written"}, ${uiState.speed.toHRSize()}/s"
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
@@ -750,7 +782,7 @@ fun JobInProgressView(
|
||||
)
|
||||
}
|
||||
|
||||
if (uiState.isVerifying) {
|
||||
if (uiState.isVerifying && !uiState.isBackup) {
|
||||
OutlinedButton(
|
||||
modifier = Modifier
|
||||
.appiumTag("skip_verification_button")
|
||||
@@ -771,7 +803,8 @@ fun JobInProgressView(
|
||||
uiState.jobId,
|
||||
uiState.isVerifying,
|
||||
uiState.destDevice!!,
|
||||
uiState.processedBytes
|
||||
uiState.processedBytes,
|
||||
isBackup = uiState.isBackup,
|
||||
)
|
||||
ReconnectUsbDriveDialog(exception = uiState.exception as RecoverableException)
|
||||
}
|
||||
@@ -882,13 +915,17 @@ fun SuccessViewLayout(
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun SuccessView() {
|
||||
fun SuccessView(state: ProgressActivityState) {
|
||||
SuccessViewLayout(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
title = {
|
||||
Text(
|
||||
modifier = Modifier.appiumTag("success_write_title"),
|
||||
text = stringResource(R.string.image_written_successfully),
|
||||
modifier = Modifier.appiumTag(
|
||||
if (state.isBackup) "backup_success_title" else "success_write_title"
|
||||
),
|
||||
text = if (state.isBackup) stringResource(R.string.backup_complete) else stringResource(
|
||||
R.string.image_written_successfully
|
||||
),
|
||||
textAlign = TextAlign.Center,
|
||||
style = MaterialTheme.typography.titleLarge.copy(fontSize = 28.sp),
|
||||
)
|
||||
@@ -959,50 +996,122 @@ fun SuccessView() {
|
||||
})
|
||||
activity?.finish()
|
||||
}) {
|
||||
Text(stringResource(R.string.write_another_image))
|
||||
Text(
|
||||
stringResource(
|
||||
if (state.isBackup) R.string.back_up_another_drive
|
||||
else R.string.write_another_image
|
||||
)
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomCard = {
|
||||
Card(modifier = Modifier.padding(16.dp)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.got_an_unsupported_drive_notification),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (state.isBackup) {
|
||||
val context = LocalContext.current
|
||||
val rawName = remember(state.sourceUri) {
|
||||
// The provider may throw anything once the rename invalidated the URI.
|
||||
runCatching { state.sourceUri?.getDisplayName(context) }.getOrNull()
|
||||
}
|
||||
// The finished intent still carries the pre-rename .part URI, and the
|
||||
// rename may have invalidated it: fall back to an unknown name rather
|
||||
// than showing the encoded path the provider falls back to.
|
||||
val destinationName = rawName
|
||||
?.withoutPartSuffix()
|
||||
?.takeIf { it.isNotBlank() && !it.contains('%') }
|
||||
?: stringResource(R.string.unknown_filename)
|
||||
|
||||
val annotatedString = buildAnnotatedString {
|
||||
val learnMoreStr = stringResource(R.string.learn_what_it_means)
|
||||
val str = stringResource(R.string.it_s_safe_to_ignore, learnMoreStr)
|
||||
val startIndex = str.indexOf(learnMoreStr)
|
||||
val endIndex = startIndex + learnMoreStr.length
|
||||
append(str)
|
||||
addStyle(
|
||||
style = SpanStyle(
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
textDecoration = TextDecoration.Underline
|
||||
), start = startIndex, end = endIndex
|
||||
Card(modifier = Modifier.padding(16.dp)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
text = destinationName,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Text(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
text = state.totalBytes.toHRSize(),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
state.sha256?.let { hash ->
|
||||
Text(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 8.dp),
|
||||
text = stringResource(R.string.sha256_checksum),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
SelectionContainer {
|
||||
Text(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
text = hash,
|
||||
style = MaterialTheme.typography.bodyMedium.copy(
|
||||
fontFamily = FontFamily.Monospace
|
||||
),
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Card(modifier = Modifier.padding(16.dp)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.got_an_unsupported_drive_notification),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
addLink(
|
||||
LinkAnnotation.Url(websiteUrl("/broken_usb/")),
|
||||
startIndex,
|
||||
endIndex
|
||||
|
||||
val annotatedString = buildAnnotatedString {
|
||||
val learnMoreStr = stringResource(R.string.learn_what_it_means)
|
||||
val str = stringResource(R.string.it_s_safe_to_ignore, learnMoreStr)
|
||||
val startIndex = str.indexOf(learnMoreStr)
|
||||
val endIndex = startIndex + learnMoreStr.length
|
||||
append(str)
|
||||
addStyle(
|
||||
style = SpanStyle(
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
textDecoration = TextDecoration.Underline
|
||||
), start = startIndex, end = endIndex
|
||||
)
|
||||
addLink(
|
||||
LinkAnnotation.Url(websiteUrl("/broken_usb/")),
|
||||
startIndex,
|
||||
endIndex
|
||||
)
|
||||
}
|
||||
Text(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
text = annotatedString,
|
||||
style = MaterialTheme.typography.labelMedium.copy(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
)
|
||||
}
|
||||
Text(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
text = annotatedString,
|
||||
style = MaterialTheme.typography.labelMedium.copy(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1105,6 +1214,7 @@ fun FatalErrorView(
|
||||
imageUri: Uri,
|
||||
jobId: Int,
|
||||
device: UsbMassStorageDeviceDescriptor,
|
||||
isBackup: Boolean = false,
|
||||
) {
|
||||
FatalErrorViewLayout(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -1126,7 +1236,12 @@ fun FatalErrorView(
|
||||
)
|
||||
},
|
||||
suggestion = {
|
||||
if (exception !is NotEnoughSpaceException) {
|
||||
// Running out of space, or a provider that cannot be written, is a routine
|
||||
// condition with its own advice: do not send the user to the issue tracker.
|
||||
if (exception !is NotEnoughSpaceException &&
|
||||
exception !is NotEnoughSpaceForBackupException &&
|
||||
exception !is CouldNotWriteBackupException
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.please_report_fatal_issue),
|
||||
textAlign = TextAlign.Center,
|
||||
@@ -1176,6 +1291,24 @@ fun FatalErrorView(
|
||||
}
|
||||
}
|
||||
|
||||
// A backup's destination file is the resume point: starting the job again appends
|
||||
// from the bytes that are already there instead of re-reading the whole drive.
|
||||
if (isBackup && activity != null) {
|
||||
Button(onClick = {
|
||||
val serviceIntent = getStartBackupJobIntent(
|
||||
imageUri,
|
||||
device,
|
||||
jobId,
|
||||
activity,
|
||||
WorkerService::class.java
|
||||
)
|
||||
Log.d(TAG, "Starting service with intent: $serviceIntent")
|
||||
activity.startForegroundServiceCompat(serviceIntent)
|
||||
}) {
|
||||
Text(stringResource(R.string.resume_backup))
|
||||
}
|
||||
}
|
||||
|
||||
Button({
|
||||
context.startActivity(Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
@@ -1195,6 +1328,7 @@ fun AutoJobRestarter(
|
||||
isVerifying: Boolean,
|
||||
expectedDevice: UsbMassStorageDeviceDescriptor,
|
||||
resumeOffset: Long,
|
||||
isBackup: Boolean = false,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val activity = remember { context.activity } ?: run {
|
||||
@@ -1262,15 +1396,27 @@ fun AutoJobRestarter(
|
||||
)
|
||||
} else {
|
||||
activity.toast(context.getString(R.string.usb_device_reconnected_resuming))
|
||||
val serviceIntent = getStartJobIntent(
|
||||
imageUri,
|
||||
msd,
|
||||
jobId,
|
||||
resumeOffset,
|
||||
isVerifying,
|
||||
activity,
|
||||
WorkerService::class.java
|
||||
)
|
||||
// A backup's destination size tells the flow where to resume, so it
|
||||
// needs no offset and is never a verification pass.
|
||||
val serviceIntent = if (isBackup) {
|
||||
getStartBackupJobIntent(
|
||||
imageUri,
|
||||
msd,
|
||||
jobId,
|
||||
activity,
|
||||
WorkerService::class.java
|
||||
)
|
||||
} else {
|
||||
getStartJobIntent(
|
||||
imageUri,
|
||||
msd,
|
||||
jobId,
|
||||
resumeOffset,
|
||||
isVerifying,
|
||||
activity,
|
||||
WorkerService::class.java
|
||||
)
|
||||
}
|
||||
Log.d(TAG, "Starting service with intent: $serviceIntent")
|
||||
scope.launch {
|
||||
lifecycle.withStarted {
|
||||
@@ -1313,7 +1459,7 @@ fun AutoJobRestarter(
|
||||
fun SuccessViewPreview() {
|
||||
val viewModel = remember { ProgressActivityViewModel() }
|
||||
MainView(viewModel) {
|
||||
SuccessView()
|
||||
SuccessView(ProgressActivityState.Empty)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import androidx.compose.runtime.remember
|
||||
import androidx.lifecycle.ViewModel
|
||||
import eu.depau.etchdroid.AppSettings
|
||||
import eu.depau.etchdroid.Intents
|
||||
import eu.depau.etchdroid.JobOperation
|
||||
import eu.depau.etchdroid.JobStatusInfo
|
||||
import eu.depau.etchdroid.SettingChangeListener
|
||||
import eu.depau.etchdroid.ThemeMode
|
||||
@@ -87,6 +88,9 @@ data class MainActivityState(
|
||||
val massStorageDevices: Set<UsbMassStorageDeviceDescriptor> = emptySet(),
|
||||
val telemetry: Boolean = false,
|
||||
val showTelemetry: Boolean = true,
|
||||
val backupDevicePickerOpen: Boolean = false,
|
||||
val pendingBackupDevice: UsbMassStorageDeviceDescriptor? = null,
|
||||
val showIncompleteBackupAlertForUri: Uri? = null,
|
||||
) : IThemeState {
|
||||
companion object {
|
||||
val Empty: MainActivityState
|
||||
@@ -123,6 +127,24 @@ class MainActivityViewModel : ViewModel(), SettingChangeListener, IThemeViewMode
|
||||
}
|
||||
}
|
||||
|
||||
fun setBackupDevicePickerOpen(open: Boolean) {
|
||||
_state.update {
|
||||
it.copy(backupDevicePickerOpen = open)
|
||||
}
|
||||
}
|
||||
|
||||
fun setPendingBackupDevice(device: UsbMassStorageDeviceDescriptor?) {
|
||||
_state.update {
|
||||
it.copy(pendingBackupDevice = device)
|
||||
}
|
||||
}
|
||||
|
||||
fun setIncompleteBackupAlertUri(uri: Uri?) {
|
||||
_state.update {
|
||||
it.copy(showIncompleteBackupAlertForUri = uri)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun usbDeviceAttached(device: UsbDevice) {
|
||||
_state.update {
|
||||
@@ -172,6 +194,7 @@ data class ConfirmOperationActivityState(
|
||||
val openedImage: Uri? = null,
|
||||
val selectedDevice: UsbMassStorageDeviceDescriptor? = null,
|
||||
val hasUsbPermission: Boolean = false,
|
||||
val operation: JobOperation = JobOperation.WRITE,
|
||||
) : IThemeState {
|
||||
companion object {
|
||||
val Empty: ConfirmOperationActivityState
|
||||
@@ -197,11 +220,16 @@ class ConfirmOperationActivityViewModel : ViewModel(), SettingChangeListener,
|
||||
_state.update { state }
|
||||
}
|
||||
|
||||
fun init(openedImage: Uri?, selectedDevice: UsbMassStorageDeviceDescriptor?) = _state.update {
|
||||
fun init(
|
||||
openedImage: Uri?,
|
||||
selectedDevice: UsbMassStorageDeviceDescriptor?,
|
||||
operation: JobOperation = JobOperation.WRITE,
|
||||
) = _state.update {
|
||||
it.copy(
|
||||
openedImage = openedImage,
|
||||
selectedDevice = selectedDevice,
|
||||
hasUsbPermission = false,
|
||||
operation = operation,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -235,6 +263,8 @@ data class ProgressActivityState(
|
||||
val lastNotificationTime: Long = System.currentTimeMillis(),
|
||||
/** Whether the progress screen is currently receiving job updates. */
|
||||
val isForeground: Boolean = true,
|
||||
val isBackup: Boolean = false,
|
||||
val sha256: String? = null,
|
||||
) : IThemeState {
|
||||
companion object {
|
||||
val Empty: ProgressActivityState
|
||||
@@ -302,6 +332,9 @@ class ProgressActivityViewModel : ViewModel(), SettingChangeListener, IThemeView
|
||||
destDevice = status.destDevice,
|
||||
exception = null,
|
||||
lastNotificationTime = System.currentTimeMillis(),
|
||||
isBackup = status.isBackup,
|
||||
// Never let a previous backup's hash leak onto a later screen.
|
||||
sha256 = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -316,6 +349,8 @@ class ProgressActivityViewModel : ViewModel(), SettingChangeListener, IThemeView
|
||||
totalBytes = status.totalBytes,
|
||||
percent = 100,
|
||||
lastNotificationTime = System.currentTimeMillis(),
|
||||
isBackup = status.isBackup,
|
||||
sha256 = status.sha256,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -332,6 +367,8 @@ class ProgressActivityViewModel : ViewModel(), SettingChangeListener, IThemeView
|
||||
totalBytes = status.totalBytes,
|
||||
percent = status.percent,
|
||||
lastNotificationTime = System.currentTimeMillis(),
|
||||
isBackup = status.isBackup,
|
||||
sha256 = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package eu.depau.etchdroid.utils
|
||||
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
|
||||
/** Suffix appended to a backup file name while the backup is still being written. */
|
||||
const val BACKUP_PART_SUFFIX = ".part"
|
||||
|
||||
private const val FALLBACK_BACKUP_NAME = "usb-drive"
|
||||
private const val MAX_BACKUP_NAME_LENGTH = 24
|
||||
private const val TIMESTAMP_PATTERN = "yyyyMMdd-HHmm"
|
||||
|
||||
/** True when this file name marks an unfinished backup. */
|
||||
fun String.isIncompleteBackupName(): Boolean = endsWith(BACKUP_PART_SUFFIX, ignoreCase = true)
|
||||
|
||||
/** Drops the [BACKUP_PART_SUFFIX] suffix, if present. */
|
||||
fun String.withoutPartSuffix(): String =
|
||||
if (isIncompleteBackupName()) dropLast(BACKUP_PART_SUFFIX.length) else this
|
||||
|
||||
/** Builds a human-recognizable, filesystem-safe name for a backup of [deviceName]. */
|
||||
fun suggestedBackupFileName(deviceName: String, now: Date = Date()): String {
|
||||
val sanitized = deviceName.lowercase(Locale.US)
|
||||
.replace(Regex("[^a-z0-9]+"), "-")
|
||||
.trim('-')
|
||||
.take(MAX_BACKUP_NAME_LENGTH)
|
||||
.ifEmpty { FALLBACK_BACKUP_NAME }
|
||||
val timestamp = SimpleDateFormat(TIMESTAMP_PATTERN, Locale.US)
|
||||
.apply { timeZone = TimeZone.getTimeZone("UTC") }
|
||||
.format(now)
|
||||
return "backup-$sanitized-$timestamp.img$BACKUP_PART_SUFFIX"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package eu.depau.etchdroid.utils.exception
|
||||
|
||||
import android.content.Context
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.utils.exception.base.FatalException
|
||||
import kotlinx.parcelize.Parcelize
|
||||
|
||||
@Parcelize
|
||||
class CouldNotWriteBackupException(override val message: String, override val cause: Throwable?) :
|
||||
FatalException(message, cause) {
|
||||
|
||||
override fun getUiMessage(context: Context): String {
|
||||
return context.getString(R.string.could_not_write_backup_file)
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package eu.depau.etchdroid.utils.exception
|
||||
|
||||
import android.content.Context
|
||||
import eu.depau.etchdroid.R
|
||||
import eu.depau.etchdroid.utils.exception.base.FatalException
|
||||
import eu.depau.etchdroid.utils.ktexts.toHRSize
|
||||
import kotlinx.parcelize.Parcelize
|
||||
|
||||
@Parcelize
|
||||
class NotEnoughSpaceForBackupException(val requiredBytes: Long, val availableBytes: Long) :
|
||||
FatalException("Not enough space for backup ($requiredBytes needed, $availableBytes available)") {
|
||||
|
||||
override fun getUiMessage(context: Context): String {
|
||||
return context.getString(
|
||||
R.string.not_enough_space_for_backup, requiredBytes.toHRSize(),
|
||||
availableBytes.toHRSize()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,23 @@
|
||||
<string name="notification_write_tap_for_progress_text" comment=" Notification content for long-running job status, used when the user has granted the notification permission but no progress info is available. The first parameter will be replaced with the source file name, the second one with the USB stick name">Tap for progress • Writing %1$s to %2$s</string>
|
||||
<string name="notification_write_progress_content" comment=" Notification content: "{file name} to {device name}", used when the user has granted the notification permission; The notification title will be: "Writing image…" and this string will show up right below it.">%1$s to %2$s</string>
|
||||
<string name="notification_verify_progress_content" comment=" Notification content: "{device name} against {file name}", used when the user has granted the notification permission; The notification title will be: "Verifying image…" and this string will show up right below it.">%1$s against %2$s</string>
|
||||
<string name="notification_backup_progress_title" comment="Notification title used for long-running backup job status">Backing up…</string>
|
||||
<string name="notification_backup_prefix_progress_title" comment="Notification title used while a resumed backup checks the data it already wrote to the destination file">Checking existing data…</string>
|
||||
<string name="notification_backup_progress_content" comment="Notification content: "{device name} to {file name}", used when the user has granted the notification permission; The notification title will be: "Backing up…" and this string will show up right below it.">%1$s to %2$s</string>
|
||||
<string name="notification_backup_no_notifications_text" comment="Notification content for long-running backup job status, used when the user has not granted the notification permission. The first parameter will be replaced with the USB drive name, the second one with the destination file name">Enable notifications for progress • Backing up %1$s to %2$s</string>
|
||||
<string name="notification_backup_tap_for_progress_text" comment="Notification content for long-running backup job status, used when the user has granted the notification permission but no progress info is available. The first parameter will be replaced with the USB drive name, the second one with the destination file name">Tap for progress • Backing up %1$s to %2$s</string>
|
||||
<string name="backup_finished" comment="Notification title when the backup operation is successful">Backup finished</string>
|
||||
<string name="backup_success_notif_content_text" comment="Notification content when the backup operation is successful. Parameters: device name, destination file name">%1$s backed up to %2$s</string>
|
||||
<string name="backup_failed" comment="Notification title when a non-recoverable backup error occurs">Backup failed</string>
|
||||
<string name="unknown_filename" comment="Placeholder file name">Unknown file name</string>
|
||||
<string name="no_file_picker" comment="Toast shown when the device has no app to pick a file">No file picker app found on this device. Install a file manager and try again.</string>
|
||||
<string name="permission_denied_for_usb_device" comment="Displayed in a toast when the usb permission is denied">"Permission denied for USB device %1$s"</string>
|
||||
<string name="usb_permission_request_failed" comment="Displayed in a toast when Android refuses to show the USB permission prompt">Android refused to ask for USB access. If EtchDroid is running in a work profile, second space or as a dual app, try running it from the main profile.</string>
|
||||
<string name="usb_device_was_unplugged" comment="Displayed in a toast when the USB device is unplugged">USB device was unplugged</string>
|
||||
<string name="write_an_image" comment="Displayed in the home page main call-to-action button">Write an image</string>
|
||||
<string name="backup_a_drive" comment="Displayed in the home page as an alternative call-to-action button; backs up a USB drive to a file">Back up a drive</string>
|
||||
<string name="incomplete_backup_title" comment="Dialog title; the dialog warns the user that the selected file is an unfinished backup">Incomplete backup</string>
|
||||
<string name="incomplete_backup_message" comment="Dialog message; the dialog warns the user that an unfinished backup file may contain only part of a drive">This file looks like an unfinished backup. Restoring it may write only part of a drive.</string>
|
||||
<string name="whats_supported" comment="Displayed in the homepage; opens a page that lists all the supported devices and formats">What\'s supported?</string>
|
||||
<string name="style" comment="Title of the menu that allows selecting the app color scheme">Style</string>
|
||||
<string name="device_setting" comment="Style menu option that selects the device default light/dark theme">Device setting</string>
|
||||
@@ -36,16 +47,21 @@
|
||||
<string name="connect_a_usb_drive" comment="Title of the dialog listing the available USB drives, when no USB drive is connected">Connect a USB drive</string>
|
||||
<string name="looking_for_usb_drives">Looking for USB drives</string>
|
||||
<string name="confirm_operation" comment="Title of the page where the operation details are listed; the user can confirm or cancel the operation from here">Confirm operation</string>
|
||||
<string name="back_up_usb_drive" comment="Title of the page where the backup details are listed; the user can confirm or cancel the backup from here">Back up USB drive</string>
|
||||
<string name="disk_image">Disk image</string>
|
||||
<string name="image_to_write" comment="Label for the card that displays the details about the image that is about to be written">Image to write</string>
|
||||
<string name="usb_drive">USB drive</string>
|
||||
<string name="destination_usb_device" comment="Label for the card that displays the details about the USB drive that is about to be used">Destination USB device</string>
|
||||
<string name="source_usb_device" comment="Label for the card that displays the details about the USB drive that is about to be backed up">Source USB device</string>
|
||||
<string name="destination_file" comment="Label for the card that displays the details about the file that the backup will be written to">Destination file</string>
|
||||
<string name="unknown_device" comment="Device name placeholder">Unknown device</string>
|
||||
<string name="grant_access" comment="Displayed on the button to request the permission to write to the USB drive. Keep it short.">Grant access</string>
|
||||
<string name="permission_granted">Permission granted</string>
|
||||
<string name="be_careful" comment="Title of the card that alerts the user that, if they continue, all data on the USB drive will be lost">Be careful!</string>
|
||||
<string name="writing_the_image_will_erase" comment="Message displayed on the card that alerts the user that, if they continue, all data on the USB drive will be lost">Writing the image will erase all data on the selected drive</string>
|
||||
<string name="backup_warning" comment="Message displayed on the card that warns the user about what to expect while the backup is running">Keep the reader connected. The backup is as large as the card and may take a long time.</string>
|
||||
<string name="write_image" comment="Confirmation button; when pressed, the operation starts">Write image</string>
|
||||
<string name="start_backup" comment="Confirmation button of the backup page; when pressed, the backup starts">Start backup</string>
|
||||
<string name="lay_your_device_flat_no_accel" comment="Title of the dialog that forces the user to lay the device flat on a table before continuing, when the device has no gravity sensor">Lay your device flat on a table before continuing.</string>
|
||||
<string name="continue_" comment="Button displayed in the dialog that forces the user to lay the device flat on a table before continuing, when the device has no gravity sensor; when pressed the operation starts.">Continue</string>
|
||||
<string name="lay_your_device_flat" comment="Title of the dialog that forces the user to lay the device flat on a table before continuing, when the device has a gravity sensor">Lay your device flat on a table and don\'t touch it</string>
|
||||
@@ -79,17 +95,24 @@
|
||||
<string name="support_the_project" comment="Displayed in the about page links; keep it short!">Support financially</string>
|
||||
<string name="verifying_image" comment="Title of the progress page while an image is being verified">Verifying image</string>
|
||||
<string name="writing_image" comment="Title of the progress page while an image is being written">Writing image</string>
|
||||
<string name="backup_progress_title" comment="Title of the progress page while a USB drive is being backed up to a file">Backing up drive</string>
|
||||
<string name="backup_checking_existing_data" comment="Title of the progress page while a resumed backup checks the data it already wrote to the destination file">Checking existing data…</string>
|
||||
<string name="please_avoid_using_your_device" comment="Subtitle of the progress page while an image is being written">Please avoid using your device</string>
|
||||
<string name="would_you_like_to_be_notified" comment="Displayed in a card in the progress page; keep it concise, there's not much space">Would you like to be notified when done? Only progress updates, no spam or ads.</string>
|
||||
<string name="no_thanks" comment="Button to reject receiving notifications">No, thanks</string>
|
||||
<string name="sure" comment="Button to accept receiving notifications">Sure</string>
|
||||
<string name="verifying" comment="As part of the sentence: "Verifying DeviceName against FileName.iso"; keep the same word order as English. Open an issue if it's not possible in your language.">Verifying</string>
|
||||
<string name="copying" comment="As part of the sentence: "Copying FileName.iso to DeviceName"; keep the same word order as English. Open an issue if it's not possible in your language.">Copying</string>
|
||||
<string name="backup_copying" comment="As part of the sentence: "Backing up DeviceName to FileName.img"; keep the same word order as English. Open an issue if it's not possible in your language.">Backing up</string>
|
||||
<string name="backup_progress_summary" comment="Progress details while a USB drive is being backed up. Parameters are the bytes copied so far, the total bytes to copy, and the current speed">%1$s / %2$s copied, %3$s/s</string>
|
||||
<string name="backup_prefix_progress_summary" comment="Progress details while a resumed backup checks the data already written to the destination file. Parameters are the bytes checked so far and the total bytes of the drive">%1$s / %2$s checked</string>
|
||||
<string name="against" comment="As part of the sentence: "Verifying DeviceName against FileName.iso"; keep the same word order as English. Open an issue if it's not possible in your language.">against</string>
|
||||
<string name="to" comment="As part of the sentence: "Copying FileName.iso to DeviceName"; keep the same word order as English. Open an issue if it's not possible in your language.">to</string>
|
||||
<string name="getting_ready" comment="Displayed in the progress info indicator while no progress data is available">Getting ready…</string>
|
||||
<string name="skip_verification" comment="Displayed on a button that, when pressed, skips the verification of the written image">Skip verification</string>
|
||||
<string name="image_written_successfully" comment="Title of the success page">Image written successfully!</string>
|
||||
<string name="backup_complete" comment="Title of the success page shown after a USB drive has been backed up to a file">Backup complete!</string>
|
||||
<string name="sha256_checksum" comment="Label shown above the SHA-256 hash of a finished backup file, so the user can verify the copy later">SHA-256</string>
|
||||
<string name="write_a_review" comment="Displayed in a button on the success page">Write a review</string>
|
||||
<string name="star_on_github" comment="Displayed in a button on the success page">Star on GitHub</string>
|
||||
<string name="got_an_unsupported_drive_notification" comment="Title of the card that teaches the user about any "Issues with this drive" notifications">Got an \"Issues with this drive\" notification?</string>
|
||||
@@ -99,6 +122,7 @@
|
||||
<string name="error">Error</string>
|
||||
<string name="start_over" comment="Button in the error page that, when pressed, restarts the app">Start over</string>
|
||||
<string name="try_again" comment="Button in the error page that, when pressed, retries the write from scratch">Try again</string>
|
||||
<string name="resume_backup" comment="Button in the error page of a backup that, when pressed, continues the backup from the data already written to the destination file">Resume backup</string>
|
||||
<string name="i_did_not_unplug_it" comment="Title of the card that, when a USB disconnection is detected, teaches the user how it could have happened inadvertently">I did not unplug it!</string>
|
||||
<string name="how_did_this_happen" comment="Title of the card that, when a recoverable error occurs, teaches the user why it could have happened">How did this happen?</string>
|
||||
<string name="perhaps_your_usb_port_is_dirty" comment="Message of the card that, when a USB disconnection is detected, teaches the user how it could have happened inadvertently">Perhaps your USB port is dirty, your adapter is defective, or your device can\'t provide enough electrical power. Consider trying a different adapter or device.</string>
|
||||
@@ -113,12 +137,15 @@
|
||||
<string name="the_usb_drive_is_too_large" comment="Error message">The USB drive is too large and EtchDroid does not support it.</string>
|
||||
<string name="no_medium_in_usb_drive" comment="Error message">No storage medium found in the USB drive. If it\'s a card reader, make sure a memory card is inserted.</string>
|
||||
<string name="the_image_is_is_larger_than_the_device" comment="Error message; parameters are the image file size and the device size">The image (%1$s) is larger than the device (%2$s)</string>
|
||||
<string name="not_enough_space_for_backup" comment="Error message; parameters are the space required for the backup and the space available on the destination">Not enough space: the backup needs %1$s but only %2$s is available</string>
|
||||
<string name="could_not_write_backup_file" comment="Error message shown when the backup file could not be written to the chosen location">Could not write the backup file. Check that there is enough free space and try again.</string>
|
||||
<string name="could_not_open_the_source_file" comment="Error message">Could not open the source file</string>
|
||||
<string name="an_unknown_error_occurred" comment="Error message; parameter is the underlying error message">An unknown error occurred: %1$s</string>
|
||||
<string name="the_usb_drive_was_unplugged" comment="Error message">The USB drive was unplugged</string>
|
||||
<string name="the_usb_drive_stopped_responding" comment="Error message">The USB drive stopped responding</string>
|
||||
<string name="the_usb_device_content_does_not_match_the_image" comment="Error message displayed when the verification failed">The USB device content does not match the image</string>
|
||||
<string name="write_another_image" comment="Displayed in the successful write page, when clicked the app goes back to the initial page">Write another image</string>
|
||||
<string name="back_up_another_drive" comment="Displayed in the successful backup page, when clicked the app goes back to the initial page">Back up another drive</string>
|
||||
<string name="title_activity_confirm_operation" comment="Title of the screen that displays the summary of the operation about to be performed">Confirm operation</string>
|
||||
<string name="no_image_uri_provided" comment="Error message (shown in a toast) when the operation confirmation screen is opened without a source file; the app redirects back to the home page">No image URI provided</string>
|
||||
<string name="no_destination_device_selected" comment="Error message (shown in a toast) when the operation confirmation screen is opened without a destination device; the app redirects back to the home page">No destination device selected</string>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import eu.depau.etchdroid.service.WorkerServiceFlowImpl
|
||||
import eu.depau.etchdroid.utils.exception.CouldNotWriteBackupException
|
||||
import eu.depau.etchdroid.utils.exception.NotEnoughSpaceForBackupException
|
||||
import eu.depau.etchdroid.utils.exception.UsbCommunicationException
|
||||
import me.jahnen.libaums.core.usb.PipeException
|
||||
import org.junit.jupiter.api.Assertions.assertSame
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.robolectric.annotation.Config
|
||||
import tech.apter.junit.jupiter.robolectric.RobolectricExtension
|
||||
import java.io.IOException
|
||||
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class BackupErrorMappingTest {
|
||||
@Test
|
||||
fun backupExceptionsPassThroughUnwrapped() {
|
||||
val write = CouldNotWriteBackupException("boom", IOException("ENOSPC"))
|
||||
assertSame(write, WorkerServiceFlowImpl.toJobException(write))
|
||||
val space = NotEnoughSpaceForBackupException(10, 5)
|
||||
assertSame(space, WorkerServiceFlowImpl.toJobException(space))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deviceErrorsStillMapToUsbCommunication() {
|
||||
val mapped = WorkerServiceFlowImpl.toJobException(PipeException())
|
||||
assertTrue(mapped is UsbCommunicationException)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import eu.depau.etchdroid.utils.isIncompleteBackupName
|
||||
import eu.depau.etchdroid.utils.suggestedBackupFileName
|
||||
import eu.depau.etchdroid.utils.withoutPartSuffix
|
||||
import java.util.Date
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class BackupFileNamesTest {
|
||||
@Test
|
||||
fun detectsPartSuffixCaseInsensitively() {
|
||||
assertTrue("backup.img.part".isIncompleteBackupName())
|
||||
assertTrue("BACKUP.IMG.PART".isIncompleteBackupName())
|
||||
assertFalse("backup.img".isIncompleteBackupName())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsOnlyThePartSuffix() {
|
||||
assertEquals("backup.img", "backup.img.part".withoutPartSuffix())
|
||||
assertEquals("backup.img", "backup.img".withoutPartSuffix())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suggestsSanitizedTimestampedName() {
|
||||
assertEquals(
|
||||
"backup-card-reader-usb-3-0-19700101-0000.img.part",
|
||||
suggestedBackupFileName("Card Reader / USB 3.0", Date(0))
|
||||
)
|
||||
assertEquals(
|
||||
"backup-usb-drive-19700101-0000.img.part",
|
||||
suggestedBackupFileName("///", Date(0))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import eu.depau.etchdroid.service.BackupFlow
|
||||
import eu.depau.etchdroid.utils.exception.CouldNotWriteBackupException
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import me.jahnen.libaums.core.driver.BlockDeviceDriver
|
||||
import org.junit.jupiter.api.Assertions.assertArrayEquals
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.assertThrows
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.robolectric.annotation.Config
|
||||
import tech.apter.junit.jupiter.robolectric.RobolectricExtension
|
||||
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class BackupFlowTest {
|
||||
/**
|
||||
* Delegates to a memory driver but makes each block read take a moment, so the flow's reader
|
||||
* is waiting for the next buffer when a simulated device error hits. That is the realistic
|
||||
* case (a real card reader is orders of magnitude slower than the consumer), and it delivers
|
||||
* the driver exception straight through the stream instead of relying on the I/O timeout.
|
||||
*/
|
||||
private class SlowReadBlockDeviceDriver(
|
||||
private val inner: MemoryBufferBlockDeviceDriver,
|
||||
) : BlockDeviceDriver by inner {
|
||||
override fun read(deviceOffset: Long, buffer: ByteBuffer) {
|
||||
Thread.sleep(20)
|
||||
inner.read(deviceOffset, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.IO)
|
||||
|
||||
private fun sha256(bytes: ByteArray): String =
|
||||
MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
|
||||
private fun MemoryBufferBlockDeviceDriver.sizeBytes() = blocks * blockSize
|
||||
|
||||
@Test
|
||||
fun copiesWholeDeviceAndHashesIt() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(4L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val out = ByteArrayOutputStream()
|
||||
val hash = BackupFlow.backupImage(
|
||||
dev, out, null, 0, dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
assertArrayEquals(dev.backingBuffer, out.toByteArray())
|
||||
assertEquals(sha256(dev.backingBuffer), hash)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumesFromExistingPrefix() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(4L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val prefix = dev.backingBuffer.copyOfRange(0, 1 shl 20)
|
||||
val out = ByteArrayOutputStream().apply { write(prefix) }
|
||||
val hash = BackupFlow.backupImage(
|
||||
dev, out, prefix.inputStream(), prefix.size.toLong(),
|
||||
dev.sizeBytes(), 1 shl 20, {}, scope, {}, { _, _, _, _ -> })
|
||||
assertArrayEquals(dev.backingBuffer, out.toByteArray())
|
||||
assertEquals(sha256(dev.backingBuffer), hash)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wrapsOutputFailures(): Unit = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(1L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val failing = object : OutputStream() {
|
||||
var written = 0
|
||||
|
||||
override fun write(b: Int) {
|
||||
if (++written > 4096) throw IOException("ENOSPC")
|
||||
}
|
||||
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {
|
||||
if (written + len > 4096) throw IOException("ENOSPC")
|
||||
written += len
|
||||
}
|
||||
}
|
||||
assertThrows<CouldNotWriteBackupException> {
|
||||
BackupFlow.backupImage(
|
||||
dev, failing, null, 0, dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun zeroSizedDeviceWritesNothing() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(0, 512)
|
||||
val out = ByteArrayOutputStream()
|
||||
val hash = BackupFlow.backupImage(
|
||||
dev, out, null, 0, 0, 1 shl 20, {}, scope, {}, { _, _, _, _ -> })
|
||||
assertEquals(0, out.size())
|
||||
assertEquals(sha256(ByteArray(0)), hash)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failsWhenResumeOffsetExceedsDeviceSize(): Unit = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(1L * 1024 * 1024, 512)
|
||||
assertThrows<CouldNotWriteBackupException> {
|
||||
BackupFlow.backupImage(
|
||||
dev, ByteArrayOutputStream(), null, 2L shl 20, dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failsWhenDeviceIsShorterThanDeviceSize(): Unit = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(1L * 1024 * 1024, 512)
|
||||
val out = ByteArrayOutputStream()
|
||||
assertThrows<CouldNotWriteBackupException> {
|
||||
BackupFlow.backupImage(
|
||||
dev, out, null, 0, 2L * 1024 * 1024, 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
// Whatever was written stays a valid resumable prefix, but no hash is returned.
|
||||
assertEquals(dev.backingBuffer.size, out.size())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failsWhenResumeOffsetSkipsPastTheRealDeviceEnd(): Unit = runBlocking {
|
||||
val realSize = 1L * 1024 * 1024
|
||||
val dev = MemoryBufferBlockDeviceDriver(realSize, 512)
|
||||
val resumeOffset = realSize + 512 * 1024
|
||||
val existing = ByteArray(resumeOffset.toInt())
|
||||
assertThrows<CouldNotWriteBackupException> {
|
||||
BackupFlow.backupImage(
|
||||
dev, ByteArrayOutputStream(), existing.inputStream(), resumeOffset,
|
||||
2L * 1024 * 1024, 1 shl 20, {}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failsWhenExistingPrefixIsShorterThanResumeOffset(): Unit = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(2L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val shortPrefix = ByteArray(1024)
|
||||
assertThrows<CouldNotWriteBackupException> {
|
||||
BackupFlow.backupImage(
|
||||
dev, ByteArrayOutputStream(), shortPrefix.inputStream(),
|
||||
1L shl 20, dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reportsProgressWhileHashingTheExistingPrefix() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(2L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val chunk = (1 shl 17).toLong()
|
||||
val prefix = dev.backingBuffer.copyOfRange(0, 1 shl 19)
|
||||
val prefixProgress = mutableListOf<Long>()
|
||||
val deviceProgress = mutableListOf<Long>()
|
||||
val out = ByteArrayOutputStream().apply { write(prefix) }
|
||||
|
||||
BackupFlow.backupImage(
|
||||
dev, out, prefix.inputStream(), prefix.size.toLong(), dev.sizeBytes(), chunk,
|
||||
{}, scope, {}, { _, processed, _, isVerifying ->
|
||||
// The prefix phase is reported as the "verifying" phase so the UI can tell the
|
||||
// user the existing data is being checked; the copy phase is not.
|
||||
if (processed <= prefix.size) {
|
||||
assertTrue(isVerifying)
|
||||
prefixProgress.add(processed)
|
||||
} else {
|
||||
assertTrue(!isVerifying)
|
||||
deviceProgress.add(processed)
|
||||
}
|
||||
})
|
||||
|
||||
// The prefix phase must report progress as it reads, not only once it is done.
|
||||
assertEquals(
|
||||
(1L..prefixProgress.size.toLong()).map { it * chunk }, prefixProgress
|
||||
)
|
||||
assertTrue(prefixProgress.isNotEmpty())
|
||||
assertTrue(deviceProgress.isNotEmpty())
|
||||
assertEquals(dev.sizeBytes(), deviceProgress.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deviceReadFailurePropagatesAndLeavesAValidPrefix() = runBlocking {
|
||||
val memoryDev = MemoryBufferBlockDeviceDriver(4L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
memoryDev.throwAtBlockOffset = memoryDev.blocks / 2
|
||||
memoryDev.exceptionToThrow = { IOException("card removed") }
|
||||
val dev = SlowReadBlockDeviceDriver(memoryDev)
|
||||
val out = ByteArrayOutputStream()
|
||||
|
||||
assertThrows<IOException> {
|
||||
BackupFlow.backupImage(
|
||||
dev, out, null, 0, memoryDev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
|
||||
// The device error is not wrapped, and whatever reached the destination is sequential:
|
||||
// a valid prefix that a later resume can build on.
|
||||
assertTrue(out.size() > 0)
|
||||
assertTrue(out.size() < memoryDev.sizeBytes())
|
||||
assertArrayEquals(memoryDev.backingBuffer.copyOf(out.size()), out.toByteArray())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cancellationLeavesAValidPrefixAndClosesTheStream() = runBlocking {
|
||||
val devSize = 16L * 1024 * 1024
|
||||
val dev = MemoryBufferBlockDeviceDriver(devSize, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val out = ByteArrayOutputStream()
|
||||
val ioScope = CoroutineScope(Dispatchers.IO)
|
||||
val failure = AtomicReference<Throwable?>()
|
||||
|
||||
val job = launch(Dispatchers.IO) {
|
||||
try {
|
||||
BackupFlow.backupImage(
|
||||
dev, out, null, 0, dev.sizeBytes(), 1 shl 20,
|
||||
{}, ioScope, {},
|
||||
{ _, processed, _, _ -> if (processed >= 2L shl 20) cancel() })
|
||||
} catch (e: Throwable) {
|
||||
failure.set(e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
job.join()
|
||||
|
||||
assertTrue(job.isCancelled)
|
||||
assertTrue(failure.get() is CancellationException)
|
||||
assertTrue(out.size() > 0)
|
||||
assertArrayEquals(dev.backingBuffer.copyOf(out.size()), out.toByteArray())
|
||||
|
||||
// The flow closes its BlockDeviceInputStream: if it leaked it, the prefetch worker would
|
||||
// stay parked on a full channel with no reader and never finish.
|
||||
withTimeout(10_000) {
|
||||
ioScope.coroutineContext[Job]!!.children.toList().forEach { it.join() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leavesTheStreamsItDoesNotOwnOpen() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(2L * 1024 * 1024, 512).apply {
|
||||
fillWithGrowingSequence()
|
||||
}
|
||||
val prefix = dev.backingBuffer.copyOfRange(0, 1 shl 19)
|
||||
val trailing = byteArrayOf(1, 2, 3)
|
||||
val existing = ByteArrayInputStream(prefix + trailing)
|
||||
// Like the service's destination file, the output already holds the prefix.
|
||||
val out = ByteArrayOutputStream().apply { write(prefix) }
|
||||
|
||||
BackupFlow.backupImage(
|
||||
dev, out, existing, prefix.size.toLong(), dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
|
||||
assertArrayEquals(dev.backingBuffer, out.toByteArray())
|
||||
// The service owns both streams: the flow neither closes them nor drains past the
|
||||
// resume offset, so the caller can keep using them.
|
||||
val rest = ByteArray(trailing.size)
|
||||
assertEquals(trailing.size, existing.read(rest))
|
||||
assertArrayEquals(trailing, rest)
|
||||
out.write("still writable".toByteArray())
|
||||
assertArrayEquals(dev.backingBuffer + "still writable".toByteArray(), out.toByteArray())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun formatsTheDigestAsLowercaseHex() = runBlocking {
|
||||
// Known vector: SHA-256("abc"), so the hex formatting is pinned by a constant.
|
||||
val hash = BackupFlow.backupImage(
|
||||
MemoryBufferBlockDeviceDriver(0, 512), ByteArrayOutputStream(),
|
||||
"abc".byteInputStream(), 3, 3, 1 shl 20, {}, scope, {}, { _, _, _, _ -> })
|
||||
assertEquals(
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", hash
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.storage.StorageManager
|
||||
import android.os.storage.StorageVolume
|
||||
import android.provider.DocumentsContract
|
||||
import eu.depau.etchdroid.service.availableBytesFor
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertNull
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.mockito.ArgumentMatchers.any
|
||||
import org.mockito.Mockito.mock
|
||||
import org.mockito.Mockito.`when`
|
||||
import org.robolectric.annotation.Config
|
||||
import tech.apter.junit.jupiter.robolectric.RobolectricExtension
|
||||
|
||||
/**
|
||||
* `availableBytesFor` must not touch `StorageVolume.getStorageUuid()` before API 31, where that
|
||||
* method does not exist in the public SDK (it throws `NoSuchMethodError` on Android 11).
|
||||
* The JUnit 5 Robolectric extension refuses per-method SDK overrides, hence the class-level config.
|
||||
*/
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(sdk = [30], application = EtchDroidApplication::class)
|
||||
class BackupSpacePreSApiTest {
|
||||
@Test
|
||||
fun usesPublicVolumeUuid() {
|
||||
// A valid UUID returned by the public getUuid(): if getStorageUuid() were called it would
|
||||
// raise NoSuchMethodError on API 30 and the result would be null.
|
||||
val volume = mock(StorageVolume::class.java)
|
||||
val storageManager = mockStorageManager(volume)
|
||||
`when`(volume.isPrimary).thenReturn(false)
|
||||
`when`(volume.uuid).thenReturn("41217664-9172-527a-b3d5-f87d3daf3e78")
|
||||
`when`(storageManager.getAllocatableBytes(any())).thenReturn(42L)
|
||||
|
||||
assertEquals(
|
||||
42L,
|
||||
availableBytesFor(
|
||||
mockContext(storageManager), externalStorageUri("41217664-9172-527a-b3d5-f87d3daf3e78:backup.img")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun primaryVolumeIsUnknown() {
|
||||
// The primary volume has no public UUID below API 31: report "unknown" instead of guessing.
|
||||
val volume = mock(StorageVolume::class.java)
|
||||
val storageManager = mockStorageManager(volume)
|
||||
`when`(volume.isPrimary).thenReturn(true)
|
||||
`when`(volume.uuid).thenReturn(null)
|
||||
|
||||
assertNull(
|
||||
availableBytesFor(
|
||||
mockContext(storageManager), externalStorageUri("primary:Download/x.img")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun linkageFailuresAreContained() {
|
||||
val volume = mock(StorageVolume::class.java)
|
||||
val storageManager = mockStorageManager(volume)
|
||||
`when`(volume.isPrimary).thenReturn(false)
|
||||
`when`(volume.uuid).thenReturn("41217664-9172-527a-b3d5-f87d3daf3e78")
|
||||
`when`(storageManager.getAllocatableBytes(any()))
|
||||
.thenThrow(NoSuchMethodError("hidden API blocked"))
|
||||
|
||||
assertNull(
|
||||
availableBytesFor(
|
||||
mockContext(storageManager),
|
||||
externalStorageUri("41217664-9172-527a-b3d5-f87d3daf3e78:backup.img")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun mockStorageManager(volume: StorageVolume): StorageManager {
|
||||
val storageManager = mock(StorageManager::class.java)
|
||||
`when`(storageManager.storageVolumes).thenReturn(listOf(volume))
|
||||
return storageManager
|
||||
}
|
||||
|
||||
private fun mockContext(storageManager: StorageManager): Context {
|
||||
val context = mock(Context::class.java)
|
||||
`when`(context.getSystemService(Context.STORAGE_SERVICE)).thenReturn(storageManager)
|
||||
return context
|
||||
}
|
||||
|
||||
private fun externalStorageUri(documentId: String): Uri =
|
||||
DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", documentId)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import android.provider.DocumentsContract
|
||||
import eu.depau.etchdroid.service.documentVolumeId
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertNull
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.robolectric.annotation.Config
|
||||
import tech.apter.junit.jupiter.robolectric.RobolectricExtension
|
||||
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class BackupSpaceTest {
|
||||
@Test
|
||||
fun externalStorageVolumeIds() {
|
||||
assertEquals(
|
||||
"primary", documentVolumeId(
|
||||
DocumentsContract.buildDocumentUri(
|
||||
"com.android.externalstorage.documents", "primary:Download/x.img"
|
||||
)
|
||||
)
|
||||
)
|
||||
assertEquals(
|
||||
"1234-ABCD", documentVolumeId(
|
||||
DocumentsContract.buildDocumentUri(
|
||||
"com.android.externalstorage.documents", "1234-ABCD:backup.img"
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun otherProvidersAreUnknown() {
|
||||
assertNull(
|
||||
documentVolumeId(
|
||||
DocumentsContract.buildDocumentUri(
|
||||
"com.android.providers.downloads.documents", "42"
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import androidx.core.net.toUri
|
||||
import eu.depau.etchdroid.massstorage.UsbMassStorageDeviceDescriptor
|
||||
import eu.depau.etchdroid.ui.ConfirmOperationActivityState
|
||||
import eu.depau.etchdroid.ui.ConfirmOperationActivityViewModel
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.robolectric.annotation.Config
|
||||
import tech.apter.junit.jupiter.robolectric.RobolectricExtension
|
||||
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class ConfirmOperationActivityViewModelTest {
|
||||
@Test
|
||||
fun initStoresOperation() {
|
||||
val vm = ConfirmOperationActivityViewModel()
|
||||
vm.init("content://test/x".toUri(), UsbMassStorageDeviceDescriptor(), JobOperation.BACKUP)
|
||||
assertEquals(JobOperation.BACKUP, vm.state.value.operation)
|
||||
assertEquals(JobOperation.WRITE, ConfirmOperationActivityState.Empty.operation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package eu.depau.etchdroid
|
||||
|
||||
import androidx.core.net.toUri
|
||||
import eu.depau.etchdroid.massstorage.UsbMassStorageDeviceDescriptor
|
||||
import eu.depau.etchdroid.ui.ConfirmOperationActivityViewModel
|
||||
import eu.depau.etchdroid.ui.JobState
|
||||
import eu.depau.etchdroid.ui.ProgressActivityViewModel
|
||||
import eu.depau.etchdroid.utils.ktexts.safeParcelableExtra
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.BeforeAll
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import org.robolectric.annotation.Config
|
||||
import tech.apter.junit.jupiter.robolectric.RobolectricExtension
|
||||
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class IntentsTest {
|
||||
private val uri = "content://com.android.externalstorage.documents/document/primary%3ADownload%2Fb.img".toUri()
|
||||
private val device = UsbMassStorageDeviceDescriptor()
|
||||
|
||||
@Test
|
||||
fun backupIntentCarriesActionDataAndDevice() {
|
||||
val intent = getStartBackupJobIntent(uri, device, jobId = 42)
|
||||
assertEquals(Intents.START_BACKUP, intent.action)
|
||||
assertEquals(uri, intent.data)
|
||||
assertEquals(42, intent.getIntExtra("jobId", -1))
|
||||
assertEquals(device, intent.safeParcelableExtra<UsbMassStorageDeviceDescriptor>("destDevice"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun finishedBackupStatusCarriesHashAndFlag() {
|
||||
val intent = getFinishedIntent(uri, device, 100, isBackup = true, sha256 = "abc")
|
||||
val status = intent.safeParcelableExtra<JobStatusInfo>("status")!!
|
||||
assertEquals(Intents.FINISHED, intent.action)
|
||||
assertTrue(status.isBackup)
|
||||
assertEquals("abc", status.sha256)
|
||||
assertEquals(100, status.percent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun progressUpdateMarksBackup() {
|
||||
val intent = getProgressUpdateIntent(uri, device, 1, 12f, 50, 100, isBackup = true)
|
||||
assertTrue(intent.safeParcelableExtra<JobStatusInfo>("status")!!.isBackup)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmIntentCarriesOperation() {
|
||||
val intent = getConfirmOperationActivityIntent(uri, device, operation = JobOperation.BACKUP)
|
||||
assertEquals("BACKUP", intent.getStringExtra("operation"))
|
||||
val write = getConfirmOperationActivityIntent(uri, device)
|
||||
assertEquals("WRITE", write.getStringExtra("operation"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun progressStateTracksBackupFields() {
|
||||
val vm = ProgressActivityViewModel()
|
||||
vm.updateFromIntent(getProgressUpdateIntent(uri, device, 1, 1f, 50, 100, isBackup = true))
|
||||
assertTrue(vm.state.value.isBackup)
|
||||
vm.updateFromIntent(getFinishedIntent(uri, device, 100, isBackup = true, sha256 = "abc"))
|
||||
assertEquals(JobState.SUCCESS, vm.state.value.jobState)
|
||||
assertEquals("abc", vm.state.value.sha256)
|
||||
assertTrue(vm.state.value.isBackup)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmViewModelStoresOperation() {
|
||||
val vm = ConfirmOperationActivityViewModel()
|
||||
vm.init(uri, device, JobOperation.BACKUP)
|
||||
assertEquals(JobOperation.BACKUP, vm.state.value.operation)
|
||||
assertEquals(uri, vm.state.value.openedImage)
|
||||
assertEquals(device, vm.state.value.selectedDevice)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
@BeforeAll
|
||||
fun setUp() {
|
||||
setUpMockTelemetry()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
# USB Drive Image Backup Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a "Back up a drive" flow that reads a USB mass storage device (SD card in a card reader) into a raw `.img` file, resumable, with a SHA-256 shown on success.
|
||||
|
||||
**Architecture:** A new `START_BACKUP` job runs in `WorkerService`. It reads the device through the existing `BlockDeviceInputStream`, appends to a SAF document opened in append mode, hashes the already-written prefix on resume, and renames `.part` to `.img` on success. UI reuses the existing device picker, confirmation screen and progress screen behind a new `JobOperation.BACKUP` mode.
|
||||
|
||||
**Tech Stack:** Kotlin, Jetpack Compose, libaums (USB mass storage), SAF (`ACTION_CREATE_DOCUMENT`), JUnit 5 + Robolectric, coroutines.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-17-usb-image-backup-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- minSdk 23, targetSdk/compileSdk 36; Compose UI; FOSS and GPlay flavors must both build.
|
||||
- No root and no `/dev/block`: USB mass storage through libaums only.
|
||||
- Destination is a SAF document; never assume a filesystem path; never seek the output (append only).
|
||||
- FOSS build/test commands: unset or empty `ETCHDROID_ENABLE_SENTRY`.
|
||||
- Do not pass `--scan` to Gradle.
|
||||
- Commit style: Conventional Commits, one logical change per commit; rebase onto `main`, never merge.
|
||||
- Run `./gradlew lint` before finishing.
|
||||
- Existing write/verify behaviour must not change; all existing unit tests must pass.
|
||||
- New user-visible strings go in `app/src/main/res/values/strings.xml` with a `comment` attribute.
|
||||
|
||||
## Review Focus
|
||||
|
||||
- **Output storage fills mid-write** — a provider returning ENOSPC must surface "Could not write the backup file" and leave the partial file resumable, never crash. Test: `BackupFlowTest.wrapsOutputFailures`.
|
||||
- **Destination open fails / grant lost** — the job must fail fatally with a clear message, not an unknown error. Test: `BackupErrorMappingTest`.
|
||||
- **Interrupted backup resumed** — the device must start at the existing file size and the digest must cover the prefix. Test: `BackupFlowTest.resumesFromExistingPrefix`.
|
||||
- **Incomplete file selected for restore** — a `.part` name must trigger the warning dialog. Test: `BackupFileNamesTest` plus the dialog wiring in Task 5.
|
||||
- **Device reports zero blocks / empty document** — the job must finish with the empty-image digest and write nothing. Test: `BackupFlowTest.zeroSizedDeviceWritesNothing`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Job model, intents and progress state
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/Intents.kt`
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/ui/ViewModel.kt`
|
||||
- Create: `app/src/test/java/eu/depau/etchdroid/IntentsTest.kt`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: nothing new.
|
||||
- Produces:
|
||||
```kotlin
|
||||
enum class JobOperation { WRITE, BACKUP } // top-level in Intents.kt
|
||||
|
||||
object Intents { const val START_BACKUP = "eu.depau.etchdroid.action.START_BACKUP"; /* existing */ }
|
||||
|
||||
data class JobStatusInfo(
|
||||
sourceUri: Uri, destDevice: UsbMassStorageDeviceDescriptor,
|
||||
processedBytes: Long, totalBytes: Long, speed: Float = -1f, jobId: Int,
|
||||
isVerifying: Boolean = false, exception: EtchDroidException? = null,
|
||||
isBackup: Boolean = false, sha256: String? = null,
|
||||
)
|
||||
|
||||
fun getStartBackupJobIntent(destinationUri: Uri, sourceDevice: UsbMassStorageDeviceDescriptor,
|
||||
jobId: Int, packageContext: Context? = null, cls: Class<*>? = null): Intent
|
||||
|
||||
fun getConfirmOperationActivityIntent(..., packageContext: Context? = null,
|
||||
cls: Class<*>? = null, operation: JobOperation = JobOperation.WRITE): Intent
|
||||
|
||||
fun getProgressUpdateIntent(..., isVerifying: Boolean = false, packageContext: Context? = null,
|
||||
cls: Class<*>? = null, isBackup: Boolean = false): Intent
|
||||
|
||||
fun getErrorIntent(..., packageContext: Context? = null, cls: Class<*>? = null,
|
||||
isBackup: Boolean = false): Intent
|
||||
|
||||
fun getFinishedIntent(..., packageContext: Context? = null, cls: Class<*>? = null,
|
||||
isBackup: Boolean = false, sha256: String? = null): Intent
|
||||
|
||||
data class ConfirmOperationActivityState(..., val operation: JobOperation = JobOperation.WRITE)
|
||||
fun ConfirmOperationActivityViewModel.init(openedImage: Uri?, selectedDevice: UsbMassStorageDeviceDescriptor?,
|
||||
operation: JobOperation = JobOperation.WRITE)
|
||||
|
||||
data class ProgressActivityState(..., val isBackup: Boolean = false, val sha256: String? = null)
|
||||
```
|
||||
- New extras: `"operation"` on the confirmation intent; keep `"sourceUri"`, `"destDevice"`, `"jobId"`, `"status"`.
|
||||
- `getStartBackupJobIntent`: action `START_BACKUP`, `data = destinationUri`, extra `destDevice = sourceDevice`, extra `jobId`; add `FLAG_GRANT_READ_URI_PERMISSION` and `FLAG_GRANT_WRITE_URI_PERMISSION` when `packageContext.checkCallingOrSelfUriPermission(...)` grants them (mirror the existing write helper).
|
||||
- `ProgressActivityViewModel.updateFromIntent` must copy `status.isBackup` on all three actions, and `status.sha256` on `FINISHED`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Create `IntentsTest.kt` (mirror the annotations of `BlockDeviceStreamTest`):
|
||||
```kotlin
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class IntentsTest {
|
||||
private val uri = "content://com.android.externalstorage.documents/document/primary%3ADownload%2Fb.img".toUri()
|
||||
private val device = UsbMassStorageDeviceDescriptor()
|
||||
|
||||
@Test
|
||||
fun backupIntentCarriesActionDataAndDevice() {
|
||||
val intent = getStartBackupJobIntent(uri, device, jobId = 42)
|
||||
assertEquals(Intents.START_BACKUP, intent.action)
|
||||
assertEquals(uri, intent.data)
|
||||
assertEquals(42, intent.getIntExtra("jobId", -1))
|
||||
assertEquals(device, intent.safeParcelableExtra<UsbMassStorageDeviceDescriptor>("destDevice"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun finishedBackupStatusCarriesHashAndFlag() {
|
||||
val intent = getFinishedIntent(uri, device, 100, isBackup = true, sha256 = "abc")
|
||||
val status = intent.safeParcelableExtra<JobStatusInfo>("status")!!
|
||||
assertEquals(Intents.FINISHED, intent.action)
|
||||
assertTrue(status.isBackup)
|
||||
assertEquals("abc", status.sha256)
|
||||
assertEquals(100, status.percent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun progressUpdateMarksBackup() {
|
||||
val intent = getProgressUpdateIntent(uri, device, 1, 12f, 50, 100, isBackup = true)
|
||||
assertTrue(intent.safeParcelableExtra<JobStatusInfo>("status")!!.isBackup)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmIntentCarriesOperation() {
|
||||
val intent = getConfirmOperationActivityIntent(uri, device, operation = JobOperation.BACKUP)
|
||||
assertEquals("BACKUP", intent.getStringExtra("operation"))
|
||||
val write = getConfirmOperationActivityIntent(uri, device)
|
||||
assertEquals("WRITE", write.getStringExtra("operation"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun progressStateTracksBackupFields() {
|
||||
val vm = ProgressActivityViewModel()
|
||||
vm.updateFromIntent(getProgressUpdateIntent(uri, device, 1, 1f, 50, 100, isBackup = true))
|
||||
assertTrue(vm.state.value.isBackup)
|
||||
vm.updateFromIntent(getFinishedIntent(uri, device, 100, isBackup = true, sha256 = "abc"))
|
||||
assertEquals(JobState.SUCCESS, vm.state.value.jobState)
|
||||
assertEquals("abc", vm.state.value.sha256)
|
||||
assertTrue(vm.state.value.isBackup)
|
||||
}
|
||||
}
|
||||
```
|
||||
Add a `confirmViewModelStoresOperation` test for `ConfirmOperationActivityViewModel.init(uri, device, JobOperation.BACKUP)`.
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.IntentsTest"`
|
||||
Expected: compilation failure (`START_BACKUP`, `isBackup`, `JobOperation`, etc. unresolved).
|
||||
|
||||
- [ ] **Step 3: Implement the model, intent helpers and state fields**
|
||||
|
||||
Add the enum and constants, extend `JobStatusInfo` at the end of its parameter list (existing call sites stay valid), add the new helpers/parameters exactly as in the Interfaces block, and store the operation extra as `operation.name` on the confirmation intent. In `updateFromIntent`, add `isBackup = status.isBackup` to all three `_state.update` branches and `sha256 = status.sha256` to `FINISHED`.
|
||||
|
||||
- [ ] **Step 4: Run the tests to verify they pass**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.IntentsTest"`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/Intents.kt app/src/main/java/eu/depau/etchdroid/ui/ViewModel.kt app/src/test/java/eu/depau/etchdroid/IntentsTest.kt
|
||||
git commit -m "feat(intents): add backup job plumbing"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: File-name helpers, free-space helpers and backup exceptions
|
||||
|
||||
**Files:**
|
||||
- Create: `app/src/main/java/eu/depau/etchdroid/utils/BackupFileNames.kt`
|
||||
- Create: `app/src/main/java/eu/depau/etchdroid/service/BackupSpace.kt`
|
||||
- Create: `app/src/main/java/eu/depau/etchdroid/utils/exception/NotEnoughSpaceForBackupException.kt`
|
||||
- Create: `app/src/main/java/eu/depau/etchdroid/utils/exception/CouldNotWriteBackupException.kt`
|
||||
- Modify: `app/src/main/res/values/strings.xml`
|
||||
- Create: `app/src/test/java/eu/depau/etchdroid/BackupFileNamesTest.kt`
|
||||
- Create: `app/src/test/java/eu/depau/etchdroid/BackupSpaceTest.kt`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: nothing.
|
||||
- Produces:
|
||||
```kotlin
|
||||
const val BACKUP_PART_SUFFIX = ".part"
|
||||
fun String.isIncompleteBackupName(): Boolean // case-insensitive .part suffix
|
||||
fun String.withoutPartSuffix(): String // drops .part, otherwise unchanged
|
||||
fun suggestedBackupFileName(deviceName: String, now: Date = Date()): String
|
||||
// e.g. "backup-card-reader-usb-3-0-19700101-0000.img.part" (UTC, fixed clock in tests)
|
||||
|
||||
fun documentVolumeId(uri: Uri): String? // "primary" / "1234-ABCD" / null
|
||||
fun availableBytesFor(context: Context, uri: Uri): Long? // best effort, null when unknown
|
||||
|
||||
@Parcelize class NotEnoughSpaceForBackupException(val requiredBytes: Long, val availableBytes: Long)
|
||||
@Parcelize class CouldNotWriteBackupException(override val message: String, override val cause: Throwable?)
|
||||
```
|
||||
- `suggestedBackupFileName`: lowercase `deviceName`, replace runs of non-`[a-z0-9]` with `-`, trim `-`, truncate to 24 chars, fall back to `usb-drive`; timestamp `SimpleDateFormat("yyyyMMdd-HHmm", Locale.US)` with `TimeZone.getTimeZone("UTC")`; result `backup-<name>-<stamp>.img.part`.
|
||||
- `documentVolumeId`: return null unless `uri.authority == "com.android.externalstorage.documents"`; take `DocumentsContract.getDocumentId(uri)` and return `substringBefore(':')` when non-empty.
|
||||
- `availableBytesFor`: null below API 26 or when the volume cannot be resolved; otherwise `StorageManager.getAllocatableBytes(volume.storageUuid)`, matching `volume.isPrimary` for `"primary"` and `volume.uuid` otherwise; swallow exceptions and return null.
|
||||
- Strings: `not_enough_space_for_backup` = "Not enough space: the backup needs %1$s but only %2$s is available"; `could_not_write_backup_file` = "Could not write the backup file. Check that there is enough free space and try again."
|
||||
- Both exceptions are `FatalException` subclasses whose `getUiMessage` returns the matching string.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
`BackupFileNamesTest`:
|
||||
```kotlin
|
||||
@Test fun detectsPartSuffixCaseInsensitively() {
|
||||
assertTrue("backup.img.part".isIncompleteBackupName())
|
||||
assertTrue("BACKUP.IMG.PART".isIncompleteBackupName())
|
||||
assertFalse("backup.img".isIncompleteBackupName())
|
||||
}
|
||||
@Test fun stripsOnlyThePartSuffix() {
|
||||
assertEquals("backup.img", "backup.img.part".withoutPartSuffix())
|
||||
assertEquals("backup.img", "backup.img".withoutPartSuffix())
|
||||
}
|
||||
@Test fun suggestsSanitizedTimestampedName() {
|
||||
assertEquals("backup-card-reader-usb-3-0-19700101-0000.img.part",
|
||||
suggestedBackupFileName("Card Reader / USB 3.0", Date(0)))
|
||||
assertEquals("backup-usb-drive-19700101-0000.img.part",
|
||||
suggestedBackupFileName("///", Date(0)))
|
||||
}
|
||||
```
|
||||
`BackupSpaceTest`:
|
||||
```kotlin
|
||||
@Test fun externalStorageVolumeIds() {
|
||||
assertEquals("primary", documentVolumeId(
|
||||
DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", "primary:Download/x.img")))
|
||||
assertEquals("1234-ABCD", documentVolumeId(
|
||||
DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", "1234-ABCD:backup.img")))
|
||||
}
|
||||
@Test fun otherProvidersAreUnknown() {
|
||||
assertNull(documentVolumeId(
|
||||
DocumentsContract.buildDocumentUri("com.android.providers.downloads.documents", "42")))
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the tests to verify they fail**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.BackupFileNamesTest" --tests "eu.depau.etchdroid.BackupSpaceTest"`
|
||||
Expected: compilation failure (helpers missing).
|
||||
|
||||
- [ ] **Step 3: Implement the helpers, exceptions and strings**
|
||||
|
||||
No I/O in the name helpers. `BackupNameTest` needs no Robolectric; `BackupSpaceTest` needs Robolectric for `DocumentsContract`/`Uri` (`@ExtendWith(RobolectricExtension::class)` + `@Config(application = EtchDroidApplication::class)`).
|
||||
|
||||
- [ ] **Step 4: Run the tests to verify they pass**
|
||||
|
||||
Run the same command as Step 2.
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/utils/BackupFileNames.kt app/src/main/java/eu/depau/etchdroid/service/BackupSpace.kt app/src/main/java/eu/depau/etchdroid/utils/exception/NotEnoughSpaceForBackupException.kt app/src/main/java/eu/depau/etchdroid/utils/exception/CouldNotWriteBackupException.kt app/src/main/res/values/strings.xml app/src/test/java/eu/depau/etchdroid/BackupFileNamesTest.kt app/src/test/java/eu/depau/etchdroid/BackupSpaceTest.kt
|
||||
git commit -m "feat(backup): add file naming, space and error helpers"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Stream the block device into the destination
|
||||
|
||||
**Files:**
|
||||
- Create: `app/src/main/java/eu/depau/etchdroid/service/BackupFlow.kt`
|
||||
- Create: `app/src/test/java/eu/depau/etchdroid/BackupFlowTest.kt`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `BlockDeviceInputStream`, `timeoutWatchdog`, `CouldNotWriteBackupException`.
|
||||
- Produces:
|
||||
```kotlin
|
||||
object BackupFlow {
|
||||
suspend fun backupImage(
|
||||
blockDev: BlockDeviceDriver,
|
||||
output: OutputStream,
|
||||
existing: InputStream?, // destination bytes 0..resumeOffset, or null/empty
|
||||
resumeOffset: Long, // == bytes to hash from existing; device start position
|
||||
deviceSize: Long,
|
||||
bufferSize: Long,
|
||||
notifyCurrentOffset: (offset: Long) -> Unit,
|
||||
coroScope: CoroutineScope,
|
||||
grabWakeLock: () -> Unit,
|
||||
sendProgressUpdate: (lastReadBytes: Int, processedBytes: Long, totalBytes: Long,
|
||||
isVerifying: Boolean) -> Unit,
|
||||
): String // lowercase hex SHA-256 of the whole file
|
||||
}
|
||||
```
|
||||
- Behaviour:
|
||||
- `MessageDigest.getInstance("SHA-256")`.
|
||||
- If `resumeOffset > 0`: read exactly `resumeOffset` bytes from `existing` in `bufferSize` chunks, update the digest, report progress with `processedBytes` growing from 0 to `resumeOffset`, `isVerifying = false`, and `grabWakeLock()` per chunk. EOF before `resumeOffset` → `CouldNotWriteBackupException`.
|
||||
- `BlockDeviceInputStream(blockDev, coroScope, BUFFER_BLOCKS / QUEUE_SIZE, QUEUE_SIZE)`, `seekAsync(resumeOffset)`, then loop from `resumeOffset` to `deviceSize`: read up to `bufferSize` bytes, update the digest, `output.write(...)`, `output.flush()`, `notifyCurrentOffset`, `sendProgressUpdate`. Wrap `output.*` exceptions and prefix-read exceptions in `CouldNotWriteBackupException`; let device-read exceptions propagate.
|
||||
- `timeoutWatchdog(IO_TIMEOUT)` around the loop with `watchdog.bump()` before/after each device read and write.
|
||||
- `finally { src.closeAsync() }`; do not close `output` or `existing` (the service owns them).
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```kotlin
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class BackupFlowTest {
|
||||
private val scope = CoroutineScope(Dispatchers.IO)
|
||||
private fun sha256(bytes: ByteArray): String =
|
||||
MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
|
||||
private fun MemoryBufferBlockDeviceDriver.sizeBytes() = blocks * blockSize
|
||||
|
||||
@Test fun copiesWholeDeviceAndHashesIt() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(4L * 1024 * 1024, 512).apply { fillWithGrowingSequence() }
|
||||
val out = ByteArrayOutputStream()
|
||||
val hash = BackupFlow.backupImage(dev, out, null, 0, dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
assertArrayEquals(dev.backingBuffer, out.toByteArray())
|
||||
assertEquals(sha256(dev.backingBuffer), hash)
|
||||
}
|
||||
|
||||
@Test fun resumesFromExistingPrefix() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(4L * 1024 * 1024, 512).apply { fillWithGrowingSequence() }
|
||||
val prefix = dev.backingBuffer.copyOfRange(0, 1 shl 20)
|
||||
val out = ByteArrayOutputStream().apply { write(prefix) }
|
||||
val hash = BackupFlow.backupImage(dev, out, prefix.inputStream(), prefix.size.toLong(),
|
||||
dev.sizeBytes(), 1 shl 20, {}, scope, {}, { _, _, _, _ -> })
|
||||
assertArrayEquals(dev.backingBuffer, out.toByteArray())
|
||||
assertEquals(sha256(dev.backingBuffer), hash)
|
||||
}
|
||||
|
||||
@Test fun wrapsOutputFailures() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(1L * 1024 * 1024, 512).apply { fillWithGrowingSequence() }
|
||||
val failing = object : OutputStream() {
|
||||
var written = 0
|
||||
override fun write(b: Int) { if (++written > 4096) throw IOException("ENOSPC") }
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {
|
||||
if (written + len > 4096) throw IOException("ENOSPC")
|
||||
written += len
|
||||
}
|
||||
}
|
||||
assertThrows<CouldNotWriteBackupException> {
|
||||
BackupFlow.backupImage(dev, failing, null, 0, dev.sizeBytes(), 1 shl 20,
|
||||
{}, scope, {}, { _, _, _, _ -> })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun zeroSizedDeviceWritesNothing() = runBlocking {
|
||||
val dev = MemoryBufferBlockDeviceDriver(0, 512)
|
||||
val out = ByteArrayOutputStream()
|
||||
val hash = BackupFlow.backupImage(dev, out, null, 0, 0, 1 shl 20, {}, scope, {}, { _, _, _, _ -> })
|
||||
assertEquals(0, out.size())
|
||||
assertEquals(sha256(ByteArray(0)), hash)
|
||||
}
|
||||
}
|
||||
```
|
||||
Add helper `private fun MemoryBufferBlockDeviceDriver.sizeBytes() = blocks * blockSize` in the test file, and an `assertThrows` from `org.junit.jupiter.api`.
|
||||
|
||||
- [ ] **Step 2: Run the tests to verify they fail**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.BackupFlowTest"`
|
||||
Expected: compilation failure (`BackupFlow` missing).
|
||||
|
||||
- [ ] **Step 3: Implement `BackupFlow.backupImage`**
|
||||
|
||||
Keep it in a new file; reuse `BUFFER_BLOCKS`, `QUEUE_SIZE`, `IO_TIMEOUT` from `service`. Use `io.github.oshai`-free logging (`android.util.Log`) or none. Report the prefix phase through the same `sendProgressUpdate` callback so the progress watchdog never sees silence.
|
||||
|
||||
- [ ] **Step 4: Run the tests to verify they pass**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.BackupFlowTest"`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/service/BackupFlow.kt app/src/test/java/eu/depau/etchdroid/BackupFlowTest.kt
|
||||
git commit -m "feat(backup): stream a block device to an output stream"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Run backup jobs in `WorkerService`
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/service/WorkerService.kt`
|
||||
- Modify: `app/src/main/res/values/strings.xml`
|
||||
- Create: `app/src/test/java/eu/depau/etchdroid/BackupErrorMappingTest.kt`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `START_BACKUP`, `JobOperation`, `getStartBackupJobIntent` (Task 1); `BackupFlow`, `BackupSpace`, exceptions, name helpers (Tasks 2–3).
|
||||
- Produces:
|
||||
- `private var mOperation = JobOperation.WRITE`
|
||||
- `private suspend fun runBackup(blockDev: BlockDeviceDriver, devSize: Long, coroScope: CoroutineScope): String`
|
||||
- `private fun renameToFinalName(uri: Uri)`
|
||||
- Strings to add: `notification_backup_progress_title` ("Backing up…"), `notification_backup_progress_content` ("%1$s to %2$s", device then file), `notification_backup_no_notifications_text`, `notification_backup_tap_for_progress_text`, `backup_finished` ("Backup finished"), `backup_success_notif_content_text` ("%1$s backed up to %2$s"), `backup_failed` ("Backup failed").
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```kotlin
|
||||
@ExtendWith(RobolectricExtension::class)
|
||||
@Config(application = EtchDroidApplication::class)
|
||||
class BackupErrorMappingTest {
|
||||
@Test fun backupExceptionsPassThroughUnwrapped() {
|
||||
val write = CouldNotWriteBackupException("boom", IOException("ENOSPC"))
|
||||
assertSame(write, WorkerServiceFlowImpl.toJobException(write))
|
||||
val space = NotEnoughSpaceForBackupException(10, 5)
|
||||
assertSame(space, WorkerServiceFlowImpl.toJobException(space))
|
||||
}
|
||||
@Test fun deviceErrorsStillMapToUsbCommunication() {
|
||||
val mapped = WorkerServiceFlowImpl.toJobException(PipeException())
|
||||
assertTrue(mapped is UsbCommunicationException)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.BackupErrorMappingTest"`
|
||||
Expected: compilation failure until Task 2's exception classes exist; then PASS. This test pins that the new fatal exceptions are not re-wrapped.
|
||||
|
||||
- [ ] **Step 3: Implement the service branch**
|
||||
|
||||
In `onStartCommand`:
|
||||
- Accept `START_JOB` and `START_BACKUP`; otherwise stop as today. Set `mOperation`.
|
||||
- Set telemetry tag `job.type` to `backup` or `write`.
|
||||
- Skip `offset`/`verifyOnly` parsing for backup (defaults 0/false).
|
||||
- Add `isBackup = mOperation == JobOperation.BACKUP` to every telemetry/config scope place.
|
||||
|
||||
In the job coroutine, after device init and `devSize`:
|
||||
- `if (mOperation == JobOperation.BACKUP) { ... } else { existing write/verify block }`.
|
||||
- Backup branch:
|
||||
- `imageSize = devSize` so error broadcasts report a sane total.
|
||||
- Best-effort space check: `val existingSize = try { mSourceUri.getFileSize(this@WorkerService) } catch (_: Exception) { null }`; `val available = availableBytesFor(this@WorkerService, mSourceUri)`; only when both are non-null and `available < devSize - existingSize`, throw `NotEnoughSpaceForBackupException(devSize - existingSize, available)`. When the size cannot be queried, skip the pre-check rather than risk failing a resumable job.
|
||||
- Broadcast the first progress intent with `processedBytes = 0L`, `totalBytes = devSize`, `speed = 0f`, `isBackup = true` (the prefix-hash phase advances it to the resume offset, so the bar never moves backwards).
|
||||
- `val sha256 = runBackup(blockDev, devSize, coroScope)`.
|
||||
- `getFinishedIntent(mSourceUri, mDestDevice, devSize, isBackup = true, sha256 = sha256).broadcastLocallySync(this)`.
|
||||
- `runBackup`:
|
||||
- `val pfd = contentResolver.openFileDescriptor(mSourceUri, "wa") ?: throw CouldNotWriteBackupException("open failed", null)`.
|
||||
- `val offset = pfd.statSize`; if `< 0` throw `CouldNotWriteBackupException("unknown size", null)`.
|
||||
- `val existing = if (offset > 0) contentResolver.openInputStream(mSourceUri) else null`.
|
||||
- `val out = BufferedOutputStream(ParcelFileDescriptor.AutoCloseOutputStream(pfd), 1 shl 20)`.
|
||||
- call `BackupFlow.backupImage(blockDev, out, existing, offset, devSize, BUFFER_BLOCKS * blockDev.blockSize, ...)`; `out.flush()`; `pfd.fileDescriptor.sync()`; close in `finally` (`out.close()`, `existing?.close()`).
|
||||
- Catch `SecurityException`/`FileNotFoundException` from open and rethrow as `CouldNotWriteBackupException`.
|
||||
- `renameToFinalName(mSourceUri)`: if `getDisplayName()?.isIncompleteBackupName() == true`, call `DocumentsContract.renameDocument(contentResolver, uri, getDisplayName()!!.withoutPartSuffix())` inside try/catch; ignore null result and failures. Rename after the data is synced and before the `FINISHED` broadcast. Do not replace `mSourceUri` with the renamed URI.
|
||||
- Progress/error/finished notifications: use backup titles/content when `status.isBackup` or `mOperation == BACKUP`; the foreground notification uses the backup strings. Pass `isBackup` to `getProgressUpdateIntent`/`getErrorIntent`/`getFinishedIntent`.
|
||||
- `sendProgressUpdate` passes `isBackup = mOperation == JobOperation.BACKUP`.
|
||||
|
||||
- [ ] **Step 4: Run tests and build**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.BackupErrorMappingTest" --tests "eu.depau.etchdroid.WorkerServiceFlowTest"` and `./gradlew assembleFossDebug`.
|
||||
Expected: PASS and BUILD SUCCESSFUL.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/service/WorkerService.kt app/src/main/res/values/strings.xml app/src/test/java/eu/depau/etchdroid/BackupErrorMappingTest.kt
|
||||
git commit -m "feat(service): run backup jobs in the worker service"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: "Back up a drive" entry point and restore warning
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/ui/MainActivity.kt`
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/ui/ViewModel.kt`
|
||||
- Modify: `app/src/main/res/values/strings.xml`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `JobOperation`, `getConfirmOperationActivityIntent(..., operation)` (Task 1); `suggestedBackupFileName`, `isIncompleteBackupName` (Task 2).
|
||||
- Produces:
|
||||
- `MainActivityState.backupDevicePickerOpen: Boolean = false`, `pendingBackupDevice: UsbMassStorageDeviceDescriptor? = null`, `showIncompleteBackupAlertForUri: Uri? = null` with setters `setBackupDevicePickerOpen`, `setPendingBackupDevice`, `setIncompleteBackupAlertUri`.
|
||||
- `launchConfirmationActivity(device, uri, operation: JobOperation = WRITE)`.
|
||||
- Compose `IncompleteBackupAlertDialog(onDismissRequest, onConfirm)`.
|
||||
- Strings: `backup_a_drive` ("Back up a drive"), `incomplete_backup_title` ("Incomplete backup"), `incomplete_backup_message` ("This file looks like an unfinished backup. Restoring it may write only part of a drive.").
|
||||
|
||||
- [ ] **Step 1: Implement the state and dialog**
|
||||
|
||||
Add the three state fields/setters. Add the dialog modeled on `WindowsImageAlertDialog` with `continue_anyway` and `cancel`. In `openUri`, before the Windows check, when `filename?.isIncompleteBackupName() == true` and `!userSaysYolo`, call `setIncompleteBackupAlertUri(uri)` and return; the dialog's confirm calls `openUri(uri, true)`, cancel clears the state.
|
||||
|
||||
- [ ] **Step 2: Implement the entry point**
|
||||
|
||||
- `StartViewLayout`: add a `secondaryButton: @Composable () -> Unit` slot; in `normal`, put `mainButton()` and `secondaryButton()` in a nested `Column(verticalArrangement = Arrangement.spacedBy(16.dp))`; in `compact`, add `secondaryButton()` after `mainButton()`.
|
||||
- `StartView` gains `onBackupCTAClick: () -> Unit`; renders an `OutlinedButton` labeled `R.string.backup_a_drive` with `modifier = Modifier.appiumTag("backupDriveCTA")` and icon `Icons.TwoTone.Archive`.
|
||||
- `MainActivity`: `private val mCreateDocumentLauncher = registerForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri -> onBackupDestinationPicked(uri) }`.
|
||||
- Backup CTA: `setBackupDevicePickerOpen(true)`.
|
||||
- Show `UsbDevicePickerBottomSheet` when `openedImage != null || backupDevicePickerOpen`; on select, cast `it as UsbMassStorageDeviceDescriptor`. If backup mode: `setPendingBackupDevice(device); setBackupDevicePickerOpen(false); mCreateDocumentLauncher.launch(suggestedBackupFileName(device.name))`, else the existing write path. The backup flow always shows the picker, even with a single device.
|
||||
- `onBackupDestinationPicked(uri: Uri?)`: `uri ?: return`; `val device = pendingBackupDevice ?: return`; `try { contentResolver.takePersistableUriPermission(uri, FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION) } catch (_: Exception) {}`; `launchConfirmationActivity(device, uri, JobOperation.BACKUP)`; clear `pendingBackupDevice`.
|
||||
- `launchConfirmationActivity` passes `operation` to `getConfirmOperationActivityIntent`.
|
||||
- Telemetry: add a breadcrumb for the backup CTA and destination pick, matching existing style.
|
||||
|
||||
- [ ] **Step 3: Build and check previews**
|
||||
|
||||
Run: `./gradlew assembleFossDebug`
|
||||
Expected: BUILD SUCCESSFUL. Open `StartViewPreview` in the IDE preview; both buttons render.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/ui/MainActivity.kt app/src/main/java/eu/depau/etchdroid/ui/ViewModel.kt app/src/main/res/values/strings.xml
|
||||
git commit -m "feat(ui): add the back up a drive entry point and part-file warning"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Backup mode on the confirmation screen
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/ui/ConfirmOperationActivity.kt`
|
||||
- Modify: `app/src/main/res/values/strings.xml`
|
||||
- Create: `app/src/test/java/eu/depau/etchdroid/ConfirmOperationActivityViewModelTest.kt`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `JobOperation`, `getStartBackupJobIntent`, state `operation` (Task 1), `withoutPartSuffix` (Task 2).
|
||||
- Produces: `ConfirmOperationActivity` reads `"operation"` (`JobOperation.valueOf(getStringExtra("operation") ?: "WRITE")`), passes it to `mViewModel.init(...)`, and starts `getStartBackupJobIntent` with the initial `getProgressUpdateIntent(..., isBackup = true)` for backup.
|
||||
- Strings: `back_up_usb_drive` ("Back up USB drive"), `source_usb_device` ("Source USB device"), `destination_file` ("Destination file"), `backup_warning` ("Keep the reader connected. The backup is as large as the card and may take a long time."), `start_backup` ("Start backup").
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```kotlin
|
||||
@Test fun initStoresOperation() {
|
||||
val vm = ConfirmOperationActivityViewModel()
|
||||
vm.init("content://test/x".toUri(), UsbMassStorageDeviceDescriptor(), JobOperation.BACKUP)
|
||||
assertEquals(JobOperation.BACKUP, vm.state.value.operation)
|
||||
assertEquals(JobOperation.WRITE, ConfirmOperationActivityState.Empty.operation)
|
||||
}
|
||||
```
|
||||
(Needs Robolectric for `Uri`; use the standard annotations.)
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.ConfirmOperationActivityViewModelTest"`
|
||||
Expected: compilation failure until `init`/`operation` land (Task 1); if Task 1 already added them, the test passes — keep it.
|
||||
|
||||
- [ ] **Step 3: Implement the UI branch**
|
||||
|
||||
- Parse the extra in `onCreate`; if invalid, fall back to `WRITE`. Treat the existing `openedImage` field as "the job URI" (source image for write, destination file for backup); when the destination is inaccessible in backup mode, toast `R.string.could_not_write_backup_file` instead of `could_not_open_the_source_file`.
|
||||
- `ConfirmationView`: in backup mode:
|
||||
- title `back_up_usb_drive`;
|
||||
- source card shows the device (name, vidpid) and the "Grant access" button (so the permission control lives next to the source);
|
||||
- destination card shows the picked file's display name (strip `.part` for display) under `destination_file`, with the image icon;
|
||||
- warning card uses `be_careful` + `backup_warning`;
|
||||
- confirm button text `start_backup` and the tag `writeImageButton` stays.
|
||||
In write mode, render exactly what exists today.
|
||||
- On confirm, after the lay-flat sheet: call `startJob()` which branches:
|
||||
```kotlin
|
||||
if (operation == BACKUP) getStartBackupJobIntent(uri, device, jobId, this, WorkerService::class.java)
|
||||
else getStartJobIntent(uri, device, jobId, 0, false, this, WorkerService::class.java)
|
||||
```
|
||||
and starts the progress activity with
|
||||
`getProgressUpdateIntent(uri, device, jobId, 0f, 0, 0, false, this, ProgressActivity::class.java, isBackup = operation == BACKUP)`.
|
||||
- Keep the telemetry tags (`usb.*`, `image.filename`); for backup, tag the output filename and add `job.type=backup`.
|
||||
|
||||
- [ ] **Step 4: Run tests and build**
|
||||
|
||||
Run: `./gradlew testFossDebugUnitTest --tests "eu.depau.etchdroid.ConfirmOperationActivityViewModelTest"` and `./gradlew assembleFossDebug`.
|
||||
Expected: PASS, BUILD SUCCESSFUL.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/ui/ConfirmOperationActivity.kt app/src/main/res/values/strings.xml app/src/test/java/eu/depau/etchdroid/ConfirmOperationActivityViewModelTest.kt
|
||||
git commit -m "feat(ui): add backup mode to the confirmation screen"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Backup progress, success checksum and resume
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/src/main/java/eu/depau/etchdroid/ui/ProgressActivity.kt`
|
||||
- Modify: `app/src/main/res/values/strings.xml`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ProgressActivityState.isBackup`/`sha256` (Task 1), `getStartBackupJobIntent` (Task 1), `withoutPartSuffix` (Task 2).
|
||||
- Produces:
|
||||
- `AutoJobRestarter(..., isBackup: Boolean = false)`; when true, starts `getStartBackupJobIntent(imageUri, msd, jobId, activity, WorkerService::class.java)` (no offset, `isVerifying = false`).
|
||||
- `SuccessView(state: ProgressActivityState)`.
|
||||
- Strings: `backup_progress_title` ("Backing up drive"), `backup_copying` ("Backing up"), `backup_progress_summary` ("%1$s / %2$s copied, %3$s/s"), `backup_complete` ("Backup complete!"), `sha256_checksum` ("SHA-256"), `back_up_another_drive` ("Back up another drive").
|
||||
|
||||
- [ ] **Step 1: Implement the progress screen**
|
||||
|
||||
- `JobInProgressView`: title `backup_progress_title` when `isBackup`; progress row text `backup_copying` + device name, then `to` + destination file name; size line uses `backup_progress_summary` when backup; hide the "Skip verification" button for backup; graphic direction uses `uiState.isVerifying || uiState.isBackup`, magnifier only for `isVerifying`.
|
||||
- Call site: `SuccessView(appState)`.
|
||||
- `SuccessView(state)`: title `backup_complete` for backup; keep the Lottie; in `bottomCard`, when `isBackup`, add a `Card` above the existing one showing:
|
||||
- the destination name: `state.sourceUri?.getDisplayName(context)?.withoutPartSuffix() ?: stringResource(R.string.unknown_filename)`;
|
||||
- `state.totalBytes.toHRSize()`;
|
||||
- when `state.sha256 != null`, `stringResource(R.string.sha256_checksum)` with `SelectionContainer { Text(state.sha256) }`.
|
||||
The back button label is `back_up_another_drive` for backup; keep review/donate buttons.
|
||||
- `AutoJobRestarter` call gains `isBackup = uiState.isBackup`.
|
||||
|
||||
- [ ] **Step 2: Build**
|
||||
|
||||
Run: `./gradlew assembleFossDebug`
|
||||
Expected: BUILD SUCCESSFUL.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add app/src/main/java/eu/depau/etchdroid/ui/ProgressActivity.kt app/src/main/res/values/strings.xml
|
||||
git commit -m "feat(ui): show backup progress and checksum"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Verification
|
||||
|
||||
**Files:** none expected.
|
||||
|
||||
- [ ] **Step 1: Run all unit tests**
|
||||
|
||||
Run: `env -u ETCHDROID_ENABLE_SENTRY ./gradlew testFossDebugUnitTest`
|
||||
Expected: PASS (including the pre-existing `WorkerServiceFlowTest`, `BlockDeviceStreamTest`, `EnvironmentalFaultTest`, `UriQueryTest`).
|
||||
|
||||
- [ ] **Step 2: Build both flavors**
|
||||
|
||||
Run: `env -u ETCHDROID_ENABLE_SENTRY ./gradlew assembleFossDebug`
|
||||
Run: `cp misc/mock-google-services.json app/google-services.json && ETCHDROID_ENABLE_SENTRY=true ./gradlew assembleGplayDebug`
|
||||
Expected: BUILD SUCCESSFUL for both.
|
||||
|
||||
- [ ] **Step 3: Lint**
|
||||
|
||||
Run: `./gradlew lint`
|
||||
Expected: BUILD SUCCESSFUL (record any pre-existing warnings; do not introduce new errors).
|
||||
|
||||
- [ ] **Step 4: Manual smoke test on a device**
|
||||
|
||||
1. `./gradlew installFossDebug` (FOSS flavor, Sentry unset).
|
||||
2. Plug in a USB card reader with a card; tap "Back up a drive"; pick the drive; save `backup-….img.part`.
|
||||
3. Confirm the progress screen shows "Backing up drive", the size grows, and the notification updates. Let it finish.
|
||||
4. Verify the success screen shows the SHA-256; compare the file with `sha256sum` on a PC.
|
||||
5. Unplug mid-job on a second run: the reconnect dialog appears; reconnect; the job resumes from the same percentage instead of 0.
|
||||
6. Restore the image with the normal write flow.
|
||||
7. Select an incomplete `.part` file in the write flow: the warning dialog appears; Cancel returns to the picker, Continue proceeds.
|
||||
|
||||
- [ ] **Step 5: Report and commit any fixes**
|
||||
|
||||
Fix anything the smoke test surfaces as separate, atomic commits (`fix(...)`), then re-run the relevant test task.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review Notes
|
||||
|
||||
- Spec coverage: entry point (Task 5), confirmation (Task 6), intents/state (Task 1), service and resume (Task 4), flow/hash (Task 3), grants and rename (Tasks 4–5), `.part` safety (Tasks 2, 5), errors/free space (Tasks 2–4), progress/success (Task 7), tests (Tasks 1–4, 8).
|
||||
- Chunk size and buffer tuning are left to the builder as the spec allows; the default is `BUFFER_BLOCKS * blockDev.blockSize`.
|
||||
- All new functions referenced by later tasks are defined in an earlier task's Interfaces block.
|
||||
@@ -0,0 +1,312 @@
|
||||
# USB drive image backup — design
|
||||
|
||||
Date: 2026-11-17
|
||||
Status: draft
|
||||
|
||||
## Intent
|
||||
|
||||
EtchDroid can write a raw image to a USB mass storage device. This adds the
|
||||
mirror operation: read a whole device (typically an SD card in a USB card
|
||||
reader) into a raw `.img` file, for archiving a stock card before modifying it.
|
||||
The motivating case is a 64 GB card from an AliExpress retro game console: a
|
||||
byte-exact image that can be restored later with the existing write flow.
|
||||
|
||||
## Goals
|
||||
|
||||
- Choose a USB mass storage device as the **source**, choose a destination file
|
||||
through the system file picker (SAF), and stream every block of the device
|
||||
into that file.
|
||||
- Reuse the existing progress screen, notifications, foreground service,
|
||||
wakelock and error handling.
|
||||
- Compute SHA-256 over the finished image and show it on the success screen.
|
||||
- The produced file is a plain raw image; restoring it needs no changes to the
|
||||
write flow.
|
||||
- A USB hiccup mid-job can resume after reconnecting, instead of starting over.
|
||||
- Interrupted jobs leave an obviously incomplete file, so it cannot be mistaken
|
||||
for a good backup.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- The phone's internal SD slot, eMMC, or any block device that needs root.
|
||||
EtchDroid only speaks USB mass storage.
|
||||
- Bad-sector tolerance (`dd conv=noerror,sync`), retries on media errors, or
|
||||
partial recovery. A SCSI read error aborts the job.
|
||||
- Compression, split files, sparse/trimmed images, or incremental backups.
|
||||
- Direct card-to-card cloning, USB hubs, or a second USB device as destination.
|
||||
- A user-facing cancel button. Like the write flow, a job ends by completing,
|
||||
failing, or the service being destroyed.
|
||||
- Changes to the write/verify flow beyond a warning for `.part` files.
|
||||
|
||||
## Constraints
|
||||
|
||||
- USB Mass Storage (SCSI transparent command set over bulk transfers) only,
|
||||
via libaums. No root, no `/dev/block`.
|
||||
- Destination is a SAF document (`ACTION_CREATE_DOCUMENT`); the app cannot
|
||||
assume a filesystem path, and some providers are not local storage.
|
||||
- A full image is as large as the device (64 GB for the motivating card). The
|
||||
user confirmed 91 GB free on the destination.
|
||||
- Free-space queries for an arbitrary SAF URI are not reliable. A best-effort
|
||||
check is possible on API 26+ when the document belongs to a local storage
|
||||
volume; otherwise space exhaustion is reported when the write fails.
|
||||
- USB 2.0 OTG reads are roughly 20–40 MB/s, so a 64 GB backup takes tens of
|
||||
minutes. The existing foreground service, progress notification and wakelock
|
||||
are required.
|
||||
- SAF append mode (`"wa"`) is the only universally supported way to extend an
|
||||
existing document; random-access writes are not guaranteed. The design never
|
||||
seeks the output.
|
||||
- minSdk 23, targetSdk 36, Compose UI, FOSS and GPlay flavors.
|
||||
|
||||
## Approaches considered
|
||||
|
||||
**A. Raw image to a SAF file, streamed from the device (chosen).** The read
|
||||
path already exists for verification (`BlockDeviceInputStream`), and the
|
||||
service already has progress, notifications, wakelock and teardown. Output is
|
||||
restorable with the current write flow. Costs one new UI flow, a service
|
||||
branch and tests. Needs device-sized free space.
|
||||
|
||||
**B. Compressed image (gzip/zstd) written on the fly.** Saves space on mostly
|
||||
empty cards, but ROMs on these cards are usually already compressed, so the
|
||||
gain is unpredictable; restore would also need decompression support in the
|
||||
write path, and CPU cost adds a new bottleneck. Rejected for v1.
|
||||
|
||||
**C. Back up to a second USB drive through a hub.** Avoids phone storage but
|
||||
requires extra hardware and more plumbing (two device connections, a second
|
||||
target picker). Rejected.
|
||||
|
||||
Doing it on a PC with `dd` or GNOME Disks remains the cheaper option for a
|
||||
one-off card; the app feature is for doing it phone-only and repeatably.
|
||||
|
||||
## Design
|
||||
|
||||
### Entry point and flow
|
||||
|
||||
1. The start screen gains a second action, "Back up a drive", below the
|
||||
existing "Write an image" CTA.
|
||||
2. Tapping it opens the existing USB device picker bottom sheet. The picker is
|
||||
read-only for this flow: selecting a device does not touch it yet.
|
||||
3. After a device is selected, launch
|
||||
`ActivityResultContracts.CreateDocument("application/octet-stream")` with a
|
||||
suggested name such as
|
||||
`backup-card-reader-20261117-1530.img.part` (device name sanitized;
|
||||
`usb-drive` when empty). The `.part` suffix marks the file as incomplete
|
||||
until the job succeeds. Cancelling returns to the start screen.
|
||||
4. On picker result, take a persistable write grant for the destination (see
|
||||
"URI permissions"), then open the confirmation screen in backup mode with
|
||||
the source device and the destination URI.
|
||||
5. On confirm, the confirmation screen takes the USB permission, shows the
|
||||
existing lay-flat sheet (the reader must stay connected for the whole job),
|
||||
then starts the backup job and opens the progress screen.
|
||||
|
||||
### Confirmation screen
|
||||
|
||||
Reuse `ConfirmOperationActivity` with a new `"operation"` string extra
|
||||
(`write` default, `backup`). In backup mode:
|
||||
|
||||
- Title: "Back up USB drive".
|
||||
- Source card: the selected device. Destination card: the chosen file name.
|
||||
- Warning: the reader must stay connected, the image is the size of the card,
|
||||
and the job may take a long time.
|
||||
- Confirm button: "Start backup".
|
||||
- USB permission, device-detach handling, and theme setup are unchanged.
|
||||
|
||||
### URI permissions
|
||||
|
||||
`MainActivity` takes persistable read and write grants on the CreateDocument
|
||||
result (read is needed for the resume-time prefix hash and the success card's
|
||||
file size), mirroring the existing read-grant handling in `openUri`, and never
|
||||
releases them (the system evicts the oldest grants past its cap, as the
|
||||
existing comment notes). This keeps the destination usable after the
|
||||
confirmation activity finishes, when the task is swiped away, and when the
|
||||
progress screen is reopened from the result notification or a retry.
|
||||
|
||||
Some providers do not support persistable grants; that is caught and ignored.
|
||||
The temporary grant plus `FLAG_GRANT_WRITE_URI_PERMISSION` on the intents still
|
||||
covers the running job. A retry that can no longer open the URI fails with the
|
||||
same "could not write the file" error.
|
||||
|
||||
### Intents and state
|
||||
|
||||
- New `Intents.START_BACKUP` action and
|
||||
`getStartBackupJobIntent(destinationUri, sourceDevice, jobId)`:
|
||||
`data` is the destination URI, with
|
||||
`FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION` when the
|
||||
activity holds them; extras: `destDevice`, `jobId`. There is no offset
|
||||
extra: the resume point is derived from the destination file (see "Resume").
|
||||
- `getConfirmOperationActivityIntent` gains the `operation` extra.
|
||||
- `JobStatusInfo` gains `isBackup: Boolean = false` and `sha256: String? = null`.
|
||||
`getFinishedIntent` gains `isBackup` and `sha256` parameters, defaulted so
|
||||
existing call sites are unchanged.
|
||||
- `ProgressActivityState` gains `isBackup` and `sha256`; progress titles use
|
||||
backup strings, and the success card shows "Backup complete", the file size
|
||||
and a selectable SHA-256.
|
||||
|
||||
### Worker service
|
||||
|
||||
`WorkerService.onStartCommand` accepts `START_BACKUP` in addition to
|
||||
`START_JOB`. Shared setup (single-job guard, job id, telemetry scope,
|
||||
foreground notification, error broadcast, device teardown, wakelock) stays in
|
||||
one place; only the job body branches.
|
||||
|
||||
Backup body:
|
||||
|
||||
1. Build and initialize the mass storage device; pick LUN 0, or the only LUN
|
||||
with media (same rule as the write flow today).
|
||||
2. `devSize = blocks * blockSize`; this is the progress total.
|
||||
3. Best-effort free-space check (API 26+, local storage volume only). Check
|
||||
against `devSize - existingFileSize` when resuming. If it can prove space is
|
||||
insufficient, fail before writing with a clear "not enough space" error.
|
||||
Otherwise continue and rely on the write failure being mapped.
|
||||
4. Open the destination for append (`"wa"`), and query the current document
|
||||
size. That size is the resume offset; a fresh document is 0 bytes.
|
||||
5. Recompute the running SHA-256 for the existing prefix by reading the
|
||||
destination from 0 to the resume offset. This is a local read and is fast
|
||||
relative to the USB transfer; it only happens on a resumed job.
|
||||
6. Read the device with `BlockDeviceInputStream`, seeked to the resume offset,
|
||||
using the same buffer/prefetch settings as `verifyImage`, in chunks (target
|
||||
1 MiB). For each chunk: wakelock, update the digest, append to the output,
|
||||
flush, notify progress. The existing `timeoutWatchdog(IO_TIMEOUT)` guards
|
||||
USB stalls.
|
||||
7. Flush, `fd.sync()`, close the file descriptor.
|
||||
8. Rename the document to drop the `.part` suffix (best-effort; use the URI
|
||||
returned by `DocumentsContract.renameDocument` when non-null). Then
|
||||
broadcast `FINISHED` with `isBackup = true` and the hex digest.
|
||||
|
||||
### Resume
|
||||
|
||||
A restarted backup resumes instead of restarting from zero. Because writes
|
||||
always append in file order, the destination file is always a valid prefix of
|
||||
the device, at every length. The service therefore trusts the file size rather
|
||||
than any offset carried in an intent:
|
||||
|
||||
- Fresh job: the new document is empty, so it starts at 0.
|
||||
- After a USB error and reconnect: `AutoJobRestarter` starts the same backup
|
||||
intent for the same URI and device; the service sees a non-empty document,
|
||||
seeks the device there, re-hashes the prefix, and continues.
|
||||
- After a fatal error (for example the destination ran out of space or could not
|
||||
be written), the error screen offers "Resume backup" for backups. It starts
|
||||
the same backup intent for the same URI and device, so the service appends to
|
||||
the existing document and continues as above. The write-only "Try again"
|
||||
action is unchanged.
|
||||
- If the document has grown past what a previous run meant to write, the extra
|
||||
bytes are still device bytes in order, so continuing from the actual end is
|
||||
correct.
|
||||
|
||||
Resume does not cover process death or force-stop in v1: the only way to create
|
||||
a destination is the `ACTION_CREATE_DOCUMENT` picker, which always creates a
|
||||
new document, and there is no way to choose an existing document as the resume
|
||||
target. A `.part` file left behind by a killed process can therefore not be
|
||||
continued from the app; it stays on disk as an incomplete file.
|
||||
|
||||
`AutoJobRestarter` gains an `isBackup` mode that calls
|
||||
`getStartBackupJobIntent`; its `resumeOffset` is ignored (the service derives
|
||||
it), and `isVerifying` is always false for backup.
|
||||
|
||||
### Output file safety
|
||||
|
||||
- The suggested name ends in `.part`. On success it is renamed to drop the
|
||||
suffix. If the provider refuses the rename, the success screen shows the
|
||||
actual current name, so nothing is hidden from the user.
|
||||
- A failed or interrupted job leaves the `.part` file in place; it is the
|
||||
resume target when the app can continue it, and an incomplete file otherwise.
|
||||
It is never deleted automatically.
|
||||
- The restore flow gains a guard: if the user opens a file whose name ends in
|
||||
`.part`, show a warning dialog ("this looks like an incomplete backup;
|
||||
restoring it may write only part of the card") with continue/cancel, modeled
|
||||
on the existing Windows-image warning. Nothing else in the write flow
|
||||
changes.
|
||||
|
||||
### Failure behaviour
|
||||
|
||||
- USB errors map through the existing `toJobException`; recoverable ones drive
|
||||
the reconnect dialog and the resume path above.
|
||||
- `ENOSPC` maps to a "not enough space" error; a lost URI permission or a
|
||||
failed open maps to a clear "could not write the file" error.
|
||||
- `SKIP_VERIFY` is ignored; there is no verify pass. The digest already covers
|
||||
the whole file.
|
||||
- The partial `.part` file is kept, as described above.
|
||||
|
||||
### Telemetry
|
||||
|
||||
Same scope as the write job, with a `job.type = backup` tag, the output
|
||||
filename, the device name/vidpid, and the resume offset when non-zero. No file
|
||||
contents or paths beyond the existing conventions.
|
||||
|
||||
### Restore
|
||||
|
||||
Unchanged apart from the `.part` warning. The backup file is a normal raw
|
||||
image; the write flow checks the device is at least as large as the image
|
||||
(equal is accepted), writes it, and verifies as usual. A restore of a
|
||||
full-card image takes about twice as long as the backup because of the verify
|
||||
pass; that is existing behaviour.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit (`WorkerServiceFlowImpl`): back up a `MemoryBufferBlockDeviceDriver`
|
||||
filled with a deterministic pattern into a `ByteArrayOutputStream`; assert
|
||||
exact bytes, SHA-256, progress totals, and that the stream closes. Test error
|
||||
propagation when the driver throws (partial output present and complete
|
||||
prefix), and resuming from a non-empty output stream with the digest still
|
||||
covering the whole file.
|
||||
- Unit: cancellation (coroutine cancellation) leaves a valid prefix and the
|
||||
stream closed.
|
||||
- Robolectric: intent builders set the right action, data, extras and flags;
|
||||
`JobStatusInfo.percent` and defaults remain compatible.
|
||||
- Existing write/verify, stream and service tests must keep passing.
|
||||
- Manual/e2e: the Appium suite can be extended later; not part of this change.
|
||||
|
||||
## Files expected to change
|
||||
|
||||
- `app/src/main/java/eu/depau/etchdroid/Intents.kt`
|
||||
- `app/src/main/java/eu/depau/etchdroid/service/WorkerService.kt`
|
||||
- `app/src/main/java/eu/depau/etchdroid/ui/MainActivity.kt`
|
||||
- `app/src/main/java/eu/depau/etchdroid/ui/ViewModel.kt`
|
||||
- `app/src/main/java/eu/depau/etchdroid/ui/ConfirmOperationActivity.kt`
|
||||
- `app/src/main/java/eu/depau/etchdroid/ui/ProgressActivity.kt`
|
||||
- `app/src/main/java/eu/depau/etchdroid/ui/Notifications*` / notification helpers
|
||||
- `app/src/main/res/values/strings.xml`
|
||||
- new unit test file(s)
|
||||
|
||||
## UX sketch
|
||||
|
||||
```
|
||||
Start screen Device picker Save dialog Confirm
|
||||
[ Write an image ] Select USB device backup-card-…img.part Back up USB drive
|
||||
[ Back up a drive ] (card reader) [Save] [Cancel] card reader → file
|
||||
[Cancel] [Start backup]
|
||||
|
||||
Progress: Backing up… 12.4 GB of 59.6 GB • 18.2 MB/s
|
||||
Done: Backup complete
|
||||
backup-card-reader-20261117-1530.img
|
||||
SHA-256: 9f2c… (selectable)
|
||||
```
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- Exact chunk size and buffer tuning (measure on the 64 GB card).
|
||||
- Hashing/formatting details and device-name sanitization rules.
|
||||
- Whether the free-space check is worth its complexity on the providers the
|
||||
user actually picks.
|
||||
- Test file organization.
|
||||
- Whether the read-back-to-hash prefix should report progress through the
|
||||
normal progress channel or stay silent.
|
||||
|
||||
## Risks
|
||||
|
||||
- A long job is battery- and thermally heavy; the wakelock is renewed while
|
||||
progress updates flow, as in the write job.
|
||||
- Some cheap card readers are flaky (existing reconnect/timeout handling
|
||||
applies); a disconnect mid-backup is resumable, but the reader must be
|
||||
reconnected for the job to continue.
|
||||
- If SAF writes are slower than USB reads on some devices, the transfer is
|
||||
limited by storage; buffers may need tuning. Internal storage is normally
|
||||
much faster than USB 2.0.
|
||||
- A provider that does not support append or rename degrades: no resume
|
||||
(append is still supported per SAF, but a provider that ignores it can
|
||||
corrupt), and the `.part` name stays. `"wa"` is part of the SAF contract, so
|
||||
this is a theoretical concern.
|
||||
- Resuming assumes the same medium is still in the reader. If the user swaps the
|
||||
card between a failed attempt and a resume, the append splices two different
|
||||
cards into one image that is presented as a complete backup. libaums does not
|
||||
expose a medium identity that could be checked, so v1 documents this
|
||||
limitation instead of enforcing it. Resuming right after the error, without
|
||||
unplugging the card, is the intended flow.
|
||||
Reference in new issue
Block a user