diff --git a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java index 6bb620eb0..efcc830fb 100644 --- a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java +++ b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java @@ -19,7 +19,8 @@ * speed(bytes/s), * detail, error } * POST /api/kiwix/jobs/:id/cancel -> { ok:true } - * phase is one of: queued|downloading|indexing|processing|done|error|canceled. + * POST /api/kiwix/jobs/:id/pause|resume -> { ok:true } (ADFA-4893) + * phase is one of: queued|downloading|indexing|processing|paused|done|error|canceled. * ============================================================================ */ package org.iiab.controller.content; @@ -51,11 +52,19 @@ public interface Listener { void onLog(String line); // free-form detail line (for logs) void onDone(); // success (terminal) void onError(String message); // failure (terminal) + /** ADFA-4893: 'paused' phase (best-effort). Default no-op so existing implementers compile unchanged. */ + default void onPaused(int percent) {} + /** ADFA-4893: server is reconnecting (attempt n of total) after a network drop; keeps polling. */ + default void onReconnecting(int attempt, int total) {} } private static final String BASE = BoxEndpoints.API + "/kiwix"; private static final long POLL_MS = 1000L; private static final int MAX_POLL_ERRORS = 10; // tolerate ~10s of transient network blips + // ADFA-4893: the START (download) POST is before any server job exists, so the server's own + // reconnect can't cover a still-warming box; give the kickoff a few quick tries before failing. + private static final int START_TRIES = 3; + private static final long START_RETRY_MS = 2000L; private final Handler main = new Handler(Looper.getMainLooper()); private Listener listener; @@ -70,15 +79,25 @@ public interface Listener { public void addZim(@NonNull String zimFilename, @NonNull Listener l) { this.listener = l; AppExecutors.get().io().execute(() -> { - try { - JSONObject body = new JSONObject().put("ids", new JSONArray().put(zimFilename)); - JSONObject resp = httpJson("POST", BASE + "/download", body); - String id = resp.optString("id", ""); - if (id.isEmpty()) { fail("content service did not start the job"); return; } - jobId = id; - main.postDelayed(pollTask, POLL_MS); - } catch (Exception e) { - fail("couldn't reach the content service"); + final JSONObject body; + try { body = new JSONObject().put("ids", new JSONArray().put(zimFilename)); } + catch (Exception e) { fail("couldn't build the request"); return; } + // ADFA-4893: retry ONLY the kickoff POST (connectivity blip / server still warming) a few + // times. An empty id is a server refusal, not a blip, so it fails without retrying. Once the + // job exists, the server owns reconnection (visible), not this loop. + for (int attempt = 1; !finished; attempt++) { + try { + JSONObject resp = httpJson("POST", BASE + "/download", body); + String id = resp.optString("id", ""); + if (id.isEmpty()) { fail("content service did not start the job"); return; } + jobId = id; + main.postDelayed(pollTask, POLL_MS); + return; + } catch (Exception e) { + if (attempt >= START_TRIES) { fail("couldn't reach the content service"); return; } + try { Thread.sleep(START_RETRY_MS); } + catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } + } } }); } @@ -93,12 +112,17 @@ private void pollOnce() { long speed = j.optLong("speed", 0L); String detail = j.isNull("detail") ? null : j.optString("detail", null); String error = j.isNull("error") ? null : j.optString("error", null); + int retryAttempt = j.optInt("retryAttempt", 0); // ADFA-4893: reconnect state (0 when not retrying) + int retryTotal = j.optInt("retryTotal", 0); if (detail != null && !detail.isEmpty()) deliver(() -> listener.onLog(detail)); switch (phase) { case "downloading": - if (percent >= 0) { + if (retryAttempt > 0) { + final int a = retryAttempt, t = retryTotal; + deliver(() -> listener.onReconnecting(a, t)); + } else if (percent >= 0) { final int p = percent; final String rate = formatRate(speed); deliver(() -> listener.onProgress(p, rate)); } @@ -116,6 +140,12 @@ private void pollOnce() { case "canceled": fail("canceled"); return; + case "paused": { + // ADFA-4893: not terminal — surface it and keep polling so resume/progress is seen. + final int pp = percent; + deliver(() -> listener.onPaused(pp)); + break; + } default: break; // queued / unknown: keep polling } @@ -128,6 +158,7 @@ private void pollOnce() { /** Best-effort cancel of the in-flight job. */ public void cancel() { + finished = true; // ADFA-4893: also stops the START retry loop if a cancel lands mid-kickoff final String id = jobId; if (id != null && !id.isEmpty()) { AppExecutors.get().io().execute(() -> { @@ -137,6 +168,26 @@ public void cancel() { teardown(); } + /** ADFA-4893: best-effort pause of the in-flight job. Keeps polling so 'paused' is observed and resume works. */ + public void pause() { + final String id = jobId; + if (id != null && !id.isEmpty()) { + AppExecutors.get().io().execute(() -> { + try { httpJson("POST", BASE + "/jobs/" + id + "/pause", null); } catch (Exception ignore) { /* best effort */ } + }); + } + } + + /** ADFA-4893: best-effort resume of a paused job; polling continues, so progress flows again. */ + public void resume() { + final String id = jobId; + if (id != null && !id.isEmpty()) { + AppExecutors.get().io().execute(() -> { + try { httpJson("POST", BASE + "/jobs/" + id + "/resume", null); } catch (Exception ignore) { /* best effort */ } + }); + } + } + private void done() { if (finished) return; finished = true; diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java index 4b5801dfc..d36cb20e5 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java @@ -605,13 +605,13 @@ private void render() { zimSession, ZimDownloadService.status(), ZimDownloadService.DONE, ZimDownloadService.FAILED, zimSession && ZimDownloadService.isComplete(), content.banked(ContentType.ZIM), - ZimDownloadService.speed())); + ZimDownloadService.speed(), zimOverallPercent())); if (booksShown) (booksSession ? started : waiting).add( streamRow(getString(R.string.k2go_gm_books_title), "books", booksSession, BooksDownloadService.status(), BooksDownloadService.DONE, BooksDownloadService.FAILED, booksSession && BooksDownloadService.isComplete(), content.banked(ContentType.BOOKS), - 0L)); + 0L, -1)); // ADFA-4893: Books has no per-item size yet -> no determinate bar // ADFA-4954. Statuses come from an observable snapshot rather than static arrays, so the // ordinals are mapped to the checklist's PENDING=0 / doneVal / failedVal convention here. if (kolibriShown) (kolibriState.hasSession() ? started : waiting).add( @@ -619,7 +619,7 @@ private void render() { kolibriState.hasSession(), kolibriState.statusOrdinals(), KolibriSeedState.Status.DONE.ordinal(), KolibriSeedState.Status.FAILED.ordinal(), kolibriState.hasSession() && kolibriState.isComplete(), kolibriBanked, - kolibriState.speedBytesPerSec())); + kolibriState.speedBytesPerSec(), -1)); // ADFA-4893: Kolibri keeps its indicator for (View v : started) sections.addView(v); for (View v : waiting) sections.addView(v); @@ -894,7 +894,7 @@ private String rateSuffix(long bytesPerSec) { } private View streamRow(String heading, String key, boolean sess, int[] status, int doneVal, int failedVal, - boolean complete, int wishlistCount, long bytesPerSec) { + boolean complete, int wishlistCount, long bytesPerSec, int barPercent) { int n = sess && status != null ? status.length : wishlistCount; int done = 0, failed = 0; if (sess && status != null) for (int st : status) { if (st == doneVal) done++; else if (st == failedVal) failed++; } @@ -959,6 +959,7 @@ private View streamRow(String heading, String key, boolean sess, int[] status, i sub.setText(state); sub.setTextColor(ContextCompat.getColor(this, (sess && failed > 0) ? R.color.k2go_amber_text : R.color.k2go_muted)); col.addView(sub); + addRowProgressBar(col, barPercent, sess && !complete); // ADFA-4893: determinate bar for REST streams (ZIM) row.addView(col, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)); ImageView chev = new ImageView(this); @@ -981,12 +982,18 @@ private View streamRow(String heading, String key, boolean sess, int[] status, i * it). Only shown while the module is running and has a task table (percent >= 0); otherwise the * row keeps its indeterminate indicator. Lifted off the card's bottom edge with a small margin. */ private void addRowProgressBar(LinearLayout col, ModuleQueueState mq, boolean running) { - if (!(running && mq.percent >= 0)) return; + addRowProgressBar(col, mq.percent, running); // ADFA-5228 (proot rows) + } + + /** ADFA-4893: same determinate row bar driven by a plain percent, for REST streams (ZIM). Hidden + * when not running or percent < 0, so a paused/indeterminate stream keeps its indicator. */ + private void addRowProgressBar(LinearLayout col, int percent, boolean running) { + if (!(running && percent >= 0)) return; com.google.android.material.progressindicator.LinearProgressIndicator bar = new com.google.android.material.progressindicator.LinearProgressIndicator(this); bar.setIndeterminate(false); bar.setMax(100); - bar.setProgressCompat(mq.percent, true); + bar.setProgressCompat(percent, true); LinearLayout.LayoutParams barLp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); barLp.topMargin = px(8); @@ -994,6 +1001,14 @@ private void addRowProgressBar(LinearLayout col, ModuleQueueState mq, boolean ru col.addView(bar, barLp); } + /** ADFA-4893: the ZIM index row bar shares one formula with the status screen — see + * {@link ZimDownloadService#overallPercent()}. Here we only gate visibility: -1 (no bar) unless a + * job is actively running, so a terminal/failed row falls back to its indicator. */ + private int zimOverallPercent() { + return (ZimDownloadService.isRunning() && !ZimDownloadService.isComplete()) + ? ZimDownloadService.overallPercent() : -1; + } + private View mapsRow() { ModuleQueueState mq = ModuleQueueRepository.get().current(); boolean done = mapsStartFailed || (mapsInSession() && mq.phase == ModuleQueueState.Phase.DONE); diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java index ea606dca7..5304e9573 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java @@ -41,6 +41,8 @@ public final class ZimDownloadService extends Service { public static final String ACTION_START = "org.iiab.controller.ZIM_DOWNLOAD_START"; public static final String ACTION_RETRY = "org.iiab.controller.ZIM_DOWNLOAD_RETRY"; public static final String ACTION_CANCEL = "org.iiab.controller.ZIM_DOWNLOAD_CANCEL"; + public static final String ACTION_PAUSE = "org.iiab.controller.ZIM_DOWNLOAD_PAUSE"; // ADFA-4893 + public static final String ACTION_RESUME = "org.iiab.controller.ZIM_DOWNLOAD_RESUME"; // ADFA-4893 public static final String EXTRA_FILES = "files"; public static final String EXTRA_LABELS = "labels"; public static final String EXTRA_BYTES = "bytes"; @@ -59,9 +61,15 @@ public interface Listener { void onUpdate(); } private static int sPercent = 0; private static long sSpeed = 0; private static volatile long sLastProgressAt = 0L; // ADFA-5146: last-progress heartbeat (elapsedRealtime) + private static volatile boolean sPaused = false; // ADFA-4893: active job paused on the server (session-level) + private static volatile int sReconnectAttempt = 0; // ADFA-4893: >0 while the server reconnects (n of total) + private static volatile int sReconnectTotal = 0; private static Listener sListener; public static boolean isRunning() { return sRunning; } + public static boolean isPaused() { return sPaused; } + public static int reconnectAttempt() { return sReconnectAttempt; } + public static int reconnectTotal() { return sReconnectTotal; } public static boolean hasSession() { return sFiles.length > 0; } /** All items are terminal (done/failed) and nothing is in flight. */ public static boolean isComplete() { @@ -86,17 +94,49 @@ public static boolean isActiveNow() { public static long speed() { return sSpeed; } public static void setListener(Listener l) { sListener = l; } + /** ADFA-4893: byte-weighted overall percent across the session (0-100). The single source both the + * status-screen bar (ZimPreparingFragment) and the index row bar (SetupProgressActivity) read, so + * the two can never drift. Active item contributes its live percent; done/failed count in full. */ + public static int overallPercent() { + long total = 0, done = 0; + for (int i = 0; i < sBytes.length && i < sStatus.length; i++) { + total += sBytes[i]; + if (sStatus[i] == DONE || sStatus[i] == FAILED) done += sBytes[i]; + else if (i == sIndex && (sStatus[i] == ACTIVE || sStatus[i] == INDEXING) && sPercent >= 0) + done += sBytes[i] * sPercent / 100; + } + return total > 0 ? (int) Math.min(100, done * 100 / total) : (isComplete() ? 100 : 0); + } + public static void start(Context ctx, String[] files, String[] labels, long[] bytes) { Intent i = new Intent(ctx, ZimDownloadService.class).setAction(ACTION_START) .putExtra(EXTRA_FILES, files).putExtra(EXTRA_LABELS, labels).putExtra(EXTRA_BYTES, bytes); ContextCompat.startForegroundService(ctx, i); } - /** Re-queue a failed item; resume processing if the session had already stopped. */ - public static void retry(Context ctx, int i) { - if (i < 0 || i >= sStatus.length) return; - sStatus[i] = PENDING; - if (!sRunning) { + /** ADFA-4893: pause the active job (the server keeps the partial). No-op if nothing is running. */ + public static void pause(Context ctx) { + if (!sRunning) return; + ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_PAUSE)); + } + + /** ADFA-4893: resume a paused job; polling/progress continues from the partial. */ + public static void resume(Context ctx) { + ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_RESUME)); + } + + /** ADFA-4893: true when any item is FAILED (so the status screen can offer a single Retry). */ + public static boolean hasFailed() { + for (int st : sStatus) if (st == FAILED) return true; + return false; + } + + /** ADFA-4893: re-queue ALL failed items and resume the session — the status-screen Retry (the + * Pause button morphs into it), so a failed run doesn't fall back to a separate per-item control. */ + public static void retryFailed(Context ctx) { + boolean any = false; + for (int i = 0; i < sStatus.length; i++) if (sStatus[i] == FAILED) { sStatus[i] = PENDING; any = true; } + if (any && !sRunning) { ContextCompat.startForegroundService(ctx, new Intent(ctx, ZimDownloadService.class).setAction(ACTION_RETRY)); } } @@ -104,15 +144,12 @@ public static void retry(Context ctx, int i) { /** Clear the session so a new selection can start fresh. */ public static void finishSession() { sFiles = new String[0]; sLabels = new String[0]; sBytes = new long[0]; sStatus = new int[0]; - sIndex = 0; sPercent = 0; sSpeed = 0; sRunning = false; sLastProgressAt = 0L; + sIndex = 0; sPercent = 0; sSpeed = 0; sRunning = false; sPaused = false; + sReconnectAttempt = 0; sReconnectTotal = 0; sLastProgressAt = 0L; } - private static final int MAX_ATTEMPTS = 3; // total tries per ZIM before marking it failed - private static final long RETRY_DELAY_MS = 4000L; - private final Handler main = new Handler(Looper.getMainLooper()); private RestContentClient client; - private int attempts = 0; // attempts for the ZIM currently in flight @Override public void onCreate() { super.onCreate(); createNotificationChannel(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @@ -123,12 +160,28 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (ACTION_CANCEL.equals(action)) { if (client != null) client.cancel(); - sRunning = false; + sRunning = false; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0; publish(); main.post(() -> { stopForeground(true); stopSelf(); }); return START_NOT_STICKY; } + // ADFA-4893: pause/resume the active job. Handled BEFORE the sRunning guard (the session is + // still "running" while paused). The queue never advances during a pause because the paused + // job never reaches onDone/onError, so processNext() isn't called. + if (ACTION_PAUSE.equals(action)) { + if (client != null) client.pause(); + sPaused = true; + publish(); + return START_NOT_STICKY; + } + if (ACTION_RESUME.equals(action)) { + if (client != null) client.resume(); + sPaused = false; + publish(); + return START_NOT_STICKY; + } + if (sRunning) return START_NOT_STICKY; if (ACTION_RETRY.equals(action)) { @@ -142,7 +195,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (sLabels == null) sLabels = sFiles; if (sBytes == null) sBytes = new long[sFiles.length]; sStatus = new int[sFiles.length]; - sIndex = 0; sPercent = 0; sSpeed = 0; + sIndex = 0; sPercent = 0; sSpeed = 0; sPaused = false; sReconnectAttempt = 0; sReconnectTotal = 0; sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: seed the heartbeat at session start } @@ -165,7 +218,6 @@ private void processNext() { int i = firstPending(); if (i < 0) { sessionComplete(); return; } sIndex = i; sPercent = 0; sStatus[i] = ACTIVE; - attempts = 0; publish(); updateNotification(sLabels[i]); startItem(i); @@ -176,34 +228,39 @@ private void startItem(final int i) { client = new RestContentClient(); client.addZim(sFiles[i], new RestContentClient.Listener() { @Override public void onProgress(int percent, String speed) { + if (sPaused) sPaused = false; // ADFA-4893: progress means the server resumed + sReconnectAttempt = 0; // ADFA-4893: progress means the reconnect succeeded sPercent = percent; sSpeed = parseRate(speed); sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: heartbeat on each poll if (sStatus[i] != INDEXING) sStatus[i] = ACTIVE; publish(); updateNotification(sLabels[i]); } @Override public void onIndexing() { sStatus[i] = INDEXING; sLastProgressAt = android.os.SystemClock.elapsedRealtime(); publish(); } + @Override public void onPaused(int percent) { + // ADFA-4893: server acknowledged the pause. Keep the heartbeat fresh (a pause is + // intentional, not a dead session) and let the screen render the paused state. + sPercent = percent; sPaused = true; + sLastProgressAt = android.os.SystemClock.elapsedRealtime(); + publish(); + } + @Override public void onReconnecting(int attempt, int total) { + // ADFA-4893: the server lost the link and is retrying (n of total). Surface it so the + // screen shows "Reconnecting n/N"; keep the heartbeat fresh — this is not a dead session. + sReconnectAttempt = attempt; sReconnectTotal = total; + sLastProgressAt = android.os.SystemClock.elapsedRealtime(); + publish(); + } @Override public void onLog(String line) { /* logcat only */ } @Override public void onDone() { android.util.Log.i("K2Go-Provision", "zim job done [" + i + "]"); sStatus[i] = DONE; publish(); processNext(); } @Override public void onError(String message) { + // ADFA-4893: the server owns reconnection (5 visible attempts). When it gives up we mark + // the item FAILED and let the user retry it (checklist tap) — no invisible app-side re-POST. android.util.Log.w("K2Go-Provision", "zim job [" + i + "] error: " + message); - retryOrFail(i); + sStatus[i] = FAILED; sReconnectAttempt = 0; publish(); processNext(); } }); } - /** Transient failure (server warming up, a flaky mirror): retry the same ZIM a couple times - * before giving up, so a blip doesn't leave content missing. */ - private void retryOrFail(int i) { - attempts++; - if (attempts < MAX_ATTEMPTS) { - android.util.Log.w("K2Go-Provision", "zim job [" + i + "] transient failure, retry " + attempts + "/" + (MAX_ATTEMPTS - 1)); - main.postDelayed(() -> startItem(i), RETRY_DELAY_MS); - } else { - android.util.Log.w("K2Go-Provision", "zim job [" + i + "] failed after " + attempts + " attempts"); - sStatus[i] = FAILED; publish(); processNext(); - } - } - private void sessionComplete() { sRunning = false; publish(); diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java index 76c13de55..a24c29c43 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimPreparingFragment.java @@ -12,16 +12,19 @@ */ package org.iiab.controller.redesign; +import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import java.util.Locale; @@ -33,6 +36,9 @@ public class ZimPreparingFragment extends Fragment { private TextView label, pct, detail; private ProgressBar bar; private LinearLayout listv; + private LinearLayout controls; // ADFA-4893: session control row (pause/resume + cancel) + private Button pauseBtn, cancelBtn; + private boolean pauseSupported = false; // ADFA-4893: box dash-node >= 1.2.4 exposes pause/resume (4894) /** * ADFA-5074: {@code newInstance(boolean fromIndex)} used to live here, and every caller now @@ -53,6 +59,33 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c detail = root.findViewById(R.id.k2go_zprep_detail); bar = root.findViewById(R.id.k2go_zprep_bar); listv = root.findViewById(R.id.k2go_zprep_list); + // ADFA-4893: session controls on the status screen. Poll (service) drives label + visibility. + controls = root.findViewById(R.id.k2go_zprep_controls); + pauseBtn = root.findViewById(R.id.k2go_zprep_pause); + cancelBtn = root.findViewById(R.id.k2go_zprep_cancel); + // ADFA-4893: the primary button morphs Pause -> Resume -> Retry; the action is decided at tap + // time from the live state, so we don't remove/re-add buttons across states. + pauseBtn.setOnClickListener(v -> { + android.content.Context ctx = requireContext().getApplicationContext(); + if (!ZimDownloadService.isRunning() && ZimDownloadService.hasFailed()) ZimDownloadService.retryFailed(ctx); + else if (ZimDownloadService.isPaused()) ZimDownloadService.resume(ctx); + else ZimDownloadService.pause(ctx); + }); + // Cancel is always available: cancels a running session, or dismisses a failed/terminal one. + cancelBtn.setOnClickListener(v -> { + android.content.Context ctx = requireContext().getApplicationContext(); + if (ZimDownloadService.isRunning()) { + ContextCompat.startForegroundService(ctx, + new Intent(ctx, ZimDownloadService.class).setAction(ZimDownloadService.ACTION_CANCEL)); + } else { + ZimDownloadService.finishSession(); + render(); + } + }); + // ADFA-4893: only offer the controls when the box's dash-node exposes pause/resume (>= 1.2.4, + // ADFA-4894). atLeast() returns false for an unknown/older version, so old boxes hide the row + // (notification Cancel still works) instead of showing a Pause that 404s. + pauseSupported = DashboardVersion.atLeast(DashboardVersion.installed(requireContext()), 1, 2, 4); // ADFA-5074: the shared animation block declares no asset; the rule picks it. org.iiab.controller.util.ProgressVisuals.apply(root, org.iiab.controller.system.domain.ContentType.ZIM); @@ -70,8 +103,10 @@ private void render() { int idx = ZimDownloadService.index(); int p = ZimDownloadService.percent(); int n = labels.length; - if (n == 0) return; + if (n == 0) { controls.setVisibility(View.GONE); return; } + // Byte figures for the "X of Y · N of M" detail line; the bar percent comes from the single + // shared source (ZimDownloadService.overallPercent) so the status screen and the index can't drift. long totalBytes = 0, doneBytes = 0; int doneCount = 0; for (int i = 0; i < n; i++) { @@ -83,30 +118,65 @@ private void render() { doneBytes += bytes[i] * p / 100; } } - int overall = totalBytes > 0 ? (int) Math.min(100, doneBytes * 100 / totalBytes) - : (ZimDownloadService.isComplete() ? 100 : 0); + int overall = ZimDownloadService.overallPercent(); bar.setProgress(overall); pct.setText(overall + "%"); - boolean allDone = ZimDownloadService.isComplete(); - label.setText(allDone - ? getString(R.string.k2go_zim_all_ready) - : getString(R.string.k2go_zim_downloading_fmt, idx < n ? labels[idx] : "")); + boolean anyFailed = ZimDownloadService.hasFailed(); + boolean running = ZimDownloadService.isRunning(); + boolean paused = ZimDownloadService.isPaused(); + int rc = ZimDownloadService.reconnectAttempt(); + boolean allOk = ZimDownloadService.isComplete() && !anyFailed; + + // Label reflects the true state — honest: never "all ready" when something failed. + if (!running && anyFailed) { + int f = firstFailed(status); + label.setText(f >= 0 ? labels[f] + getString(R.string.k2go_zim_item_failed_suffix) + : getString(R.string.k2go_zim_downloading_fmt, "")); + } else if (paused) { + label.setText(R.string.k2go_dl_paused); + } else if (running && rc > 0) { + // ADFA-4893: match rootfs wording exactly — "Reconnecting… n of N" (static ellipsis). + label.setText(getString(R.string.k2go_dl_attempt, rc, ZimDownloadService.reconnectTotal())); + } else if (allOk) { + label.setText(R.string.k2go_zim_all_ready); + } else { + label.setText(getString(R.string.k2go_zim_downloading_fmt, idx < n ? labels[idx] : "")); + } + long sp = ZimDownloadService.speed(); - String speedPart = (!allDone && sp > 0) + String speedPart = (running && !paused && rc <= 0 && sp > 0) ? " · " + humanRate(sp) + getString(R.string.k2go_rate_per_second) : ""; detail.setText(getString(R.string.k2go_zim_prep_detail_fmt, gb(doneBytes / (1024L * 1024L)), gb(totalBytes / (1024L * 1024L)), speedPart, doneCount, n)); + // ADFA-4893: [primary][Cancel] row. The primary morphs Pause -> Resume -> Retry; Cancel is always + // present. Shown while running (needs pause support, dash-node >= 1.2.4) OR whenever an item failed + // (Retry works on any version). Old boxes keep the notification Cancel while running. + boolean showControls = (running && pauseSupported) || anyFailed; + controls.setVisibility(showControls ? View.VISIBLE : View.GONE); + if (showControls) { + if (!running && anyFailed) pauseBtn.setText(R.string.k2go_dl_retry); + else if (paused) pauseBtn.setText(R.string.k2go_dl_resume); + else pauseBtn.setText(R.string.k2go_dl_pause); + } + drawChecklist(labels, status); } private void drawChecklist(String[] labels, int[] status) { + // ADFA-4893: no per-item Retry pill — the status-screen Retry (the morphing primary button) owns + // retry now, so the checklist is display-only and the retry affordance stays one consistent size. ProvisioningChecklist.render(requireContext(), listv, labels.length, status, ZimDownloadService.DONE, ZimDownloadService.FAILED, i -> (status[i] == ZimDownloadService.FAILED) ? labels[i] + getString(R.string.k2go_zim_item_failed_suffix) : labels[i], - i -> ZimDownloadService.retry(requireContext().getApplicationContext(), i)); + null); + } + + private static int firstFailed(int[] status) { + for (int i = 0; i < status.length; i++) if (status[i] == ZimDownloadService.FAILED) return i; + return -1; } private String gb(long mb) { // ADFA-4910: one standard size formatter for the whole UI diff --git a/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml b/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml index 399a0e987..a010ead4a 100644 --- a/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml +++ b/controller/app/src/main/res/layout/fragment_k2go_zim_preparing.xml @@ -75,6 +75,39 @@ android:textAppearance="?attr/textAppearanceBodySmall" android:textColor="@color/k2go_muted" /> + + + +