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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 61 additions & 35 deletions core/design/src/main/kotlin/io/putdotio/android/design/RowText.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package io.putdotio.android.design

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.referentialEqualityPolicy
import androidx.compose.runtime.remember
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.snapshots.Snapshot
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
Expand All @@ -22,55 +22,82 @@ public class RowText<T : Any, V> internal constructor(
private val placeholder: V,
private val build: (T) -> V,
) {
private class Entry<T, V>(val item: T, val value: V, val refresh: Any?)
internal class Entry<T, V>(val item: T, val value: V, val refresh: Any?)

@Volatile
private var entries = ConcurrentHashMap<Any, Entry<T, V>>()
private class Prepared<T, V>(
val items: List<T>,
val entries: Map<Any, Entry<T, V>>,
val previous: Map<Any, Entry<T, V>>,
)

private val waiting = ConcurrentHashMap<Any, T>()
internal class Batch<T, V> internal constructor(
internal val items: List<T>,
internal val entries: Map<Any, Entry<T, V>>,
internal val changed: Boolean,
)

private val prepared = mutableIntStateOf(0)
private val prepared = mutableStateOf<Prepared<T, V>?>(null, referentialEqualityPolicy())

private val generation = AtomicLong()
private val waiting = ConcurrentHashMap<Any, T>()

private val stale = AtomicBoolean()
private val stale = mutableIntStateOf(0)

public operator fun get(item: T): V {
prepared.intValue
stale.intValue
val key = key(item)
val entry = entries[key]?.takeIf { it.item == item } ?: await(key, item)
return entry?.value ?: placeholder
val shown = Snapshot.withoutReadObservation { prepared.value }
val entry = shown?.entries?.get(key)?.takeIf { it.item == item }
?: shown?.previous?.get(key)?.takeIf { it.item == item }
?: return wait(key, item, shown)
return entry.value
}

private fun await(key: Any, item: T): Entry<T, V>? {
private fun wait(key: Any, item: T, shown: Prepared<T, V>?): V {
waiting[key] = item
val entry = entries[key]
if (entry?.item == item) waiting.remove(key, item)
return entry
return shown?.entries?.get(key)?.value ?: placeholder
}

internal suspend fun prepare(items: List<T>, refresh: Any?) {
val run = generation.incrementAndGet()
val known = entries
val built = ConcurrentHashMap<Any, Entry<T, V>>(items.size)
public fun isBuiltFor(items: List<T>): Boolean = prepared.value?.items === items

internal suspend fun prepare(items: List<T>, refresh: Any?): Batch<T, V> {
val known = Snapshot.withoutReadObservation { prepared.value }?.entries.orEmpty()
val built = HashMap<Any, Entry<T, V>>(items.size)
var changed = false
items.forEach { item ->
currentCoroutineContext().ensureActive()
val old = known[key(item)]?.takeIf { it.item == item }
built[key(item)] = old?.takeIf { it.refresh == refresh }
?: Entry(item, build(item), refresh).also { if (old != null && old.value != it.value) changed = true }
}
val context = currentCoroutineContext()
synchronized(generation) {
if (run != generation.get() || !context.isActive) return
entries = built
if (waiting.entries.removeIf { (key, item) -> built[key]?.item == item } || changed) stale.set(true)
}
return Batch(items, built, changed)
}

internal fun show(batch: Batch<T, V>) {
val previous = prepared.value?.entries.orEmpty()
prepared.value = Prepared(batch.items, batch.entries, previous)
val arrived = waiting.entries.removeIf { (key, item) -> batch.entries[key]?.item == item }
if (arrived || batch.changed) stale.intValue++
}
}

private class Shown<S>(var source: S?)

internal fun recomposeStaleRows() {
if (stale.getAndSet(false)) prepared.intValue++
@Composable
public fun <T : Any, S : Any> RowText<T, *>.shown(source: S?, items: List<T>, vararg keys: Any?): S? {
val last = remember(*keys) { Shown<S>(null) }
val shown = when {
source == null -> null
isBuiltFor(items) -> source
else -> last.source
}
SideEffect { last.source = shown }
return shown
}

private class Identity(val value: Any) {
override fun equals(other: Any?): Boolean = other is Identity && other.value === value

override fun hashCode(): Int = System.identityHashCode(value)
}

@Composable
Expand All @@ -84,13 +111,12 @@ public fun <T : Any, V> rememberRowText(
build: (T) -> V,
): RowText<T, V> {
val text = remember(*inputs) { RowText(key, placeholder, build) }
LaunchedEffect(text, items, refresh, everyMinute) {
text.recomposeStaleRows()
val dispatcher = LocalBuildDispatcher.current
LaunchedEffect(text, Identity(items), refresh, everyMinute, dispatcher) {
while (isActive) {
val minute = currentMinute()
withContext(Dispatchers.Default) { text.prepare(items, if (everyMinute) refresh to minute else refresh) }
withFrameNanos {}
text.recomposeStaleRows()
val batch = withContext(dispatcher) { text.prepare(items, if (everyMinute) refresh to minute else refresh) }
text.show(batch)
if (!everyMinute) break
if (currentMinute() == minute) delay(MINUTE_MILLIS - System.currentTimeMillis() % MINUTE_MILLIS)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ class RowTextTest {
invalidated = invalidated || changed.any { it in reads }
}
prepare()
text.recomposeStaleRows()
Snapshot.sendApplyNotifications()
observer.dispose()
return invalidated
Expand All @@ -38,30 +37,30 @@ class RowTextTest {
assertEquals("", text[Row(1, "a")])
assertEquals(emptyList<Row>(), built)

assertTrue(recomposesRowsAfter { text.prepare(listOf(Row(1, "a"), Row(2, "b")), refresh = null) })
assertTrue(recomposesRowsAfter { text.show(text.prepare(listOf(Row(1, "a"), Row(2, "b")), refresh = null)) })
assertEquals("a text", text[Row(1, "a")])
}

@Test
fun aChangedRowKeepsItsOldTextUntilTheNewTextIsBuilt() = runTest {
text.prepare(listOf(Row(1, "a")), refresh = null)
text.show(text.prepare(listOf(Row(1, "a")), refresh = null))
built.clear()

assertEquals("a text", text[Row(1, "renamed")])
assertEquals(emptyList<Row>(), built)

text.prepare(listOf(Row(1, "renamed")), refresh = null)
text.show(text.prepare(listOf(Row(1, "renamed")), refresh = null))
assertEquals("renamed text", text[Row(1, "renamed")])
}

@Test
fun aRefreshRecomposesRowsOnlyWhenTheirTextChanges() = runTest {
text.prepare(listOf(Row(1, "a")), refresh = 1)
text.show(text.prepare(listOf(Row(1, "a")), refresh = 1))

assertFalse(recomposesRowsAfter { text.prepare(listOf(Row(1, "a")), refresh = 2) })
assertFalse(recomposesRowsAfter { text.show(text.prepare(listOf(Row(1, "a")), refresh = 2)) })

suffix = "later"
assertTrue(recomposesRowsAfter { text.prepare(listOf(Row(1, "a")), refresh = 3) })
assertTrue(recomposesRowsAfter { text.show(text.prepare(listOf(Row(1, "a")), refresh = 3)) })
assertEquals("a later", text[Row(1, "a")])
}
}
102 changes: 63 additions & 39 deletions mobile/src/main/kotlin/io/putdotio/android/files/MobileFilesScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ import io.putdotio.android.LoadNextPageNow
import io.putdotio.android.MobileInlineError
import io.putdotio.android.RetryWhenOnline
import io.putdotio.android.design.RowText
import io.putdotio.android.design.shown
import io.putdotio.android.isUnreachable
import io.putdotio.android.MobileErrorState
import io.putdotio.android.MobileKeyCommand
Expand Down Expand Up @@ -258,6 +259,18 @@ private fun MobileFilesCopyLine(state: FilesBrowserState, onEvent: (FilesBrowser
}
}

@Composable
private fun BuiltFilesPage(
page: Pair<FilesContent.Ready, Long>,
headers: MobileFilesHeaders,
rowText: RowText<FilesItem, FilesRowText>,
pinnedText: RowText<FilesItem, FilesRowText>,
content: @Composable (FilesContent.Ready, Long, MobileFilesHeaders) -> Unit,
) {
val (shownPage, shownGeneration) = rowText.shown(page, page.first.items) ?: return
content(shownPage, shownGeneration, pinnedText.shown(headers, headers.pinned) ?: return)
}

@Composable
private fun MobileRefreshableFilesContent(
state: FilesBrowserState,
Expand Down Expand Up @@ -424,46 +437,57 @@ private fun MobileRefreshableFilesContent(
is FilesContent.Ready -> {
val rowText = rememberFilesRowText(content.items)
val pinnedText = rememberFilesRowText(headers.pinned)
// The depth tells a folder opened from Search apart from the same folder under it. A
// header set that grew or shrank restarts the list from the row-relative viewport.
key(
state.stack.size,
state.current.folder.id.value,
state.current.viewportGeneration,
headers.itemCount,
) {
MobileFilesList(
content = content,
headers = headers,
onPlayEntry = { onPlayMedia(it.toFilesItem()) },
onRemoveEntry = hideStarted,
rowText = rowText,
pinnedRows = MobilePinnedRows(
pinnedText,
itemActions.pinnedActions { item ->
openPinned(item, state.current, fileOpening, onEvent, onPlayMedia)
BuiltFilesPage(
content to state.current.viewportGeneration,
headers,
rowText,
pinnedText,
) { shownContent, shownGeneration, shownHeaders ->
// The depth tells a folder opened from Search apart from the same folder under it. A
// header set that grew or shrank restarts the list from the row-relative viewport.
key(
state.stack.size,
state.current.folder.id.value,
shownGeneration,
shownHeaders.itemCount,
) {
MobileFilesList(
content = shownContent,
headers = shownHeaders,
onPlayEntry = { onPlayMedia(it.toFilesItem()) },
onRemoveEntry = hideStarted,
rowText = rowText,
pinnedRows = MobilePinnedRows(
pinnedText,
itemActions.pinnedActions { item ->
openPinned(item, state.current, fileOpening, onEvent, onPlayMedia)
},
),
revealItemId = state.current.revealItemId,
pagingEnabled = operation == FilesFolderOperation.Idle,
onEvent = onEvent,
onPlayMedia = onPlayMedia,
onActions = { selectedItemId = it.id.value },
hasActions = {
it.hasMobileActions(
onDownloadItem != null,
onShareItem != null,
onCopyItem != null,
)
},
operation = operation,
downloads = downloads,
onItemFocusChanged = { id, focused ->
focusedItemId = focusedItemId.afterFocusChange(id.value, focused)
},
),
revealItemId = state.current.revealItemId,
pagingEnabled = operation == FilesFolderOperation.Idle,
onEvent = onEvent,
onPlayMedia = onPlayMedia,
onActions = { selectedItemId = it.id.value },
hasActions = {
it.hasMobileActions(onDownloadItem != null, onShareItem != null, onCopyItem != null)
},
operation = operation,
downloads = downloads,
onItemFocusChanged = { id, focused ->
focusedItemId = focusedItemId.afterFocusChange(id.value, focused)
},
fileDragOut = fileDragOut,
// A touch drag starts after the long press; it closes any sheet that press opened.
onDragStarted = dismissSelection,
fileOpening = fileOpening,
selection = selection.listSelection(state, toolbarClearance),
onStartSelection = selection.starter { currentState },
)
fileDragOut = fileDragOut,
// A touch drag starts after the long press; it closes any sheet that press opened.
onDragStarted = dismissSelection,
fileOpening = fileOpening,
selection = selection.listSelection(state, toolbarClearance),
onStartSelection = selection.starter { currentState },
)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ import io.putdotio.android.MobileRow
import io.putdotio.android.MobileSectionLabel
import io.putdotio.android.PutioFailure
import io.putdotio.android.R
import io.putdotio.android.design.RowText
import io.putdotio.android.design.shown
import io.putdotio.android.design.PutioEmptyGlyph
import io.putdotio.android.design.PutioEmptyState
import io.putdotio.android.design.putioMono
Expand Down Expand Up @@ -391,10 +393,23 @@ private fun MobileSearchResults(
onNextPage: () -> Unit,
onRetry: () -> Unit,
modifier: Modifier = Modifier,
) {
val rowText = rememberFilesRowText(content.items, dated = false)
val shown = rowText.shown(content, content.items) ?: return
MobileSearchResultList(shown, rowText, rows, onNextPage, onRetry, modifier)
}

@Composable
private fun MobileSearchResultList(
content: SearchContent.Ready,
rowText: RowText<FilesItem, FilesRowText>,
rows: MobileSearchRows,
onNextPage: () -> Unit,
onRetry: () -> Unit,
modifier: Modifier,
) {
val (folders, files) = remember(content.items) { content.items.partition(FilesItem::isFolder) }
val rootName = stringResource(R.string.mobile_destination_files)
val rowText = rememberFilesRowText(content.items, dated = false)
val listState = rememberLazyListState()
LoadNextPageNearEnd(listState, nextPage = content.paging as? SearchPaging.Available, onLoadNextPage = onNextPage)
LazyColumn(state = listState, modifier = modifier.testTag(MOBILE_SEARCH_RESULTS_TAG)) {
Expand Down
Loading