diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java index 6effdac0f..c9c1f2aaf 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReader.java @@ -70,42 +70,55 @@ public static List parse(byte[] manifestBytes) throws Exception { return out; } - /** Scan a manifest-less folder: recognize what each file belongs to by its name alone. */ + /** Scan a manifest-less folder: recognize what each file belongs to by its name alone. A v2 bundle + * file arrives as a relative path ("kiwix/foo.zim"): recognize and key on its basename, but keep + * the full relative path as the payload so the carrier can open it. */ public static ImportManifest scan(List files) throws Exception { List entries = new ArrayList<>(); List unrecognized = new ArrayList<>(); if (files != null) { for (ImportCarrier.DriveFile file : files) { - String name = file.name(); - if (name == null || MANIFEST_NAME.equalsIgnoreCase(name)) { + String payload = file.name(); + if (payload == null) { continue; } - String app = ImportScan.recognizeApp(name); + String base = basename(payload); + if (MANIFEST_NAME.equalsIgnoreCase(base)) { + continue; + } + String app = ImportScan.recognizeApp(base); if (ImportScan.APP_KIWIX.equals(app)) { - entries.add(kiwixEntry(name, file.size())); + entries.add(kiwixEntry(payload, base, file.size())); } else { - unrecognized.add(name); + unrecognized.add(payload); } } } return new ImportManifest(entries, false, unrecognized); } - /** Synthesize a Kiwix entry from a .zim filename: dedup keys from the name, no UUID (soft). */ - private static ImportEntry kiwixEntry(String name, long size) throws Exception { - String[] p = ImportScan.parseZimFilename(name); - String stem = name.toLowerCase(java.util.Locale.US).endsWith(".zim") - ? name.substring(0, name.length() - 4) : name; + /** The file name after the last path separator (the item's own handle), for a flat or nested name. */ + private static String basename(String path) { + int slash = path.lastIndexOf('/'); + return slash >= 0 ? path.substring(slash + 1) : path; + } + + /** Synthesize a Kiwix entry from a .zim basename: dedup keys from the name, no UUID (soft). The + * payload is the drive-relative path, the identity localRef is the basename. */ + private static ImportEntry kiwixEntry(String payload, String base, long size) throws Exception { + String[] p = ImportScan.parseZimFilename(base); + String stem = base.toLowerCase(java.util.Locale.US).endsWith(".zim") + ? base.substring(0, base.length() - 4) : base; JSONObject line = new JSONObject() .put("creator", p[0]).put("lang", p[1]).put("flavour", p[2]); JSONObject dedup = new JSONObject() .put("line", line).put("build", JSONObject.NULL) .put("version", p[3]).put("idKind", "SOFT"); - JSONObject identity = new JSONObject().put("localRef", name).put("dedup", dedup); + JSONObject identity = new JSONObject().put("localRef", base).put("dedup", dedup); JSONObject entry = new JSONObject() .put("app", ImportScan.APP_KIWIX).put("kind", "zim") .put("title", stem).put("bytes", size) - .put("identity", identity).put("payload", name); - return new ImportEntry(ImportScan.APP_KIWIX, name, stem, size, name, entry.toString()); + .put("identity", identity).put("payload", payload); + return new ImportEntry(ImportScan.APP_KIWIX, base, stem, size, payload, entry.toString()); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java index 5e1535c3d..943d9ca05 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafExportCarrier.java @@ -24,22 +24,35 @@ import java.io.IOException; import java.io.OutputStream; +import java.util.HashMap; +import java.util.Map; /** * One SAF document tree as an {@link ExportCarrier}. The tree Uri comes from * {@code ACTION_OPEN_DOCUMENT_TREE} and must already carry a persisted permission. + * + *

The bundle is laid out human-navigable: each item's archive goes in a per-app subfolder + * ({@code kiwix/}, {@code kolibri/}, {@code calibre/}) with {@code manifest.json} at the root. A write + * overwrites any existing file of the same name (manifest or item), so a re-export leaves exactly one + * of each, never a {@code manifest (1).json} / {@code name (1).tar} copy that SAF would make on a clash. */ public final class SafExportCarrier implements ExportCarrier { private static final String MANIFEST_NAME = "manifest.json"; private static final String MIME_JSON = "application/json"; private static final String MIME_BINARY = "application/octet-stream"; + private static final String MIME_DIR = DocumentsContract.Document.MIME_TYPE_DIR; private final ContentResolver resolver; + private final Uri treeUri; private final Uri treeDocUri; + /** app subfolder name -> its document Uri, created/looked-up once per run. */ + private final Map subfolders = new HashMap<>(); + public SafExportCarrier(Context context, Uri treeUri) { this.resolver = context.getContentResolver(); + this.treeUri = treeUri; this.treeDocUri = DocumentsContract.buildDocumentUriUsingTree( treeUri, DocumentsContract.getTreeDocumentId(treeUri)); } @@ -51,26 +64,84 @@ public String destinationLabel() { } @Override - public PayloadSink openPayload(String desiredName) throws IOException { - Uri file = createDocument(MIME_BINARY, desiredName); + public PayloadSink openPayload(String subfolder, String desiredName) throws IOException { + boolean nested = subfolder != null && !subfolder.isEmpty(); + Uri parent = nested ? ensureSubfolder(subfolder) : treeDocUri; + deleteExisting(parent, desiredName); // overwrite, so a retry leaves no "name (1)" copy + Uri file = createDocument(parent, MIME_BINARY, desiredName); OutputStream out = openOutput(file); - // SAF may rename on a collision; record the name actually stored so the manifest matches. + // SAF may still adjust the name; record the stored name (relative to the bundle root) so the + // manifest payload points at the real file. String actual = queryDisplayName(file); - return new PayloadSink(out, actual != null ? actual : desiredName); + String stored = actual != null ? actual : desiredName; + return new PayloadSink(out, nested ? subfolder + "/" + stored : stored); } @Override public OutputStream openManifest() throws IOException { - return openOutput(createDocument(MIME_JSON, MANIFEST_NAME)); + deleteExisting(treeDocUri, MANIFEST_NAME); // one authoritative manifest, never "manifest (1)" + return openOutput(createDocument(treeDocUri, MIME_JSON, MANIFEST_NAME)); + } + + /** Create the per-app subfolder once (reuse it if it is already on the drive). */ + private Uri ensureSubfolder(String name) throws IOException { + Uri cached = subfolders.get(name); + if (cached != null) { + return cached; + } + Uri existing = findChild(treeDocUri, name, true); + Uri dir = existing != null ? existing : createDocument(treeDocUri, MIME_DIR, name); + subfolders.put(name, dir); + return dir; + } + + /** Delete a child of {@code parent} whose display name matches, so the next create does not clash. */ + private void deleteExisting(Uri parent, String name) { + Uri child = findChild(parent, name, false); + if (child != null) { + try { + DocumentsContract.deleteDocument(resolver, child); + } catch (Exception ignored) { + // best-effort: if the delete fails, createDocument may fall back to a renamed copy + } + } + } + + /** The document Uri of a child of {@code parent} with the given display name, or null. */ + private Uri findChild(Uri parent, String name, boolean wantDir) { + String parentId = DocumentsContract.getDocumentId(parent); + Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentId); + String[] columns = { + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + }; + try (Cursor c = resolver.query(childrenUri, columns, null, null, null)) { + while (c != null && c.moveToNext()) { + String childName = c.getString(1); + if (!name.equals(childName)) { + continue; + } + boolean isDir = MIME_DIR.equals(c.getString(2)); + if (wantDir == isDir) { + return DocumentsContract.buildDocumentUriUsingTree(treeUri, c.getString(0)); + } + } + } catch (Exception ignored) { + // fall through to null + } + return null; } - private Uri createDocument(String mime, String name) throws IOException { + private Uri createDocument(Uri parent, String mime, String name) throws IOException { try { - Uri uri = DocumentsContract.createDocument(resolver, treeDocUri, mime, name); + Uri uri = DocumentsContract.createDocument(resolver, parent, mime, name); if (uri == null) { throw new IOException("Could not create " + name + " on the destination"); } return uri; + } catch (IOException e) { + throw e; } catch (Exception e) { // Includes a SecurityException if the grant was revoked, or a provider failure. throw new IOException("Could not create " + name + ": " + e.getMessage(), e); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java index c6db6dd1e..1e04803b2 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/data/SafImportCarrier.java @@ -25,9 +25,13 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Set; /** * One SAF document tree as an {@link ImportCarrier}. The tree Uri comes from @@ -40,6 +44,10 @@ public final class SafImportCarrier implements ImportCarrier { private static final String MANIFEST_NAME = "manifest.json"; /** A manifest larger than this is treated as absent: the real index is a few KB. */ private static final long MANIFEST_MAX_BYTES = 8L * 1024 * 1024; + private static final String MIME_DIR = DocumentsContract.Document.MIME_TYPE_DIR; + /** The per-app subfolders a v2 bundle lays items in; walked one level for the no-manifest scan. */ + private static final Set APP_SUBFOLDERS = new HashSet<>( + Arrays.asList("kiwix", "kolibri", "calibre")); private final ContentResolver resolver; private final Uri treeUri; @@ -105,21 +113,84 @@ public List listFiles() throws IOException { public InputStream openPayload(String name) throws IOException { index(); String id = docIds.get(name); + if (id == null) { + // A v2 payload path ("app/file") whose folder the index did not pre-walk: walk it directly. + int slash = name.indexOf('/'); + if (slash > 0) { + id = resolveNestedId(name.substring(0, slash), name.substring(slash + 1)); + } + } if (id == null) { throw new IOException("File not found on the drive: " + name); } return openStream(DocumentsContract.buildDocumentUriUsingTree(treeUri, id)); } - /** List the folder's direct children once (name + size + document id). */ + /** + * Index the bundle once: files directly in the chosen folder by bare name (a flat pre-v2 bundle), + * plus files one level down in each per-app subfolder by relative path ("app/file", a v2 bundle). + * Both forms land in the same map, so {@code openPayload} and the no-manifest scan resolve either. + */ private void index() throws IOException { if (docIds != null) { return; } Map ids = new LinkedHashMap<>(); List found = new ArrayList<>(); - Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( - treeUri, DocumentsContract.getTreeDocumentId(treeUri)); + String rootId = DocumentsContract.getTreeDocumentId(treeUri); + for (String[] row : listChildren(rootId)) { + String id = row[0]; + String name = row[1]; + if (name == null) { + continue; + } + if (MIME_DIR.equals(row[3])) { + // Walk one level into a known app subfolder; index its files by "app/file". + if (APP_SUBFOLDERS.contains(name.toLowerCase(Locale.US))) { + for (String[] sub : listChildren(id)) { + String subName = sub[1]; + if (subName == null || MIME_DIR.equals(sub[3])) { + continue; + } + String rel = name + "/" + subName; + ids.put(rel, sub[0]); + found.add(new DriveFile(rel, parseSize(sub[2]))); + } + } + continue; + } + ids.put(name, id); + found.add(new DriveFile(name, parseSize(row[2]))); + } + this.docIds = ids; + this.files = found; + } + + /** Resolve "dir/child" by walking into the named subfolder (one level), for a folder the index did + * not pre-walk. Returns the child's document id, or null. */ + private String resolveNestedId(String dir, String child) throws IOException { + String dirId = null; + for (String[] row : listChildren(DocumentsContract.getTreeDocumentId(treeUri))) { + if (dir.equals(row[1]) && MIME_DIR.equals(row[3])) { + dirId = row[0]; + break; + } + } + if (dirId == null) { + return null; + } + for (String[] row : listChildren(dirId)) { + if (child.equals(row[1]) && !MIME_DIR.equals(row[3])) { + return row[0]; + } + } + return null; + } + + /** One children query, each row as {docId, displayName, size, mimeType}. */ + private List listChildren(String parentDocId) throws IOException { + List rows = new ArrayList<>(); + Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocId); String[] columns = { DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, @@ -131,23 +202,24 @@ private void index() throws IOException { throw new IOException("Could not read the selected folder"); } while (c.moveToNext()) { - String id = c.getString(0); - String name = c.getString(1); - long size = c.isNull(2) ? 0L : c.getLong(2); - String mime = c.getString(3); - if (name == null || DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) { - continue; // files only: sub-folders are not part of a flat bundle - } - ids.put(name, id); - found.add(new DriveFile(name, size)); + rows.add(new String[]{ + c.getString(0), c.getString(1), + c.isNull(2) ? "0" : Long.toString(c.getLong(2)), c.getString(3)}); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Could not read the selected folder: " + e.getMessage(), e); } - this.docIds = ids; - this.files = found; + return rows; + } + + private static long parseSize(String s) { + try { + return Long.parseLong(s); + } catch (NumberFormatException e) { + return 0L; + } } private InputStream openStream(Uri docUri) throws IOException { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java index d7d79f695..434b479d2 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/ExportCarrier.java @@ -10,17 +10,23 @@ * *

Only {@code java.io} crosses this boundary: no Android, no SAF type. The carrier chooses the * final name for a payload (a destination may rename on a collision), so {@link #openPayload} - * reports the name actually used, which the manifest then records. + * reports the name actually used (relative to the bundle root), which the manifest then records. */ public interface ExportCarrier { /** A short, human name of the chosen destination (e.g. the folder name), for the UI. */ String destinationLabel(); - /** Open a writable stream for one payload file; reports the name the destination stored. */ - PayloadSink openPayload(String desiredName) throws IOException; + /** + * Open a writable stream for one payload file inside the bundle, under a per-app {@code subfolder} + * (e.g. {@code kiwix}); a null or empty subfolder writes at the bundle root. An existing file of + * the same name in that folder is overwritten (replaced), never left as a {@code name (1)} copy. + * Reports the stored name relative to the bundle root ({@code subfolder/name}), for the manifest. + */ + PayloadSink openPayload(String subfolder, String desiredName) throws IOException; - /** Open a writable stream for the top-level {@code manifest.json}. */ + /** Open a writable stream for the top-level {@code manifest.json}, overwriting any existing one so + * the bundle has exactly one authoritative manifest (never a {@code manifest (1).json} copy). */ OutputStream openManifest() throws IOException; /** An open payload stream plus the name the destination actually stored it under. */ diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/GroupSelection.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/GroupSelection.java new file mode 100644 index 000000000..c8a85b798 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/domain/GroupSelection.java @@ -0,0 +1,34 @@ +package org.appdevforall.k2go.contentexchange.domain; + +/** + * Pure tri-state rule for a per-app group "select all" control. A group header reports NONE, SOME or + * ALL from how many of the group's selectable items are selected, and one tap flips the whole group. + * + *

No Android, no state of its own: the counts are derived from the single selection source (the + * ViewModel's selected set), so this never becomes a second place that stores "what is selected". + * Unit-testable on a plain JVM. + */ +public final class GroupSelection { + + public static final int NONE = 0; + public static final int SOME = 1; + public static final int ALL = 2; + + private GroupSelection() {} + + /** Tri-state for a group given its selectable member count and how many of them are selected. */ + public static int state(int selectableCount, int selectedCount) { + if (selectableCount <= 0 || selectedCount <= 0) { + return NONE; + } + if (selectedCount >= selectableCount) { + return ALL; + } + return SOME; + } + + /** A header tap selects the whole group unless it is already fully selected, then it clears it. */ + public static boolean shouldSelectAll(int state) { + return state != ALL; + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java index 7af060bc1..61dbce284 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentDeleteService.java @@ -119,7 +119,9 @@ public int onStartCommand(Intent intent, int flags, int startId) { // delivery's start-foreground obligation while the worker winds down. startForeground(NOTIFICATION_ID, buildNotification(currentLabel())); } else { - // Nothing is draining (the run already settled): tear down here. + // Nothing is draining (the run already settled, or a fresh service instance handles the + // cancel): satisfy the FGS start-foreground obligation before tearing down. + startForeground(NOTIFICATION_ID, buildNotification(currentLabel())); SESSION.clear(); stopForeground(true); stopSelf(); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java index 8f27a54d8..6bb686068 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentExportService.java @@ -148,11 +148,19 @@ public int onStartCommand(Intent intent, int flags, int startId) { String action = intent != null ? intent.getAction() : null; if (ACTION_CANCEL.equals(action)) { + // A fresh service instance may handle this cancel (no run ever started in it), so satisfy the + // FGS start-foreground obligation before tearing down. Idempotent if already foreground. + startForeground(NOTIFICATION_ID, buildNotification(null)); releaseGrant(getApplicationContext(), SESSION.treeUri()); + boolean wasRunning = SESSION.isRunning(); SESSION.markCancelled(); - SESSION.clear(); - stopForeground(true); - stopSelf(); + if (!wasRunning) { + // No worker draining: tear down here. When a run IS draining, its cancelled branch owns + // teardown (clear + stop), so clearing here would race the worker's reads of refs/job. + SESSION.clear(); + stopForeground(true); + stopSelf(); + } return START_NOT_STICKY; } @@ -238,7 +246,9 @@ private void drain(boolean fresh) { try (ContentExportSource.ItemPayload payload = source.open(ref)) { String name = ExportFilenames.resolve(payload.filename(), ref, used); - ExportCarrier.PayloadSink sink = carrier.openPayload(name); + // Write into the item's per-app subfolder; the sink reports the stored path + // ("app/name"), which becomes the manifest payload. + ExportCarrier.PayloadSink sink = carrier.openPayload(ref.app(), name); SESSION.setPayloadName(i, sink.name()); copy(payload.stream(), sink.stream(), i, job, runStart); job.setDone(i); @@ -373,7 +383,10 @@ private Set seedUsedNames() { for (int i = 0; i < SESSION.itemCount(); i++) { String name = SESSION.payloadName(i); if (name != null) { - used.add(name); + // payloadName is the bundle-relative path ("app/file"); ExportFilenames dedups on the + // bare file name, so seed the bare name. + int slash = name.lastIndexOf('/'); + used.add(slash >= 0 ? name.substring(slash + 1) : name); } } return used; diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java index 8648b6cf0..0c8f91df7 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentImportService.java @@ -158,6 +158,9 @@ public int onStartCommand(Intent intent, int flags, int startId) { boolean wasRunning = SESSION.isRunning(); SESSION.markCancelled(); if (!wasRunning) { + // No worker owns teardown: a fresh service instance may be handling this cancel, so + // satisfy the FGS start-foreground obligation before stopping. + startForeground(NOTIFICATION_ID, buildNotification(null)); SESSION.clear(); stopForeground(true); stopSelf(); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java index f69758115..2e2ee5031 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerAdapter.java @@ -17,6 +17,7 @@ import org.appdevforall.k2go.R; import org.appdevforall.k2go.contentexchange.domain.ContentItem; +import org.appdevforall.k2go.contentexchange.domain.GroupSelection; import org.appdevforall.k2go.util.ByteFormatter; import java.util.ArrayList; @@ -40,6 +41,12 @@ public interface SelectionController { boolean isSelected(String selectionId); void toggle(String selectionId); + + /** Tri-state of a group (by app): {@link GroupSelection#NONE}/{@code SOME}/{@code ALL}. */ + int groupState(String app); + + /** Select or clear every item in a group (by app). */ + void toggleGroup(String app); } static final int TYPE_HEADER = 0; @@ -60,6 +67,11 @@ public void submit(List newRows) { notifyDataSetChanged(); } + /** Rebind visible rows so group headers and item checkboxes reflect a changed selection. */ + public void refreshSelectionStates() { + notifyDataSetChanged(); + } + @Override public int getItemViewType(int position) { return rows.get(position).type; @@ -78,7 +90,7 @@ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int case TYPE_HEADER: return new HeaderVH(ctx); case TYPE_GROUP: - return new GroupVH(ctx); + return new GroupVH(ctx, selection); case TYPE_EMPTY: return new EmptyVH(ctx); default: @@ -131,13 +143,17 @@ public HeaderRow(String title, String subtitle, String usedLine, String freeLine } public static final class GroupRow extends Row { + final String app; final String name; final String meta; + final boolean selectable; // the group has at least one item that can be picked - public GroupRow(String name, String meta) { + public GroupRow(String app, String name, String meta, boolean selectable) { super(TYPE_GROUP); + this.app = app; this.name = name; this.meta = meta; + this.selectable = selectable; } } @@ -225,27 +241,59 @@ void bind(HeaderRow row) { } static final class GroupVH extends RecyclerView.ViewHolder { + private final MaterialCheckBox checkBox; private final TextView name; private final TextView meta; + private final SelectionController selection; + private String boundApp; - GroupVH(Context ctx) { + GroupVH(Context ctx, SelectionController selection) { super(new LinearLayout(ctx)); + this.selection = selection; LinearLayout root = (LinearLayout) itemView; root.setOrientation(LinearLayout.HORIZONTAL); root.setGravity(Gravity.CENTER_VERTICAL); root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 8))); + checkBox = new MaterialCheckBox(ctx); + checkBox.setContentDescription(ctx.getString(R.string.k2go_cx_select_group)); + // Same 40dp leading slot as the item rows, so the group box sits above the item boxes. + FrameLayout slot = new FrameLayout(ctx); + FrameLayout.LayoutParams clp = new FrameLayout.LayoutParams(-2, -2); + clp.gravity = Gravity.CENTER; + slot.addView(checkBox, clp); + LinearLayout.LayoutParams slotLp = new LinearLayout.LayoutParams(px(ctx, 40), -2); + slotLp.rightMargin = px(ctx, 4); + root.addView(slot, slotLp); + name = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink); name.setTypeface(name.getTypeface(), Typeface.BOLD); root.addView(name, new LinearLayout.LayoutParams(0, -2, 1f)); meta = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted); root.addView(meta); + + // User taps only: setCheckedState() during bind does not fire this (no OnCheckedChange + // listener), so a recycled header never toggles the model by itself. + checkBox.setOnClickListener(v -> { + if (boundApp != null) { + this.selection.toggleGroup(boundApp); + } + }); } void bind(GroupRow row) { + boundApp = row.app; name.setText(row.name); meta.setText(row.meta); + // An empty group gets a disabled box, not a live control that does nothing when tapped. + checkBox.setEnabled(row.selectable); + int state = row.selectable ? selection.groupState(row.app) : GroupSelection.NONE; + checkBox.setCheckedState(state == GroupSelection.ALL + ? MaterialCheckBox.STATE_CHECKED + : state == GroupSelection.SOME + ? MaterialCheckBox.STATE_INDETERMINATE + : MaterialCheckBox.STATE_UNCHECKED); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java index 7cd1a98e6..08e243223 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerFragment.java @@ -32,8 +32,6 @@ import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.google.android.material.dialog.MaterialAlertDialogBuilder; - import org.appdevforall.k2go.R; import org.appdevforall.k2go.contentexchange.domain.ContentGroup; import org.appdevforall.k2go.contentexchange.domain.ContentItem; @@ -41,6 +39,7 @@ import org.appdevforall.k2go.contentexchange.domain.ManagedContent; import org.appdevforall.k2go.contentexchange.domain.StorageStatus; import org.appdevforall.k2go.storage.StorageProbe; +import org.appdevforall.k2go.ui.dialog.BrandDialog; import org.appdevforall.k2go.util.ByteFormatter; import java.util.ArrayList; @@ -112,6 +111,16 @@ public boolean isSelected(String selectionId) { public void toggle(String selectionId) { viewModel.toggle(selectionId); } + + @Override + public int groupState(String app) { + return viewModel.groupState(app); + } + + @Override + public void toggleGroup(String app) { + viewModel.toggleGroup(app); + } }); list.setLayoutManager(new LinearLayoutManager(requireContext())); list.setAdapter(adapter); @@ -179,9 +188,11 @@ private List buildRows(ManagedContent content, Storag } for (ContentGroup group : content.groups()) { rows.add(new ContentManagerAdapter.GroupRow( + group.app(), appDisplayName(group.app()), getString(R.string.k2go_cx_group_meta_fmt, - group.items().size(), ByteFormatter.humanBytes(group.totalBytes())))); + group.items().size(), ByteFormatter.humanBytes(group.totalBytes())), + !group.isEmpty())); if (group.isEmpty()) { rows.add(new ContentManagerAdapter.EmptyRow(getString(R.string.k2go_cx_group_empty))); } else { @@ -216,6 +227,10 @@ private String freeLine() { /** Updates the bottom action bar from the selection. Export and Delete act; Share is pending. */ private void renderSelection(SelectionSummary sel) { + // Rebind rows so group headers (tri-state) and item checkboxes match the new selection. + if (adapter != null) { + adapter.refreshSelectionStates(); + } if (sel == null || sel.isEmpty()) { actionBar.setVisibility(View.GONE); return; @@ -228,9 +243,10 @@ private void renderSelection(SelectionSummary sel) { /** The selection captured when Export was tapped, held across the folder picker round-trip. */ private List pendingExport; - /** Export: if a run is already active, just show it; otherwise capture the selection and pick a drive. */ + /** Export: if a run is still active, just show it; otherwise capture the selection and pick a drive. + * A settled (finished) run is not active, so a new tap starts fresh instead of reopening it. */ private void onExportClicked() { - if (ContentExportService.session().hasSession()) { + if (ContentExportService.session().isRunning()) { showProgress(); return; } @@ -243,9 +259,10 @@ private void onExportClicked() { openTree.launch(null); } - /** Import: if a run is already active, show it; otherwise pick the drive that holds the bundle. */ + /** Import: if a run is still active, show it; otherwise pick the drive that holds the bundle. + * A settled (finished) run is not active, so a new tap starts fresh instead of reopening it. */ private void onImportClicked() { - if (ContentImportService.session().hasSession()) { + if (ContentImportService.session().isRunning()) { showImportProgress(); return; } @@ -336,11 +353,12 @@ private void confirmAndStart(Uri treeUri, List selected) { } String message = getString(R.string.k2go_cx_export_confirm_fmt, selected.size(), ByteFormatter.humanBytes(total)); - new MaterialAlertDialogBuilder(requireContext()) + // Export is not destructive: a plain primary confirm (the shared branded dialog). + new BrandDialog(requireContext()) .setTitle(R.string.k2go_cx_action_export) .setMessage(message) - .setNegativeButton(R.string.k2go_dash_cancel, null) - .setPositiveButton(R.string.k2go_cx_action_export, (d, w) -> startExport(treeUri, selected)) + .setPositive(R.string.k2go_cx_action_export, () -> startExport(treeUri, selected)) + .setNegative(R.string.k2go_dash_cancel, null) .show(); } @@ -363,9 +381,10 @@ private void showProgress() { // ---- delete -------------------------------------------------------------------------------- - /** Delete: if a run is already active, just show it; otherwise confirm and start. */ + /** Delete: if a run is still active, just show it; otherwise confirm and start. + * A settled (finished) run is not active, so a new tap starts fresh instead of reopening it. */ private void onDeleteClicked() { - if (ContentDeleteService.session().hasSession()) { + if (ContentDeleteService.session().isRunning()) { showDeleteProgress(); return; } @@ -384,11 +403,12 @@ private void confirmAndDelete(List selected) { } String message = getString(R.string.k2go_cx_delete_confirm_fmt, selected.size(), ByteFormatter.humanBytes(total)); - new MaterialAlertDialogBuilder(requireContext()) + // Delete is destructive: the shared branded dialog's clay confirm (mirrors confirmReinstall). + new BrandDialog(requireContext()) .setTitle(R.string.k2go_cx_delete_confirm_title) .setMessage(message) - .setNegativeButton(R.string.k2go_dash_cancel, null) - .setPositiveButton(R.string.k2go_cx_action_delete, (d, w) -> startDelete(selected)) + .setDestructive(R.string.k2go_cx_action_delete, () -> startDelete(selected)) + .setNegative(R.string.k2go_dash_cancel, null) .show(); } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java index c3410e51d..dfc721a47 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ContentManagerViewModel.java @@ -7,6 +7,7 @@ import org.appdevforall.k2go.contentexchange.domain.ContentGroup; import org.appdevforall.k2go.contentexchange.domain.ContentItem; import org.appdevforall.k2go.contentexchange.domain.GetStorageStatusUseCase; +import org.appdevforall.k2go.contentexchange.domain.GroupSelection; import org.appdevforall.k2go.contentexchange.domain.ListManagedContentUseCase; import org.appdevforall.k2go.contentexchange.domain.ManagedContent; import org.appdevforall.k2go.contentexchange.domain.StorageStatus; @@ -115,6 +116,53 @@ public void clearSelection() { } } + /** + * Tri-state of a group (by app) for the header's "select all" control: NONE, SOME or ALL. Derived + * from the single selection source, never stored separately. + */ + public int groupState(String app) { + ManagedContent content = lastContent; + if (content == null || app == null) { + return GroupSelection.NONE; + } + int selectable = 0; + int selected = 0; + for (ContentGroup group : content.groups()) { + if (!app.equals(group.app())) { + continue; + } + for (ContentItem item : group.items()) { + selectable++; + if (selectedIds.contains(item.selectionId())) { + selected++; + } + } + } + return GroupSelection.state(selectable, selected); + } + + /** Select or clear every item in a group (by app) in one tap of its header control. */ + public void toggleGroup(String app) { + ManagedContent content = lastContent; + if (content == null || app == null) { + return; + } + boolean selectAll = GroupSelection.shouldSelectAll(groupState(app)); + boolean changed = false; + for (ContentGroup group : content.groups()) { + if (!app.equals(group.app())) { + continue; + } + for (ContentItem item : group.items()) { + String id = item.selectionId(); + changed |= selectAll ? selectedIds.add(id) : selectedIds.remove(id); + } + } + if (changed) { + publishSelection(); + } + } + /** Rebuilds the id->bytes index and drops any selected id that no longer exists. */ private void indexBytes(ManagedContent content) { bytesById.clear(); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java index e264fc410..90b03eacc 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportProgressFragment.java @@ -11,15 +11,18 @@ */ package org.appdevforall.k2go.contentexchange.presentation; +import android.content.Context; 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.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import com.google.android.material.progressindicator.LinearProgressIndicator; @@ -28,6 +31,7 @@ import org.appdevforall.k2go.contentexchange.domain.ExportJob; import org.appdevforall.k2go.util.ByteFormatter; +import java.util.Collections; import java.util.List; import java.util.Locale; @@ -39,6 +43,8 @@ public class ExportProgressFragment extends Fragment { private TextView overallDetail; private TextView itemLabel; private LinearProgressIndicator itemBar; + private TextView categoriesLabel; + private LinearLayout categories; private TextView message; private TextView skipped; private Button cancel; @@ -57,6 +63,8 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c overallDetail = root.findViewById(R.id.k2go_cxx_overall_detail); itemLabel = root.findViewById(R.id.k2go_cxx_item_label); itemBar = root.findViewById(R.id.k2go_cxx_item_bar); + categoriesLabel = root.findViewById(R.id.k2go_cxx_categories_label); + categories = root.findViewById(R.id.k2go_cxx_categories); message = root.findViewById(R.id.k2go_cxx_message); skipped = root.findViewById(R.id.k2go_cxx_skipped); cancel = root.findViewById(R.id.k2go_cxx_cancel); @@ -111,6 +119,7 @@ private void render() { overallDetail.setText(preparing ? "" : overallDetail()); renderCurrentItem(running, preparing); + renderCategories(running, preparing); renderSettled(running, preparing, error); cancel.setVisibility(running ? View.VISIBLE : View.GONE); @@ -132,6 +141,86 @@ private void renderCurrentItem(boolean running, boolean preparing) { } } + /** + * One progress bar per app being exported ("3 bars if 3 categories"), beside the overall bar. Shown + * only while running with at least two apps: with a single app the overall bar already is it. + */ + private void renderCategories(boolean running, boolean preparing) { + List cats = (running && !preparing) + ? session.categories() : Collections.emptyList(); + if (cats.size() < 2) { + categoriesLabel.setVisibility(View.GONE); + categories.setVisibility(View.GONE); + categories.removeAllViews(); + return; + } + categoriesLabel.setVisibility(View.VISIBLE); + categories.setVisibility(View.VISIBLE); + Context ctx = requireContext(); + // The apps are fixed for a run, so build the rows once, then just update text/progress. + if (categories.getChildCount() != cats.size()) { + categories.removeAllViews(); + for (int i = 0; i < cats.size(); i++) { + categories.addView(buildCategoryRow(ctx)); + } + } + for (int i = 0; i < cats.size(); i++) { + ExportSession.Category c = cats.get(i); + LinearLayout row = (LinearLayout) categories.getChildAt(i); + TextView label = (TextView) row.getChildAt(0); + LinearProgressIndicator bar = (LinearProgressIndicator) row.getChildAt(1); + label.setText(getString(R.string.k2go_cx_export_category_fmt, appDisplayName(c.app), c.percent)); + bar.setProgressCompat(c.percent, true); + } + } + + /** A per-category row: the app label over its own progress bar. */ + private LinearLayout buildCategoryRow(Context ctx) { + int gap = px(ctx, 8); + LinearLayout row = new LinearLayout(ctx); + row.setOrientation(LinearLayout.VERTICAL); + LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); + rlp.topMargin = gap; + row.setLayoutParams(rlp); + + TextView label = new TextView(ctx); + label.setTextAppearance(com.google.android.material.R.style.TextAppearance_Material3_BodySmall); + label.setTextColor(ContextCompat.getColor(ctx, R.color.k2go_muted)); + row.addView(label); + + LinearProgressIndicator bar = new LinearProgressIndicator(ctx); + bar.setMax(100); + bar.setTrackThickness(px(ctx, 6)); + bar.setTrackCornerRadius(px(ctx, 3)); + LinearLayout.LayoutParams blp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); + blp.topMargin = px(ctx, 4); + row.addView(bar, blp); + return row; + } + + private static int px(Context ctx, int dp) { + return Math.round(dp * ctx.getResources().getDisplayMetrics().density); + } + + /** Friendly app label; falls back to the raw key for an unknown app. */ + private String appDisplayName(String app) { + if (app == null) { + return ""; + } + switch (app) { + case "kiwix": + return getString(R.string.k2go_cx_app_kiwix); + case "kolibri": + return getString(R.string.k2go_cx_app_kolibri); + case "calibre": + return getString(R.string.k2go_cx_app_calibre); + default: + return app; + } + } + private void renderSettled(boolean running, boolean preparing, String error) { if (running || preparing) { message.setVisibility(View.GONE); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java index 37106a7b3..584206ee2 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ExportSession.java @@ -20,7 +20,9 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; final class ExportSession { @@ -238,6 +240,54 @@ int currentItemPercent() { return job.currentItemPercent(); } + /** One per-app progress row (a category), in the order the apps first appear in the request. */ + static final class Category { + final String app; + final int percent; + final long copiedBytes; + final long plannedBytes; + + Category(String app, int percent, long copiedBytes, long plannedBytes) { + this.app = app; + this.percent = percent; + this.copiedBytes = copiedBytes; + this.plannedBytes = plannedBytes; + } + } + + /** + * Per-category (per-app) progress for the run, derived from the job and the request: one bar per + * app being exported. Not stored separately: the job and refs stay the single source. + */ + List categories() { + Map agg = new LinkedHashMap<>(); // app -> {plannedSum, copiedSum} + for (int i = 0; i < refs.length; i++) { + String app = refs[i] != null && refs[i].app() != null ? refs[i].app() : ""; + long[] v = agg.get(app); + if (v == null) { + v = new long[2]; + agg.put(app, v); + } + long planned = Math.max(0L, job.planned(i)); + v[0] += planned; + long copied; + if (job.status(i) == ExportJob.DONE) { + copied = planned; + } else { + copied = planned > 0 ? Math.min(job.copied(i), planned) : job.copied(i); + } + v[1] += Math.max(0L, copied); + } + List out = new ArrayList<>(); + for (Map.Entry e : agg.entrySet()) { + long planned = e.getValue()[0]; + long copied = e.getValue()[1]; + int percent = planned > 0 ? (int) Math.min(100L, copied * 100L / planned) : 0; + out.add(new Category(e.getKey(), percent, copied, planned)); + } + return out; + } + long copiedTotal() { return job.copiedTotal(); } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java index e25bd6ab1..2cc32145d 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewAdapter.java @@ -15,6 +15,7 @@ import com.google.android.material.checkbox.MaterialCheckBox; import org.appdevforall.k2go.R; +import org.appdevforall.k2go.contentexchange.domain.GroupSelection; import java.util.ArrayList; import java.util.List; @@ -35,6 +36,12 @@ interface SelectionController { boolean isSelected(int index); void toggle(int index); + + /** Tri-state of a group (by app): {@link GroupSelection#NONE}/{@code SOME}/{@code ALL}. */ + int groupState(String app); + + /** Select or clear every selectable item in a group (by app). */ + void toggleGroup(String app); } static final int TYPE_HEADER = 0; @@ -55,6 +62,11 @@ void submit(List newRows) { notifyDataSetChanged(); } + /** Rebind visible rows so group headers and item checkboxes reflect a changed selection. */ + void refreshSelectionStates() { + notifyDataSetChanged(); + } + @Override public int getItemViewType(int position) { return rows.get(position).type; @@ -73,7 +85,7 @@ public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int case TYPE_HEADER: return new HeaderVH(ctx); case TYPE_GROUP: - return new GroupVH(ctx); + return new GroupVH(ctx, selection); case TYPE_NOTE: return new NoteVH(ctx); default: @@ -122,13 +134,17 @@ static final class HeaderRow extends Row { } static final class GroupRow extends Row { + final String app; final String name; final String meta; + final boolean selectable; // the group has at least one item that can be picked - GroupRow(String name, String meta) { + GroupRow(String app, String name, String meta, boolean selectable) { super(TYPE_GROUP); + this.app = app; this.name = name; this.meta = meta; + this.selectable = selectable; } } @@ -210,27 +226,60 @@ void bind(HeaderRow row) { } static final class GroupVH extends RecyclerView.ViewHolder { + private final MaterialCheckBox checkBox; private final TextView name; private final TextView meta; + private final SelectionController selection; + private String boundApp; - GroupVH(Context ctx) { + GroupVH(Context ctx, SelectionController selection) { super(new LinearLayout(ctx)); + this.selection = selection; LinearLayout root = (LinearLayout) itemView; root.setOrientation(LinearLayout.HORIZONTAL); root.setGravity(Gravity.CENTER_VERTICAL); root.setLayoutParams(fullWidth(px(ctx, 16), px(ctx, 8))); + checkBox = new MaterialCheckBox(ctx); + checkBox.setContentDescription(ctx.getString(R.string.k2go_cx_select_group)); + // Same 40dp leading slot as the item rows, so the group box sits above the item boxes. + FrameLayout slot = new FrameLayout(ctx); + FrameLayout.LayoutParams clp = new FrameLayout.LayoutParams(-2, -2); + clp.gravity = Gravity.CENTER; + slot.addView(checkBox, clp); + LinearLayout.LayoutParams slotLp = new LinearLayout.LayoutParams(px(ctx, 40), -2); + slotLp.rightMargin = px(ctx, 4); + root.addView(slot, slotLp); + name = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_TitleMedium, R.color.k2go_ink); name.setTypeface(name.getTypeface(), Typeface.BOLD); root.addView(name, new LinearLayout.LayoutParams(0, -2, 1f)); meta = text(ctx, com.google.android.material.R.style.TextAppearance_Material3_BodySmall, R.color.k2go_muted); root.addView(meta); + + // User taps only: setCheckedState() during bind does not fire this (no OnCheckedChange + // listener), so a recycled header never toggles the model by itself. + checkBox.setOnClickListener(v -> { + if (boundApp != null) { + this.selection.toggleGroup(boundApp); + } + }); } void bind(GroupRow row) { + boundApp = row.app; name.setText(row.name); meta.setText(row.meta); + // A group with nothing selectable (all same-version / no-app) gets a disabled box, not a + // live control that does nothing when tapped. + checkBox.setEnabled(row.selectable); + int state = row.selectable ? selection.groupState(row.app) : GroupSelection.NONE; + checkBox.setCheckedState(state == GroupSelection.ALL + ? MaterialCheckBox.STATE_CHECKED + : state == GroupSelection.SOME + ? MaterialCheckBox.STATE_INDETERMINATE + : MaterialCheckBox.STATE_UNCHECKED); } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java index 9448f50bf..997eb3df6 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewFragment.java @@ -91,6 +91,16 @@ public boolean isSelected(int index) { public void toggle(int index) { viewModel.toggle(index); } + + @Override + public int groupState(String app) { + return viewModel.groupState(app); + } + + @Override + public void toggleGroup(String app) { + viewModel.toggleGroup(app); + } }); list.setLayoutManager(new LinearLayoutManager(requireContext())); list.setAdapter(adapter); @@ -144,23 +154,26 @@ private List buildRows(ImportReviewUiState st) { String currentApp = null; int groupCount = 0; long groupBytes = 0L; + boolean groupSelectable = false; int groupHeaderAt = -1; for (ImportReviewItem item : st.items) { String app = item.entry().app(); if (currentApp == null || !currentApp.equals(app)) { currentApp = app; groupHeaderAt = rows.size(); - rows.add(new ImportReviewAdapter.GroupRow(appDisplayName(app), "")); + rows.add(new ImportReviewAdapter.GroupRow(app, appDisplayName(app), "", false)); groupCount = 0; groupBytes = 0L; + groupSelectable = false; } rows.add(itemRow(item)); groupCount++; groupBytes += Math.max(0L, item.entry().bytes()); + groupSelectable |= item.selectable(); // Rewrite the group header meta as the running totals (header was added first). - rows.set(groupHeaderAt, new ImportReviewAdapter.GroupRow(appDisplayName(app), + rows.set(groupHeaderAt, new ImportReviewAdapter.GroupRow(app, appDisplayName(app), getString(R.string.k2go_cx_group_meta_fmt, groupCount, - ByteFormatter.humanBytes(groupBytes)))); + ByteFormatter.humanBytes(groupBytes)), groupSelectable)); } } @@ -202,6 +215,10 @@ private String stateLabel(ImportReviewItem item) { } private void renderSelection(ImportSelectionSummary sel) { + // Rebind rows so group headers (tri-state) and item checkboxes match the new selection. + if (adapter != null) { + adapter.refreshSelectionStates(); + } if (sel == null || sel.isEmpty()) { actionBar.setVisibility(View.GONE); currentFits = false; diff --git a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java index 39281db2d..e81cb3c83 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/contentexchange/presentation/ImportReviewViewModel.java @@ -20,6 +20,7 @@ import org.appdevforall.k2go.contentexchange.data.ImportManifestReader; import org.appdevforall.k2go.contentexchange.data.SafImportCarrier; +import org.appdevforall.k2go.contentexchange.domain.GroupSelection; import org.appdevforall.k2go.contentexchange.domain.ImportEntry; import org.appdevforall.k2go.contentexchange.domain.ImportManifest; import org.appdevforall.k2go.contentexchange.domain.ImportPreflight; @@ -123,6 +124,47 @@ void toggle(int index) { } } + /** + * Tri-state of a group (by app) over its SELECTABLE items only (a same-version or no-app item can + * never be picked, so it is not counted). Derived from the single selection source. + */ + int groupState(String app) { + if (app == null) { + return GroupSelection.NONE; + } + int selectable = 0; + int chosen = 0; + for (ImportReviewItem it : items) { + if (!it.selectable() || !app.equals(safe(it.entry().app()))) { + continue; + } + selectable++; + if (selected.contains(it.index())) { + chosen++; + } + } + return GroupSelection.state(selectable, chosen); + } + + /** Select or clear every selectable item in a group (by app) in one tap of its header control. */ + void toggleGroup(String app) { + if (app == null) { + return; + } + boolean selectAll = GroupSelection.shouldSelectAll(groupState(app)); + boolean changed = false; + for (ImportReviewItem it : items) { + if (!it.selectable() || !app.equals(safe(it.entry().app()))) { + continue; + } + int idx = it.index(); + changed |= selectAll ? selected.add(idx) : selected.remove(idx); + } + if (changed) { + publishSelection(); + } + } + /** The entries the user picked, in display order, for the import service. */ List selectedEntries() { List out = new ArrayList<>(); diff --git a/controller/app/src/main/res/layout/fragment_k2go_content_export.xml b/controller/app/src/main/res/layout/fragment_k2go_content_export.xml index a446d00d8..53f5751d4 100644 --- a/controller/app/src/main/res/layout/fragment_k2go_content_export.xml +++ b/controller/app/src/main/res/layout/fragment_k2go_content_export.xml @@ -76,6 +76,25 @@ app:trackThickness="6dp" app:trackCornerRadius="3dp" /> + + + + + + + + Select all in this group + + + By category + + %1$s: %2$d%% + diff --git a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReaderTest.java b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReaderTest.java index 38b333200..0abd0590a 100644 --- a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReaderTest.java +++ b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/data/ImportManifestReaderTest.java @@ -86,4 +86,33 @@ public void scanRecoversKiwixAndFlagsTheRest() throws Exception { assertEquals(1, m.unrecognized().size()); assertEquals("channel.tar", m.unrecognized().get(0)); } + + @Test + public void parseKeepsASubfolderPayloadVerbatim() throws Exception { + // A v2 manifest records "app/file" as the payload; the reader must keep it for openPayload. + List out = ImportManifestReader.parse( + manifest(entry("calibre", "book-7", "calibre/book-7.tar", 30L))); + assertEquals(1, out.size()); + assertEquals("calibre/book-7.tar", out.get(0).payloadName()); + assertEquals("book-7", out.get(0).localRef()); + } + + @Test + public void scanRecognizesAZimInsideAnAppSubfolder() throws Exception { + // A v2 no-manifest bundle: the drive file arrives as a relative path. Recognize on the basename, + // keep the full relative path as the payload, use the basename as the identity. + List files = new ArrayList<>(); + files.add(new ImportCarrier.DriveFile("kiwix/wikipedia_en_all_2023-10.zim", 123L)); + + ImportManifest m = ImportManifestReader.scan(files); + assertEquals(1, m.entries().size()); + ImportEntry zim = m.entries().get(0); + assertEquals("kiwix", zim.app()); + assertEquals("wikipedia_en_all_2023-10.zim", zim.localRef()); + assertEquals("kiwix/wikipedia_en_all_2023-10.zim", zim.payloadName()); + JSONObject back = new JSONObject(zim.entryJson()); + assertEquals("kiwix/wikipedia_en_all_2023-10.zim", back.getString("payload")); + assertEquals("wikipedia", back.getJSONObject("identity").getJSONObject("dedup") + .getJSONObject("line").getString("creator")); + } } diff --git a/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/GroupSelectionTest.java b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/GroupSelectionTest.java new file mode 100644 index 000000000..e11b9761b --- /dev/null +++ b/controller/app/src/test/java/org/appdevforall/k2go/contentexchange/domain/GroupSelectionTest.java @@ -0,0 +1,44 @@ +package org.appdevforall.k2go.contentexchange.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** Pure-logic tests for the group select-all tri-state. */ +public class GroupSelectionTest { + + @Test + public void noneWhenNothingSelected() { + assertEquals(GroupSelection.NONE, GroupSelection.state(5, 0)); + } + + @Test + public void someWhenPartiallySelected() { + assertEquals(GroupSelection.SOME, GroupSelection.state(5, 2)); + } + + @Test + public void allWhenEverySelectableIsSelected() { + assertEquals(GroupSelection.ALL, GroupSelection.state(5, 5)); + } + + @Test + public void noneWhenGroupHasNoSelectableMembers() { + assertEquals(GroupSelection.NONE, GroupSelection.state(0, 0)); + } + + @Test + public void selectedCountOverTheMemberCountStillCountsAsAll() { + // Defensive: a selected count that exceeds the member count is still a full group. + assertEquals(GroupSelection.ALL, GroupSelection.state(3, 4)); + } + + @Test + public void tapSelectsAllUnlessAlreadyFull() { + assertTrue(GroupSelection.shouldSelectAll(GroupSelection.NONE)); + assertTrue(GroupSelection.shouldSelectAll(GroupSelection.SOME)); + assertFalse(GroupSelection.shouldSelectAll(GroupSelection.ALL)); + } +}