Skip to content

Commit 3ff0f91

Browse files
committed
Show watch Gutenberg download progress inline
1 parent 4f0e459 commit 3ff0f91

1 file changed

Lines changed: 29 additions & 2 deletions

File tree

app/src/main/kotlin/com/fredapp/wbooks/ui/library/WatchGutenbergScreen.kt

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.fredapp.wbooks.ui.library
22

33
import android.content.Intent
4+
import android.os.SystemClock
45
import android.speech.RecognizerIntent
56
import androidx.activity.compose.BackHandler
67
import androidx.activity.compose.rememberLauncherForActivityResult
@@ -257,15 +258,28 @@ fun WatchGutenbergScreen(onBack: () -> Unit, onLibraryChanged: () -> Unit) {
257258
dest.outputStream().use { output ->
258259
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
259260
var copied = 0L
261+
var lastProgressBytes = 0L
262+
var lastProgressMs = SystemClock.elapsedRealtime()
260263
while (true) {
261264
val read = source.read(buffer)
262265
if (read < 0) break
263266
output.write(buffer, 0, read)
264267
copied += read
265-
withContext(Dispatchers.Main) {
266-
downloadProgressBytes = copied
268+
val now = SystemClock.elapsedRealtime()
269+
if (
270+
copied - lastProgressBytes >= DOWNLOAD_PROGRESS_STEP_BYTES ||
271+
now - lastProgressMs >= DOWNLOAD_PROGRESS_STEP_MS
272+
) {
273+
lastProgressBytes = copied
274+
lastProgressMs = now
275+
withContext(Dispatchers.Main) {
276+
downloadProgressBytes = copied
277+
}
267278
}
268279
}
280+
withContext(Dispatchers.Main) {
281+
downloadProgressBytes = copied
282+
}
269283
val expectedBytes = totalBytes.takeIf { it > 0L } ?: book.sizeBytes
270284
if (expectedBytes != null && copied < expectedBytes) {
271285
error("Download stopped after ${formatBytes(copied)} of ${formatBytes(expectedBytes)}")
@@ -534,7 +548,18 @@ private fun GutenbergBookChip(
534548
progressTotal: Long,
535549
onAdd: () -> Unit,
536550
) {
551+
val progress = if (progressTotal > 0L) (progressBytes.toFloat() / progressTotal).coerceIn(0f, 1f) else 0f
537552
Chip(
553+
icon = if (adding) {
554+
{
555+
CircularProgressIndicator(
556+
progress = progress,
557+
modifier = Modifier.size(24.dp),
558+
)
559+
}
560+
} else {
561+
null
562+
},
538563
label = {
539564
Text(
540565
book.title,
@@ -613,3 +638,5 @@ private fun buildSearchIntent(): Intent = Intent(RecognizerIntent.ACTION_RECOGNI
613638
}
614639

615640
private const val MAX_LIST_ITEMS = 150
641+
private const val DOWNLOAD_PROGRESS_STEP_BYTES = 256L * 1024L
642+
private const val DOWNLOAD_PROGRESS_STEP_MS = 250L

0 commit comments

Comments
 (0)