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
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ members = ["crates/net", "crates/core", "crates/ffi", "apps/desktop/src-tauri"]
exclude = ["spike"]

[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2021"
rust-version = "1.95"
license = "Apache-2.0"
Expand All @@ -13,7 +13,7 @@ authors = ["Nigel Scott"]
[workspace.dependencies]
# iroh: default-features = false drops "portmapper" (UPnP/NAT-PMP), "metrics" and
# "fast-apple-datapath". Only "tls-ring" (the mandatory crypto provider) is enabled.
# Versions pinned exactly: the M0 spike proved this pair (spike/RESULTS.md).
# Versions pinned exactly: this pair was tested together.
iroh = { version = "=1.4.1", default-features = false, features = ["tls-ring"] }
iroh-mdns-address-lookup = "=0.6.1"
n0-future = "0.3.2"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ To test the build on GitHub without a tag, run the workflow manually (Actions, R
Needs Bun and Rust (see `RUST_VERSION` and `BUN_VERSION` in the release workflow for the pinned versions).

- Windows: also needs the Visual Studio C++ Build Tools (MSVC Rust target). In `apps/desktop` run `bun install`, then `bun run tauri build`. The installer lands in `target/release/bundle/nsis`.
- Android: needs the Android SDK with platform 37 (Gradle finds it through `ANDROID_HOME` or `sdk.dir` in `apps/android/local.properties`; Android Studio's SDK Manager installs it), the Rust targets `aarch64-linux-android` and `x86_64-linux-android`, `cargo-ndk`, NDK 30.0.16248370 (`ANDROID_NDK_HOME`, the default used by `build-rust.cmd`) and JDK 17. Run `apps/android/build-rust.cmd`, then `gradlew.bat bundleRelease` in `apps/android`. The bundle is unsigned: sign it before uploading to Google Play.
- Android: needs the Android SDK with platform 37 (Gradle finds it through `ANDROID_HOME` or `sdk.dir` in `apps/android/local.properties`; Android Studio's SDK Manager installs it), the Rust targets `aarch64-linux-android` and `x86_64-linux-android`, `cargo-ndk`, NDK 30.0.16248370 (`ANDROID_NDK_HOME`, the default used by `build-rust.cmd`) and JDK 17. Run `apps/android/build-rust.cmd` (it builds the Windows host library first, so the Visual Studio C++ Build Tools are needed here too), then `gradlew.bat bundleRelease` in `apps/android`. The bundle is unsigned: sign it before uploading to Google Play.

## Licence

Expand Down
40 changes: 26 additions & 14 deletions apps/android/FFI.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Generated by UniFFI 0.32.2 from `crates/ffi` into
native library `libtugboat_ffi.so`, loaded by JNA as `tugboat_ffi`). Never edit the .kt file:
`apps\android\build-rust.cmd` regenerates it. This page lists the API exactly as generated.

Gradle needs: `net.java.dev.jna:jna:5.17.0@aar` (the spike's proven setup). The bindings use no
Gradle needs: `net.java.dev.jna:jna:5.17.0@aar` (the version the bindings were built against). The bindings use no
coroutines. `.so` files: `app/src/main/jniLibs/arm64-v8a` and `x86_64`, only `libtugboat_ffi.so`.

## Rules for calling it
Expand Down Expand Up @@ -85,7 +85,7 @@ throw; every other method carries `@Throws(SnapException::class)` in the generat
| `open` | Logging, database (backup, migrate; a newer database is refused with `NewerDatabase`), default folders Inbox / Keep / Unsorted, one Bin sweep, event pump, ticker (Bin sweep and pairing expiry at the core's next due time, at most 60 s apart). Does not touch the network. |
| `deviceId` | This phone's public key, 64 hex chars. |
| `logPath` | Current log file. `<path>.1` and `<path>.2` are the older rotated files (5 MB each, three kept). "Export log" shares all that exist, oldest first. |
| `freeSpaceBytes` | Free bytes on the volume holding phone copies, for the storage guard banner against `Settings.storageGuardBytes`. Core does not enforce the guard yet (M4): the banner is the app's. |
| `freeSpaceBytes` | Free bytes on the volume holding phone copies. Used for Settings' storage line and for refusing a shared file that does not fit. The storage guard itself is enforced by the core since 0.2.0 (downloads stop below `Settings.storageGuardBytes`); the banner follows `SyncStatus.storageLow`, not this number. |
| `startNetwork(mdns)` | Starts the endpoint (binds `0.0.0.0`, random UDP port) and the connect loop to the paired PC (cached addresses first, `mdns` = then look it up by name). `Invalid` if already started. |
| `stopNetwork` | Stops it. |
| `reconnectNow` | Wi-Fi changed or app came to the front: dial the PC now instead of waiting out the back-off (up to 30 s). Safe any time. |
Expand All @@ -106,8 +106,8 @@ throw; every other method carries `@Throws(SnapException::class)` in the generat
| `activity(before, limit)` | Newest first. `before` = last `id` of the previous page. |
| `settings` / `saveSettings` | Values are validated by core (`Invalid` for nonsense, the old value stays). |

Not exported (not an M3 screen): creating, renaming and deleting folders, retention changes and
places editing (`put_place`). Add them as thin passthroughs in M4.
Not exported yet: creating, renaming and deleting folders, retention changes and places editing
(`put_place`). Add them as thin passthroughs when a screen needs them.

## Data types

Expand Down Expand Up @@ -169,11 +169,11 @@ data class PairingPreview(

data class NewFile(
var srcPath: kotlin.String, // file the app owns; core copies it, the caller deletes it
var name: kotlin.String, // display name; extension and magic bytes must agree
var name: kotlin.String, // display name. Any type: a photo/video extension must match its bytes, every other name (or none) is a plain File. Shortcut and folder-setting names are refused
var folderId: kotlin.String?, // null = Inbox
var capturedAtMs: kotlin.Long,
var geo: GeoFix?,
var thumbPath: kotlin.String?, // JPEG, longest side 512 px, made by the app
var thumbPath: kotlin.String?, // JPEG, longest side 512 px, made by the app. Photos and videos only: the core ignores it for a File
var imported: kotlin.Boolean // false = camera shot, true = Share > Tugboat
)

Expand All @@ -188,8 +188,9 @@ data class SyncStatus(
var state: SyncState,
var peerName: kotlin.String?,
var lastSyncedAt: kotlin.Long?, // unix ms, "Synced 10s ago"
var waiting: kotlin.UInt, // items waiting for the PC's receipt ("3 waiting")
var downloading: kotlin.UInt,
var waiting: kotlin.UInt, // held here, not in the Bin, no receipt from the PC yet ("3 waiting"); nothing is held back for it: items expire on time
var downloading: kotlin.UInt, // items that wait on the PC (Pending here)
var storageLow: kotlin.Boolean, // 0.2.0: the storage guard is holding downloads back (red banner: "PHONE STORAGE LOW - 37 items wait on the PC")
var message: kotlin.String? // one line for REFUSED / PAUSED / "PC NOT TOLD YET ..."
)

Expand All @@ -206,7 +207,7 @@ data class Settings(

```kotlin
enum class FolderKind { INBOX, KEEP, UNSORTED, USER }
enum class MediaKind { IMAGE, VIDEO }
enum class MediaKind { IMAGE, VIDEO, FILE } // FILE (0.2.0) = any other file type: icon tile, no thumbnail
enum class LocalFileState { PENDING, PRESENT, BINNED, PURGED, LOST, REFUSED }
enum class SyncState { UNPAIRED, OFFLINE, CONNECTING, SYNCING, SYNCED, PAUSED, REFUSED }
enum class ActivityAction {
Expand All @@ -220,7 +221,6 @@ sealed class ItemStateInfo {
data class Expired(val binnedAtMs: kotlin.Long) : ItemStateInfo() // in the Bin, expired
object Kept : ItemStateInfo() // pinned: "Kept"
object FolderKeep : ItemStateInfo() // folder never expires: "Keep"
object Waiting : ItemStateInfo() // PC has not confirmed the file: "Waiting for PC"
data class Live(val expiresAtMs: kotlin.Long) : ItemStateInfo() // "Expires in 5h"
}

Expand Down Expand Up @@ -274,7 +274,8 @@ sealed class SnapException(message: String) : kotlin.Exception(message) {
class NotFound(message: String)
class InvalidName(message: String)
class Invalid(message: String) // rule broken: unknown/deleted folder, restore of a non-Bin item, bad setting
class NotMedia(message: String) // not a supported photo/video (extension or magic bytes)
class NotMedia(message: String) // a photo/video extension whose bytes are not one (an exe renamed .jpg)
class Refused(message: String) // 0.2.0: always-refused name (.lnk .url .scf .library-ms .searchConnector-ms, desktop.ini, autorun.inf) or over 16 GB
class FileGone(message: String)
class NotPaired(message: String)
class AlreadyPaired(message: String)
Expand All @@ -296,16 +297,27 @@ sealed class SnapException(message: String) : kotlin.Exception(message) {
class Pairing(message: String) // any other pairing failure
}
```
Onboarding mapping: `PairBadPayload` = "That is not a Tugboat code"; `PairExpired` = show a new
QR on the PC; `PairSecretReused` = "already used"; `NetTimeout` / `NetUnreachable` =
Onboarding mapping: `PairBadPayload` = "That is not a Tugboat code" (only this); `PairExpired` = the core's
"PAIRING CODE EXPIRED - show a new QR". The PC opens a NEW pairing window when the old one runs out, so
an old QR can also come back as `PairBadSecret` or `PairNotOpen`: the app reads the payload's expiry
(`inspectPairingPayload`, before dialing) and shows the expired text when its time has passed by the
phone's clock (`Texts.pairFailure(..., codeExpired)`); `PairSecretReused` = "already used"; `NetTimeout` / `NetUnreachable` =
"PC not found: same Wi-Fi? Local network allowed?"; `PairConfirmTimeout`, `PairCancelled` =
retry.

Typed checks pinned by `crates/ffi/tests/phone_flow.rs`: `addFile` of a missing file is `Io`
(message names the file), of an exe renamed `.jpg` is `NotMedia`, into an unknown folder is
(message names the file), of an exe renamed `.jpg` is `NotMedia`, of `x.lnk` is `Refused`, into an unknown folder is
`Invalid`; a malformed id is `InvalidInput`; junk to `pairWith` is `PairBadPayload`; `unpair`
with nothing paired is `NotPaired`; `saveSettings` with `binDays = 0` is `Invalid`.

## Name rules (0.2.0)

Top-level functions, the same code the PC runs, so the app keeps no copy of the rules:
`namesExtOf(name)` (lowercase extension or ""), `namesIsRefused(name)`, `namesRefusedText()`.
`ShareNames` calls them through the `NameRules` interface (a JVM test cannot load the .so, so tests
pass a stand-in). `ItemInfo.neverReachedPeer` = in the Bin because it expired before the PC confirmed it
(shown as "NOT ON PC").

## Build

`apps\android\build-rust.cmd` (cmd.exe, from anywhere): host build with the bindgen binary,
Expand Down
4 changes: 2 additions & 2 deletions apps/android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ android {
applicationId = providers.gradleProperty("tugboat.applicationId").get()
minSdk = 31
targetSdk = 37
versionCode = 3
versionName = "0.1.1"
versionCode = 5
versionName = "0.2.0"
// Only the two ABIs build-rust.cmd produces: arm64-v8a (phone) and x86_64 (emulator).
ndk { abiFilters += listOf("arm64-v8a", "x86_64") }
}
Expand Down
14 changes: 7 additions & 7 deletions apps/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@
</intent-filter>
</activity>

<!-- Share > Tugboat. Photos and videos only in 0.1.0 (checked again by magic bytes). -->
<!-- Share > Tugboat. Any file type since 0.2.0. Photos and videos are still checked by magic bytes; shortcut
and folder-setting files are refused (ShareNames, then the core); only content:// streams are read. -->
<activity
android:name=".ShareActivity"
android:exported="true"
Expand All @@ -69,14 +70,12 @@
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
<data android:mimeType="*/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>

Expand All @@ -95,7 +94,7 @@
</intent-filter>
</receiver>

<!-- PLAN: no telemetry, no outbound internet traffic. ML Kit barcode scanning pulls in the
<!-- No telemetry and no outbound internet traffic. ML Kit barcode scanning pulls in the
datatransport library, whose "cct" backend uploads usage analytics to Google. Without
the backend the library has nowhere to send, and its scheduler pieces have nothing to run. -->
<service
Expand All @@ -108,8 +107,9 @@
android:name="com.google.android.datatransport.runtime.scheduling.jobscheduling.AlarmManagerSchedulerBroadcastReceiver"
tools:node="remove" />

<!-- ItemFileProvider = FileProvider that tells other apps a held file's real name (not <uuid>.ext). -->
<provider
android:name="androidx.core.content.FileProvider"
android:name=".ItemFileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
Expand Down
4 changes: 2 additions & 2 deletions apps/android/app/src/main/java/app/localtugboat/Background.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ object ServiceGate {
val core = c.applicationContext.core
val wanted = wanted(c, why)
KLog.log(c, "start check ($why): wanted=$wanted running=${core.serviceRunning}")
if (wanted && !core.serviceRunning) SnapService.start(c)
if (wanted && !core.serviceRunning) SnapService.start(c, why)
return wanted
}
}
Expand Down Expand Up @@ -75,7 +75,7 @@ class CatchUpWorker(c: Context, p: WorkerParameters) : CoroutineWorker(c, p) {
if (p.settings().stayConnected && !core.serviceRunning) {
if (Perms.batteryExempt(app)) {
KLog.log(app, "worker: service not running, restarting it")
SnapService.start(app)
SnapService.start(app, "worker")
} else {
KLog.log(app, "worker: service not running and not exempt from battery optimisation, cannot restart it")
}
Expand Down
12 changes: 12 additions & 0 deletions apps/android/app/src/main/java/app/localtugboat/CameraScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,15 @@ fun CameraScreen(vm: SnapViewModel, ui: UiState, banners: List<UiLogic.BannerUi>

LightSystemIcons()

// Rotating the phone recreates the activity (no configChanges), which unbinds CameraX and ends the recording.
// So the orientation is locked for exactly as long as a recording runs, and released the moment it ends or the screen leaves.
val activity = androidx.activity.compose.LocalActivity.current
val isRecording = recording != null
DisposableEffect(isRecording, activity) {
if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(true)
onDispose { if (isRecording) activity?.requestedOrientation = UiLogic.recordingOrientation(false) }
}

// Location only while this screen is visible (while-in-use permission, never background).
LifecycleResumeEffect(tracker) {
tracker.start()?.let { KLog.log(ctx, "location not started: $it") }
Expand Down Expand Up @@ -327,6 +336,9 @@ fun CameraScreen(vm: SnapViewModel, ui: UiState, banners: List<UiLogic.BannerUi>
is VideoRecordEvent.Status -> recordMs.longValue = ev.recordingStats.recordedDurationNanos / 1_000_000
is VideoRecordEvent.Finalize -> {
recording = null
// Released here, not only when the effect above disposes: that waits for a recomposition, which
// does not come while the app is stopped (and never, if the process is killed meanwhile).
activity?.requestedOrientation = UiLogic.recordingOrientation(false)
if (ev.hasError()) {
// The file is still handed over when it has content: the core checks it, a recording is never thrown away here.
ctx.core.reportError("video: error ${ev.error} ${ev.cause?.message.orEmpty()}")
Expand Down
25 changes: 25 additions & 0 deletions apps/android/app/src/main/java/app/localtugboat/Components.kt
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,31 @@ fun ThumbImage(path: String?, desc: String?, modifier: Modifier = Modifier, scal
}
}

@DrawableRes
fun fileIcon(ext: String): Int = when (FileRules.glyph(ext)) {
FileGlyph.DOCUMENT -> R.drawable.ic_file_doc
FileGlyph.ARCHIVE -> R.drawable.ic_file_archive
FileGlyph.AUDIO -> R.drawable.ic_file_audio
FileGlyph.OTHER -> R.drawable.ic_file
}

/** What a file that is not a photo or video shows where a thumbnail would be: type icon, name, "PDF, 1.2 MB". */
@Composable
fun FileFace(item: uniffi.tugboat_ffi.ItemInfo, modifier: Modifier = Modifier) {
val cs = MaterialTheme.colorScheme
Column(
modifier.background(cs.surfaceVariant).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 30.dp),
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
) {
Ico(fileIcon(item.ext), null, tint = cs.onSurfaceVariant, size = 28)
Text(
FileRules.displayName(item.name, item.ext), style = MaterialTheme.typography.labelMedium, color = cs.onSurface,
maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = androidx.compose.ui.text.style.TextAlign.Center,
)
Text(FileRules.meta(item.ext, item.size.toLong()), style = MaterialTheme.typography.labelSmall, color = cs.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}

/**
* Bottom sheet to pick a folder. [autoLabel] non-null adds a first row (the rule-based choice).
* [currentId] gets a check mark and a "Current" word, so the choice is not colour or icon alone.
Expand Down
7 changes: 6 additions & 1 deletion apps/android/app/src/main/java/app/localtugboat/Core.kt
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ class Core(private val app: Application) {
// Runs on a Rust runtime thread: record and return, never call back into the core.
when (event) {
is FfiEvent.Sync -> _status.value = event.status
is FfiEvent.Error -> reportError("${event.kind}: ${event.message}")
// The storage guard already has its own red banner (status.storageLow, with the count): a second amber one
// with the raw "storage_low:" text only repeats it and outlives it. It stays in the log.
is FfiEvent.Error -> if (event.kind == STORAGE_LOW_KIND) KLog.log(app, "core: ${event.kind}: ${event.message}") else reportError("${event.kind}: ${event.message}")
else -> {}
}
_events.tryEmit(event)
Expand Down Expand Up @@ -196,5 +198,8 @@ class Core(private val app: Application) {
companion object {
const val BURST_MS = 30_000L
const val PAUSE_MS = 120_000L

/** FfiEvent.Error kind the core uses when the storage guard turns on (the banner shows it already). */
const val STORAGE_LOW_KIND = "storage_low"
}
}
Loading