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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.sameerasw.essentials.island.model

import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update

/**
* A shape drawn below an item's expanded view, bonded to it like the queue pill. Content draws its own
* black background; the slot clips it and owns position, motion and the liquid neck.
*
* @param content Gets the slot width in px and whether the attachment is settled (not animating or being
* dragged), which is when a live surface may be shown.
*/
class IslandAttachment(
val key: String,
val anchor: String,
val matchTitle: String? = null,
val beat: IslandBeat? = null,
val content: @Composable (widthPx: Int, settled: Boolean) -> Unit,
) {
fun matches(title: String?): Boolean {
val wanted = matchTitle?.normalized()?.takeIf { it.isNotEmpty() } ?: return true
val actual = title?.normalized()?.takeIf { it.isNotEmpty() } ?: return false
return actual.contains(wanted) || wanted.contains(actual)
}

private fun String.normalized() = trim().lowercase()

companion object {
val CORNER = 28.dp
}
}

data class IslandBeat(val periodMs: Float, val offsetMs: Float)

object IslandAttachments {
private val byOwner = MutableStateFlow<Map<String, List<IslandAttachment>>>(emptyMap())

val all: StateFlow<Map<String, List<IslandAttachment>>> = byOwner

fun set(owner: String, attachments: List<IslandAttachment>) {
byOwner.update { if (attachments.isEmpty()) it - owner else it + (owner to attachments) }
}

fun resolve(all: Map<String, List<IslandAttachment>>, anchor: String, title: String?): IslandAttachment? =
all.entries
.sortedBy { it.key }
.firstNotNullOfOrNull { (_, list) -> list.firstOrNull { it.anchor == anchor && it.matches(title) } }
}
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ class IslandItem(
val expandedQueueOnly: Boolean = false,
val queueAccent: Color? = null,

val attachmentAnchor: String? = null,
val attachmentTitle: String? = null,
val attachmentActive: Boolean = true,
val attachmentPositionMs: (() -> Long)? = null,

val stack: List<StackIcon> = emptyList(),
val queued: List<StackIcon>? = null,
val priorityGroup: String? = null,
Expand Down Expand Up @@ -224,6 +229,10 @@ class IslandItem(
hideExpandedQueue = hideExpandedQueue,
expandedQueueOnly = expandedQueueOnly,
queueAccent = queueAccent,
attachmentAnchor = attachmentAnchor,
attachmentTitle = attachmentTitle,
attachmentActive = attachmentActive,
attachmentPositionMs = attachmentPositionMs,
stack = stack,
queued = queued,
priorityGroup = priorityGroup,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import com.sameerasw.essentials.island.ui.components.MediaArtCue
import com.sameerasw.essentials.island.ui.components.TrackSkipPill
import com.sameerasw.essentials.island.ui.components.IslandBitmap
import com.sameerasw.essentials.services.NotificationListener
import com.sameerasw.island.sdk.IslandAnchor
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
Expand Down Expand Up @@ -300,6 +301,10 @@ class MediaPlugin : BaseIslandPlugin() {
queueAccent = t.accent?.let { Color(it) },
stack = stack,
sideBubble = if (settings.isIslandMediaBubbleEnabled()) mediaBubble(t, isPlaying, artAccent) else null,
attachmentAnchor = IslandAnchor.MEDIA,
attachmentTitle = t.title,
attachmentActive = isPlaying,
attachmentPositionMs = { active?.let(MediaSessionSource::positionMs) ?: 0L },
),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,16 @@ class MediaSessionSource(
return ((state.position + elapsed) / duration.toFloat()).coerceIn(0f, 1f)
}

fun positionMs(controller: MediaController): Long {
val state = controller.playbackState ?: return 0L
val elapsed = if (state.state == PlaybackState.STATE_PLAYING) {
(SystemClock.elapsedRealtime() - state.lastPositionUpdateTime) * state.playbackSpeed
} else {
0f
}
return (state.position + elapsed).toLong().coerceAtLeast(0L)
}

fun canSeek(controller: MediaController): Boolean {
val actions = controller.playbackState?.actions ?: return false
val duration = controller.metadata?.getLong(MediaMetadata.METADATA_KEY_DURATION) ?: 0L
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import android.graphics.Bitmap
import com.sameerasw.island.sdk.BriefCardPayload
import com.sameerasw.island.sdk.DecodedPayload
import com.sameerasw.island.sdk.IslandAction
import com.sameerasw.island.sdk.IslandAnchor
import com.sameerasw.island.sdk.IslandAttachmentPayload
import com.sameerasw.island.sdk.IslandCellPayload
import com.sameerasw.island.sdk.IslandExpandedPayload
import com.sameerasw.island.sdk.IslandInteractionsPayload
Expand All @@ -24,6 +26,11 @@ object PayloadValidator {
private const val MAX_LINE_TEXT = 120
private const val MIN_HEIGHT_DP = 80
private const val MAX_HEIGHT_DP = 640
private const val MIN_ATTACHMENT_DP = 40
private const val MAX_ATTACHMENT_DP = 240
private val ANCHORS = setOf(IslandAnchor.MEDIA)
private const val MIN_BEAT_MS = 250f
private const val MAX_BEAT_MS = 2000f

fun sanitize(decoded: DecodedPayload): DecodedPayload {
val items = decoded.payload.items
Expand All @@ -41,7 +48,14 @@ object PayloadValidator {
.distinctBy { it.key.take(MAX_KEY) }
.take(MAX_OPTIONS)
.map { it.copy(key = it.key.take(MAX_KEY), title = it.title.take(MAX_OPTION_TITLE)) }
return DecodedPayload(IslandPayload(decoded.payload.schema, items, cards, options), assets(decoded.assets))
val attachments = decoded.payload.attachments.orEmpty()
.filter { it.key.isNotBlank() && it.anchor in ANCHORS }
.distinctBy { it.anchor }
.map(::attachment)
return DecodedPayload(
IslandPayload(decoded.payload.schema, items, cards, options = options, attachments = attachments),
assets(decoded.assets),
)
}

private fun assets(source: Map<String, Bitmap>): Map<String, Bitmap> {
Expand Down Expand Up @@ -99,6 +113,14 @@ object PayloadValidator {
pageHeightDp = card.pageHeightDp?.coerceIn(MIN_HEIGHT_DP, MAX_HEIGHT_DP),
)

private fun attachment(attachment: IslandAttachmentPayload) = attachment.copy(
key = attachment.key.take(MAX_KEY),
heightDp = attachment.heightDp.coerceIn(MIN_ATTACHMENT_DP, MAX_ATTACHMENT_DP),
matchTitle = attachment.matchTitle?.take(MAX_LINE_TEXT),
beatMs = attachment.beatMs?.takeIf { it.isFinite() && it in MIN_BEAT_MS..MAX_BEAT_MS },
beatOffsetMs = attachment.beatOffsetMs?.takeIf { it.isFinite() },
)

private fun action(action: IslandAction) = action.copy(target = action.target?.take(MAX_KEY))

private fun tone(tone: String): String = if (tone in TONES) tone else "none"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.toArgb
import com.sameerasw.essentials.data.repository.SettingsRepository
import com.sameerasw.essentials.island.model.IslandAttachments
import com.sameerasw.essentials.island.model.IslandExpandedScope
import com.sameerasw.essentials.island.model.IslandItem
import com.sameerasw.essentials.island.model.IslandPriorityEntries
Expand Down Expand Up @@ -207,6 +208,7 @@ class ProviderConnection(
pending.value = null
_items.value = emptyList()
RemoteBriefCards.set(info.packageName, emptyList())
IslandAttachments.set(info.packageName, emptyList())
RemoteProviderOptions.clear(info.packageName)
lastDecoded = null
onItemsChanged()
Expand All @@ -223,6 +225,7 @@ class ProviderConnection(
val siblings = decoded.payload.items.map { it.key }.toSet()
_items.value = decoded.payload.items.mapNotNull { RemoteItemMapper.map(it, decoded.assets, siblings, this) }
RemoteBriefCards.set(info.packageName, decoded.payload.briefCards.map { RemoteBriefCard(info.packageName, it, decoded.assets, this) })
IslandAttachments.set(info.packageName, decoded.payload.attachments.map { RemoteAttachments.map(info.packageName, it, this) })
RemoteProviderOptions.set(info.packageName, decoded.payload.options, ::setOption)
onItemsChanged()
}
Expand Down Expand Up @@ -250,6 +253,7 @@ class ProviderConnection(
cameraSlotWidthPx = snapshot?.cameraSlotWidthPx ?: 0,
cornerPx = snapshot?.cornerPx ?: 0,
powerSave = DeviceUtils.isPowerSaveMode(context),
supportsAttachments = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R,
)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.sameerasw.essentials.island.remote

import android.os.Build
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import com.sameerasw.essentials.island.model.IslandAttachment
import com.sameerasw.essentials.island.model.IslandBeat
import com.sameerasw.island.sdk.IslandAttachmentPayload
import com.sameerasw.island.sdk.IslandSurfaceKey

object RemoteAttachments {
fun map(
packageName: String,
payload: IslandAttachmentPayload,
handler: RemoteItemHandler
): IslandAttachment {
val surfaceKey = IslandSurfaceKey.attachment(payload.key)
return IslandAttachment(
key = "$packageName:${payload.key}",
anchor = payload.anchor,
matchTitle = payload.matchTitle,
beat = payload.beatMs?.let { IslandBeat(it, payload.beatOffsetMs ?: 0f) },
) { widthPx, settled ->
val density = LocalDensity.current
val reported = handler.reportedHeightPx(surfaceKey)
val heightPx =
if (reported > 0) reported else with(density) { payload.heightDp.dp.roundToPx() }
val size = with(density) { Modifier
.width(widthPx.toDp())
.height(heightPx.toDp()) }
val session =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) handler.surfaceSession(
surfaceKey
) else null
if (session == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
Spacer(size)
} else {
val interactive by rememberUpdatedState(settled)
RemoteSurfaceBox(
session = session,
widthPx = widthPx,
heightPx = heightPx,
cornerPx = minOf(
with(density) { IslandAttachment.CORNER.toPx() },
heightPx / 2f
),
showLive = settled && session.hasSurface,
snapshot = handler.snapshot(surfaceKey),
aboveHost = true,
modifier = size.pointerInput(session) {
detectTapGestures { if (interactive) session.tap(it.x, it.y) }
},
)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.tween
import androidx.annotation.RequiresApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
Expand All @@ -27,6 +28,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
Expand Down Expand Up @@ -79,22 +81,43 @@ fun RemoteExpanded(
val paused = LocalRemotePaused.current
val dragging by remember { derivedStateOf { collapse() > 0.02f || paused() } }
val showLive = revealed && !dragging && session.hasSurface
val fade by animateFloatAsState(if (showLive) 1f else 0f, if (showLive) motionTween(160) else snap(), label = "remoteFade")
val cornerPx = with(density) { scope.spec.expandedCorner.toPx() }
val current = remember { intArrayOf(0, 0) }
val corner = remember { floatArrayOf(0f) }
val interactive by rememberUpdatedState(revealed && !dragging)
Box(
size.pointerInput(session) {
RemoteSurfaceBox(
session = session,
widthPx = widthPx,
heightPx = heightPx,
cornerPx = cornerPx,
showLive = showLive,
snapshot = snapshot,
modifier = size.pointerInput(session) {
detectTapGestures { if (interactive) session.tap(it.x, it.y) }
},
) {
)
}

@RequiresApi(Build.VERSION_CODES.R)
@Composable
internal fun RemoteSurfaceBox(
session: RemoteSurfaceSession,
widthPx: Int,
heightPx: Int,
cornerPx: Float,
showLive: Boolean,
snapshot: ImageBitmap?,
modifier: Modifier = Modifier,
aboveHost: Boolean = false,
) {
val fade by animateFloatAsState(if (showLive) 1f else 0f, if (showLive) motionTween(160) else snap(), label = "remoteFade")
val current = remember { intArrayOf(0, 0) }
val corner = remember { floatArrayOf(0f) }
Box(modifier) {
snapshot?.let {
Image(
bitmap = it,
contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = Modifier.matchParentSize(),
modifier = Modifier.matchParentSize().graphicsLayer { alpha = if (aboveHost) 1f - fade else 1f },
)
}
AndroidView(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ class IslandWindowHost(
name: String,
): Boolean {
try {
if (added) wm.updateViewLayout(view, lp) else wm.addView(view, lp)
if (added && view.parent != null) wm.updateViewLayout(view, lp) else wm.addView(view, lp)
return true
} catch (e: Exception) {
Log.e(TAG, "Failed to place island $name window, re-adding", e)
Expand Down
Loading
Loading