android: stop threading nativeLib through every screen

With NativeLib an object, the ~60 nativeLib parameters and the ~100
arguments passing it down — from MainActivity through each screen, its
sections, its repositories and its helpers — carried nothing a call to
NativeLib doesn't. They go, along with the repositories' now-empty
constructors. (F2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 5.5 committed 2026-09-29 03:36:46 -07:00
1 parent 88146069a4
commit 6e7e77de31
45 files changed
+329 -544

No files matched your search

@@ -17,12 +17,10 @@ import uniffi.synchronicity.getAgents
* App-level state for the root composable: opening the shared native store, loading the agent
* registry, and the initial node-initialized routing decision.
*
* This owns the process-wide [NativeLib] handle and runs the blocking store init off the main
* thread in [viewModelScope], so the work survives configuration changes instead of restarting on
* every recomposition.
* It runs the blocking [NativeLib] store init off the main thread in [viewModelScope], so the work
* survives configuration changes instead of restarting on every recomposition.
*/
class AppViewModel(application: Application) : AndroidViewModel(application) {
val nativeLib = NativeLib
private val _uiState = MutableStateFlow<AppUiState>(AppUiState.Loading)
val uiState: StateFlow<AppUiState> = _uiState.asStateFlow()
@@ -34,7 +32,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
// must route to the Error screen rather than crash the process.
@Suppress("TooGenericExceptionCaught")
try {
withContext(Dispatchers.IO) { nativeLib.initialize(getApplication()) }
withContext(Dispatchers.IO) { NativeLib.initialize(getApplication()) }
} catch (e: Throwable) {
Log.e(TAG, "Failed to initialize store", e)
_uiState.value = AppUiState.Error(e.userMessage)
@@ -55,8 +53,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
}
val nodeInitialized =
nativeLib
.ffi { nodeInitialized() }
NativeLib.ffi { nodeInitialized() }
.getOrElse { e ->
Log.e(TAG, "Failed to check node initialization status", e)
false
@@ -127,7 +127,7 @@ fun AppScreen(modifier: Modifier = Modifier, viewModel: AppViewModel = viewModel
) {}
}
is AppUiState.Error -> StoreInitErrorScreen(state.message, modifier = modifier)
is AppUiState.Ready -> AppContent(viewModel.nativeLib, state, modifier = modifier)
is AppUiState.Ready -> AppContent(state, modifier = modifier)
}
}
@@ -164,21 +164,17 @@ private fun StoreInitErrorScreen(message: String, modifier: Modifier = Modifier)
}
@Composable
private fun AppContent(
nativeLib: NativeLib,
state: AppUiState.Ready,
modifier: Modifier = Modifier,
) {
private fun AppContent(state: AppUiState.Ready, modifier: Modifier = Modifier) {
val context = LocalContext.current
val navController = rememberNavController()
val themeState = rememberThemeState(nativeLib)
val themeState = rememberThemeState()
// When the node already exists we boot straight into Main, so make sure the P2P
// foreground service is running for that path. The init-complete and settings-reset
// paths start/stop it themselves.
LaunchedEffect(Unit) {
if (state.nodeInitialized) {
startNodeServices(context, nativeLib)
startNodeServices(context)
}
}
@@ -218,7 +214,6 @@ private fun AppContent(
AppNavHost(
navController = navController,
startDestination = startDestination,
nativeLib = nativeLib,
state = state,
themeState = themeState,
)
@@ -240,7 +235,6 @@ private fun AppContent(
private fun AppNavHost(
navController: NavHostController,
startDestination: Any,
nativeLib: NativeLib,
state: AppUiState.Ready,
themeState: ThemeState,
) {
@@ -249,12 +243,11 @@ private fun AppNavHost(
composable<InitializationRoute> {
InitializationNavigation(
onInitializationComplete = {
startNodeServices(context, nativeLib)
startNodeServices(context)
navController.navigate(MainRoute) {
popUpTo(InitializationRoute) { inclusive = true }
}
},
nativeLib = nativeLib,
}
)
}
composable<MainRoute> {
@@ -268,7 +261,6 @@ private fun AppNavHost(
val agentId = AgentId.valueOf(backStackEntry.toRoute<AgentRoute>().agentId)
AgentDestination(
agentId = agentId,
nativeLib = nativeLib,
themeState = themeState,
onBack = { navController.popBackStack() },
onOpenHuman = { humanId -> navController.navigate(HumanDetailRoute(humanId)) },
@@ -290,8 +282,7 @@ private fun AppNavHost(
}
composable<RetirementRoute> {
RetirementScreen(
nativeLib = nativeLib,
nodeName = remember { nativeLib.nodeName().orEmpty() }.ifEmpty { "this node" },
nodeName = remember { NativeLib.nodeName().orEmpty() }.ifEmpty { "this node" },
onFinish = {
navController.navigate(InitializationRoute) {
popUpTo(RetirementRoute) { inclusive = true }
@@ -302,7 +293,6 @@ private fun AppNavHost(
composable<HumanDetailRoute> { backStackEntry ->
HumanDetailScreen(
humanId = backStackEntry.toRoute<HumanDetailRoute>().humanId,
nativeLib = nativeLib,
onBack = { navController.popBackStack() },
)
}
@@ -316,7 +306,6 @@ private fun AppNavHost(
@Composable
private fun AgentDestination(
agentId: AgentId,
nativeLib: NativeLib,
themeState: ThemeState,
onBack: () -> Unit,
onOpenHuman: (String) -> Unit,
@@ -324,32 +313,30 @@ private fun AgentDestination(
onRetire: () -> Unit,
) {
when (agentId) {
AgentId.NOTES -> NotesScreen(nativeLib = nativeLib, onBack = onBack)
AgentId.NOTES -> NotesScreen(onBack = onBack)
AgentId.PDF_VIEWER -> PdfScreen(onBackToMain = onBack)
AgentId.PODCASTS -> PodcastScreen(nativeLib = nativeLib, onBackToMain = onBack)
AgentId.PODCASTS -> PodcastScreen(onBackToMain = onBack)
AgentId.DOCUMENTS -> DocumentsScreen(onBackToMain = onBack)
AgentId.MUSIC -> MusicScreen(onBack = onBack)
AgentId.COMICS -> ComicsScreen(nativeLib = nativeLib, onBack = onBack)
AgentId.COMICS -> ComicsScreen(onBack = onBack)
AgentId.CODE -> CodeScreen(onBack = onBack)
AgentId.PICTURES -> PicturesScreen(nativeLib = nativeLib, onBack = onBack)
AgentId.PICTURES -> PicturesScreen(onBack = onBack)
AgentId.VIDEO -> VideoScreen(onBack = onBack)
AgentId.POMODORO_TIMER -> PomodoroTimerScreen(onBack = onBack)
AgentId.HUMANS ->
HumansScreen(nativeLib = nativeLib, onOpenHuman = onOpenHuman, onBack = onBack)
AgentId.HUMANS -> HumansScreen(onOpenHuman = onOpenHuman, onBack = onBack)
AgentId.QR_CODE -> QrCodeScreen(onBack = onBack)
AgentId.JOBS -> JobsScreen(nativeLib = nativeLib, onBack = onBack)
AgentId.CLIPPINGS -> ClippingsScreen(nativeLib = nativeLib, onBack = onBack)
AgentId.JOBS -> JobsScreen(onBack = onBack)
AgentId.CLIPPINGS -> ClippingsScreen(onBack = onBack)
// The Ensemble and Settings buttons both open the settings screen; the Ensemble button
// just lands on its Ensemble section.
AgentId.ENSEMBLE,
AgentId.SETTINGS ->
SettingsScreen(
themeState = themeState,
nativeLib = nativeLib,
initialSection =
if (agentId == AgentId.ENSEMBLE) SettingsSection.ENSEMBLE
else SettingsSection.SYSTEM,
onBackToMain = { backToMainAfterSettings(nativeLib, onBack, onNodeReset) },
onBackToMain = { backToMainAfterSettings(onBack, onNodeReset) },
onRetire = onRetire,
)
}
@@ -359,14 +346,9 @@ private fun AgentDestination(
* Routes back from the settings screen. The node may have been reset from the System section, so
* re-check initialization status and fall back to the initialization flow when it's gone.
*/
private fun backToMainAfterSettings(
nativeLib: NativeLib,
onBack: () -> Unit,
onNodeReset: () -> Unit,
) {
private fun backToMainAfterSettings(onBack: () -> Unit, onNodeReset: () -> Unit) {
val initialized =
nativeLib
.ffi { nodeInitialized() }
NativeLib.ffi { nodeInitialized() }
.getOrElse { e ->
Log.e("AppContent", "Failed to check node initialization status after settings", e)
false
@@ -379,10 +361,9 @@ private fun backToMainAfterSettings(
* background sync scheduler's periodic `WorkManager` tick (re-enqueued with this node's current
* scheduler settings, since that tick depends on P2P coming up the same way).
*/
private fun startNodeServices(context: Context, nativeLib: NativeLib) {
private fun startNodeServices(context: Context) {
context.startForegroundService(Intent(context, P2PService::class.java))
nativeLib
.ffi { settings().getSchedulerSettings() }
NativeLib.ffi { settings().getSchedulerSettings() }
.onSuccess { settings -> SchedulerWorker.schedule(context, settings) }
.onFailure { Log.w("AppContent", "Failed to load scheduler settings", it) }
}
@@ -60,14 +60,14 @@ object NodeReset {
* thread for as long as it takes, so it goes to [Dispatchers.IO]; the audio transport is a
* Media3 `MediaController`, which may only be touched from the main thread.
*/
suspend fun perform(context: Context, nativeLib: NativeLib): Result<Unit> =
suspend fun perform(context: Context): Result<Unit> =
withContext(NonCancellable) {
val app = context.applicationContext
withContext(Dispatchers.Main) { AudioPlayerProvider.release(app) }
SchedulerWorker.cancel(app)
val wiped = withContext(Dispatchers.IO) { nativeLib.ffi { resetNode() } }
val wiped = withContext(Dispatchers.IO) { NativeLib.ffi { resetNode() } }
app.stopService(Intent(app, P2PService::class.java))
withContext(Dispatchers.IO) { clearCaches(app) }
@@ -73,11 +73,11 @@ object StoreChanges {
* The latest cursor, or `null` until the first one has been read. Screens collect this through
* [OnStoreChange] rather than directly.
*/
fun cursor(nativeLib: NativeLib): StateFlow<ChangeCursor?> =
fun cursor(): StateFlow<ChangeCursor?> =
shared
?: synchronized(lock) {
shared
?: watch(nativeLib)
?: watch()
.stateIn(scope, SharingStarted.WhileSubscribed(LINGER_MS), null)
.also { shared = it }
}
@@ -88,20 +88,20 @@ object StoreChanges {
* The first emission is the cursor as of starting, which is what the screens are already at —
* so [OnStoreChange] never treats it as a change and nothing reloads what it just read.
*/
private fun watch(nativeLib: NativeLib): Flow<ChangeCursor> = flow {
var since = readCursor(nativeLib)
private fun watch(): Flow<ChangeCursor> = flow {
var since = readCursor()
emit(since)
while (currentCoroutineContext().isActive) {
val woken =
withContext(Dispatchers.IO) {
nativeLib.ffi { changes().wait(since, WAIT_TIMEOUT_MS.toULong()) }
NativeLib.ffi { changes().wait(since, WAIT_TIMEOUT_MS.toULong()) }
}
val next = woken.getOrNull()
if (next == null) {
delay(RETRY_DELAY_MS)
continue
}
since = settle(nativeLib, next)
since = settle(next)
emit(since)
}
}
@@ -113,9 +113,9 @@ object StoreChanges {
* quiet, and a screen that stopped updating until it did would be worse than one updating a few
* times a second. A read that fails here just reports what woke us.
*/
private suspend fun settle(nativeLib: NativeLib, woken: ChangeCursor): ChangeCursor {
private suspend fun settle(woken: ChangeCursor): ChangeCursor {
delay(COALESCE_MS)
return withContext(Dispatchers.IO) { nativeLib.ffi { changes().cursor() } }
return withContext(Dispatchers.IO) { NativeLib.ffi { changes().cursor() } }
.getOrDefault(woken)
}
@@ -125,10 +125,10 @@ object StoreChanges {
* A screen can be composed before onboarding has opened a store, and the answer to that is to
* wait for one rather than to leave this collector with no signal for as long as it lives.
*/
private suspend fun readCursor(nativeLib: NativeLib): ChangeCursor {
private suspend fun readCursor(): ChangeCursor {
while (true) {
val cursor =
withContext(Dispatchers.IO) { nativeLib.ffi { changes().cursor() } }.getOrNull()
withContext(Dispatchers.IO) { NativeLib.ffi { changes().cursor() } }.getOrNull()
if (cursor != null) return cursor
delay(RETRY_DELAY_MS)
}
@@ -148,12 +148,8 @@ object StoreChanges {
* the user is pointing at is alerted, not rewritten underneath them.
*/
@Composable
fun OnStoreChange(
nativeLib: NativeLib,
vararg channels: ChangeChannel,
onChange: suspend () -> Unit,
) {
val cursor by StoreChanges.cursor(nativeLib).collectAsState()
fun OnStoreChange(vararg channels: ChangeChannel, onChange: suspend () -> Unit) {
val cursor by StoreChanges.cursor().collectAsState()
val applied = remember { mutableStateOf<ChangeCursor?>(null) }
// The effect restarts on a new cursor, not on a new lambda, so a screen whose reload closes
// over state that has since moved — "is this list settled?" — would otherwise act on the
@@ -178,9 +174,9 @@ fun OnStoreChange(
* the watch is scoped to composition, so a screen off the back stack re-reads nothing.
*/
@Composable
fun rememberReloadKey(nativeLib: NativeLib, vararg channels: ChangeChannel): MutableIntState {
fun rememberReloadKey(vararg channels: ChangeChannel): MutableIntState {
val key = remember { mutableIntStateOf(0) }
OnStoreChange(nativeLib, *channels) { key.intValue++ }
OnStoreChange(*channels) { key.intValue++ }
return key
}
@@ -101,9 +101,9 @@ private const val PREFETCH_ROWS = 10
* is appended, never spliced in at the top, so nothing under the user's finger moves.
*/
@Composable
fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Modifier) {
fun ClippingsScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
val copy = remember { clippingsCopy() }
val timezone = remember { nativeLib.timezone() }
val timezone = remember { NativeLib.timezone() }
val listState = rememberLazyListState()
val session = activityViewModel<ClippingEditSession>()
@@ -136,8 +136,7 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// settled, so the rows they can see are the rows they get) or is held aside; either way the
// list re-anchors at the top and pages down again from there.
fun load(intoView: Boolean) {
nativeLib
.ffi { clippings().listPage(null) }
NativeLib.ffi { clippings().listPage(null) }
.onSuccess { page ->
error = null
if (intoView) {
@@ -155,8 +154,7 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
val cursor = nextCursor ?: return
if (loadingMore) return
loadingMore = true
nativeLib
.ffi { clippings().listPage(cursor) }
NativeLib.ffi { clippings().listPage(cursor) }
.onSuccess { page ->
clippings = clippings + page.items
nextCursor = page.nextCursor
@@ -175,8 +173,7 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// change signal that write set off re-reads the list anyway, so the worst case is one stale
// card for a coalescing interval.
fun refreshRow(id: String) {
nativeLib
.ffi { clippings().get(id) }
NativeLib.ffi { clippings().get(id) }
.onSuccess { updated ->
if (updated != null) {
clippings = clippings.map { if (it.id == id) updated else it }
@@ -187,8 +184,7 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// Write the buffer, and report a failure on the editor rather than losing what it holds.
fun write(id: String, text: String, thenClose: Boolean) {
nativeLib
.ffi { clippings().update(id, text) }
NativeLib.ffi { clippings().update(id, text) }
.onSuccess {
if (thenClose) session.close() else session.saved(text)
refreshRow(id)
@@ -198,12 +194,12 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// Navigating to the screen is an explicit act, so the first read applies outright.
LaunchedEffect(reloadToken) { load(intoView = true) }
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) {
OnStoreChange(ChangeChannel.DOCUMENTS) {
// The open editor first: it is what the user is actually in, and the list's own answer to
// the same signal may hold rows back on account of it.
val openId = session.clippingId
if (openId != null) {
val stored = nativeLib.ffi { clippings().get(openId) }.getOrNull()?.text
val stored = NativeLib.ffi { clippings().get(openId) }.getOrNull()?.text
// Gone, unreadable, or its body is no longer held here: none of those is a version to
// offer the user a choice between. Nor is an answer about a clipping the editor has
// since moved off.
@@ -266,8 +262,7 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
Composer(
copy = copy,
onKeep = { text, sourceUrl ->
nativeLib
.ffi { clippings().capture(text, sourceUrl, null) }
NativeLib.ffi { clippings().capture(text, sourceUrl, null) }
.onSuccess {
composing = false
reloadToken++
@@ -339,8 +334,7 @@ fun ClippingsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
expandedId = if (expandedId == clipping.id) null else clipping.id
},
onDelete = {
nativeLib
.ffi { clippings().delete(clipping.id) }
NativeLib.ffi { clippings().delete(clipping.id) }
.onSuccess { reloadToken++ }
.onFailure { error = clippingDeleteFailed(it.userMessage) }
},
@@ -32,7 +32,6 @@ import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.ui.AbsentContentPane
import com.gregshuflin.synchronicity.ui.RemoteFetchOrSpinner
import com.gregshuflin.synchronicity.ui.SubAppScreen
@@ -74,7 +73,6 @@ fun ComicReaderScreen(
var direction by remember(node.id) { mutableStateOf(ReadingDirection.LEFT_TO_RIGHT) }
val coroutineScope = rememberCoroutineScope()
// For the jobs surface only — page bytes still come through [repository].
val nativeLib = NativeLib
LaunchedEffect(node.id) {
open = repository.openComic(node)
@@ -156,7 +154,6 @@ fun ComicReaderScreen(
val isCurrent = pageIndex == pagerState.currentPage
ComicPage(
repository = repository,
nativeLib = nativeLib,
pageId = pages[pageIndex],
isCurrent = isCurrent,
availability = node.availability,
@@ -222,7 +219,6 @@ private fun ReaderBottomBar(
@Composable
private fun ComicPage(
repository: ComicRepository,
nativeLib: NativeLib,
pageId: String,
isCurrent: Boolean,
availability: DocumentAvailability,
@@ -238,7 +234,7 @@ private fun ComicPage(
// composed, and those are the read-ahead's business — untracked by design, so watching them
// would poll for job rows that never exist.
val fetchStrings = rememberContentFetchStrings()
val remoteFetch = rememberRemoteFetch(nativeLib, pageId.takeIf { isCurrent && page == null })
val remoteFetch = rememberRemoteFetch(pageId.takeIf { isCurrent && page == null })
// Only the current page follows the reader's zoom; a neighbor the pager keeps composed sits at
// rest, so a page swiped into view never arrives already zoomed.
val resting = remember(pageId) { ZoomState() }
@@ -251,7 +247,7 @@ private fun ComicPage(
) {
when (val resolved = page) {
// The page hasn't resolved yet.
null -> RemoteFetchOrSpinner(remoteFetch, fetchStrings.comicPage, nativeLib)
null -> RemoteFetchOrSpinner(remoteFetch, fetchStrings.comicPage)
is ComicRepository.PageImage.Ready ->
ZoomableBitmap(
bitmap = resolved.bitmap,
@@ -44,7 +44,7 @@ private const val PREFETCH_CACHE_BYTES = 32 * 1024 * 1024
* its [uniffi.synchronicity.DocumentAvailability]. Repository state is one reading session's
* read-ahead cache, cleared by [openComic].
*/
class ComicRepository(private val nativeLib: NativeLib) {
class ComicRepository {
/** What [openComic] resolves before the reader can page through a comic. */
data class OpenComic(
@@ -93,7 +93,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
*/
suspend fun loadShelf(): ComicShelf? =
withContext(Dispatchers.IO) {
nativeLib.ffi { comics().shelf() }.getOrLog(TAG, "Failed to load the comics library")
NativeLib.ffi { comics().shelf() }.getOrLog(TAG, "Failed to load the comics library")
}
/**
@@ -102,8 +102,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
suspend fun loadCover(comicId: String, maxEdgePx: Int): ImageBitmap? =
withContext(Dispatchers.IO) {
val bytes =
nativeLib
.ffi { comics().getCoverBytes(comicId) }
NativeLib.ffi { comics().getCoverBytes(comicId) }
.getOrLog(TAG, "Cover not available for comic $comicId")
?: return@withContext null
decodeSampledImage(bytes, maxEdgePx)?.asImageBitmap()
@@ -120,22 +119,20 @@ class ComicRepository(private val nativeLib: NativeLib) {
// correctness — but a phone has no room to keep the last series around either.
prefetched.evictAll()
val pageIds =
nativeLib
.ffi { comics().listPageIds(node.id) }
NativeLib.ffi { comics().listPageIds(node.id) }
.getOrElse {
return@withContext null
}
if (pageIds.isEmpty()) return@withContext null
val parent = node.parentId
if (parent != null) {
nativeLib
.ffi { comics().setLatestReadChild(parent, node.id) }
NativeLib.ffi { comics().setLatestReadChild(parent, node.id) }
.onFailure { Log.w(TAG, "Failed to record latest-read child of $parent", it) }
}
val expected =
nativeLib.ffi { comics().pageCount(node.id) }.getOrNull()?.toInt() ?: pageIds.size
NativeLib.ffi { comics().pageCount(node.id) }.getOrNull()?.toInt() ?: pageIds.size
val progress =
nativeLib.ffi { comics().getReadingProgress(node.id) }.getOrNull()?.toInt() ?: 0
NativeLib.ffi { comics().getReadingProgress(node.id) }.getOrNull()?.toInt() ?: 0
OpenComic(pageIds, expected, progress.coerceIn(0, pageIds.size - 1))
}
@@ -149,8 +146,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
withContext(Dispatchers.IO) {
val bytes =
prefetched.get(pageId)
?: nativeLib
.ffi { comics().getPageBytes(pageId) }
?: NativeLib.ffi { comics().getPageBytes(pageId) }
.getOrLog(TAG, "Page $pageId not available locally or from any peer")
?: return@withContext PageImage.NotHere
val bitmap =
@@ -177,8 +173,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
// twice over the same link is precisely what reading ahead exists to avoid.
val current = pageIds.getOrNull(currentIndex)
val wanted =
nativeLib
.ffi { comics().pagesNeedingPrefetch(pageIds, currentIndex.toUInt()) }
NativeLib.ffi { comics().pagesNeedingPrefetch(pageIds, currentIndex.toUInt()) }
.onFailure { Log.w(TAG, "Failed to compute the prefetch window", it) }
.getOrDefault(emptyList())
.filter { it != current && prefetched.get(it) == null }
@@ -187,8 +182,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
// cancellation can only take effect between pages — check for it explicitly
// rather than reading ahead of a reader who has already moved on.
if (!isActive) return@withContext
nativeLib
.ffi { comics().prefetchPageBytes(pageId) }
NativeLib.ffi { comics().prefetchPageBytes(pageId) }
.getOrLog(TAG, "Read-ahead of page $pageId did not land")
?.let { prefetched.put(pageId, it) }
}
@@ -200,8 +194,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
// than dropped, though: this used to fail completely silently.
suspend fun saveProgress(comicId: String, page: Int) {
withContext<Unit>(Dispatchers.IO) {
nativeLib
.ffi { comics().setReadingProgress(comicId, page.toUInt()) }
NativeLib.ffi { comics().setReadingProgress(comicId, page.toUInt()) }
.onFailure { Log.w(TAG, "Failed to save reading progress for $comicId", it) }
}
}
@@ -209,15 +202,14 @@ class ComicRepository(private val nativeLib: NativeLib) {
/** The "In Progress" cards for [shelf] — see the Rust `ComicShelf::in_progress`. */
suspend fun inProgress(shelf: ComicShelf): List<ComicInProgress> =
withContext(Dispatchers.IO) {
nativeLib
.ffi { comics().inProgress(shelf) }
NativeLib.ffi { comics().inProgress(shelf) }
.getOrLog(TAG, "Failed to list comics in progress")
.orEmpty()
}
/** Import the archive the user picked; see [importPickedFile]. */
suspend fun importPicked(context: Context, uri: Uri): Result<String> =
nativeLib.importPickedFile(context, uri)
NativeLib.importPickedFile(context, uri)
/**
* Set [id]'s series-level reading direction and persist it, best-effort (same pattern as
@@ -230,8 +222,7 @@ class ComicRepository(private val nativeLib: NativeLib) {
// `IgnoredReturnValue` rightly objects to a silently dropped Result.
withContext<Unit>(Dispatchers.IO) {
val root = shelf?.seriesRoot(id) ?: id
nativeLib
.ffi { comics().setReadingDirection(root, direction) }
NativeLib.ffi { comics().setReadingDirection(root, direction) }
.onFailure { Log.w(TAG, "Failed to save reading direction for $root", it) }
}
}
@@ -7,7 +7,6 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.rememberReloadKey
import uniffi.synchronicity.ChangeChannel
import uniffi.synchronicity.ComicTreeItem
@@ -20,10 +19,10 @@ import uniffi.synchronicity.ComicTreeItem
* "continue reading" state the session may have changed.
*/
@Composable
fun ComicsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Modifier) {
val repository = remember(nativeLib) { ComicRepository(nativeLib) }
fun ComicsScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
val repository = remember { ComicRepository() }
var openNode by remember { mutableStateOf<ComicTreeItem?>(null) }
var reloadKey by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
var reloadKey by rememberReloadKey(ChangeChannel.DOCUMENTS)
Box(modifier = modifier) {
ComicLibraryScreen(
@@ -84,7 +84,6 @@ private data class DetailRows(
@Composable
fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modifier = Modifier) {
val nativeLib = NativeLib
var section by rememberSaveable { mutableStateOf(DocumentDetailSection.OVERVIEW) }
var document by remember { mutableStateOf<DocumentItem?>(null) }
@@ -103,7 +102,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
// availability for the freshly-pulled assets. This document's own rows — presence, artifacts,
// sync state — move as content arrives from other nodes, which is the whole subject of this
// screen.
var reloadKey by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
var reloadKey by rememberReloadKey(ChangeChannel.DOCUMENTS)
// The Pin/Exclude choices a Placement row offers, with their copy. Sourced from Rust so the
// two modalities cannot drift.
var syncOverrideOptions by remember {
@@ -133,14 +132,14 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
// "Delete Locally" confirmation flow (evaluate → confirm → execute); null is idle.
var deleteLocallyState by remember { mutableStateOf<EvictionFlowState?>(null) }
val allowUnverifiedDeletion = remember {
nativeLib.ffi { eviction().getAllowUnverifiedDeletion() }.getOrDefault(false)
NativeLib.ffi { eviction().getAllowUnverifiedDeletion() }.getOrDefault(false)
}
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) { syncOverrideOptions = getDocumentSyncOverrideOptions() }
LaunchedEffect(documentId, reloadKey) {
withContext(Dispatchers.IO) { nativeLib.ffi { documents().get(documentId) } }
withContext(Dispatchers.IO) { NativeLib.ffi { documents().get(documentId) } }
.onSuccess {
document = it
gone = it == null
@@ -151,7 +150,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
}
if (document == null) return@LaunchedEffect
withContext(Dispatchers.IO) {
nativeLib.ffi {
NativeLib.ffi {
val docs = documents()
DetailRows(
docs.listProperties(documentId),
@@ -174,11 +173,11 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
}
// Off the main thread: this walks the subtree and stats a file per content artifact,
// which for a comic is hundreds.
withContext(Dispatchers.IO) { nativeLib.ffi { documents().documentPlacement(documentId) } }
withContext(Dispatchers.IO) { NativeLib.ffi { documents().documentPlacement(documentId) } }
.onSuccess { placement = it }
.onFailure { Log.w(TAG, "Failed to load placement for $documentId", it) }
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().countDocumentDescendants(documentId) }
NativeLib.ffi { ensemble().countDocumentDescendants(documentId) }
}
.onSuccess { count -> descendantCount = count }
.onFailure { Log.w(TAG, "Failed to count descendants for $documentId", it) }
@@ -195,7 +194,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().syncDocumentAsset(documentId, asset) }
NativeLib.ffi { ensemble().syncDocumentAsset(documentId, asset) }
}
assetSyncStates[key] =
result.fold(
@@ -236,7 +235,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
val message =
if (row.isThisNode) {
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().syncDocumentAssets(documentId) }
NativeLib.ffi { ensemble().syncDocumentAssets(documentId) }
}
.fold(
// Which of the five outcomes applies, and the words for it, are
@@ -260,7 +259,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
)
} else {
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().pushDocument(documentId, row.nodeIdHex) }
NativeLib.ffi { ensemble().pushDocument(documentId, row.nodeIdHex) }
}
.fold(
onSuccess = { r ->
@@ -290,16 +289,14 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
withContext(Dispatchers.IO) {
if (row.isThisNode) {
if (value == null) {
nativeLib
.ffi { settings().clearDocumentSyncOverride(documentId) }
NativeLib.ffi { settings().clearDocumentSyncOverride(documentId) }
.map { value }
} else {
nativeLib
.ffi { settings().setDocumentSyncOverride(documentId, value) }
NativeLib.ffi { settings().setDocumentSyncOverride(documentId, value) }
.map { value }
}
} else {
nativeLib.ffi {
NativeLib.ffi {
remoteAdmin().setDocumentOverride(row.nodeIdHex, documentId, value)
}
}
@@ -332,7 +329,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { eviction().evaluateDeleteLocally(documentId) }
NativeLib.ffi { eviction().evaluateDeleteLocally(documentId) }
}
deleteLocallyState =
result.fold(
@@ -354,7 +351,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { eviction().executeDeleteLocally(documentId, allowUnverified) }
NativeLib.ffi { eviction().executeDeleteLocally(documentId, allowUnverified) }
}
deleteLocallyState =
result.fold(
@@ -403,7 +400,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
MetadataCard(
document = loadedDocument,
totalBytes = totalBytes,
timezone = nativeLib.timezone(),
timezone = NativeLib.timezone(),
nodeStatuses = nodeStatuses,
)
}
@@ -426,7 +423,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi {
NativeLib.ffi {
ensemble().countDocumentDescendants(documentId)
}
}
@@ -483,7 +480,7 @@ fun DocumentDetailScreen(documentId: String, onBack: () -> Unit, modifier: Modif
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().purgeDocument(documentId) }
NativeLib.ffi { ensemble().purgeDocument(documentId) }
}
purging = false
result
@@ -35,7 +35,6 @@ private const val TAG = "DocumentDirectoryImport"
*/
suspend fun importDirectory(
context: Context,
nativeLib: NativeLib,
treeUri: Uri,
preserveStructure: Boolean,
): Result<String> =
@@ -55,9 +54,9 @@ suspend fun importDirectory(
// The tree URI is the dedup key, the folder's name is what the Jobs screen shows: two
// providers can both have a folder called "Music", and picking one twice should attach to
// the running import rather than start a second.
nativeLib.beginImportBatch(treeUri.toString(), rootName, totals.files, totals.bytes).map {
NativeLib.beginImportBatch(treeUri.toString(), rootName, totals.files, totals.bytes).map {
batch ->
val importer = DirectoryImporter(context, nativeLib, treeUri, preserveStructure, batch)
val importer = DirectoryImporter(context, treeUri, preserveStructure, batch)
val summary = importer.runReportingProgress(rootDocId, rootName)
Log.i(TAG, "Directory import complete: $summary")
summary.describe()
@@ -164,7 +163,6 @@ private class TreeScanner(private val context: Context, private val treeUri: Uri
*/
private class DirectoryImporter(
private val context: Context,
private val nativeLib: NativeLib,
private val treeUri: Uri,
private val preserveStructure: Boolean,
private val batch: BatchImport,
@@ -221,7 +219,7 @@ private class DirectoryImporter(
// Asked before the bytes are read, not after: they cross the FFI as one ByteArray, and a
// video sitting in a folder of PDFs would otherwise be gigabytes pulled into the heap
// only to be skipped.
if (!nativeLib.ffi { import().supports(entry.name, entry.mimeType) }.getOrDefault(false)) {
if (!NativeLib.ffi { import().supports(entry.name, entry.mimeType) }.getOrDefault(false)) {
batch.skipFile(entry.name, entry.size, "unsupported type (${entry.mimeType})")
return
}
@@ -253,8 +251,7 @@ private class DirectoryImporter(
/** Create a Collection node, returning its id, or null (logged) if creation failed. */
private fun createCollection(parentNode: String?, name: String): String? =
nativeLib
.ffi { import().createCollection(parentNode, name) }
NativeLib.ffi { import().createCollection(parentNode, name) }
.getOrElse {
Log.i(
TAG,
@@ -156,13 +156,11 @@ fun flattenDocumentTree(
}
fun searchAndParseDocuments(
nativeLib: NativeLib,
query: String = "",
types: List<DocumentType> = emptyList(),
dateFilter: String = "",
): List<DocumentItem> {
return nativeLib
.ffi {
return NativeLib.ffi {
documents()
.search(
searchQuery = query.ifEmpty { null },
@@ -67,7 +67,6 @@ fun DocumentsScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
val snackbar = LocalSnackbarController.current
val nativeLib = NativeLib
// Sourced from shared Rust so every frontend pages at the same rate.
val pageSize = remember { defaultDocumentPageSize().toInt() }
@@ -89,7 +88,7 @@ fun DocumentsScreen(
val availableDateFilters = remember { dateFilterOptions() }
val anyDateLabel = remember { dateFilterAnyLabel() }
val timezone = remember { nativeLib.timezone() }
val timezone = remember { NativeLib.timezone() }
// ── Paginated, off-main-thread document loading ─────────────────────────────
var documents by remember { mutableStateOf<List<DocumentDisplayModel>>(emptyList()) }
@@ -128,14 +127,13 @@ fun DocumentsScreen(
// A document arriving from another node, or an import finishing here, belongs in the list on
// screen — not in the one the user will see next time they open this. The watch is scoped to
// composition, so a screen off the back stack re-reads nothing.
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) {
OnStoreChange(ChangeChannel.DOCUMENTS) {
if (settled) refreshTrigger++ else changedElsewhere = true
}
suspend fun fetchPage(cursor: DocumentCursor?): DocumentPage =
withContext(Dispatchers.IO) {
nativeLib
.ffi {
NativeLib.ffi {
documents()
.searchPage(
searchQuery = searchQuery.ifEmpty { null },
@@ -185,8 +183,7 @@ fun DocumentsScreen(
scope.launch {
val children =
withContext(Dispatchers.IO) {
nativeLib
.ffi { documents().listChildren(doc.id) }
NativeLib.ffi { documents().listChildren(doc.id) }
.getOrDefault(emptyList())
}
childrenById =
@@ -264,8 +261,7 @@ fun DocumentsScreen(
// reports per file rather than bind()ing, which would abandon the batch
// at the first failure.
uris.forEach { uri ->
nativeLib
.importPickedFile(context, uri)
NativeLib.importPickedFile(context, uri)
.onSuccess { displayName ->
Toast.makeText(
context,
@@ -286,7 +282,7 @@ fun DocumentsScreen(
onUrl = { url ->
showImportModal = false
scope.launchReportingFailure(snackbar, TAG, "import from URL") {
importDocumentFromUrl(nativeLib, url).bind()
importDocumentFromUrl(url).bind()
Toast.makeText(context, "Imported from URL", Toast.LENGTH_SHORT).show()
refreshTrigger++
}
@@ -303,7 +299,7 @@ fun DocumentsScreen(
// alongside a genuine failure.
scope.launchReportingFailure(snackbar, TAG, "import folder") {
try {
val summary = importDirectory(context, nativeLib, uri, preserve).bind()
val summary = importDirectory(context, uri, preserve).bind()
Toast.makeText(context, summary, Toast.LENGTH_SHORT).show()
} finally {
refreshTrigger++
@@ -559,8 +555,8 @@ private fun PreserveStructureDialog(onDismiss: () -> Unit, onConfirm: (Boolean)
// A fetch/import failure comes back as a failed Result rather than being handled here —
// DocumentsScreen's onUrl owns reporting it through the snackbar (docs/adr/0021).
private suspend fun importDocumentFromUrl(nativeLib: NativeLib, url: String): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { import().fromUrl(url) } }
private suspend fun importDocumentFromUrl(url: String): Result<Unit> =
withContext(Dispatchers.IO) { NativeLib.ffi { import().fromUrl(url) } }
.map { docId -> Log.i(TAG, "Imported URL $url as document $docId") }
private fun <T> Set<T>.toggle(item: T): Set<T> = if (item in this) this - item else this + item
@@ -77,7 +77,6 @@ private const val TAG = "EnsembleScreen"
@Composable
fun EnsembleScreen(
nativeLib: NativeLib,
onBack: () -> Unit,
modifier: Modifier = Modifier,
applySafePadding: Boolean = true,
@@ -93,7 +92,7 @@ fun EnsembleScreen(
val syncStates = remember { mutableStateMapOf<String, SyncState>() }
// Display times in the user's configured timezone (falls back to UTC),
// matching the timezone-aware formatting used elsewhere in the app.
val zone = remember { resolveDisplayZone(nativeLib) }
val zone = remember { resolveDisplayZone() }
/**
* Read the roster. `quiet` is a read nobody asked for — one the store announced — so it neither
@@ -115,11 +114,10 @@ fun EnsembleScreen(
// not a reason to go dial the DHT — a sync writing a hundred documents would
// otherwise trigger a bootstrap for each burst of them.
if (!quiet) {
nativeLib
.ffi { ensemble().triggerGossipBootstrap() }
NativeLib.ffi { ensemble().triggerGossipBootstrap() }
.onFailure { Log.d(TAG, "Gossip bootstrap trigger failed", it) }
}
nativeLib.ffi { ensemble().getEnsembleStatus() }
NativeLib.ffi { ensemble().getEnsembleStatus() }
}
.onSuccess { data ->
screenData = data
@@ -161,7 +159,7 @@ fun EnsembleScreen(
// catalog sync finishes and writes its timestamp, documents arrive and change every row's
// coverage. Not the whole picture — gossip neighbor count and live reachability are in-memory
// P2P state that nothing announces, so pull-to-refresh stays the way to ask for those.
OnStoreChange(nativeLib, ChangeChannel.NODES, ChangeChannel.DOCUMENTS) { load(quiet = true) }
OnStoreChange(ChangeChannel.NODES, ChangeChannel.DOCUMENTS) { load(quiet = true) }
AnimatedNavHost(
navController = navController,
@@ -170,7 +168,6 @@ fun EnsembleScreen(
) {
composable<EnsembleNodesRoute> {
EnsembleNodesScreen(
nativeLib = nativeLib,
screenData = screenData,
loading = loading,
error = error,
@@ -179,8 +176,8 @@ fun EnsembleScreen(
zone = zone,
onBack = onBack,
onRefresh = { load() },
onPing = { nodeIdHex -> launchPing(scope, nativeLib, nodeIdHex, pingStates) },
onSync = { nodeIdHex -> launchSync(scope, nativeLib, nodeIdHex, syncStates, zone) },
onPing = { nodeIdHex -> launchPing(scope, nodeIdHex, pingStates) },
onSync = { nodeIdHex -> launchSync(scope, nodeIdHex, syncStates, zone) },
onNodeSelect = { nodeIdHex ->
navController.navigate(EnsembleNodeRoute(nodeIdHex))
},
@@ -192,14 +189,13 @@ fun EnsembleScreen(
val nodeIdHex = backStackEntry.toRoute<EnsembleNodeRoute>().nodeIdHex
val member = screenData?.members?.find { it.nodeIdHex == nodeIdHex }
NodeScreen(
nativeLib = nativeLib,
nodeIdHex = nodeIdHex,
member = member,
pingState = pingStates[nodeIdHex] ?: PingState(),
syncState = syncStates[nodeIdHex] ?: SyncState(),
onBack = { navController.popBackStack() },
onPing = { launchPing(scope, nativeLib, nodeIdHex, pingStates) },
onSync = { launchSync(scope, nativeLib, nodeIdHex, syncStates, zone) },
onPing = { launchPing(scope, nodeIdHex, pingStates) },
onSync = { launchSync(scope, nodeIdHex, syncStates, zone) },
onRevoke = { load() },
applySafePadding = applySafePadding,
)
@@ -209,7 +205,6 @@ fun EnsembleScreen(
@Composable
private fun EnsembleNodesScreen(
nativeLib: NativeLib,
screenData: EnsembleStatus?,
loading: Boolean,
error: String?,
@@ -409,11 +404,10 @@ private fun EnsembleNodesScreen(
}
}
item { ImportRevocationSection(nativeLib = nativeLib, onImport = onRefresh) }
item { ImportRevocationSection(onImport = onRefresh) }
item {
ThisNodeSection(
nativeLib = nativeLib,
onRetire = onRetire,
// Same landing as Settings' reset used: back out of Settings, which
// routes to onboarding when the store no longer has a node in it.
@@ -439,7 +433,7 @@ private fun EnsembleNodesScreen(
* these takes one, so nothing else would.
*/
@Composable
private fun ThisNodeSection(nativeLib: NativeLib, onRetire: () -> Unit, onLeaveNode: () -> Unit) {
private fun ThisNodeSection(onRetire: () -> Unit, onLeaveNode: () -> Unit) {
val copy = SharedCopy.revocation
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -512,7 +506,7 @@ private fun ThisNodeSection(nativeLib: NativeLib, onRetire: () -> Unit, onLeaveN
// Off the click handler's thread: the wipe stops the P2P node and deletes
// the store, neither of which the main thread may wait on.
scope.launch {
NodeReset.perform(context, nativeLib)
NodeReset.perform(context)
.onSuccess {
resetting = false
onLeaveNode()
@@ -636,7 +630,7 @@ private fun SelfRevokedNotice() {
* looking at the list of nodes it is about to name.
*/
@Composable
private fun ImportRevocationSection(nativeLib: NativeLib, onImport: () -> Unit) {
private fun ImportRevocationSection(onImport: () -> Unit) {
val scope = rememberCoroutineScope()
var blob by remember { mutableStateOf("") }
var pending by remember { mutableStateOf(false) }
@@ -669,7 +663,7 @@ private fun ImportRevocationSection(nativeLib: NativeLib, onImport: () -> Unit)
outcome = null
scope.launch {
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().importRevocation(blob.trim()) }
NativeLib.ffi { ensemble().importRevocation(blob.trim()) }
}
.onSuccess { info ->
pending = false
@@ -870,7 +864,6 @@ private fun CoverageMeter(held: ULong, total: ULong) {
/** Node-specific screen reached from the ensemble list. Starts with the ping and sync controls. */
@Composable
private fun NodeScreen(
nativeLib: NativeLib,
nodeIdHex: String,
member: EnsembleMemberInfo?,
pingState: PingState,
@@ -913,7 +906,6 @@ private fun NodeScreen(
PingControl(state = pingState, onPing = onPing)
SyncControl(nodeIdHex = nodeIdHex, state = syncState, onSync = onSync)
RevokeControl(
nativeLib = nativeLib,
nodeIdHex = nodeIdHex,
nodeName = member?.displayName ?: "this node",
onRevoke = onRevoke,
@@ -934,12 +926,7 @@ private fun NodeScreen(
* meter and two controls, and this is not something to put a thumb's width from "Sync".
*/
@Composable
private fun RevokeControl(
nativeLib: NativeLib,
nodeIdHex: String,
nodeName: String,
onRevoke: () -> Unit,
) {
private fun RevokeControl(nodeIdHex: String, nodeName: String, onRevoke: () -> Unit) {
val scope = rememberCoroutineScope()
var asking by remember { mutableStateOf(false) }
var keyphrase by remember { mutableStateOf("") }
@@ -987,7 +974,7 @@ private fun RevokeControl(
failure = null
scope.launch {
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().revokePeer(nodeIdHex, keyphrase.trim()) }
NativeLib.ffi { ensemble().revokePeer(nodeIdHex, keyphrase.trim()) }
}
.onSuccess {
pending = false
@@ -1020,8 +1007,8 @@ private val TRACK_HEIGHT = 4.dp
* Resolves the user's configured IANA timezone, falling back to UTC when unset or invalid. Mirrors
* the timezone handling used by the document and podcast screens.
*/
private fun resolveDisplayZone(nativeLib: NativeLib): ZoneId =
nativeLib.timezone()?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneOffset.UTC
private fun resolveDisplayZone(): ZoneId =
NativeLib.timezone()?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneOffset.UTC
/** Formats a Unix epoch-seconds timestamp in the given [zone] using the supplied pattern. */
private fun formatEpochSeconds(epochSecs: Long, zone: ZoneId, pattern: String): String =
@@ -156,14 +156,13 @@ private fun OutcomeText(ok: String, error: String) {
/** Kicks off a ping against [nodeIdHex], updating [pingStates] as it progresses. */
internal fun launchPing(
scope: CoroutineScope,
nativeLib: NativeLib,
nodeIdHex: String,
pingStates: MutableMap<String, PingState>,
) {
scope.launch {
pingStates[nodeIdHex] = PingState(pending = true)
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().pingNode(nodeIdHex, pingTimeoutSecs()) }
NativeLib.ffi { ensemble().pingNode(nodeIdHex, pingTimeoutSecs()) }
}
.onSuccess { rttMs -> pingStates[nodeIdHex] = PingState(ok = "%.1fms".format(rttMs)) }
.onFailure { pingStates[nodeIdHex] = PingState(error = it.userMessage) }
@@ -173,14 +172,13 @@ internal fun launchPing(
/** Kicks off a document sync against [nodeIdHex], updating [syncStates] as it progresses. */
internal fun launchSync(
scope: CoroutineScope,
nativeLib: NativeLib,
nodeIdHex: String,
syncStates: MutableMap<String, SyncState>,
zone: ZoneId,
) {
scope.launch {
syncStates[nodeIdHex] = SyncState(starting = true)
withContext(Dispatchers.IO) { nativeLib.ffi { ensemble().syncDocuments(nodeIdHex) } }
withContext(Dispatchers.IO) { NativeLib.ffi { ensemble().syncDocuments(nodeIdHex) } }
.onSuccess { result ->
// Format via shared Rust so the live value matches the persisted
// one shown after a reload.
@@ -151,12 +151,7 @@ private fun <T> diffStaged(
persisted.filter { p -> staged.none { same(p, it) } }
@Composable
fun HumanDetailScreen(
humanId: String,
nativeLib: NativeLib,
onBack: () -> Unit,
modifier: Modifier = Modifier,
) {
fun HumanDetailScreen(humanId: String, onBack: () -> Unit, modifier: Modifier = Modifier) {
var loaded by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
@@ -198,7 +193,7 @@ fun HumanDetailScreen(
var factEntry by remember(editing) { mutableStateOf(FactEntryState()) }
var contactEntry by remember(editing) { mutableStateOf(ContactEntryState()) }
val protocols = remember {
nativeLib.ffi { humans().contactProtocols() }.getOrDefault(emptyList())
NativeLib.ffi { humans().contactProtocols() }.getOrDefault(emptyList())
}
var protocol by remember(protocols) { mutableStateOf(protocols.firstOrNull()) }
@@ -213,8 +208,7 @@ fun HumanDetailScreen(
// every staged change is the same act as reloading, which is why there is
// one effect rather than a separate "revert" path to keep in step.
LaunchedEffect(humanId, reloadToken) {
nativeLib
.ffi { humans().get(humanId) }
NativeLib.ffi { humans().get(humanId) }
.onSuccess { p ->
fullName = p.fullName
nickname = p.nickname
@@ -248,18 +242,16 @@ fun HumanDetailScreen(
// silently overwrite it to wait until they have chosen. ADR 0031's "What a form needs, and
// this does not cover yet" is where that design is owed — it wants doing once for the record
// screens, not once per screen.
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) {
OnStoreChange(ChangeChannel.DOCUMENTS) {
historyReloadToken++
if (!editing) reloadToken++
}
LaunchedEffect(humanId, historyReloadToken) {
nativeLib
.ffi { humans().interactionsWith(humanId) }
NativeLib.ffi { humans().interactionsWith(humanId) }
.onSuccess { interactions = it }
.onFailure { error = it.userMessage }
nativeLib
.ffi { humans().backlinks(humanId) }
NativeLib.ffi { humans().backlinks(humanId) }
.onSuccess { backlinks = it }
.onFailure { error = it.userMessage }
}
@@ -297,7 +289,6 @@ fun HumanDetailScreen(
if (section == HumanDetailSection.HISTORY) {
HistoryTab(
humanId = humanId,
nativeLib = nativeLib,
interactions = interactions,
backlinks = backlinks,
onChange = { historyReloadToken++ },
@@ -472,7 +463,6 @@ fun HumanDetailScreen(
}
birthDateError = null
saveProfile(
nativeLib = nativeLib,
humanId = humanId,
fullName = fullName,
nickname = nickname,
@@ -526,8 +516,7 @@ fun HumanDetailScreen(
confirmLabel = SharedCopy.actions.delete,
onDismiss = { showDeleteDialog = false },
onConfirm = {
nativeLib
.ffi { humans().delete(humanId) }
NativeLib.ffi { humans().delete(humanId) }
.onSuccess { onBack() }
.onFailure { error = it.userMessage }
},
@@ -549,7 +538,6 @@ fun HumanDetailScreen(
*/
@Suppress("LongParameterList") // one parameter per field of the form it saves
private fun saveProfile(
nativeLib: NativeLib,
humanId: String,
fullName: String,
nickname: String,
@@ -569,8 +557,7 @@ private fun saveProfile(
val (factsToAdd, factsToRemove) = diffStaged(present, origFacts) { a, b -> a == b }
val (contactsToAdd, contactsToRemove) = diffStaged(contacts, origContacts, ::sameContact)
nativeLib
.ffi {
NativeLib.ffi {
humans()
.update(
humanId,
@@ -584,17 +571,16 @@ private fun saveProfile(
}
.bind()
factsToRemove.forEach { fact ->
nativeLib.ffi { humans().removeFact(humanId, fact.key, fact.value) }.bind()
NativeLib.ffi { humans().removeFact(humanId, fact.key, fact.value) }.bind()
}
factsToAdd.forEach { fact ->
nativeLib.ffi { humans().addFact(humanId, fact.key, fact.value) }.bind()
NativeLib.ffi { humans().addFact(humanId, fact.key, fact.value) }.bind()
}
contactsToRemove.forEach { row ->
nativeLib.ffi { humans().removeContactMethod(humanId, row.protocol, row.value) }.bind()
NativeLib.ffi { humans().removeContactMethod(humanId, row.protocol, row.value) }.bind()
}
contactsToAdd.forEach { row ->
nativeLib
.ffi { humans().addContactMethod(humanId, row.protocol, row.value, row.label) }
NativeLib.ffi { humans().addContactMethod(humanId, row.protocol, row.value, row.label) }
.bind()
}
}
@@ -905,7 +891,6 @@ private fun ContactSection(
@Composable
private fun HistoryTab(
humanId: String,
nativeLib: NativeLib,
interactions: List<InteractionItem>,
backlinks: List<BacklinkItem>,
onChange: () -> Unit,
@@ -974,8 +959,7 @@ private fun HistoryTab(
val editing = editingId
val result =
if (editing == null) {
nativeLib
.ffi {
NativeLib.ffi {
humans()
.logInteraction(
what,
@@ -986,7 +970,7 @@ private fun HistoryTab(
}
.map {}
} else {
nativeLib.ffi {
NativeLib.ffi {
humans().updateInteraction(editing, what, occurredOn.trim(), body)
}
}
@@ -1020,8 +1004,7 @@ private fun HistoryTab(
// Only enter edit mode once the write-up is actually in
// hand. Populating the form with a blank body on a failed
// read would offer to save that blank over the real one.
nativeLib
.ffi { humans().getInteraction(item.id) }
NativeLib.ffi { humans().getInteraction(item.id) }
.onSuccess { detail ->
editingId = item.id
title = item.title
@@ -1031,8 +1014,7 @@ private fun HistoryTab(
.onFailure { onError(it.userMessage) }
},
onDelete = {
nativeLib
.ffi { humans().deleteInteraction(item.id) }
NativeLib.ffi { humans().deleteInteraction(item.id) }
.onSuccess {
if (editingId == item.id) clearForm()
onChange()
@@ -28,23 +28,17 @@ import uniffi.synchronicity.humanFieldMaxLen
val HUMAN_FIELD_MAX_LEN = humanFieldMaxLen().toInt()
@Composable
fun HumansScreen(
nativeLib: NativeLib,
onOpenHuman: (String) -> Unit,
onBack: () -> Unit,
modifier: Modifier = Modifier,
) {
fun HumansScreen(onOpenHuman: (String) -> Unit, onBack: () -> Unit, modifier: Modifier = Modifier) {
var humans by remember { mutableStateOf<List<HumanListItem>>(emptyList()) }
var error by remember { mutableStateOf<String?>(null) }
var showCreateDialog by remember { mutableStateOf(false) }
var searchQuery by remember { mutableStateOf("") }
// Bumping this re-runs the load effect (e.g. after creating someone). A person can arrive from
// another node, or be renamed on one, while this list is open.
var reloadToken by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
var reloadToken by rememberReloadKey(ChangeChannel.DOCUMENTS)
LaunchedEffect(reloadToken) {
nativeLib
.ffi { humans().list() }
NativeLib.ffi { humans().list() }
.onSuccess {
humans = it
error = null
@@ -121,8 +115,7 @@ fun HumansScreen(
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
onDismiss = { showCreateDialog = false },
onConfirm = { fullName ->
nativeLib
.ffi { humans().create(fullName.trim()) }
NativeLib.ffi { humans().create(fullName.trim()) }
.onSuccess {
showCreateDialog = false
reloadToken++
@@ -10,7 +10,6 @@ import androidx.compose.runtime.setValue
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.ui.AnimatedNavHost
import kotlinx.serialization.Serializable
@@ -31,7 +30,6 @@ private data class PendingMnemonic(val displayLines: List<String>, val isFormatB
@Composable
fun InitializationNavigation(
onInitializationComplete: () -> Unit,
nativeLib: NativeLib,
navController: NavHostController = rememberNavController(),
) {
var pendingMnemonic by remember { mutableStateOf<PendingMnemonic?>(null) }
@@ -62,7 +60,6 @@ fun InitializationNavigation(
CreateIdentityScreen(
onBack = { navController.popBackStack() },
onNodeInitialize = onInitializationComplete,
nativeLib = nativeLib,
)
}
@@ -128,7 +128,6 @@ fun GenerateEnsembleKeyScreen(
fun CreateIdentityScreen(
onBack: () -> Unit,
onNodeInitialize: () -> Unit,
nativeLib: NativeLib,
modifier: Modifier = Modifier,
) {
var keyphrase by remember { mutableStateOf("") }
@@ -211,7 +210,7 @@ fun CreateIdentityScreen(
val trimmed = keyphrase.trim()
scope.launch {
withContext(Dispatchers.IO) {
nativeLib.ffi {
NativeLib.ffi {
ensemble().joinExistingEnsemble(trimmed, effectiveName)
}
}
@@ -90,18 +90,17 @@ object ActiveJobs {
* which is a different claim from "I couldn't tell".
*/
private fun watch(): Flow<Snapshot> = flow {
val nativeLib = NativeLib
emitAll(
StoreChanges.cursor(nativeLib)
StoreChanges.cursor()
.filterNotNull()
.map { cursor -> cursor.jobs }
.distinctUntilChanged()
.mapNotNull { _ -> listActive(nativeLib) }
.mapNotNull { _ -> listActive() }
)
}
private suspend fun listActive(nativeLib: NativeLib): Snapshot? =
withContext(Dispatchers.IO) { nativeLib.ffi { jobs().listActiveJobs() } }
private suspend fun listActive(): Snapshot? =
withContext(Dispatchers.IO) { NativeLib.ffi { jobs().listActiveJobs() } }
.onFailure { e -> Log.w(TAG, "Failed to list active jobs", e) }
.getOrNull()
?.let { jobs -> Snapshot(jobs) }
@@ -75,20 +75,19 @@ private enum class JobsTab(val label: String) {
* history from the desktop GUI's `JobRunner` against the same store.
*/
@Composable
fun JobsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Modifier) {
fun JobsScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
var tab by rememberSaveable { mutableStateOf(JobsTab.ACTIVE) }
val snapshot by ActiveJobs.snapshot.collectAsState()
val active = snapshot.jobs
var history by remember { mutableStateOf<List<JobItem>>(emptyList()) }
var error by remember { mutableStateOf<String?>(null) }
var showClearConfirm by remember { mutableStateOf(false) }
val timezone = remember { nativeLib.timezone() }
val timezone = remember { NativeLib.timezone() }
val scope = rememberCoroutineScope()
suspend fun reloadHistory() {
withContext<Unit>(Dispatchers.IO) {
nativeLib
.ffi { jobs().listJobHistory(HISTORY_LIMIT.toUInt()) }
NativeLib.ffi { jobs().listJobHistory(HISTORY_LIMIT.toUInt()) }
.onSuccess { history = it }
.onFailure { error = it.userMessage }
}
@@ -96,7 +95,7 @@ fun JobsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Mo
fun cancel(job: JobItem) {
scope.launch {
withContext(Dispatchers.IO) { nativeLib.ffi { jobs().cancelJob(job.id) } }
withContext(Dispatchers.IO) { NativeLib.ffi { jobs().cancelJob(job.id) } }
.onSuccess { canceled ->
if (canceled) {
// The Active list follows the store's own change signal; only History
@@ -118,7 +117,7 @@ fun JobsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Mo
// which a 3s poll turned into a bar that moved in jumps; this shows it as it happens. Only
// History is re-read here: the Active list follows the same signal through [ActiveJobs].
LaunchedEffect(Unit) { reloadHistory() }
OnStoreChange(nativeLib, ChangeChannel.JOBS) { reloadHistory() }
OnStoreChange(ChangeChannel.JOBS) { reloadHistory() }
if (showClearConfirm) {
ConfirmDialog(
@@ -130,7 +129,7 @@ fun JobsScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Mo
onDismiss = { showClearConfirm = false },
onConfirm = {
scope.launch {
withContext(Dispatchers.IO) { nativeLib.ffi { jobs().clearJobHistory() } }
withContext(Dispatchers.IO) { NativeLib.ffi { jobs().clearJobHistory() } }
.onSuccess { reloadHistory() }
.onFailure { error = it.userMessage }
}
@@ -20,7 +20,7 @@ import uniffi.synchronicity.MusicTreeItem
private const val TAG = "MusicRepository"
class MusicRepository(private val nativeLib: NativeLib) {
class MusicRepository {
/**
* One level of the tag-derived Artist → Album → Track library — the Library tab's model, and
* the counterpart to the desktop `MusicView::refresh_library_view`. Already in display order,
@@ -28,7 +28,7 @@ class MusicRepository(private val nativeLib: NativeLib) {
*/
suspend fun loadLibrary(level: MusicLibraryLevel): List<LibraryEntry> =
withContext(Dispatchers.IO) {
nativeLib.ffi { music().listLibrary(level) }.getOrDefault(emptyList())
NativeLib.ffi { music().listLibrary(level) }.getOrDefault(emptyList())
}
/**
@@ -38,7 +38,7 @@ class MusicRepository(private val nativeLib: NativeLib) {
*/
suspend fun loadEntryArt(entry: LibraryEntry, maxEdgePx: Int): ImageBitmap? =
withContext(Dispatchers.IO) {
val bytes = nativeLib.ffi { music().entryArt(entry.id, entry.kind) }.getOrNull()
val bytes = NativeLib.ffi { music().entryArt(entry.id, entry.kind) }.getOrNull()
bytes?.let { decodeSampledImage(it, maxEdgePx)?.asImageBitmap() }
}
@@ -48,7 +48,7 @@ class MusicRepository(private val nativeLib: NativeLib) {
* keeps the UI live while it runs rather than waiting on it.
*/
suspend fun buildLibrary(): Result<LibraryBuildSummary> =
withContext(Dispatchers.IO) { nativeLib.ffi { music().buildLibrary() } }
withContext(Dispatchers.IO) { NativeLib.ffi { music().buildLibrary() } }
/**
* The folder hierarchy the user's own files were imported under — the Folders tab's model, and
@@ -57,12 +57,12 @@ class MusicRepository(private val nativeLib: NativeLib) {
*/
suspend fun loadTree(): List<MusicTreeItem> =
withContext(Dispatchers.IO) {
nativeLib.ffi { music().listTree() }.getOrDefault(emptyList())
NativeLib.ffi { music().listTree() }.getOrDefault(emptyList())
}
suspend fun isBlobLocal(trackId: String): Boolean =
withContext(Dispatchers.IO) {
nativeLib.ffi { documents().isBlobLocal(trackId) }.getOrDefault(false)
NativeLib.ffi { documents().isBlobLocal(trackId) }.getOrDefault(false)
}
// Returns a URI suitable for ExoPlayer. If the blob is local it is loaded from the
@@ -70,10 +70,9 @@ class MusicRepository(private val nativeLib: NativeLib) {
// temp file in cacheDir (not stored permanently).
suspend fun getAudioUri(context: Context, trackId: String): Uri? =
withContext(Dispatchers.IO) {
if (nativeLib.ffi { documents().isBlobLocal(trackId) }.getOrDefault(false)) {
if (NativeLib.ffi { documents().isBlobLocal(trackId) }.getOrDefault(false)) {
val bytes =
nativeLib
.ffi { documents().getBlobBytes(trackId) }
NativeLib.ffi { documents().getBlobBytes(trackId) }
.getOrLog(TAG, "Blob not available for document $trackId")
?: return@withContext null
val file = File(context.cacheDir, "music_local_$trackId")
@@ -82,8 +81,7 @@ class MusicRepository(private val nativeLib: NativeLib) {
} else {
val file = File(context.cacheDir, "music_stream_$trackId")
val ok =
nativeLib
.ffi { documents().fetchBlobToPath(trackId, file.absolutePath) }
NativeLib.ffi { documents().fetchBlobToPath(trackId, file.absolutePath) }
.onFailure {
Log.w(TAG, "Failed to stream blob from peers for $trackId", it)
}
@@ -27,7 +27,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.jobs.JobKinds
import com.gregshuflin.synchronicity.jobs.rememberJobControl
import com.gregshuflin.synchronicity.podcast.AudioPlayerProvider
@@ -102,8 +101,7 @@ private const val MUSIC_TAB_FOLDERS = "folders"
@Composable
fun MusicScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
val context = LocalContext.current
val nativeLib = NativeLib
val repository = remember { MusicRepository(nativeLib) }
val repository = remember { MusicRepository() }
// Music's own handle on the shared transport: while a podcast holds it, this reads as idle
// rather than showing the bar where somebody else's episode is paused.
val audioPlayerManager = remember {
@@ -139,7 +137,7 @@ fun MusicScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
// Only the milliseconds between the tap and the `LibraryBuild` job row existing; after that
// the job is the whole truth. See `jobs/JobBinding.kt`.
var buildStarting by remember { mutableStateOf(false) }
var reloadKey by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
var reloadKey by rememberReloadKey(ChangeChannel.DOCUMENTS)
var blobAvailability by remember { mutableStateOf(BlobAvailability.Unknown) }
val playbackState by audioPlayerManager.playbackState.collectAsState()
@@ -14,12 +14,11 @@ private const val TAG = "NotebookActiveStateRepository"
* failure handling: a failure to persist it degrades to "reopen to the first notebook" rather than
* something worth surfacing as an error, unlike [NotebookRepository]'s writes.
*/
class NotebookActiveStateRepository(private val nativeLib: NativeLib) {
class NotebookActiveStateRepository {
suspend fun getActiveNotebook(): String? =
withContext(Dispatchers.IO) {
nativeLib
.ffi { notebook().getActiveNotebook() }
NativeLib.ffi { notebook().getActiveNotebook() }
.getOrElse {
Log.e(TAG, "Failed to load active notebook", it)
null
@@ -28,15 +27,13 @@ class NotebookActiveStateRepository(private val nativeLib: NativeLib) {
suspend fun setActiveNotebook(notebookId: String): Unit =
withContext(Dispatchers.IO) {
nativeLib
.ffi { notebook().setActiveNotebook(notebookId) }
NativeLib.ffi { notebook().setActiveNotebook(notebookId) }
.getOrElse { Log.e(TAG, "Failed to save active notebook $notebookId", it) }
}
suspend fun getActiveNote(): String? =
withContext(Dispatchers.IO) {
nativeLib
.ffi { notebook().getActiveNote() }
NativeLib.ffi { notebook().getActiveNote() }
.getOrElse {
Log.e(TAG, "Failed to load active note", it)
null
@@ -45,8 +42,7 @@ class NotebookActiveStateRepository(private val nativeLib: NativeLib) {
suspend fun setActiveNote(noteId: String): Unit =
withContext(Dispatchers.IO) {
nativeLib
.ffi { notebook().setActiveNote(noteId) }
NativeLib.ffi { notebook().setActiveNote(noteId) }
.getOrElse { Log.e(TAG, "Failed to save active note $noteId", it) }
}
}
@@ -27,23 +27,21 @@ private const val SAVE_RETRY_DELAY_MS = 2000L
// same suppression) — splitting the class wouldn't reduce real complexity, just spread the FFI
// surface across files.
@Suppress("TooManyFunctions")
class NotebookRepository(private val nativeLib: NativeLib) {
class NotebookRepository {
// ── Read ──────────────────────────────────────────────────────────────────
suspend fun loadNotebooks(): List<NotebookUiState> =
withContext(Dispatchers.IO) {
val items =
nativeLib
.ffi { notebook().listNotebooks() }
NativeLib.ffi { notebook().listNotebooks() }
.getOrElse {
Log.e(TAG, "Failed to load notebooks", it)
return@withContext emptyList()
}
items.map { item ->
val entries =
nativeLib
.ffi { notebook().getTree(item.id) }
NativeLib.ffi { notebook().getTree(item.id) }
.getOrElse {
Log.e(TAG, "Failed to load tree for notebook ${item.id}", it)
emptyList()
@@ -56,8 +54,7 @@ class NotebookRepository(private val nativeLib: NativeLib) {
suspend fun reloadNotebook(notebookId: String, currentTitle: String): NotebookUiState =
withContext(Dispatchers.IO) {
val entries =
nativeLib
.ffi { notebook().getTree(notebookId) }
NativeLib.ffi { notebook().getTree(notebookId) }
.getOrElse {
Log.e(TAG, "Failed to reload notebook $notebookId", it)
emptyList()
@@ -79,15 +76,13 @@ class NotebookRepository(private val nativeLib: NativeLib) {
suspend fun getNote(noteId: String): NoteBodyState =
withContext(Dispatchers.IO) {
val content =
nativeLib
.ffi { notebook().getNote(noteId) }
NativeLib.ffi { notebook().getNote(noteId) }
.getOrElse {
Log.e(TAG, "Failed to load note for $noteId", it)
null
}
val availability =
nativeLib
.ffi { notebook().noteBodyAvailability(noteId) }
NativeLib.ffi { notebook().noteBodyAvailability(noteId) }
.getOrElse {
Log.e(TAG, "Failed to read body availability for $noteId", it)
// Never guess "editable" on a failed read: the whole point of the check is
@@ -102,20 +97,19 @@ class NotebookRepository(private val nativeLib: NativeLib) {
/** Applies whether or not this node holds the body: the format is its own artifact. */
suspend fun setNoteFormat(noteId: String, format: TextFormat): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().setNoteFormat(noteId, format) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().setNoteFormat(noteId, format) } }
/**
* Discard a body no node has claimed and start a fresh, empty one. Destructive and explicit —
* see [uniffi.synchronicity.NotebookFfi.abandonAbsentBody].
*/
suspend fun abandonAbsentBody(noteId: String): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().abandonAbsentBody(noteId) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().abandonAbsentBody(noteId) } }
/** Edit/Preview/Split — a Notes-agent setting (not per-note), synced per ADR 0018. */
suspend fun getViewMode(): NotesViewMode =
withContext(Dispatchers.IO) {
nativeLib
.ffi { notebook().getViewMode() }
NativeLib.ffi { notebook().getViewMode() }
.getOrElse {
Log.e(TAG, "Failed to load view mode", it)
NotesViewMode.EDIT
@@ -123,15 +117,14 @@ class NotebookRepository(private val nativeLib: NativeLib) {
}
suspend fun setViewMode(mode: NotesViewMode): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().setViewMode(mode) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().setViewMode(mode) } }
/**
* LaTeX or Typst for `$...$` spans in markdown notes — see docs/notes-markup-rendering.md §5.1.
*/
suspend fun getMathDialect(): MathDialect =
withContext(Dispatchers.IO) {
nativeLib
.ffi { notebook().getMathDialect() }
NativeLib.ffi { notebook().getMathDialect() }
.getOrElse {
Log.e(TAG, "Failed to load math dialect", it)
MathDialect.LATEX
@@ -139,7 +132,7 @@ class NotebookRepository(private val nativeLib: NativeLib) {
}
suspend fun setMathDialect(dialect: MathDialect): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().setMathDialect(dialect) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().setMathDialect(dialect) } }
// ── Write ─────────────────────────────────────────────────────────────────
//
@@ -149,28 +142,28 @@ class NotebookRepository(private val nativeLib: NativeLib) {
// document ID in the UI state. Nothing here calls getOrThrow — see docs/adr/0022.
suspend fun createNotebook(title: String): Result<String> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().createNotebook(title) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().createNotebook(title) } }
/** [parentId] is the notebook or collection document ID (never ROOT_ID). */
suspend fun createNote(parentId: String, title: String): Result<String> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().createNote(parentId, title) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().createNote(parentId, title) } }
/** [parentId] is the notebook or collection document ID (never ROOT_ID). */
suspend fun createCollection(parentId: String, title: String): Result<String> =
withContext(Dispatchers.IO) {
nativeLib.ffi { notebook().createCollection(parentId, title) }
NativeLib.ffi { notebook().createCollection(parentId, title) }
}
suspend fun updateNote(noteId: String, newTitle: String, newBody: String): Result<Unit> =
withContext(Dispatchers.IO) {
retryOnBusy { nativeLib.ffi { notebook().updateNote(noteId, newTitle, newBody) } }
retryOnBusy { NativeLib.ffi { notebook().updateNote(noteId, newTitle, newBody) } }
}
suspend fun renameItem(id: String, newTitle: String): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().renameItem(id, newTitle) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().renameItem(id, newTitle) } }
suspend fun deleteItem(id: String): Result<Unit> =
withContext(Dispatchers.IO) { nativeLib.ffi { notebook().deleteItem(id) } }
withContext(Dispatchers.IO) { NativeLib.ffi { notebook().deleteItem(id) } }
/**
* Runs [block], retrying a failure up to [SAVE_RETRIES] times (waiting [SAVE_RETRY_DELAY_MS]
@@ -78,9 +78,9 @@ private enum class NotesScreenPane {
}
@Composable
fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Modifier) {
val repository = remember { NotebookRepository(nativeLib) }
val activeState = remember { NotebookActiveStateRepository(nativeLib) }
fun NotesScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
val repository = remember { NotebookRepository() }
val activeState = remember { NotebookActiveStateRepository() }
val scope = rememberCoroutineScope()
val snackbar = LocalSnackbarController.current
@@ -125,23 +125,21 @@ fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = M
val imageCache = remember { mutableStateMapOf<String, Bitmap?>() }
LaunchedEffect(session.noteId) { imageCache.clear() }
val imageContext =
remember(nativeLib) {
ImageContext { documentId ->
if (!imageCache.containsKey(documentId)) {
imageCache[documentId] = null // claim, so a slow load isn't kicked off twice
scope.launch(Dispatchers.IO) {
val bytes =
nativeLib
.ffi { documents().getBlobBytes(documentId) }
.getOrLog(TAG, "Blob not available for document $documentId")
imageCache[documentId] =
bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }
}
val imageContext = remember {
ImageContext { documentId ->
if (!imageCache.containsKey(documentId)) {
imageCache[documentId] = null // claim, so a slow load isn't kicked off twice
scope.launch(Dispatchers.IO) {
val bytes =
NativeLib.ffi { documents().getBlobBytes(documentId) }
.getOrLog(TAG, "Blob not available for document $documentId")
imageCache[documentId] =
bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }
}
imageCache[documentId]
}
imageCache[documentId]
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
@@ -211,28 +209,25 @@ fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = M
notebooks = notebooks.map { if (it.id == nbId) updated else it }
}
val linkContext =
remember(nativeLib) {
LinkContext(
onNavigateToDocument = { documentId ->
scope.launch {
saveCurrentNote()
session.noteId = documentId
}
},
// Overridden by NoteEditorPane's preview, which knows the open note's own
// heading→scroll-index map; kept here only so LinkContext is fully populated.
onNavigateToAnchor = {},
onOpenUrl = { url ->
// Best-effort: no app registered for the scheme is a normal outcome, not
// worth a snackbar — but worth a log rather than vanishing.
runCatching {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
.onFailure { Log.d(TAG, "No handler for $url", it) }
},
)
}
val linkContext = remember {
LinkContext(
onNavigateToDocument = { documentId ->
scope.launch {
saveCurrentNote()
session.noteId = documentId
}
},
// Overridden by NoteEditorPane's preview, which knows the open note's own
// heading→scroll-index map; kept here only so LinkContext is fully populated.
onNavigateToAnchor = {},
onOpenUrl = { url ->
// Best-effort: no app registered for the scheme is a normal outcome, not
// worth a snackbar — but worth a log rather than vanishing.
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
.onFailure { Log.d(TAG, "No handler for $url", it) }
},
)
}
// ── Initial load ──────────────────────────────────────────────────────────
@@ -257,12 +252,12 @@ fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = M
mathDialect = repository.getMathDialect()
// A node-local presentation preference, so it comes from Settings
// rather than the notebook's synced agent-settings document.
proseFont = nativeLib.ffi { settings().getProseFont() }.getOrElse { ProseFont.SOURCE_SERIF }
proseFont = NativeLib.ffi { settings().getProseFont() }.getOrElse { ProseFont.SOURCE_SERIF }
// Set from the note toolbar's own picker (ADR 0032 §5), which writes it straight back
// to Settings — so this is the same "read once on entry" pattern proseFont uses above,
// not a live subscription.
readingSurface =
nativeLib.ffi { settings().getReadingSurface() }.getOrElse { ReadingSurface.PAPER }
NativeLib.ffi { settings().getReadingSurface() }.getOrElse { ReadingSurface.PAPER }
}
// ── The tree and the open note follow the store ───────────────────────────
@@ -273,7 +268,7 @@ fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = M
// unsaved work in it and a body is not a row (AGENTS.md, "A sync must never disrupt what
// the user is doing"). `session.body` is untouched by anything here.
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) {
OnStoreChange(ChangeChannel.DOCUMENTS) {
notebooks = repository.loadNotebooks()
val openId = session.noteId ?: return@OnStoreChange
@@ -343,7 +338,7 @@ fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = M
onProseFontChange = { newFont ->
proseFont = newFont
scope.launchReportingFailure(snackbar, TAG, "change note body typeface") {
nativeLib.ffi { settings().setProseFont(newFont) }.bind()
NativeLib.ffi { settings().setProseFont(newFont) }.bind()
}
},
onBack = { screenPane = NotesScreenPane.NOTEBOOK },
@@ -440,7 +435,7 @@ fun NotesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = M
// Settings, not to the notebook's synced agent-settings document.
readingSurface = newSurface
scope.launchReportingFailure(snackbar, TAG, "change reading surface") {
nativeLib.ffi { settings().setReadingSurface(newSurface) }.bind()
NativeLib.ffi { settings().setReadingSurface(newSurface) }.bind()
}
},
onSaveRequest = {
@@ -29,8 +29,6 @@ class P2PService : Service() {
private const val RETRY_SUSTAINED_MS = 30_000L
}
private val nativeLib = NativeLib
// SupervisorJob alone is NOT a crash barrier: it stops a failing child from canceling its
// siblings, then hands the exception to the thread's default uncaught handler, which kills the
// process. Only the CoroutineExceptionHandler actually stops it here. This service has no UI to
@@ -45,7 +43,7 @@ class P2PService : Service() {
override fun onCreate() {
super.onCreate()
try {
nativeLib.initialize(this)
NativeLib.initialize(this)
} catch (e: Exception) {
// The store couldn't be opened; there's nothing for this service to do. The UI surfaces
// the error to the user, so just stop quietly here. Catches broadly rather than only
@@ -62,7 +60,7 @@ class P2PService : Service() {
serviceScope.launch {
val intervals = RETRY_INTERVALS_MS.iterator()
while (isActive) {
val result = nativeLib.ffi { ensemble().startP2pNode() }
val result = NativeLib.ffi { ensemble().startP2pNode() }
if (result.isSuccess) {
Log.d(TAG, "P2P node started successfully")
break
@@ -81,8 +79,7 @@ class P2PService : Service() {
override fun onDestroy() {
super.onDestroy()
serviceScope.cancel()
nativeLib
.ffi { ensemble().stopP2pNode() }
NativeLib.ffi { ensemble().stopP2pNode() }
.onSuccess { Log.d(TAG, "P2P node stopped") }
.onFailure { Log.e(TAG, "Failed to stop P2P node", it) }
}
@@ -68,13 +68,12 @@ fun PdfLibraryScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
val snackbar = LocalSnackbarController.current
val nativeLib = NativeLib
val fetchStrings = rememberContentFetchStrings()
var pdfDocuments by remember { mutableStateOf<List<PdfListItem>>(emptyList()) }
// Cover thumbnails stream in on a background dispatcher, keyed by document
// id; the MediaLibrary falls back to a PDF glyph for any not yet rendered.
val thumbnails = remember { mutableStateMapOf<String, ImageBitmap>() }
var refreshTrigger by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
var refreshTrigger by rememberReloadKey(ChangeChannel.DOCUMENTS)
// Saveable so a rotation (or a trip into the viewer and back) doesn't
// silently widen the list back out from under whatever the user was
// looking at.
@@ -87,7 +86,7 @@ fun PdfLibraryScreen(
// reason and a Try again — §4.1's settled-failed state. A snackbar can't do that job: it
// leaves, and what it leaves behind is a library that looks like nothing happened.
var openFailure by remember { mutableStateOf<OpenFailure?>(null) }
val liveFetch = rememberRemoteFetch(nativeLib, openingId)
val liveFetch = rememberRemoteFetch(openingId)
val remoteFetch =
openFailure?.let { liveFetch.copy(state = FetchDisplay.Failed(it.reason)) } ?: liveFetch
@@ -97,8 +96,7 @@ fun PdfLibraryScreen(
LaunchedEffect(refreshTrigger) {
pdfDocuments =
withContext(Dispatchers.IO) {
nativeLib
.ffi { pdf().list() }
NativeLib.ffi { pdf().list() }
.onFailure { Log.e(TAG, "Error loading PDF library", it) }
.getOrDefault(emptyList())
}
@@ -109,7 +107,7 @@ fun PdfLibraryScreen(
LaunchedEffect(pdfDocuments) {
for (doc in pdfDocuments) {
if (doc.id in thumbnails) continue
renderPdfCover(context, nativeLib, doc.id)?.let { thumbnails[doc.id] = it }
renderPdfCover(context, doc.id)?.let { thumbnails[doc.id] = it }
}
}
@@ -149,7 +147,7 @@ fun PdfLibraryScreen(
openFailure = null
openingId = id
try {
materializePdf(context, nativeLib, id)
materializePdf(context, id)
.onSuccess { path -> onDocumentPdfSelect(path, name, id) }
// The reason comes from the Rust side, which is the only layer that knows
// whether no node could be *reached* or the document has no PDF content at
@@ -175,7 +173,7 @@ fun PdfLibraryScreen(
label = "Import PDF",
onPick = { uri ->
scope.launchReportingFailure(snackbar, TAG, "import PDF") {
val name = nativeLib.importPickedFile(context, uri).bind()
val name = NativeLib.importPickedFile(context, uri).bind()
Toast.makeText(context, "Imported: $name", Toast.LENGTH_SHORT).show()
refreshTrigger++
}
@@ -223,7 +221,7 @@ fun PdfLibraryScreen(
RemoteFetchProgress(
state = remoteFetch.state,
subject = fetchStrings.pdf,
onCancel = { scope.launch { remoteFetch.cancel(nativeLib) } },
onCancel = { scope.launch { remoteFetch.cancel() } },
onRetry =
openFailure?.let { failure ->
{ scope.launch { runOpen(failure.id, failure.name) } }
@@ -251,11 +249,7 @@ fun PdfLibraryScreen(
* network, so the caller shows [com.gregshuflin.synchronicity.ui.RemoteFetchProgress] over the
* library while it runs; a snackbar at the end of a two-minute silence is not a progress state.
*/
private suspend fun materializePdf(
context: Context,
nativeLib: NativeLib,
id: String,
): Result<String> =
private suspend fun materializePdf(context: Context, id: String): Result<String> =
withContext(Dispatchers.IO) {
val target = File(context.cacheDir, "$OPEN_CACHE_PREFIX$id.pdf")
// The file has to outlive this function — the viewer reads it for as long as the PDF is
@@ -266,8 +260,7 @@ private suspend fun materializePdf(
.listFiles { file -> file.name.startsWith(OPEN_CACHE_PREFIX) && file != target }
?.forEach { it.delete() }
nativeLib
.ffi { pdf().writeToPath(id, target.absolutePath) }
NativeLib.ffi { pdf().writeToPath(id, target.absolutePath) }
.map { target.absolutePath }
.onFailure {
target.delete()
@@ -292,18 +285,14 @@ private data class OpenFailure(val id: String, val name: String, val reason: Str
* library of covers is not worth a fetch each — so a document whose bytes are elsewhere is skipped
* before it can start one.
*/
private suspend fun renderPdfCover(
context: Context,
nativeLib: NativeLib,
id: String,
): ImageBitmap? =
private suspend fun renderPdfCover(context: Context, id: String): ImageBitmap? =
withContext(Dispatchers.IO) {
if (!nativeLib.ffi { documents().isBlobLocal(id) }.getOrDefault(false))
if (!NativeLib.ffi { documents().isBlobLocal(id) }.getOrDefault(false))
return@withContext null
val cacheFile = File(context.cacheDir, "cover-$id.pdf")
@Suppress("TooGenericExceptionCaught")
try {
if (nativeLib.ffi { pdf().writeToPath(id, cacheFile.absolutePath) }.isFailure) {
if (NativeLib.ffi { pdf().writeToPath(id, cacheFile.absolutePath) }.isFailure) {
return@withContext null
}
MuPdfDocument.openFromPath(cacheFile.absolutePath).use { doc ->
@@ -43,7 +43,6 @@ fun PdfViewer(
// Read through rememberUpdatedState so the load effect (keyed only on the
// path) always reports metadata to the latest callback.
val currentOnMetadata by rememberUpdatedState(onMetadata)
val nativeLib = NativeLib
var pdfDocument by remember { mutableStateOf<MuPdfDocument?>(null) }
var pageCache by remember { mutableStateOf<PdfPageCache?>(null) }
var currentBitmap by remember { mutableStateOf<Bitmap?>(null) }
@@ -93,7 +92,7 @@ fun PdfViewer(
currentOnMetadata(withContext(Dispatchers.IO) { document.metadata() })
state.resetHistory()
val savedPage =
nativeLib.ffi { pdf().getReadingProgress(documentId) }.getOrNull()?.toInt() ?: 0
NativeLib.ffi { pdf().getReadingProgress(documentId) }.getOrNull()?.toInt() ?: 0
// Seed history with the opening page so back/forward have an anchor.
state.goToPage(savedPage)
@@ -113,8 +112,7 @@ fun PdfViewer(
LaunchedEffect(state.currentPage) {
if (state.totalPages <= 0) return@LaunchedEffect
withContext(Dispatchers.IO) {
nativeLib
.ffi { pdf().setReadingProgress(documentId, state.currentPage.toUInt()) }
NativeLib.ffi { pdf().setReadingProgress(documentId, state.currentPage.toUInt()) }
.onFailure { Log.w(TAG, "Failed to save reading progress", it) }
}
}
@@ -46,7 +46,6 @@ fun PdfViewerScreen(
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
val snackbar = LocalSnackbarController.current
val nativeLib = NativeLib
// Hoisted so the drawer can read the current page (to add a bookmark) and
// jump to a bookmark's page, while the viewer drives page rendering.
@@ -58,7 +57,7 @@ fun PdfViewerScreen(
suspend fun reloadBookmarks() {
bookmarks =
withContext(Dispatchers.IO) {
nativeLib.ffi { pdf().listBookmarks(documentId) }.getOrDefault(emptyList())
NativeLib.ffi { pdf().listBookmarks(documentId) }.getOrDefault(emptyList())
}
}
@@ -74,7 +73,7 @@ fun PdfViewerScreen(
onAddBookmark = {
scope.launchReportingFailure(snackbar, TAG, "add bookmark") {
withContext(Dispatchers.IO) {
nativeLib.ffi {
NativeLib.ffi {
pdf()
.addBookmark(
documentId,
@@ -94,7 +93,7 @@ fun PdfViewerScreen(
onDeleteBookmark = { bookmark ->
scope.launchReportingFailure(snackbar, TAG, "delete bookmark") {
withContext(Dispatchers.IO) {
nativeLib.ffi { pdf().deleteBookmark(documentId, bookmark.id) }
NativeLib.ffi { pdf().deleteBookmark(documentId, bookmark.id) }
}
.bind()
reloadBookmarks()
@@ -106,7 +106,7 @@ private const val MIN_ZOOM = 0.5f
private const val MAX_ZOOM = 8f
@Composable
fun PicturesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier = Modifier) {
fun PicturesScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
var images by remember { mutableStateOf<List<PictureTreeItem>>(emptyList()) }
var selectedId by remember { mutableStateOf<String?>(null) }
var loadState by remember { mutableStateOf<ImageLoadState>(ImageLoadState.None) }
@@ -118,12 +118,12 @@ fun PicturesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// attempt gives up — `rememberRemoteFetch` shows nothing unless a transfer actually starts,
// so arming it for a picture that turns out to be stored here costs nothing on screen.
var openingId by remember { mutableStateOf<String?>(null) }
val remoteFetch = rememberRemoteFetch(nativeLib, openingId)
val remoteFetch = rememberRemoteFetch(openingId)
val fetchStrings = rememberContentFetchStrings()
// A picture arriving from another node belongs in the tree on screen. Only the tree —
// the open image is keyed on `selectedId`, which this leaves alone.
val reloadKey by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
val reloadKey by rememberReloadKey(ChangeChannel.DOCUMENTS)
LaunchedEffect(reloadKey) {
// The agent's own tree, not a generic document search: it is where the albums and the
@@ -132,8 +132,7 @@ fun PicturesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// structural pass (ADR 0032), and nothing here has to change when it arrives.
val loaded =
withContext(Dispatchers.IO) {
nativeLib
.ffi { pictures().listTree() }
NativeLib.ffi { pictures().listTree() }
.getOrDefault(emptyList())
.filter { !it.isCollection }
}
@@ -158,8 +157,7 @@ fun PicturesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
// honest answer that nothing reachable is serving the bytes — a state to render,
// which is what `NotHere` is for.
val bytes =
nativeLib
.ffi { pictures().getImageBytes(id) }
NativeLib.ffi { pictures().getImageBytes(id) }
.getOrLog(TAG, "Image $id not available locally or from any peer")
?: return@withContext ImageLoadState.NotHere(availability)
val bitmap =
@@ -201,7 +199,7 @@ fun PicturesScreen(nativeLib: NativeLib, onBack: () -> Unit, modifier: Modifier
modifier = Modifier.weight(1f).fillMaxWidth(),
loadState = loadState,
zoom = zoom,
loadingContent = { RemoteFetchOrSpinner(remoteFetch, fetchStrings.picture, nativeLib) },
loadingContent = { RemoteFetchOrSpinner(remoteFetch, fetchStrings.picture) },
sidebarOverlay = {
AnimatedVisibility(
visible = sidebarVisible,
@@ -51,7 +51,7 @@ private const val PODCAST_AUDIO_CACHE = "podcast-audio"
// A repository is a cohesive facade over the podcast FFI surface plus in-memory
// state; its many small delegating methods are the point, not a smell.
@Suppress("TooManyFunctions")
class PodcastRepository(private val nativeLib: NativeLib) {
class PodcastRepository {
private val _podcasts = MutableStateFlow<Map<String, Podcast>>(emptyMap())
val podcasts: StateFlow<Map<String, Podcast>> = _podcasts.asStateFlow()
@@ -88,8 +88,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
withContext(Dispatchers.IO) {
Log.d(tag, "Loading podcasts from native database")
val items: List<PodcastItem> =
nativeLib
.ffi { podcast().listDocuments() }
NativeLib.ffi { podcast().listDocuments() }
.getOrElse {
Log.e(tag, "Failed to load podcasts from database", it)
return@withContext
@@ -141,8 +140,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
// getCoverArtBytes returns null on absence or failure (it logs internally).
val coverArtBytes =
carried?.coverArtBytes
?: nativeLib
.ffi { podcast().getCoverArtBytes(item.id) }
?: NativeLib.ffi { podcast().getCoverArtBytes(item.id) }
.getOrLog(tag, "Failed to load cover art for ${item.id}")
return Podcast(
@@ -168,8 +166,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
*/
suspend fun saveCustomSpeed(feedDocumentId: String, speed: Float): Result<Unit> =
withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().saveCustomSpeed(feedDocumentId, speed) }
NativeLib.ffi { podcast().saveCustomSpeed(feedDocumentId, speed) }
.onSuccess {
val updated = { m: Map<String, Podcast> ->
m.mapValues { (_, p) ->
@@ -216,8 +213,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
suspend fun loadStoredEpisodes(podcast: Podcast, feedDocumentId: String): List<PodcastEpisode> =
withContext(Dispatchers.IO) {
val items =
nativeLib
.ffi { podcast().listEpisodes(feedDocumentId) }
NativeLib.ffi { podcast().listEpisodes(feedDocumentId) }
.getOrElse { e ->
Log.e(tag, "Failed to load stored episodes for $feedDocumentId", e)
return@withContext emptyList()
@@ -262,8 +258,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
withContext(Dispatchers.IO) {
val feedDocumentId = episode.podcast.documentId.takeIf { it.isNotEmpty() }
feedDocumentId?.let {
nativeLib
.ffi { podcast().episodeDocumentId(it, episode.id) }
NativeLib.ffi { podcast().episodeDocumentId(it, episode.id) }
.onFailure { e ->
Log.w(tag, "Failed to derive document id for ${episode.id}", e)
}
@@ -282,8 +277,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
withContext(Dispatchers.IO) {
val feedDocumentId = episode.podcast.documentId.takeIf { it.isNotEmpty() }
feedDocumentId?.let {
nativeLib
.ffi { podcast().ensureEpisode(it, episode.toEpisodeInput()) }
NativeLib.ffi { podcast().ensureEpisode(it, episode.toEpisodeInput()) }
.onFailure { e -> Log.e(tag, "Failed to create document for ${episode.id}", e) }
.getOrNull()
}
@@ -299,8 +293,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
suspend fun resumePositionMillis(episodeDocumentId: String): Long =
withContext(Dispatchers.IO) {
val state =
nativeLib
.ffi { podcast().listenState(episodeDocumentId) }
NativeLib.ffi { podcast().listenState(episodeDocumentId) }
.getOrElse { e ->
Log.w(tag, "Failed to read listen state for $episodeDocumentId", e)
return@withContext 0L
@@ -327,8 +320,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
// block's value is the `Result` from `onFailure`, which this discards, and
// `IgnoredReturnValue` rightly objects to a silently dropped Result.
withContext<Unit>(Dispatchers.IO) {
nativeLib
.ffi {
NativeLib.ffi {
podcast()
.saveListenProgress(
episodeDocumentId,
@@ -343,8 +335,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
suspend fun saveListenFinished(episodeDocumentId: String) {
// `<Unit>` for the reason given in [saveListenProgress].
withContext<Unit>(Dispatchers.IO) {
nativeLib
.ffi { podcast().saveListenFinished(episodeDocumentId) }
NativeLib.ffi { podcast().saveListenFinished(episodeDocumentId) }
.onFailure { e -> Log.w(tag, "Failed to mark $episodeDocumentId finished", e) }
}
}
@@ -367,8 +358,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
): Map<String, PodcastEpisodeStateItem> =
withContext(Dispatchers.IO) {
if (feedDocumentId == null || apiIds.isEmpty()) return@withContext emptyMap()
nativeLib
.ffi { podcast().episodeStates(feedDocumentId, apiIds) }
NativeLib.ffi { podcast().episodeStates(feedDocumentId, apiIds) }
.getOrElse { e ->
Log.w(tag, "Failed to read episode state for $feedDocumentId", e)
return@withContext emptyMap()
@@ -384,8 +374,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
*/
suspend fun loadQueue(): List<PodcastQueueItem>? =
withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().queueList() }
NativeLib.ffi { podcast().queueList() }
.getOrElse { e ->
Log.e(tag, "Failed to read the podcast queue", e)
null
@@ -406,8 +395,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
suspend fun addToQueue(episode: PodcastEpisode): Result<String>? {
val documentId = ensureEpisodeDocument(episode) ?: return null
return withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().queueAdd(documentId) }
NativeLib.ffi { podcast().queueAdd(documentId) }
.onFailure { e -> Log.e(tag, "Failed to queue $documentId", e) }
.map { documentId }
}
@@ -416,24 +404,21 @@ class PodcastRepository(private val nativeLib: NativeLib) {
/** Take [episodeDocumentId] back out of the queue. */
suspend fun removeFromQueue(episodeDocumentId: String): Result<Unit> =
withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().queueRemove(episodeDocumentId) }
NativeLib.ffi { podcast().queueRemove(episodeDocumentId) }
.onFailure { e -> Log.e(tag, "Failed to unqueue $episodeDocumentId", e) }
}
/** Move [episodeDocumentId] one slot toward the front of the queue. */
suspend fun moveUpInQueue(episodeDocumentId: String): Result<Unit> =
withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().queueMoveUp(episodeDocumentId) }
NativeLib.ffi { podcast().queueMoveUp(episodeDocumentId) }
.onFailure { e -> Log.e(tag, "Failed to move $episodeDocumentId up the queue", e) }
}
/** [moveUpInQueue], toward the back. */
suspend fun moveDownInQueue(episodeDocumentId: String): Result<Unit> =
withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().queueMoveDown(episodeDocumentId) }
NativeLib.ffi { podcast().queueMoveDown(episodeDocumentId) }
.onFailure { e ->
Log.e(tag, "Failed to move $episodeDocumentId down the queue", e)
}
@@ -453,8 +438,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
suspend fun saveEpisode(episode: PodcastEpisode): Result<String>? {
val feedDocumentId = episode.podcast.documentId.takeIf { it.isNotEmpty() } ?: return null
return withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().saveEpisode(feedDocumentId, episode.toEpisodeInput()) }
NativeLib.ffi { podcast().saveEpisode(feedDocumentId, episode.toEpisodeInput()) }
.onFailure { e -> Log.e(tag, "Failed to save ${episode.id} for offline", e) }
}
}
@@ -468,8 +452,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
*/
suspend fun removeDownload(episodeDocumentId: String): Result<Boolean> =
withContext(Dispatchers.IO) {
nativeLib
.ffi { podcast().releaseEpisodeAudio(episodeDocumentId) }
NativeLib.ffi { podcast().releaseEpisodeAudio(episodeDocumentId) }
.onFailure { e ->
Log.e(tag, "Failed to drop the saved copy of $episodeDocumentId", e)
}
@@ -478,7 +461,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
/** Whether this node holds [episodeDocumentId]'s audio, so it plays with no network. */
suspend fun isSavedLocally(episodeDocumentId: String): Boolean =
withContext(Dispatchers.IO) {
nativeLib.ffi { documents().isBlobLocal(episodeDocumentId) }.getOrDefault(false)
NativeLib.ffi { documents().isBlobLocal(episodeDocumentId) }.getOrDefault(false)
}
/**
@@ -494,8 +477,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
withContext(Dispatchers.IO) {
val documentId = episodeDocumentId(episode) ?: return@withContext episode.audioUri
val path =
nativeLib
.ffi {
NativeLib.ffi {
podcast()
.localAudioPath(
documentId,
@@ -515,8 +497,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
val coverArtUri = podcast.coverArtUri?.toString()
Log.d(tag, "Subscribing to podcast: $id")
val documentId =
nativeLib
.ffi {
NativeLib.ffi {
podcast()
.subscribe(
id = id,
@@ -544,8 +525,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
suspend fun unsubscribeFromPodcast(documentId: String): Result<Unit> =
withContext(Dispatchers.IO) {
Log.d(tag, "Unsubscribing from podcast document: $documentId")
nativeLib
.ffi { podcast().unsubscribe(documentId) }
NativeLib.ffi { podcast().unsubscribe(documentId) }
.getOrElse { e ->
Log.e(tag, "Failed to unsubscribe from podcast: $documentId", e)
return@withContext Result.failure(e)
@@ -567,8 +547,7 @@ class PodcastRepository(private val nativeLib: NativeLib) {
Log.w(tag, "Failed to download cover art for $documentId", e)
return
}
nativeLib
.ffi { podcast().storeCoverArt(documentId, imageBytes) }
NativeLib.ffi { podcast().storeCoverArt(documentId, imageBytes) }
.onSuccess {
Log.d(tag, "Stored cover art for document $documentId (${imageBytes.size} bytes)")
}
@@ -13,7 +13,6 @@ import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.podcast.ui.EpisodePlayerScreen
import com.gregshuflin.synchronicity.podcast.ui.PodcastDetailScreen
import com.gregshuflin.synchronicity.podcast.ui.PodcastInfoScreen
@@ -39,9 +38,8 @@ private const val TAG = "PodcastScreen"
@Composable
fun PodcastScreen(
onBackToMain: () -> Unit,
nativeLib: NativeLib,
navController: NavHostController = rememberNavController(),
podcastRepository: PodcastRepository = remember { PodcastRepository(nativeLib) },
podcastRepository: PodcastRepository = remember { PodcastRepository() },
) {
val scope = rememberCoroutineScope()
val snackbar = LocalSnackbarController.current
@@ -58,7 +56,6 @@ fun PodcastScreen(
composable<PodcastLibraryRoute> {
PodcastLibraryScreen(
podcastRepository = podcastRepository,
nativeLib = nativeLib,
onBack = onBackToMain,
onPodcastSelect = { podcast ->
navController.navigate(PodcastDetailRoute(podcast.id))
@@ -76,7 +73,6 @@ fun PodcastScreen(
composable<PodcastSearchRoute> {
PodcastSearchScreen(
nativeLib = nativeLib,
onBack = { navController.popBackStack() },
onPodcastSelect = { podcast ->
podcastRepository.addPodcast(podcast)
@@ -94,7 +90,6 @@ fun PodcastScreen(
PodcastDetailScreen(
podcast = podcast,
podcastRepository = podcastRepository,
nativeLib = nativeLib,
onBack = { navController.popBackStack() },
onInfoSelect = { navController.navigate(PodcastInfoRoute(podcastId)) },
onEpisodeSelect = { episode ->
@@ -53,7 +53,6 @@ private const val QUEUE_ACTION = "add that episode to the queue"
fun PodcastDetailScreen(
podcast: Podcast,
podcastRepository: PodcastRepository,
nativeLib: NativeLib,
onBack: () -> Unit,
onInfoSelect: () -> Unit,
onEpisodeSelect: (PodcastEpisode) -> Unit,
@@ -89,7 +88,7 @@ fun PodcastDetailScreen(
val id =
podcastIdLong ?: return Result.failure(SyncException.InvalidInput("Invalid podcast ID"))
return withContext(Dispatchers.IO) {
nativeLib.ffi { podcast().fetchEpisodes(id, max.toLong()) }
NativeLib.ffi { podcast().fetchEpisodes(id, max.toLong()) }
}
.map { items -> items.map { it.toPodcastEpisode(podcast) } }
}
@@ -148,7 +147,7 @@ fun PodcastDetailScreen(
// An episode another node played is the ordinary way a document appears here: it wrote one, and
// it syncs to this phone like any other. So this screen re-layers the store over the list it is
// showing rather than waiting for the next fetch to notice.
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) {
OnStoreChange(ChangeChannel.DOCUMENTS) {
// The header is store data too — a title edited or cover art arriving on another node, and
// the remembered playback rate the player reads off this record.
podcastRepository.reloadPodcasts()
@@ -10,7 +10,6 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.OnStoreChange
import com.gregshuflin.synchronicity.documents.ui.DocumentList
import com.gregshuflin.synchronicity.podcast.Podcast
@@ -34,7 +33,6 @@ private enum class PodcastLibraryMode(val label: String, val icon: ImageVector)
@Composable
fun PodcastLibraryScreen(
podcastRepository: PodcastRepository,
nativeLib: NativeLib,
onBack: () -> Unit,
onPodcastSelect: (Podcast) -> Unit,
onEpisodeSelect: (PodcastEpisode) -> Unit,
@@ -51,7 +49,7 @@ fun PodcastLibraryScreen(
// announced: an arrival lands in its own place in a list sorted by nothing the user chose,
// there is no cursor here to move, and the search box above it is local state a reload leaves
// alone. The repository decides whether anything actually changed.
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) { podcastRepository.reloadPodcasts() }
OnStoreChange(ChangeChannel.DOCUMENTS) { podcastRepository.reloadPodcasts() }
// Saveable, not merely remembered: playing something from the Queue tab leaves this screen and
// comes back, and returning to Subscriptions because the composition was disposed would read as
@@ -104,7 +102,6 @@ fun PodcastLibraryScreen(
PodcastLibraryMode.Queue ->
PodcastQueueList(
podcastRepository = podcastRepository,
nativeLib = nativeLib,
subscribed = podcasts,
onEpisodeSelect = onEpisodeSelect,
modifier = Modifier.fillMaxSize(),
@@ -33,7 +33,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.OnStoreChange
import com.gregshuflin.synchronicity.podcast.Podcast
import com.gregshuflin.synchronicity.podcast.PodcastEpisode
@@ -85,7 +84,6 @@ private const val REMOVE_ACTION = "remove that episode from the queue"
@Composable
fun PodcastQueueList(
podcastRepository: PodcastRepository,
nativeLib: NativeLib,
subscribed: Map<String, Podcast>,
onEpisodeSelect: (PodcastEpisode) -> Unit,
modifier: Modifier = Modifier,
@@ -114,7 +112,7 @@ fun PodcastQueueList(
// A queue entry is an artifact, so a reorder made on another node arrives on the documents
// channel like any other change — as does this screen's own write a beat after it is made,
// which is exactly why the same list is not news.
OnStoreChange(nativeLib, ChangeChannel.DOCUMENTS) {
OnStoreChange(ChangeChannel.DOCUMENTS) {
val fresh = podcastRepository.loadQueue() ?: return@OnStoreChange
if (fresh != shown) held = fresh
}
@@ -112,7 +112,6 @@ private fun SearchResults(
@Composable
fun PodcastSearchScreen(
nativeLib: NativeLib,
onBack: () -> Unit,
onPodcastSelect: (Podcast) -> Unit,
modifier: Modifier = Modifier,
@@ -135,7 +134,7 @@ fun PodcastSearchScreen(
searchResults = emptyList()
// Any search failure degrades to the inline error state rather than the snackbar —
// this screen owns its own error surface.
withContext(Dispatchers.IO) { nativeLib.ffi { podcast().search(searchQuery) } }
withContext(Dispatchers.IO) { NativeLib.ffi { podcast().search(searchQuery) } }
.onSuccess { searchResults = it }
.onFailure { failure ->
error = failure.userMessage
@@ -80,12 +80,7 @@ private data class Attempt(val peer: String, val error: String)
* stated beside it: the user is the one who knows whether another node is reachable right now.
*/
@Composable
fun RetirementScreen(
nativeLib: NativeLib,
nodeName: String,
onFinish: () -> Unit,
modifier: Modifier = Modifier,
) {
fun RetirementScreen(nodeName: String, onFinish: () -> Unit, modifier: Modifier = Modifier) {
val context = LocalContext.current
val copy = SharedCopy.revocation
var phase by remember { mutableStateOf(Phase.STARTING) }
@@ -104,7 +99,7 @@ fun RetirementScreen(
if (wiping) return
wiping = true
phase = Phase.WIPING
NodeReset.perform(context, nativeLib)
NodeReset.perform(context)
.onSuccess {
Log.i(TAG, "This node is retired and wiped")
onFinish()
@@ -120,7 +115,7 @@ fun RetirementScreen(
LaunchedEffect(Unit) {
val started =
withContext(Dispatchers.IO) { nativeLib.ffi { ensemble().beginRetirement() } }
withContext(Dispatchers.IO) { NativeLib.ffi { ensemble().beginRetirement() } }
.onFailure {
phase = Phase.FAILED
failure = it.userMessage
@@ -140,7 +135,7 @@ fun RetirementScreen(
while (!wiping) {
val round =
withContext(Dispatchers.IO) {
nativeLib.ffi { ensemble().pushRetirementRound(blob) }
NativeLib.ffi { ensemble().pushRetirementRound(blob) }
}
.onFailure { Log.w(TAG, "Retirement delivery round failed to run", it) }
.getOrNull()
@@ -40,7 +40,7 @@ class SchedulerWorker(context: Context, params: WorkerParameters) :
Log.d(TAG, "Node not initialized yet; skipping this tick")
return Result.success()
}
return runTickIfEligible(NativeLib) ?: Result.success()
return runTickIfEligible() ?: Result.success()
}
/**
@@ -49,18 +49,16 @@ class SchedulerWorker(context: Context, params: WorkerParameters) :
* `WorkRequest`'s own [Constraints] (see [schedule]), which [schedule] rewrites on every
* settings change, and WorkManager stops a running worker whose constraints stop holding.
*/
private fun runTickIfEligible(nativeLib: NativeLib): Result? {
private fun runTickIfEligible(): Result? {
val settings =
nativeLib
.ffi { settings().getSchedulerSettings() }
NativeLib.ffi { settings().getSchedulerSettings() }
.onFailure { Log.w(TAG, "Failed to load scheduler settings", it) }
.getOrNull()
if (settings?.enabled != true) {
Log.d(TAG, "Scheduler disabled; skipping this tick")
return null
}
return nativeLib
.ffi { settings().runSchedulerPasses() }
return NativeLib.ffi { settings().runSchedulerPasses() }
.fold(
onSuccess = { summary ->
val fetched =
@@ -59,7 +59,6 @@ private val GAP = 12.dp
*/
@Composable
fun CredentialsSettingsScreen(
nativeLib: NativeLib,
onBack: () -> Unit,
modifier: Modifier = Modifier,
applySafePadding: Boolean = true,
@@ -70,8 +69,7 @@ fun CredentialsSettingsScreen(
var reloadToken by remember { mutableIntStateOf(0) }
LaunchedEffect(reloadToken) {
nativeLib
.ffi { credentials().services() }
NativeLib.ffi { credentials().services() }
.onSuccess {
services = it
error = null
@@ -116,8 +114,7 @@ fun CredentialsSettingsScreen(
error = null
for ((field, value) in entered) {
val failed =
nativeLib
.ffi { credentials().setField(service.id, field, value) }
NativeLib.ffi { credentials().setField(service.id, field, value) }
.exceptionOrNull()
if (failed != null) {
error = failed.userMessage
@@ -127,8 +124,7 @@ fun CredentialsSettingsScreen(
reloadToken++
},
onClear = {
nativeLib
.ffi { credentials().clear(service.id) }
NativeLib.ffi { credentials().clear(service.id) }
.onSuccess { error = null }
.onFailure { error = it.userMessage }
reloadToken++
@@ -42,26 +42,24 @@ fun SettingsView(
modifier: Modifier = Modifier,
applySafePadding: Boolean = true,
) {
val nativeLib = NativeLib
val buildInfo = remember { buildInfo() }
var allowUnverifiedDeletion by remember {
mutableStateOf(
nativeLib
.ffi { eviction().getAllowUnverifiedDeletion() }
NativeLib.ffi { eviction().getAllowUnverifiedDeletion() }
.onFailure { Log.w(TAG, "Failed to load allow-unverified-deletion setting", it) }
.getOrDefault(false)
)
}
// Node name state — loaded once, edited locally, saved on confirm.
var nodeName by remember { mutableStateOf(nativeLib.nodeName().orEmpty()) }
var nodeName by remember { mutableStateOf(NativeLib.nodeName().orEmpty()) }
var nodeNameSaved by remember { mutableStateOf(false) }
val logConfig = remember { nativeLib.ffi { settings().getLogConfig() }.getOrNull() }
val logConfig = remember { NativeLib.ffi { settings().getLogConfig() }.getOrNull() }
var logVerbosity by remember { mutableStateOf(logConfig?.verbosity ?: LogVerbosity.NORMAL) }
var showIrohLogs by remember { mutableStateOf(logConfig?.showIrohLogs ?: false) }
val allTimezones = remember { listTimezones() }
var timezoneSearch by remember { mutableStateOf("") }
var timezoneSaved by remember { mutableStateOf(nativeLib.timezone().orEmpty()) }
var timezoneSaved by remember { mutableStateOf(NativeLib.timezone().orEmpty()) }
val filteredTimezones =
remember(timezoneSearch) {
if (timezoneSearch.isBlank()) emptyList()
@@ -98,8 +96,7 @@ fun SettingsView(
keyboardActions =
KeyboardActions(
onDone = {
nativeLib
.ffi { settings().setNodeName(nodeName.ifBlank { null }) }
NativeLib.ffi { settings().setNodeName(nodeName.ifBlank { null }) }
.onSuccess { nodeNameSaved = true }
.onFailure { Log.w(TAG, "Failed to save node name", it) }
}
@@ -116,8 +113,7 @@ fun SettingsView(
}
TextButton(
onClick = {
nativeLib
.ffi { settings().setNodeName(nodeName.ifBlank { null }) }
NativeLib.ffi { settings().setNodeName(nodeName.ifBlank { null }) }
.onSuccess { nodeNameSaved = true }
.onFailure { Log.w(TAG, "Failed to save node name", it) }
}
@@ -152,7 +148,7 @@ fun SettingsView(
isSelected = { it == logVerbosity },
onSelect = { level ->
logVerbosity = level
nativeLib.setLogConfig(level, showIrohLogs).onFailure {
NativeLib.setLogConfig(level, showIrohLogs).onFailure {
Log.w(TAG, "Failed to save log verbosity", it)
}
},
@@ -170,7 +166,7 @@ fun SettingsView(
checked = showIrohLogs,
onCheckedChange = { checked ->
showIrohLogs = checked
nativeLib.setLogConfig(logVerbosity, checked).onFailure {
NativeLib.setLogConfig(logVerbosity, checked).onFailure {
Log.w(TAG, "Failed to save iroh log setting", it)
}
},
@@ -207,8 +203,7 @@ fun SettingsView(
)
TextButton(
onClick = {
nativeLib
.ffi { settings().setTimezone(null) }
NativeLib.ffi { settings().setTimezone(null) }
.onSuccess {
timezoneSaved = ""
timezoneSearch = ""
@@ -246,8 +241,7 @@ fun SettingsView(
modifier =
Modifier.fillMaxWidth()
.clickable {
nativeLib
.ffi { settings().setTimezone(tz) }
NativeLib.ffi { settings().setTimezone(tz) }
.onSuccess {
timezoneSaved = tz
timezoneSearch = ""
@@ -324,8 +318,7 @@ fun SettingsView(
label = "Allow deleting unverified content",
checked = allowUnverifiedDeletion,
onCheckedChange = { allow ->
nativeLib
.ffi { eviction().setAllowUnverifiedDeletion(allow) }
NativeLib.ffi { eviction().setAllowUnverifiedDeletion(allow) }
.onSuccess { allowUnverifiedDeletion = allow }
.onFailure {
Log.w(TAG, "Failed to save allow-unverified-deletion setting", it)
@@ -9,7 +9,6 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.gregshuflin.synchronicity.NativeLib
import com.gregshuflin.synchronicity.ensemble.EnsembleScreen
import com.gregshuflin.synchronicity.ui.SectionTabs
import com.gregshuflin.synchronicity.ui.fillMaxSizeWithSafePadding
@@ -29,7 +28,6 @@ import com.gregshuflin.synchronicity.ui.theme.ThemeState
@Composable
fun SettingsScreen(
themeState: ThemeState,
nativeLib: NativeLib,
onBackToMain: () -> Unit,
modifier: Modifier = Modifier,
initialSection: SettingsSection = SettingsSection.SYSTEM,
@@ -65,14 +63,9 @@ fun SettingsScreen(
SettingsSection.SYNC ->
SyncSettingsScreen(onBack = onBackToMain, applySafePadding = false)
SettingsSection.CREDENTIALS ->
CredentialsSettingsScreen(
nativeLib = nativeLib,
onBack = onBackToMain,
applySafePadding = false,
)
CredentialsSettingsScreen(onBack = onBackToMain, applySafePadding = false)
SettingsSection.ENSEMBLE ->
EnsembleScreen(
nativeLib = nativeLib,
onBack = onBackToMain,
applySafePadding = false,
// Retiring is an ensemble act and lives with the roster it affects;
@@ -80,7 +80,6 @@ fun SyncSettingsScreen(
applySafePadding: Boolean = true,
) {
val context = LocalContext.current
val nativeLib = NativeLib
val policyOptions = remember { getSyncPolicyOptions() }
// Loaded in the LaunchedEffect below rather than here: each row carries its content ledger
// now, and building that stats a file per blob-backed artifact — not something to do on the
@@ -89,12 +88,11 @@ fun SyncSettingsScreen(
var policies by remember { mutableStateOf<List<DocumentSyncPolicy>>(emptyList()) }
var reclaimFlow by remember { mutableStateOf<ReclaimFlow?>(null) }
val allowUnverifiedDeletion = remember {
nativeLib.ffi { eviction().getAllowUnverifiedDeletion() }.getOrDefault(false)
NativeLib.ffi { eviction().getAllowUnverifiedDeletion() }.getOrDefault(false)
}
var schedulerSettings by remember {
mutableStateOf(
nativeLib
.ffi { settings().getSchedulerSettings() }
NativeLib.ffi { settings().getSchedulerSettings() }
.onFailure { Log.w(TAG, "Failed to load scheduler settings", it) }
.getOrDefault(
SchedulerSettings(
@@ -123,10 +121,10 @@ fun SyncSettingsScreen(
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) { nativeLib.ffi { settings().getSyncPolicies() } }
withContext(Dispatchers.IO) { NativeLib.ffi { settings().getSyncPolicies() } }
.onSuccess { policies = it }
.onFailure { Log.w(TAG, "Failed to load sync policies", it) }
withContext(Dispatchers.IO) { nativeLib.ffi { ensemble().getEnsembleStatus() } }
withContext(Dispatchers.IO) { NativeLib.ffi { ensemble().getEnsembleStatus() } }
.onSuccess { data -> otherNodes = data.members.filter { !it.isThisNode } }
.onFailure { Log.w(TAG, "Failed to load ensemble members", it) }
}
@@ -137,7 +135,7 @@ fun SyncSettingsScreen(
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { remoteAdmin().getSyncConfig(nodeIdHex) }
NativeLib.ffi { remoteAdmin().getSyncConfig(nodeIdHex) }
}
remoteLoading = false
result
@@ -159,7 +157,7 @@ fun SyncSettingsScreen(
*/
fun reloadPolicies() {
scope.launch {
withContext(Dispatchers.IO) { nativeLib.ffi { settings().getSyncPolicies() } }
withContext(Dispatchers.IO) { NativeLib.ffi { settings().getSyncPolicies() } }
.onSuccess { policies = it }
.onFailure { Log.w(TAG, "Failed to reload sync policies", it) }
}
@@ -167,7 +165,7 @@ fun SyncSettingsScreen(
/** Re-read the scheduler row, for the same reason [reloadPolicies] re-reads the policies. */
suspend fun reloadSchedulerSettings() {
withContext(Dispatchers.IO) { nativeLib.ffi { settings().getSchedulerSettings() } }
withContext(Dispatchers.IO) { NativeLib.ffi { settings().getSchedulerSettings() } }
.onSuccess { schedulerSettings = it }
.onFailure { Log.w(TAG, "Failed to reload scheduler settings", it) }
}
@@ -176,7 +174,7 @@ fun SyncSettingsScreen(
// node's over `/syn/node-admin/…`, and until the settings row announced itself this screen
// could sit showing a policy that had stopped being true. Applied outright — these are
// switches and menus showing what is on file, with nothing staged behind them to lose.
OnStoreChange(nativeLib, ChangeChannel.SETTINGS) {
OnStoreChange(ChangeChannel.SETTINGS) {
reloadPolicies()
reloadSchedulerSettings()
}
@@ -186,7 +184,7 @@ fun SyncSettingsScreen(
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { eviction().evaluateTypeReclaim(docType) }
NativeLib.ffi { eviction().evaluateTypeReclaim(docType) }
}
reclaimFlow =
ReclaimFlow(
@@ -210,7 +208,7 @@ fun SyncSettingsScreen(
scope.launch {
val result =
withContext(Dispatchers.IO) {
nativeLib.ffi { eviction().executeTypeReclaim(docType, allowUnverified) }
NativeLib.ffi { eviction().executeTypeReclaim(docType, allowUnverified) }
}
reclaimFlow =
ReclaimFlow(
@@ -227,8 +225,7 @@ fun SyncSettingsScreen(
}
fun updateSchedulerSettings(updated: SchedulerSettings) {
nativeLib
.ffi { settings().setSchedulerSettings(updated) }
NativeLib.ffi { settings().setSchedulerSettings(updated) }
.onSuccess {
schedulerSettings = updated
SchedulerWorker.schedule(context, updated)
@@ -243,7 +240,7 @@ fun SyncSettingsScreen(
runNowStatus = null
scope.launch {
val result =
withContext(Dispatchers.IO) { nativeLib.ffi { settings().runSchedulerPasses() } }
withContext(Dispatchers.IO) { NativeLib.ffi { settings().runSchedulerPasses() } }
runNowStarting = false
runNowStatus =
result.fold(
@@ -311,8 +308,7 @@ fun SyncSettingsScreen(
entry = entry,
options = policyOptions,
onPolicyChange = { docType, policy ->
nativeLib
.ffi { settings().setSyncPolicy(docType, policy) }
NativeLib.ffi { settings().setSyncPolicy(docType, policy) }
.onSuccess { reloadPolicies() }
.onFailure {
Log.w(TAG, "Failed to save sync policy for $docType", it)
@@ -349,8 +345,7 @@ fun SyncSettingsScreen(
entry = entry,
options = policyOptions,
onPolicyChange = { docType, policy ->
nativeLib
.ffi {
NativeLib.ffi {
remoteAdmin().setSyncPolicy(nodeIdHex, docType, policy)
}
.onSuccess { remotePolicies = it }
@@ -72,9 +72,9 @@ data class RemoteFetch(val state: FetchDisplay, val jobId: String?) {
* surfaced: the user asked for this to stop, and telling them their own decision failed when
* the thing is already over would be noise.
*/
suspend fun cancel(nativeLib: NativeLib) {
suspend fun cancel() {
val jobId = jobId ?: return
withContext(Dispatchers.IO) { nativeLib.ffi { jobs().cancelJob(jobId) } }
withContext(Dispatchers.IO) { NativeLib.ffi { jobs().cancelJob(jobId) } }
.onSuccess { canceled ->
if (!canceled) Log.i(TAG, "Content-stream job $jobId had already settled")
}
@@ -113,7 +113,7 @@ fun rememberContentFetchStrings(): ContentFetchStrings = remember { contentFetch
* on a timer or it can't fire at all. `listActiveJobs` is a handful of indexed rows.
*/
@Composable
fun rememberRemoteFetch(nativeLib: NativeLib, documentId: String?): RemoteFetch {
fun rememberRemoteFetch(documentId: String?): RemoteFetch {
var fetch by remember { mutableStateOf(RemoteFetch(FetchDisplay.Idle, null)) }
LaunchedEffect(documentId) {
@@ -126,8 +126,7 @@ fun rememberRemoteFetch(nativeLib: NativeLib, documentId: String?): RemoteFetch
while (true) {
val job =
withContext(Dispatchers.IO) {
nativeLib
.ffi { jobs().listActiveJobs() }
NativeLib.ffi { jobs().listActiveJobs() }
.getOrDefault(emptyList())
.firstOrNull {
it.kind == CONTENT_STREAM_KIND && it.documentId == documentId
@@ -273,18 +272,13 @@ private fun fractionOf(bytesDone: ULong, bytesTotal: ULong?): Float? =
* plain spinner, because [rememberRemoteFetch] reports nothing until a transfer actually starts.
*/
@Composable
fun RemoteFetchOrSpinner(
fetch: RemoteFetch,
subject: String,
nativeLib: NativeLib,
modifier: Modifier = Modifier,
) {
fun RemoteFetchOrSpinner(fetch: RemoteFetch, subject: String, modifier: Modifier = Modifier) {
val scope = rememberCoroutineScope()
if (fetch.isActive) {
RemoteFetchProgress(
state = fetch.state,
subject = subject,
onCancel = { scope.launch { fetch.cancel(nativeLib) } },
onCancel = { scope.launch { fetch.cancel() } },
modifier = modifier,
)
} else {
@@ -6,11 +6,10 @@ import androidx.compose.runtime.*
import com.gregshuflin.synchronicity.NativeLib
import uniffi.synchronicity.ThemeMode
class ThemeManager(private val nativeLib: NativeLib) {
class ThemeManager {
fun getThemeMode(): ThemeMode =
nativeLib
.ffi { settings().getThemeMode() }
NativeLib.ffi { settings().getThemeMode() }
.getOrElse {
// Charcoal, matching the stored default in Rust (ADR 0032 §2) — a
// read failure should land on the same ground a fresh install does,
@@ -20,8 +19,7 @@ class ThemeManager(private val nativeLib: NativeLib) {
}
fun setThemeMode(themeMode: ThemeMode) {
nativeLib
.ffi { settings().setThemeMode(themeMode) }
NativeLib.ffi { settings().setThemeMode(themeMode) }
.onFailure { Log.e("ThemeManager", "Failed to set theme mode", it) }
}
@@ -34,8 +32,8 @@ class ThemeManager(private val nativeLib: NativeLib) {
}
@Composable
fun rememberThemeState(nativeLib: NativeLib): ThemeState {
val themeManager = remember { ThemeManager(nativeLib) }
fun rememberThemeState(): ThemeState {
val themeManager = remember { ThemeManager() }
var themeMode by remember { mutableStateOf(themeManager.getThemeMode()) }
val isSystemInDarkTheme = isSystemInDarkTheme()
@@ -50,9 +50,8 @@ fun VideoScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val snackbar = LocalSnackbarController.current
val nativeLib = NativeLib
var videoDocuments by remember { mutableStateOf<List<DocumentDisplayModel>>(emptyList()) }
var refreshTrigger by rememberReloadKey(nativeLib, ChangeChannel.DOCUMENTS)
var refreshTrigger by rememberReloadKey(ChangeChannel.DOCUMENTS)
// Saveable so a rotation doesn't silently widen the list back out from under
// whatever the user was looking at.
var searchQuery by rememberSaveable { mutableStateOf("") }
@@ -60,8 +59,8 @@ fun VideoScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
LaunchedEffect(refreshTrigger) {
videoDocuments =
withContext(Dispatchers.IO) {
searchAndParseDocuments(nativeLib, types = listOf(DocumentType.VIDEO_CLIP)).map {
it.toDisplayModel(nativeLib.timezone())
searchAndParseDocuments(types = listOf(DocumentType.VIDEO_CLIP)).map {
it.toDisplayModel(NativeLib.timezone())
}
}
}
@@ -91,7 +90,7 @@ fun VideoScreen(onBack: () -> Unit, modifier: Modifier = Modifier) {
label = "Import Video",
onPick = { uri ->
scope.launchReportingFailure(snackbar, TAG, "import video") {
val name = nativeLib.importPickedFile(context, uri).bind()
val name = NativeLib.importPickedFile(context, uri).bind()
Toast.makeText(context, "Imported: $name", Toast.LENGTH_SHORT).show()
refreshTrigger++
}