Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;

import org.appdevforall.k2go.R;
import org.appdevforall.k2go.contentexchange.data.ShareHandshake;
import org.appdevforall.k2go.contentexchange.domain.ContentGroup;
import org.appdevforall.k2go.contentexchange.domain.ContentItem;
import org.appdevforall.k2go.contentexchange.domain.ItemRef;
Expand Down Expand Up @@ -77,9 +73,6 @@ public class ContentManagerFragment extends Fragment {
private Button deleteButton;
private Button shareButton;

/** The invite-QR scanner for the receive flow (same ZXing contract Clone uses). */
private ActivityResultLauncher<ScanOptions> inviteScan;

/** The selection captured when Share was tapped, held across the hotspot-permission round-trip. */
private List<ContentItem> pendingShare;
/** Runtime hotspot permission (NEARBY_WIFI_DEVICES / ACCESS_FINE_LOCATION), requested before the
Expand Down Expand Up @@ -115,7 +108,6 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
new ActivityResultContracts.OpenDocumentTree(), this::onImportTreePicked);
hotspotPerm = registerForActivityResult(
new ActivityResultContracts.RequestMultiplePermissions(), result -> onHotspotPermissionResult());
inviteScan = registerForActivityResult(new ScanContract(), r -> onInviteScanned(r.getContents()));
exportButton.setEnabled(true);
exportButton.setOnClickListener(v -> onExportClicked());
importButton.setOnClickListener(v -> onImportClicked());
Expand Down Expand Up @@ -345,31 +337,11 @@ private void onReceiveClicked() {
}
// Tear our own hotspot down the moment Receive starts: the sender's AP IP (always 192.168.49.1)
// collides with our own hotspot IP if we are hosting, which traps the connection locally.
// Stopping here lets the interface release while the user scans; ContentReceiveFragment also
// waits for the release before it connects. K2GO-376.
// Stopping here lets the interface release while the user joins and scans; ContentReceiveFragment
// also waits for the release before it connects. K2GO-376.
LocalHotspotManager.get().stop();
ScanOptions o = new ScanOptions();
o.setDesiredBarcodeFormats(ScanOptions.QR_CODE);
o.setPrompt(getString(R.string.k2go_cx_receive_scan_prompt));
o.setBeepEnabled(false);
o.setBarcodeImageEnabled(false);
o.setOrientationLocked(false);
inviteScan.launch(o);
}

/** The scanner returned. Null means the user cancelled; a non-invite or invalid QR is rejected. */
private void onInviteScanned(@Nullable String contents) {
if (!isAdded() || contents == null) {
return;
}
ShareHandshake.ShareInvite invite = ShareHandshake.decode(contents);
if (invite == null) {
String msg = getString(R.string.k2go_cx_receive_invalid);
Snackbar.make(requireView(), msg, SnackbarDuration.millisForText(msg)).show();
return;
}
requireActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.k2go_setup_host, ContentReceiveFragment.newInstance(invite))
.replace(R.id.k2go_setup_host, new ContentReceiveStartFragment())
.addToBackStack(null)
.commit();
}
Expand Down Expand Up @@ -501,10 +473,12 @@ private void onHotspotPermissionResult() {

private void startShare(List<ContentItem> selected) {
ItemRef[] refs = new ItemRef[selected.size()];
long bytes = 0;
for (int i = 0; i < selected.size(); i++) {
refs[i] = new ItemRef(selected.get(i).app(), selected.get(i).localRef());
bytes += selected.get(i).bytes();
}
ContentShareService.start(requireContext(), refs);
ContentShareService.start(requireContext(), refs, bytes);
pendingShare = null;
viewModel.clearSelection();
showShareProgress();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* ============================================================================
* Name : ContentReceiveStartFragment.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Receive over Wi-Fi, start screen (modelled on Clone's Receive): join the sender's
* Wi-Fi, then scan the invite or enter it as text. A valid invite opens
* ContentReceiveFragment.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.presentation;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;

import org.appdevforall.k2go.R;
import org.appdevforall.k2go.contentexchange.data.ShareHandshake;
import org.appdevforall.k2go.redesign.CodeText;
import org.appdevforall.k2go.redesign.QrSection;
import org.appdevforall.k2go.util.Snackbars;

public class ContentReceiveStartFragment extends Fragment {

private static final String STATE_PASTE_OPEN = "pasteOpen";

private CodeText.PasteBlock pasteCode;
private ActivityResultLauncher<ScanOptions> inviteScan;

@Override
public void onCreate(@Nullable Bundle s) {
super.onCreate(s);
inviteScan = registerForActivityResult(new ScanContract(), r -> onInvite(r.getContents()));
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle s) {
View root = inflater.inflate(R.layout.fragment_k2go_content_receive_start, container, false);

QrSection.setStep(root.findViewById(R.id.k2go_cxst_join_hdr), "1", getString(R.string.k2go_cx_share_step_join));
QrSection.setStep(root.findViewById(R.id.k2go_cxst_receive_hdr), "2",
getString(R.string.k2go_cx_share_step_receive));
root.findViewById(R.id.k2go_cxst_wifi).setOnClickListener(v -> {
if (!CodeText.openWifiSettings(requireContext())) {
Snackbars.make(v, R.string.k2go_clone_toast_open_wifi).show();
}
});
root.findViewById(R.id.k2go_cxst_scan).setOnClickListener(
v -> inviteScan.launch(CodeText.scanOptions(getString(R.string.k2go_cx_receive_scan_prompt))));

pasteCode = new CodeText.PasteBlock(root, this::onInvite);
pasteCode.setExpanded(s != null && s.getBoolean(STATE_PASTE_OPEN));
pasteCode.show(true);
return root;
}

@Override
public void onSaveInstanceState(@NonNull Bundle out) {
super.onSaveInstanceState(out);
if (pasteCode != null) {
out.putBoolean(STATE_PASTE_OPEN, pasteCode.isExpanded());
}
}

/** A scanned or pasted invite. Null means the scan was cancelled; an invalid code is rejected. */
private void onInvite(@Nullable String contents) {
if (!isAdded() || contents == null) {
return;
}
ShareHandshake.ShareInvite invite = ShareHandshake.decode(contents);
if (invite == null) {
Snackbars.make(requireView(), R.string.k2go_cx_receive_invalid).show();
return;
}
requireActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.k2go_setup_host, ContentReceiveFragment.newInstance(invite))
.addToBackStack(null)
.commit();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Description : K2GO-376. Shows the Share invite: two stacked QR sections (join the hotspot, then
* scan to receive) once the sender foreground service has opened the share session and
* the hotspot is up. Reads state only (the ShareSession + the shared LocalHotspotManager
* state); all work is the service's. Done closes the gate + the hotspot via the service.
* state); all work is the service's. Done or Back closes the gate + the hotspot via the service.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.presentation;
Expand All @@ -18,6 +18,7 @@
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
Expand All @@ -28,9 +29,12 @@
import org.appdevforall.k2go.hotspot.HotspotPermissions;
import org.appdevforall.k2go.hotspot.LocalHotspotManager;
import org.appdevforall.k2go.hotspot.data.ApAddressResolver;
import org.appdevforall.k2go.redesign.CodeText;
import org.appdevforall.k2go.redesign.QrSection;
import org.appdevforall.k2go.redesign.SegmentedTabs;
import org.appdevforall.k2go.sync.transport.NetworkStateLiveData;
import org.appdevforall.k2go.ui.dialog.BrandDialog;
import org.appdevforall.k2go.util.ByteFormatter;

public class ContentShareFragment extends Fragment {

Expand All @@ -41,6 +45,11 @@ public class ContentShareFragment extends Fragment {
private View receiveRoot;
private QrSection secJoin;
private QrSection secReceive;
private View codeLabel;
private View codeBlock;
private TextView codeText;
/** The invite shown as text; Copy / Share hand out this exact payload. */
private String invitePayload = "";
private View transportRow;
private TextView transportHotspot;
private TextView transportWifi;
Expand Down Expand Up @@ -72,21 +81,41 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
R.id.sec_caption, R.id.sec_subcaption, R.id.sec_fallback_toggle, R.id.sec_fallback, R.id.sec_fallback_values);
secReceive = new QrSection(receiveRoot, R.id.sec_qr_frame, R.id.sec_qr, R.id.sec_qr_ph,
R.id.sec_caption, R.id.sec_subcaption, R.id.sec_fallback_toggle, R.id.sec_fallback, R.id.sec_fallback_values);
((TextView) joinRoot.findViewById(R.id.sec_badge)).setText("1");
((TextView) joinRoot.findViewById(R.id.sec_title)).setText(R.string.k2go_cx_share_step_join);
((TextView) receiveRoot.findViewById(R.id.sec_badge)).setText("2");
((TextView) receiveRoot.findViewById(R.id.sec_title)).setText(R.string.k2go_cx_share_step_receive);
QrSection.setStep(joinRoot, "1", getString(R.string.k2go_cx_share_step_join));

codeLabel = root.findViewById(R.id.k2go_code_label);
codeBlock = root.findViewById(R.id.k2go_code_block);
codeText = root.findViewById(R.id.k2go_code_text);
root.findViewById(R.id.k2go_code_copy).setOnClickListener(v -> CodeText.copy(v, invitePayload));
root.findViewById(R.id.k2go_code_share).setOnClickListener(v -> CodeText.share(requireContext(), invitePayload));

transportRow = root.findViewById(R.id.k2go_cxs_transport);
transportHotspot = root.findViewById(R.id.k2go_cxs_transport_hotspot);
transportWifi = root.findViewById(R.id.k2go_cxs_transport_wifi);
transportHotspot.setOnClickListener(v -> selectTransport(false));
transportWifi.setOnClickListener(v -> selectTransport(true));

done.setOnClickListener(v -> {
ContentShareService.cancel(requireContext());
goBack();
});
done.setOnClickListener(v -> stopAndLeave());
// Back ends the share like Done (a share left running would make the next Share reopen it
// instead of the new selection), but asks first, as Clone does: Back is easy to hit mid-transfer.
requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(),
new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (session.hasError()) {
stopAndLeave(); // nothing is being sent
return;
}
new BrandDialog(requireContext())
.setTitle(R.string.k2go_clone_stopshare_title)
// Own message, not Clone's "can start again": resume is not
// guaranteed for every app yet (K2GO-577 covers ZIM only).
.setMessage(R.string.k2go_cx_share_stop_msg)
.setNegative(R.string.k2go_cancel, null)
.setDestructive(R.string.k2go_clone_stop_confirm, () -> stopAndLeave())
.show();
}
});
// The AP IPv4 lands a beat after the hotspot reports ON; re-render when it (or the phase) changes
// so the receive QR appears the moment every piece is ready. Observed once, tied to the view.
hs.state().observe(getViewLifecycleOwner(), st -> render());
Expand Down Expand Up @@ -137,7 +166,9 @@ private void render() {
goBack();
return;
}
subtitle.setText(getString(R.string.k2go_cx_share_subtitle_fmt, session.itemCount()));
// Same "N selected : size" line Content manager showed before Share.
subtitle.setText(getString(R.string.k2go_cx_selected_fmt, session.itemCount(),
ByteFormatter.humanBytes(session.totalBytes())));

if (session.hasError()) {
showStatus(session.errorMessage() != null
Expand Down Expand Up @@ -179,6 +210,7 @@ private void renderInvite() {
}
transportRow.setVisibility(View.GONE);
waiting.setVisibility(View.GONE);
showInviteText(null);
return;
}

Expand All @@ -201,6 +233,7 @@ private void renderInvite() {
SegmentedTabs.paint(transportWifi, useWifiAddress);
}
joinRoot.setVisibility(both && useWifiAddress ? View.GONE : View.VISIBLE);
numberSteps();
String ip = both ? (useWifiAddress ? wifiIp : hotspotIp)
: (hotspotIp != null ? hotspotIp : wifiIp);

Expand All @@ -212,7 +245,6 @@ private void renderInvite() {
getString(R.string.k2go_fallback_wifi, ssid), getString(R.string.k2go_fallback_pass, pass)});

// Section 2: the share invite QR. Needs the AP IPv4, which resolves a beat after ON.
secReceive.caption.setText(R.string.k2go_cx_share_receive_caption);
secReceive.subCaption.setText("");
// The core returns its own path (/v1/share/<id>/manifest); the receiver reaches it through
// the off-box gate prefix, so the invite carries the prefixed path.
Expand All @@ -223,13 +255,24 @@ private void renderInvite() {
if (invite == null) {
// No dead QR at a guessed address; hold the slot until the real AP IP arrives (render reruns).
secReceive.setQrPending(requireContext(), getString(R.string.k2go_cx_share_resolving_address));
secReceive.caption.setText(""); // no "Ready! Scan" until there is a QR to scan
secReceive.setFallback(requireContext(), null);
waiting.setVisibility(View.GONE);
} else {
secReceive.setQr(requireContext(), invite, null);
secReceive.setFallback(requireContext(), null);
waiting.setVisibility(View.VISIBLE);
}
showInviteText(invite);
}

/** Show the invite as copyable text under the QR, or hide the block when there is no invite. */
private void showInviteText(@Nullable String invite) {
invitePayload = invite != null ? invite : "";
codeText.setText(invitePayload);
int vis = invite != null ? View.VISIBLE : View.GONE;
codeLabel.setVisibility(vis);
codeBlock.setVisibility(vis);
}

/** Pick the address the receive QR carries and repaint the strip (Connect/Clone mode pattern). */
Expand All @@ -251,12 +294,27 @@ private void showStatus(String text) {
receiveRoot.setVisibility(View.GONE);
transportRow.setVisibility(View.GONE);
waiting.setVisibility(View.GONE);
showInviteText(null);
}

private void showSections() {
status.setVisibility(View.GONE);
joinRoot.setVisibility(View.VISIBLE);
receiveRoot.setVisibility(View.VISIBLE);
numberSteps();
}

/** Number the steps the user sees: with the join step hidden (Wi-Fi transport), the invite is 1.
* The caption is Clone's one-code / two-code wording. */
private void numberSteps() {
boolean joinShown = joinRoot.getVisibility() == View.VISIBLE;
QrSection.setStep(receiveRoot, joinShown ? "2" : "1", getString(R.string.k2go_cx_action_share));
secReceive.caption.setText(joinShown ? R.string.k2go_clone_ready_scan2 : R.string.k2go_clone_ready_scan);
}

private void stopAndLeave() {
ContentShareService.cancel(requireContext());
goBack();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public final class ContentShareService extends Service {

public static final String EXTRA_APPS = "apps";
public static final String EXTRA_LOCAL_REFS = "localRefs";
public static final String EXTRA_TOTAL_BYTES = "totalBytes";

private static final String CHANNEL_ID = "content_share_channel";
private static final int NOTIFICATION_ID = NotificationIds.CONTENT_SHARE;
Expand All @@ -70,7 +71,7 @@ static ShareSession session() {

// ---- static control surface (the fragment calls these) -------------------------------------

public static void start(Context ctx, ItemRef[] refs) {
public static void start(Context ctx, ItemRef[] refs, long totalBytes) {
String[] apps = new String[refs.length];
String[] locals = new String[refs.length];
for (int i = 0; i < refs.length; i++) {
Expand All @@ -79,7 +80,8 @@ public static void start(Context ctx, ItemRef[] refs) {
}
Intent i = new Intent(ctx, ContentShareService.class).setAction(ACTION_START)
.putExtra(EXTRA_APPS, apps)
.putExtra(EXTRA_LOCAL_REFS, locals);
.putExtra(EXTRA_LOCAL_REFS, locals)
.putExtra(EXTRA_TOTAL_BYTES, totalBytes);
ContextCompat.startForegroundService(ctx, i);
}

Expand Down Expand Up @@ -137,7 +139,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
stopSelf();
return START_NOT_STICKY;
}
SESSION.beginPreparing(refs.length);
SESSION.beginPreparing(refs.length, intent.getLongExtra(EXTRA_TOTAL_BYTES, 0L));
startForeground(NOTIFICATION_ID, buildNotification());
acquireHardwareLocks();
ensureHotspot();
Expand Down
Loading
Loading