|
1 | 1 | package com.fredapp.wbooks.ui.library |
2 | 2 |
|
3 | 3 | import android.content.Intent |
| 4 | +import android.os.SystemClock |
4 | 5 | import android.speech.RecognizerIntent |
5 | 6 | import androidx.activity.compose.BackHandler |
6 | 7 | import androidx.activity.compose.rememberLauncherForActivityResult |
@@ -257,15 +258,28 @@ fun WatchGutenbergScreen(onBack: () -> Unit, onLibraryChanged: () -> Unit) { |
257 | 258 | dest.outputStream().use { output -> |
258 | 259 | val buffer = ByteArray(DEFAULT_BUFFER_SIZE) |
259 | 260 | var copied = 0L |
| 261 | + var lastProgressBytes = 0L |
| 262 | + var lastProgressMs = SystemClock.elapsedRealtime() |
260 | 263 | while (true) { |
261 | 264 | val read = source.read(buffer) |
262 | 265 | if (read < 0) break |
263 | 266 | output.write(buffer, 0, read) |
264 | 267 | 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 | + } |
267 | 278 | } |
268 | 279 | } |
| 280 | + withContext(Dispatchers.Main) { |
| 281 | + downloadProgressBytes = copied |
| 282 | + } |
269 | 283 | val expectedBytes = totalBytes.takeIf { it > 0L } ?: book.sizeBytes |
270 | 284 | if (expectedBytes != null && copied < expectedBytes) { |
271 | 285 | error("Download stopped after ${formatBytes(copied)} of ${formatBytes(expectedBytes)}") |
@@ -534,7 +548,18 @@ private fun GutenbergBookChip( |
534 | 548 | progressTotal: Long, |
535 | 549 | onAdd: () -> Unit, |
536 | 550 | ) { |
| 551 | + val progress = if (progressTotal > 0L) (progressBytes.toFloat() / progressTotal).coerceIn(0f, 1f) else 0f |
537 | 552 | Chip( |
| 553 | + icon = if (adding) { |
| 554 | + { |
| 555 | + CircularProgressIndicator( |
| 556 | + progress = progress, |
| 557 | + modifier = Modifier.size(24.dp), |
| 558 | + ) |
| 559 | + } |
| 560 | + } else { |
| 561 | + null |
| 562 | + }, |
538 | 563 | label = { |
539 | 564 | Text( |
540 | 565 | book.title, |
@@ -613,3 +638,5 @@ private fun buildSearchIntent(): Intent = Intent(RecognizerIntent.ACTION_RECOGNI |
613 | 638 | } |
614 | 639 |
|
615 | 640 | 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