2
0
mirror of https://github.com/FWGS/xash3d-fwgs synced 2025-01-23 00:42:05 +01:00

android: FileCopyWorker: implement simple progress tracking

This commit is contained in:
Alibek Omarov 2024-11-20 10:36:24 +03:00
parent 9e9a9847fc
commit cd3cc7e696

View File

@ -19,20 +19,58 @@ const val KEY_FILE_URI = "KEY_FILE_URI"
class FileCopyWorker(ctx: Context, params: WorkerParameters) : CoroutineWorker(ctx, params) {
companion object {
const val Input = "Input"
const val Progress = "Progress"
}
private var fileCount = 0
private var fileCopied = 0
override suspend fun doWork(): Result {
withContext(Dispatchers.IO) {
val fileUri = inputData.getString(KEY_FILE_URI)
setProgress(workDataOf(Input to fileUri))
val target = DocumentFile.fromFile(applicationContext.getExternalFilesDir(null)!!)
val source = DocumentFile.fromTreeUri(applicationContext, Uri.parse(fileUri))
val uri = Uri.parse(fileUri)
val source = DocumentFile.fromTreeUri(applicationContext, uri)
source?.copyDirTo(applicationContext, target) ?: return@withContext Result.failure()
fileCount = source?.countDirFiles() ?: return@withContext Result.failure()
setProgress(workDataOf(Progress to 0f))
val gamedir = source.name!!
val externalFilesDir = DocumentFile.fromFile(applicationContext.getExternalFilesDir(null)!!)
// create a directory to store staged files
val target = externalFilesDir.createDirectory(".$gamedir")!!
source.copyDirTo(applicationContext, this@FileCopyWorker, target)
target.renameTo(gamedir)
}
return Result.success()
}
suspend fun fileCopied(count: Int) {
if(count == 0)
return
fileCopied += count
val percentage: Float = fileCopied.toFloat() / fileCount.toFloat();
setProgress(workDataOf(Progress to percentage))
}
}
fun DocumentFile.countDirFiles(): Int {
var count: Int = 0
listFiles().forEach {
if (it.isDirectory)
count += it.countDirFiles()
else
count++
}
return count
}
fun DocumentFile.copyFileTo(ctx: Context, file: DocumentFile) {
@ -45,14 +83,18 @@ fun DocumentFile.copyFileTo(ctx: Context, file: DocumentFile) {
}
}
fun DocumentFile.copyDirTo(ctx: Context, dir: DocumentFile) {
val outDir = dir.createDirectory(name!!)!!
suspend fun DocumentFile.copyDirTo(ctx: Context, worker: FileCopyWorker, dir: DocumentFile) {
var count: Int = 0
listFiles().forEach {
if (it.isDirectory) {
it.copyDirTo(ctx, outDir)
val outDir = dir.createDirectory(it.name!!)!!
it.copyDirTo(ctx, worker, outDir)
} else {
it.copyFileTo(ctx, outDir)
it.copyFileTo(ctx, dir)
count++
}
}
}
worker.fileCopied(count)
}