Android ServerScreen state in holders: nav, find, picking; overlays apart

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 20:35:45 +00:00
co-authored by Claude Opus 5.5
parent a2a12804ad
commit 78b66ef346
8 changed files with 848 additions and 613 deletions
@@ -0,0 +1,126 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.Conversation
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.TreeFind
import eu.lixko.ts3j.client.android.findIn
/** The channel tree as it shows under the find bar: what of it, which rows are folded, and the match it is on. */
@Stable
internal class TreeView(
private val server: ServerController,
private val source: State<ServerTree>,
private val collapsedSource: State<Set<Int>>,
private val find: FindState,
) {
val treeFind by derivedStateOf { TreeFind(find.usable, find.channels) }
val filtering by derivedStateOf { find.filter && !treeFind.query.isEmpty }
val tree by derivedStateOf { if (filtering) source.value.only(treeFind) else source.value }
val hits by derivedStateOf { source.value.hits(treeFind) }
val found by derivedStateOf { hits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }
/** The match the tree is on. */
private var at by mutableStateOf<Int?>(null)
val current: TreeRef? get() = at?.takeIf { it in hits }?.let { TreeRef(treeFind.channels, it) }
val position: Int get() = hits.indexOf(at) + 1
/** A row to bring into view. */
var reveal by mutableStateOf<TreeRef?>(null)
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
private var folded by mutableStateOf(Folded(null, emptySet()))
private val filterFolded: Set<Int> get() = folded.ids.takeIf { folded.find == treeFind }.orEmpty()
val collapsed: Set<Int> get() = if (filtering) filterFolded else collapsedSource.value
private data class Folded(val find: TreeFind?, val ids: Set<Int>)
fun toggle(channelId: Int) {
if (!filtering) server.toggleCollapsed(channelId)
else if (channelId in filterFolded) folded = Folded(treeFind, filterFolded - channelId)
else folded = Folded(treeFind, filterFolded + channelId)
}
/** Opens the channels down to [ref] and brings it into view. */
fun show(ref: TreeRef) {
val tree = source.value
val path = (if (ref.channel) tree.parentsOf(ref.id) else tree.pathTo(ref.id)).orEmpty()
if (filtering) folded = Folded(treeFind, filterFolded - path.toSet()) else server.expand(path)
reveal = ref
}
private fun showHit(id: Int) {
at = id
show(TreeRef(treeFind.channels, id))
}
/** For a new search: on the first match while the tree is on screen, else on none. */
fun restart(onScreen: Boolean) {
at = null
if (onScreen) hits.firstOrNull()?.let(::showHit)
}
fun step(delta: Int) {
if (hits.isNotEmpty()) showHit(hits[next(hits.indexOf(at), delta, hits.size)])
}
}
@Composable
internal fun rememberTreeView(
server: ServerController,
tree: State<ServerTree>,
collapsed: State<Set<Int>>,
find: FindState,
): TreeView = remember(server, tree, collapsed, find) { TreeView(server, tree, collapsed, find) }
/** A conversation as it shows under the find bar: its lines, and the match it is on. */
@Stable
internal class ChatSearch(private val conversation: State<Conversation>, private val find: FindState) {
val query get() = find.usable
val lines by derivedStateOf {
val all = conversation.value.lines
if (find.filter && !query.isEmpty) all.filter { query.matches(it.plain) } else all
}
val hits by derivedStateOf { findIn(lines, query, MAX_CHAT_MATCHES) }
val capped: Boolean get() = hits.size == MAX_CHAT_MATCHES
/** The match the chat is on. */
var at by mutableStateOf<ChatMatch?>(null)
private set
val position: Int get() = hits.indexOf(at) + 1
/** A line to bring into view. */
var reveal by mutableStateOf<Long?>(null)
/** For a new search: on the newest match while the chat is on screen, else on none. */
fun restart(onScreen: Boolean) {
at = if (onScreen) hits.lastOrNull() else null
reveal = at?.line
}
fun step(delta: Int) {
if (hits.isEmpty()) return
at = hits[next(hits.indexOf(at), delta, hits.size)]
reveal = at?.line
}
}
@Composable
internal fun rememberChatSearch(conversation: State<Conversation>, find: FindState): ChatSearch =
remember(conversation, find) { ChatSearch(conversation, find) }
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
@@ -0,0 +1,105 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.config.WhisperList
/** What fills a server's screen: its tree and chat, or a page of its own. */
internal sealed interface ServerPage {
data object Main : ServerPage
data object BanList : ServerPage
data object WhisperLists : ServerPage
data class EditChannel(val edit: ChannelEdit) : ServerPage
/** A channel's files, with the password the channel takes. */
data class Files(val channelId: Int, val name: String, val password: String) : ServerPage
data class ConnectionInfo(val clientId: Int) : ServerPage
}
/** A sheet or dialog over the tree and chat; one at a time. */
internal sealed interface Overlay {
data object None : Overlay
data object Server : Overlay
/** [fromTree] when it was opened from the tree rather than a link. */
data class Client(val id: Int, val fromTree: Boolean) : Overlay
data class Channel(val id: Int) : Overlay
/** A locked channel being joined, while its password is asked for. */
data class JoinLocked(val channelId: Int) : Overlay
/** A locked channel whose files are wanted, while its password is asked for. */
data class FilesLocked(val channelId: Int) : Overlay
data class DeleteChannel(val id: Int) : Overlay
/** Kicking the clients picked in the tree: from the server, or from their channels. */
data class Kick(val fromServer: Boolean) : Overlay
/** Something being added to a whisper list, while the list is picked: its name and how to add it. */
class AddToWhisperList(val name: String, val add: (WhisperList) -> Unit) : Overlay
}
/** Where a server's screen is: on which page, the tree or the chat, and what is over it. */
@Stable
internal class ServerNav(page: ServerPage = ServerPage.Main, showChat: Boolean = false, chatKey: ChatKey = ChatKey.CHANNEL) {
var page by mutableStateOf(page)
var showChat by mutableStateOf(showChat)
/** The conversation the chat shows. */
var chatKey by mutableStateOf(chatKey)
var overlay by mutableStateOf<Overlay>(Overlay.None)
fun openChat(key: ChatKey) {
chatKey = key
showChat = true
}
fun back() {
page = ServerPage.Main
}
fun dismiss() {
overlay = Overlay.None
}
companion object {
// Sheets and dialogs are not kept: they would come back over a tree that has moved on.
val Saver = listSaver<ServerNav, Any>(
save = { listOf(it.showChat, saveKey(it.chatKey)) + savePage(it.page) },
restore = { ServerNav(restorePage(it.drop(2)), it[0] as Boolean, restoreKey(it[1] as String)) },
)
private fun saveKey(key: ChatKey) = when (key.scope()) {
ChatScope.SERVER -> "server"
ChatScope.CHANNEL -> "channel"
ChatScope.PRIVATE -> "private:${key.clientId()}"
}
private fun restoreKey(saved: String) = when {
saved == "server" -> ChatKey.SERVER
saved.startsWith("private:") -> ChatKey.privateWith(saved.substringAfter(':').toInt())
else -> ChatKey.CHANNEL
}
private fun savePage(page: ServerPage): List<Any> = when (page) {
ServerPage.Main -> listOf("main")
ServerPage.BanList -> listOf("bans")
ServerPage.WhisperLists -> listOf("whisper")
is ServerPage.EditChannel -> listOf("edit", page.edit.channelId, page.edit.parentId)
is ServerPage.Files -> listOf("files", page.channelId, page.name, page.password)
is ServerPage.ConnectionInfo -> listOf("info", page.clientId)
}
private fun restorePage(saved: List<Any>): ServerPage = when (saved[0]) {
"bans" -> ServerPage.BanList
"whisper" -> ServerPage.WhisperLists
"edit" -> ServerPage.EditChannel(ChannelEdit(saved[1] as Int, saved[2] as Int))
"files" -> ServerPage.Files(saved[1] as Int, saved[2] as String, saved[3] as String)
"info" -> ServerPage.ConnectionInfo(saved[1] as Int)
else -> ServerPage.Main
}
}
}
@Composable
internal fun rememberServerNav(): ServerNav = rememberSaveable(saver = ServerNav.Saver) { ServerNav() }
@@ -0,0 +1,167 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import kotlinx.coroutines.launch
/** Joins [channel], asking for its password first when it is locked. */
internal fun ServerNav.join(server: ServerController, channel: ChannelItem) {
if (channel.locked) overlay = Overlay.JoinLocked(channel.id) else server.joinChannel(channel.id)
}
/** The sheet or dialog [ServerNav.overlay] names; a sheet goes with its client or channel when that leaves the tree. */
@Composable
internal fun ServerOverlay(
nav: ServerNav,
vm: SessionController,
server: ServerController,
state: SessionState,
tree: ServerTree,
treeView: TreeView,
picking: TreePicking,
snackbar: SnackbarHostState,
onLink: (String) -> Unit,
onEditContact: (String) -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
) {
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val can = server.permissions
// Out here: the dialog leaves the composition, and would take its scope along, before the deletion fails.
val scope = rememberCoroutineScope()
val dismiss = nav::dismiss
/** Closes the overlay, then does [action]. */
fun then(action: () -> Unit): () -> Unit = { dismiss(); action() }
when (val o = nav.overlay) {
Overlay.None -> {}
Overlay.Server -> remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = dismiss,
onBookmark = then { server.bookmark(state.channelId)?.let { b -> onEditBookmark(BookmarkEdit(-1, b)) } },
onBanList = if (can.canViewBanList()) then { nav.page = ServerPage.BanList } else null,
onCreateChannel = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, 0)) } else null)
}
is Overlay.Client -> {
val id = o.id
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = dismiss,
onMessage = then { nav.openChat(server.openPrivateChat(id)) },
onPoke = { server.poke(id, it); dismiss() },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); dismiss() },
onTalkRequest = if (client.self && (client.talkRequest || server.canRequestTalkPower)) {
{ server.setTalkRequest(it); dismiss() }
} else null,
onAddContact = { server.addContact(id, it) },
onEditContact = then { onEditContact(client.uniqueId) },
onConnectionInfo = then { nav.page = ServerPage.ConnectionInfo(id) },
onWhisper = if (state.whisperControls) then { server.whisperToClient(id) } else null,
onAddToWhisperList = if (state.whisperControls) then {
server.clientRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(client.name) { it.clients.add(ref) } }
} else null,
onMove = if (can.canMoveClients()) then { picking.moving = setOf(id) } else null,
onMoveToOwnChannel = if (can.canMoveClients() && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
then { server.moveClients(listOf(id), state.channelId) }
} else null,
onFindInTree = if (o.fromTree) null else then {
nav.showChat = false
treeView.show(TreeRef(false, id))
},
moderation = clientModeration(server, client, dismiss),
)
}
}
is Overlay.Channel -> {
val id = o.id
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = dismiss,
onJoin = then { nav.join(server, channel) },
onSubscribe = { server.setSubscribed(id, it); dismiss() },
onWhisper = if (state.whisperControls) then { server.whisperToChannel(id) } else null,
onAddToWhisperList = if (state.whisperControls) then {
server.channelRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(channel.name) { it.channels.add(ref) } }
} else null,
onFiles = if (can.canBrowseFiles()) then {
if (channel.locked) nav.overlay = Overlay.FilesLocked(id)
else nav.page = ServerPage.Files(id, channel.name, "")
} else null,
onCreateSub = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, id)) } else null,
onEdit = if (can.canEditChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(id)) } else null,
onDelete = if (can.canDeleteChannels()) then { nav.overlay = Overlay.DeleteChannel(id) } else null,
)
}
}
is Overlay.Kick -> {
val others = picking.kickable(o.fromServer)
val whom = others.singleOrNull()?.let { tree.client(it)?.name } ?: "${others.size} clients"
KickPrompt(
if (o.fromServer) "Kick $whom from the server?" else "Kick $whom from the channel?",
onDismiss = dismiss,
) { reason ->
dismiss()
picking.kick(o.fromServer, reason)
}
}
is Overlay.JoinLocked -> TextPrompt(
title = "Join ${tree.channel(o.channelId)?.name.orEmpty()}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = dismiss,
onConfirm = { dismiss(); server.joinChannel(o.channelId, it) },
)
is Overlay.FilesLocked -> TextPrompt(
title = "Files of ${tree.channel(o.channelId)?.name.orEmpty()}",
label = "Channel password",
confirm = "Open",
password = true,
onDismiss = dismiss,
onConfirm = { dismiss(); nav.page = ServerPage.Files(o.channelId, tree.channel(o.channelId)?.name.orEmpty(), it) },
)
is Overlay.DeleteChannel -> {
val channel = tree.channel(o.id)
AlertDialog(
onDismissRequest = dismiss,
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = then {
scope.launch { server.deleteChannel(o.id).onFailure { snackbar.showSnackbar("Could not delete the channel: ${it.message}") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } },
)
}
is Overlay.AddToWhisperList -> AddToWhisperListDialog(vm, o.name, onDismiss = dismiss) { index, newName ->
dismiss()
vm.addToWhisperList(index, newName, o.add)
}
}
}
@@ -1,123 +1,42 @@
package eu.lixko.ts3j.client.android.ui package eu.lixko.ts3j.client.android.ui
import android.widget.Toast
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isCtrlPressed import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.TreeFind
import eu.lixko.ts3j.client.android.TreeSwipe import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.android.findIn
import eu.lixko.ts3j.client.chat.ChatKey import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.text.TsLink import eu.lixko.ts3j.client.text.TsLink
import kotlinx.coroutines.launch
private val ChatKeySaver = Saver<ChatKey, String>(
save = { key ->
when (key.scope()) {
ChatScope.SERVER -> "server"
ChatScope.CHANNEL -> "channel"
ChatScope.PRIVATE -> "private:${key.clientId()}"
}
},
restore = { saved ->
when {
saved == "server" -> ChatKey.SERVER
saved.startsWith("private:") -> ChatKey.privateWith(saved.substringAfter(':').toInt())
else -> ChatKey.CHANNEL
}
},
)
private val ChannelEditSaver = Saver<ChannelEdit?, IntArray>(
save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } },
restore = { ChannelEdit(it[0], it[1]) },
)
/** A channel whose files are browsed, with the password they take. */
private data class FilesOf(val channelId: Int, val name: String, val password: String)
private val FilesOfSaver = Saver<FilesOf?, List<Any>>(
save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } },
restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) },
)
/** A connection: the channel tree and the chat, with the voice controls underneath. */ /** A connection: the channel tree and the chat, with the voice controls underneath. */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@@ -137,56 +56,19 @@ fun ServerScreen(
/** False for a server beside the one on show while swiping to it. */ /** False for a server beside the one on show while swiping to it. */
active: Boolean = true, active: Boolean = true,
) { ) {
val state by server.state.collectAsStateWithLifecycle() val sessionState = server.state.collectAsStateWithLifecycle()
val tree by server.tree.collectAsStateWithLifecycle() val state by sessionState
val chats by server.chats.collectAsStateWithLifecycle() val treeState = server.tree.collectAsStateWithLifecycle()
val collapsed by server.collapsed.collectAsStateWithLifecycle() val tree by treeState
val chatsState = server.chats.collectAsStateWithLifecycle()
val chats by chatsState
var showChat by rememberSaveable { mutableStateOf(false) } val nav = rememberServerNav()
// Out here, so the tree keeps its place while the chat or another screen replaces it. // Out here, so the tree keeps its place while the chat or another page replaces it.
val treeList = rememberLazyListState() val treeList = rememberLazyListState()
var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf<ChatKey>(ChatKey.CHANNEL) } val conversationState = remember(chatsState, nav) { derivedStateOf { chatsState.value[nav.chatKey] ?: chatsState.value.channel } }
val conversation = chats[chatKey] ?: chats.channel val conversation by conversationState
var clientSheet by remember { mutableStateOf<Int?>(null) } val picking = rememberTreePicking(server, treeState, sessionState)
var clientSheetFromTree by remember { mutableStateOf(false) }
/** A row to show in the tree. */
var reveal by remember { mutableStateOf<TreeRef?>(null) }
var channelSheet by remember { mutableStateOf<Int?>(null) }
/** A locked channel being joined, while its password is asked for. */
var joinLocked by remember { mutableStateOf<Int?>(null) }
val join = { channel: ChannelItem ->
if (channel.locked) joinLocked = channel.id else server.joinChannel(channel.id)
}
var serverSheet by remember { mutableStateOf(false) }
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
var banList by rememberSaveable { mutableStateOf(false) }
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf<FilesOf?>(null) }
/** A locked channel whose files are wanted, while its password is asked for. */
var filesLocked by remember { mutableStateOf<Int?>(null) }
var deletingChannel by remember { mutableStateOf<Int?>(null) }
var whisperLists by rememberSaveable { mutableStateOf(false) }
/** What is being added to a whisper list, while the list is picked: its name and how to add it. */
var toWhisperList by remember { mutableStateOf<Pair<String, (WhisperList) -> Unit>?>(null) }
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
/** The clients to move, while a channel for them is being picked. */
var moving by remember { mutableStateOf<Set<Int>?>(null) }
/** Clients picked by a long press, to be moved or kicked together; those who left fall out. */
var picked by remember { mutableStateOf(emptySet<Int>()) }
val selection = remember(picked, tree) { picked.filterTo(LinkedHashSet()) { tree.client(it) != null } }
/** Whether the selection is being kicked: from the server, or from their channels. */
var kickingSelection by remember { mutableStateOf<Boolean?>(null) }
/** Whom of the selection a kick goes to: never us, and from a channel, nobody already in the default one. */
val kickable = { fromServer: Boolean ->
val inDefault = if (fromServer) emptySet() else tree.channel(server.defaultChannelId)?.clients.orEmpty().map { it.id }.toSet()
selection - state.selfClientId - inDefault
}
val moveTo = { channelId: Int, clients: Set<Int> ->
server.moveClients(clients, channelId)
moving = null
picked = emptySet()
}
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle() val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle()
val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle() val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle()
@@ -197,12 +79,11 @@ fun ServerScreen(
val chatRequest by server.chatRequest.collectAsStateWithLifecycle() val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
LaunchedEffect(chatRequest) { LaunchedEffect(chatRequest) {
val key = chatRequest ?: return@LaunchedEffect val key = chatRequest ?: return@LaunchedEffect
chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId) nav.openChat(if (chats[key] != null) key else server.openPrivateChat(key.clientId))
showChat = true
server.chatRequestHandled() server.chatRequestHandled()
} }
val viewing = if (showChat) conversation.key else null val viewing = if (nav.showChat) conversation.key else null
LifecycleResumeEffect(viewing, active) { LifecycleResumeEffect(viewing, active) {
if (active) server.viewing = viewing if (active) server.viewing = viewing
onPauseOrDispose { server.viewing = null } onPauseOrDispose { server.viewing = null }
@@ -216,81 +97,31 @@ fun ServerScreen(
ChatAttachment.isHref(href) -> attachments.open(href) ChatAttachment.isHref(href) -> attachments.open(href)
ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) } ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) }
ref == null -> runCatching { uriHandler.openUri(href) } ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false } ref.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false)
else -> channelSheet = ref.id else -> nav.overlay = Overlay.Channel(ref.id)
} }
} }
// Find: in the tree, clients or channels; in the chat, the conversation on screen. // Find: in the tree, clients or channels; in the chat, the conversation on screen.
val find = rememberSaveable(saver = FindState.Saver) { FindState() } val find = rememberSaveable(saver = FindState.Saver) { FindState() }
val treeFind = TreeFind(find.usable, find.channels) val treeView = rememberTreeView(server, treeState, server.collapsed.collectAsStateWithLifecycle(), find)
val treeHits = remember(tree, treeFind) { tree.hits(treeFind) } val chatSearch = rememberChatSearch(conversationState, find)
val treeFiltering = find.filter && !treeFind.query.isEmpty LaunchedEffect(treeView.treeFind, nav.showChat) { treeView.restart(onScreen = !nav.showChat) }
val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree } LaunchedEffect(chatSearch.query, conversation.key, find.filter, nav.showChat) { chatSearch.restart(onScreen = nav.showChat) }
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet<Int>()) } when (val page = nav.page) {
/** The match the tree is on. */ ServerPage.Main -> {}
var treeAt by remember { mutableStateOf<Int?>(null) } ServerPage.BanList -> return BanListScreen(server, vm.banReasons, onBack = nav::back)
// Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured. ServerPage.WhisperLists -> return WhisperListsScreen(vm, server, onBack = nav::back)
val showTreeHit = { id: Int? -> is ServerPage.EditChannel -> return ChannelEditScreen(server, page.edit, onDone = nav::back)
if (id != null) { is ServerPage.Files -> return FilesScreen(server, page.channelId, page.name, page.password, onBack = nav::back)
treeAt = id is ServerPage.ConnectionInfo -> return ConnectionInfoScreen(server, page.clientId, tree.client(page.clientId), onBack = nav::back)
val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(treeFind.channels, id)
}
}
LaunchedEffect(treeFind, showChat) {
treeAt = null
if (!showChat) showTreeHit(treeHits.firstOrNull())
} }
val chatQuery = find.usable val onTree = !nav.showChat
val chatLines = remember(conversation.lines, chatQuery, find.filter) { BackHandler(active && nav.showChat) { nav.showChat = false }
if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines BackHandler(active && onTree && picking.moving != null) { picking.moving = null }
} BackHandler(active && onTree && picking.moving == null && picking.selection.isNotEmpty()) { picking.clear() }
val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) }
/** The match the chat is on; a new search starts from the newest. */
var chatAt by remember { mutableStateOf<ChatMatch?>(null) }
var chatReveal by remember { mutableStateOf<Long?>(null) }
LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) {
chatAt = if (showChat) chatHits.lastOrNull() else null
chatReveal = chatAt?.line
}
val step = { delta: Int ->
if (showChat && chatHits.isNotEmpty()) {
chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)]
chatReveal = chatAt?.line
} else if (!showChat && treeHits.isNotEmpty()) {
showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)])
}
}
if (banList) {
BanListScreen(server, vm.banReasons, onBack = { banList = false })
return
}
channelEdit?.let {
ChannelEditScreen(server, it, onDone = { channelEdit = null })
return
}
files?.let {
FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null })
return
}
if (whisperLists) {
WhisperListsScreen(vm, server, onBack = { whisperLists = false })
return
}
connectionInfo?.let { id ->
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
return
}
BackHandler(active && showChat) { showChat = false }
BackHandler(active && moving != null && !showChat) { moving = null }
BackHandler(active && moving == null && selection.isNotEmpty() && !showChat) { picked = emptySet() }
BackHandler(active && find.open) { find.open = false } BackHandler(active && find.open) { find.open = false }
Scaffold( Scaffold(
@@ -302,11 +133,10 @@ fun ServerScreen(
}, },
topBar = { topBar = {
if (find.open) { if (find.open) {
if (showChat) { if (nav.showChat) {
FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size, FindBar(find, inTree = false, chatSearch.position, chatSearch.hits.size, chatSearch.capped, chatSearch::step)
chatHits.size == MAX_CHAT_MATCHES, step)
} else { } else {
FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step) FindBar(find, inTree = true, treeView.position, treeView.hits.size, false, treeView::step)
} }
} else { } else {
TopAppBar( TopAppBar(
@@ -314,7 +144,7 @@ fun ServerScreen(
expandedHeight = 48.dp, expandedHeight = 48.dp,
actions = { actions = {
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } } state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
if (state.connected && state.whisperControls) WhisperMenu(vm, server, state) { whisperLists = true } if (state.connected && state.whisperControls) WhisperMenu(vm, server, state) { nav.page = ServerPage.WhisperLists }
IconButton(onClick = find::show) { PackIcon("FIND", "Find") } IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
}, },
@@ -325,112 +155,81 @@ fun ServerScreen(
Column { Column {
val ptt = rememberPttTarget(vm) val ptt = rememberPttTarget(vm)
WhisperBanner(state) { server.setWhisper(null) } WhisperBanner(state) { server.setWhisper(null) }
VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) { VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, nav.showChat, chats.anyUnread) {
showChat = !showChat nav.showChat = !nav.showChat
} }
} }
}, },
snackbarHost = { SnackbarHost(snackbar) }, snackbarHost = { SnackbarHost(snackbar) },
) { padding -> ) { padding ->
SwipeHost( SwipeHost(
pageSwipe, showChat, pageSwipe, nav.showChat,
neighbour = { chat, dir -> if (chatBesideTree && (dir > 0) != chat) !chat else null }, neighbour = { chat, dir -> if (chatBesideTree && (dir > 0) != chat) !chat else null },
onSwipe = { showChat = it }, onSwipe = { nav.showChat = it },
modifier = Modifier.padding(padding).consumeWindowInsets(padding).imePadding(), modifier = Modifier.padding(padding).consumeWindowInsets(padding).imePadding(),
) { chat -> ) { chat ->
if (!chat) Column(Modifier.fillMaxSize()) { if (!chat) Column(Modifier.fillMaxSize()) {
val movingNow = moving PickingBar(picking, server, tree, state.channelId) { nav.overlay = Overlay.Kick(it) }
if (movingNow != null) {
val clients = movingNow.mapNotNull { tree.client(it) }
if (clients.isEmpty()) {
LaunchedEffect(movingNow) { moving = null }
} else {
MovePrompt(clients.singleOrNull()?.name ?: "${clients.size} clients") { moving = null }
}
} else if (selection.isNotEmpty()) {
val outside = tree.channel(state.channelId)?.clients.orEmpty().map { it.id }.let { selection - it.toSet() }
SelectionBar(
count = selection.size,
onMove = if (server.permissions.canMoveClients()) ({ moving = selection }) else null,
onMoveHere = if (server.permissions.canMoveClients() && outside.isNotEmpty()) ({ moveTo(state.channelId, outside) }) else null,
onKickChannel = if (server.permissions.canKickFromChannel() && kickable(false).isNotEmpty()) ({ kickingSelection = false }) else null,
onKickServer = if (server.permissions.canKickFromServer() && kickable(true).isNotEmpty()) ({ kickingSelection = true }) else null,
onClear = { picked = emptySet() },
)
}
ChannelTree( ChannelTree(
serverName = state.title, serverName = state.title,
tree = shownTree, tree = treeView.tree,
collapsed = if (treeFiltering) filterCollapsed else collapsed, collapsed = treeView.collapsed,
currentChannel = state.channelId, currentChannel = state.channelId,
onToggle = { onToggle = { treeView.toggle(it.id) },
if (!treeFiltering) server.toggleCollapsed(it.id)
else if (it.id in filterCollapsed) filterCollapsed -= it.id
else filterCollapsed += it.id
},
onChannel = { channel -> onChannel = { channel ->
val clients = moving val clients = picking.moving
when { when {
channel.spacer != null -> {} channel.spacer != null -> {}
clients != null -> moveTo(channel.id, clients) clients != null -> picking.moveTo(channel.id, clients)
else -> channelSheet = channel.id else -> nav.overlay = Overlay.Channel(channel.id)
} }
}, },
onChannelDoubleTap = { channel -> onChannelDoubleTap = { channel ->
val clients = moving val clients = picking.moving
when { when {
clients != null -> moveTo(channel.id, clients) clients != null -> picking.moveTo(channel.id, clients)
channel.id == state.channelId -> {} channel.id == state.channelId -> {}
else -> join(channel) else -> nav.join(server, channel)
} }
}, },
onClient = { onClient = {
when { if (picking.selection.isEmpty()) nav.overlay = Overlay.Client(it.id, fromTree = true)
selection.isEmpty() -> { clientSheet = it.id; clientSheetFromTree = true } else picking.toggle(it.id)
it.id in selection -> picked = selection - it.id
else -> picked = selection + it.id
}
}, },
onServer = { serverSheet = true }, onServer = { nav.overlay = Overlay.Server },
modifier = Modifier.weight(1f).swipeSource(when (treeSwipe) { modifier = Modifier.weight(1f).swipeSource(when (treeSwipe) {
TreeSwipe.CHAT -> pageSwipe TreeSwipe.CHAT -> pageSwipe
TreeSwipe.SERVERS -> serverSwipe TreeSwipe.SERVERS -> serverSwipe
TreeSwipe.OFF -> null TreeSwipe.OFF -> null
}), }),
reveal = reveal, reveal = treeView.reveal,
onRevealed = { reveal = null }, onRevealed = { treeView.reveal = null },
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }, found = treeView.found,
foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) }, foundCurrent = treeView.current,
listState = treeList, listState = treeList,
selected = selection, selected = picking.selection,
onClientLongPress = if (server.permissions.canMoveClients() || server.permissions.canKickFromChannel() || server.permissions.canKickFromServer()) { onClientLongPress = if (picking.canPick) ({ picking.pick(it.id) }) else null,
{ picked = selection + it.id } onShowSelf = { treeView.show(TreeRef(false, state.selfClientId)) },
} else null,
onShowSelf = {
val path = tree.pathTo(state.selfClientId).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(false, state.selfClientId)
},
) )
} else { } else {
ChatPane( ChatPane(
chats = chats, chats = chats,
selected = conversation, selected = conversation,
canSend = state.connected, canSend = state.connected,
onSelect = { chatKey = it }, onSelect = { nav.chatKey = it },
onClose = { key -> onClose = { key ->
if (chatKey == key) chatKey = ChatKey.CHANNEL if (nav.chatKey == key) nav.chatKey = ChatKey.CHANNEL
server.closePrivateChat(key) server.closePrivateChat(key)
}, },
onSend = { server.send(conversation.key, it) }, onSend = { server.send(conversation.key, it) },
onAttach = attachments.share, onAttach = attachments.share,
onLink = onLink, onLink = onLink,
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
lines = chatLines, lines = chatSearch.lines,
find = chatQuery, find = chatSearch.query,
current = chatAt, current = chatSearch.at,
reveal = chatReveal, reveal = chatSearch.reveal,
onRevealed = { chatReveal = null }, onRevealed = { chatSearch.reveal = null },
swipeTabs = chatTabSwipe, swipeTabs = chatTabSwipe,
linesModifier = Modifier.swipeSource(if (chatBesideTree) pageSwipe else null), linesModifier = Modifier.swipeSource(if (chatBesideTree) pageSwipe else null),
) )
@@ -438,347 +237,5 @@ fun ServerScreen(
} }
} }
// A sheet goes with its client or channel when that leaves the tree. ServerOverlay(nav, vm, server, state, tree, treeView, picking, snackbar, onLink, onEditContact, onEditBookmark)
clientSheet?.let { id ->
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = { clientSheet = null },
onMessage = {
clientSheet = null
chatKey = server.openPrivateChat(id)
showChat = true
},
onPoke = { server.poke(id, it); clientSheet = null },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); clientSheet = null },
onTalkRequest = if (client.self && (client.talkRequest || server.canRequestTalkPower)) {
{ server.setTalkRequest(it); clientSheet = null }
} else null,
onAddContact = { server.addContact(id, it) },
onEditContact = { clientSheet = null; onEditContact(client.uniqueId) },
onConnectionInfo = { clientSheet = null; connectionInfo = id },
onWhisper = if (state.whisperControls) ({ clientSheet = null; server.whisperToClient(id) }) else null,
onAddToWhisperList = if (state.whisperControls) ({
clientSheet = null
server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } }
}) else null,
onMove = if (server.permissions.canMoveClients()) ({ clientSheet = null; moving = setOf(id) }) else null,
onMoveToOwnChannel = if (server.permissions.canMoveClients() && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
{ server.moveClients(listOf(id), state.channelId); clientSheet = null }
} else null,
onFindInTree = if (clientSheetFromTree) null else ({
clientSheet = null
tree.pathTo(id)?.let { server.expand(it) }
showChat = false
reveal = TreeRef(false, id)
}),
moderation = clientModeration(server, client) { clientSheet = null },
)
}
}
channelSheet?.let { id ->
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = { channelSheet = null },
onJoin = { join(channel); channelSheet = null },
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
onWhisper = if (state.whisperControls) ({ channelSheet = null; server.whisperToChannel(id) }) else null,
onAddToWhisperList = if (state.whisperControls) ({
channelSheet = null
server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } }
}) else null,
onFiles = if (server.permissions.canBrowseFiles()) ({
channelSheet = null
if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "")
}) else null,
onCreateSub = if (server.permissions.canCreateChannels()) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
onEdit = if (server.permissions.canEditChannels()) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
onDelete = if (server.permissions.canDeleteChannels()) ({ channelSheet = null; deletingChannel = id }) else null,
)
}
}
kickingSelection?.let { fromServer ->
val others = kickable(fromServer)
val whom = others.singleOrNull()?.let { tree.client(it)?.name } ?: "${others.size} clients"
KickPrompt(
if (fromServer) "Kick $whom from the server?" else "Kick $whom from the channel?",
onDismiss = { kickingSelection = null },
) { reason ->
kickingSelection = null
if (fromServer) server.kickFromServer(others, reason) else server.kickFromChannel(others, reason)
picked = emptySet()
}
}
joinLocked?.let { id ->
TextPrompt(
title = "Join ${tree.channel(id)?.name.orEmpty()}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = { joinLocked = null },
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
)
}
filesLocked?.let { id ->
TextPrompt(
title = "Files of ${tree.channel(id)?.name.orEmpty()}",
label = "Channel password",
confirm = "Open",
password = true,
onDismiss = { filesLocked = null },
onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) },
)
}
deletingChannel?.let { id ->
val channel = tree.channel(id)
val scope = rememberCoroutineScope()
AlertDialog(
onDismissRequest = { deletingChannel = null },
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = {
deletingChannel = null
scope.launch { server.deleteChannel(id).onFailure { snackbar.showSnackbar("Could not delete the channel: ${it.message}") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } },
)
}
toWhisperList?.let { (name, add) ->
AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName ->
toWhisperList = null
vm.addToWhisperList(index, newName, add)
}
}
if (serverSheet) {
remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = { serverSheet = false },
onBookmark = { serverSheet = false; bookmarkHere(state.channelId) },
onBanList = if (server.permissions.canViewBanList()) ({ serverSheet = false; banList = true }) else null,
onCreateChannel = if (server.permissions.canCreateChannels()) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null)
}
}
} }
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
/** How many clients are picked in the tree, and what may be done with them at once. */
@Composable
private fun SelectionBar(
count: Int,
onMove: (() -> Unit)?,
onMoveHere: (() -> Unit)?,
onKickChannel: (() -> Unit)?,
onKickServer: (() -> Unit)?,
onClear: () -> Unit,
) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Clear selection") }
Text("$count selected", Modifier.weight(1f), maxLines = 1, style = MaterialTheme.typography.bodyMedium)
onMove?.let { IconButton(onClick = it) { PackIcon("CHANNEL_SWITCH", "Move to…") } }
onMoveHere?.let { IconButton(onClick = it) { PackIcon("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to my channel") } }
onKickChannel?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_CHANNEL", "Kick from channel") } }
onKickServer?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_SERVER", "Kick from server") } }
}
}
}
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
private fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
vm: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = vm.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
}
}
}
val away = @Composable {
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
}
}
val chat = @Composable {
IconToggleButton(showChat, { onChat() }) {
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
Modifier.alpha(if (showChat) 1f else 0.7f))
}
}
}
Surface(tonalElevation = 3.dp) {
// The same places whatever shows: sides of three buttons each keep the talk button centred.
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
Slot { mic() }; Slot { deafen() }; Slot { activate() }
}
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
Slot { away() }; Slot { chat() }
}
}
}
}
private val SLOT = 48.dp
private val SIDE = SLOT * 3
/** One button's place in the bar, kept whether or not the button shows. */
@Composable
private fun Slot(content: @Composable () -> Unit) {
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
}
/** An icon button that also answers a long press. */
@Composable
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
Box(
Modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(CircleShape)
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.alpha(if (enabled) 1f else 0.38f),
contentAlignment = Alignment.Center,
) { content() }
}
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by vm.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; vm.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -0,0 +1,94 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
internal fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by vm.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; vm.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -0,0 +1,145 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionState
/** Clients picked in the tree by a long press, to act on together, and clients being moved while a channel is picked. */
@Stable
internal class TreePicking(
private val server: ServerController,
private val tree: State<ServerTree>,
private val state: State<SessionState>,
) {
/** The clients to move, while a channel for them is being picked. */
var moving by mutableStateOf<Set<Int>?>(null)
private var picked by mutableStateOf(emptySet<Int>())
/** The picked clients still on the server. */
val selection by derivedStateOf { picked.filterTo(LinkedHashSet()) { tree.value.client(it) != null } }
val canPick: Boolean get() = with(server.permissions) { canMoveClients() || canKickFromChannel() || canKickFromServer() }
fun pick(clientId: Int) {
picked = selection + clientId
}
fun toggle(clientId: Int) {
picked = if (clientId in selection) selection - clientId else selection + clientId
}
fun clear() {
picked = emptySet()
}
/** Those of the selection not in our channel. */
val outsideOwnChannel: Set<Int>
get() = selection - tree.value.channel(state.value.channelId)?.clients.orEmpty().map { it.id }.toSet()
/** Whom of the selection a kick goes to: never us, and from a channel, nobody already in the default one. */
fun kickable(fromServer: Boolean): Set<Int> {
val inDefault = if (fromServer) emptySet() else tree.value.channel(server.defaultChannelId)?.clients.orEmpty().map { it.id }.toSet()
return selection - state.value.selfClientId - inDefault
}
fun kick(fromServer: Boolean, reason: String) {
val whom = kickable(fromServer)
if (fromServer) server.kickFromServer(whom, reason) else server.kickFromChannel(whom, reason)
clear()
}
fun moveTo(channelId: Int, clients: Set<Int>) {
server.moveClients(clients, channelId)
moving = null
clear()
}
}
@Composable
internal fun rememberTreePicking(server: ServerController, tree: State<ServerTree>, state: State<SessionState>): TreePicking =
remember(server, tree, state) { TreePicking(server, tree, state) }
/** Above the tree: the clients being moved, or what may be done with those picked. */
@Composable
internal fun PickingBar(picking: TreePicking, server: ServerController, tree: ServerTree, ownChannel: Int, onKick: (fromServer: Boolean) -> Unit) {
val moving = picking.moving
val selection = picking.selection
if (moving != null) {
val clients = moving.mapNotNull { tree.client(it) }
if (clients.isEmpty()) {
LaunchedEffect(moving) { picking.moving = null }
} else {
MovePrompt(clients.singleOrNull()?.name ?: "${clients.size} clients") { picking.moving = null }
}
} else if (selection.isNotEmpty()) {
val can = server.permissions
val outside = picking.outsideOwnChannel
SelectionBar(
count = selection.size,
onMove = if (can.canMoveClients()) ({ picking.moving = selection }) else null,
onMoveHere = if (can.canMoveClients() && outside.isNotEmpty()) ({ picking.moveTo(ownChannel, outside) }) else null,
onKickChannel = if (can.canKickFromChannel() && picking.kickable(false).isNotEmpty()) ({ onKick(false) }) else null,
onKickServer = if (can.canKickFromServer() && picking.kickable(true).isNotEmpty()) ({ onKick(true) }) else null,
onClear = picking::clear,
)
}
}
/** How many clients are picked in the tree, and what may be done with them at once. */
@Composable
private fun SelectionBar(
count: Int,
onMove: (() -> Unit)?,
onMoveHere: (() -> Unit)?,
onKickChannel: (() -> Unit)?,
onKickServer: (() -> Unit)?,
onClear: () -> Unit,
) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Clear selection") }
Text("$count selected", Modifier.weight(1f), maxLines = 1, style = MaterialTheme.typography.bodyMedium)
onMove?.let { IconButton(onClick = it) { PackIcon("CHANNEL_SWITCH", "Move to…") } }
onMoveHere?.let { IconButton(onClick = it) { PackIcon("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to my channel") } }
onKickChannel?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_CHANNEL", "Kick from channel") } }
onKickServer?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_SERVER", "Kick from server") } }
}
}
}
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
@@ -0,0 +1,141 @@
package eu.lixko.ts3j.client.android.ui
import android.widget.Toast
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.config.Settings
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
internal fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
vm: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = vm.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
}
}
}
val away = @Composable {
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
}
}
val chat = @Composable {
IconToggleButton(showChat, { onChat() }) {
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
Modifier.alpha(if (showChat) 1f else 0.7f))
}
}
}
Surface(tonalElevation = 3.dp) {
// The same places whatever shows: sides of three buttons each keep the talk button centred.
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
Slot { mic() }; Slot { deafen() }; Slot { activate() }
}
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
Slot { away() }; Slot { chat() }
}
}
}
}
private val SLOT = 48.dp
private val SIDE = SLOT * 3
/** One button's place in the bar, kept whether or not the button shows. */
@Composable
private fun Slot(content: @Composable () -> Unit) {
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
}
/** An icon button that also answers a long press. */
@Composable
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
Box(
Modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(CircleShape)
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.alpha(if (enabled) 1f else 0.38f),
contentAlignment = Alignment.Center,
) { content() }
}
+2 -2
View File
@@ -23,8 +23,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo
| 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | done, in sub-steps: | | 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | done, in sub-steps: |
| 9a | … byte-size formatters | done (`5358599`): `text.ByteSize` writes sizes and rates as TeamSpeak does (`1023 Bytes`, `353.98 KiB`); chat attachments and the file browser now use it too, so they show KiB/MiB with two decimals | | 9a | … byte-size formatters | done (`5358599`): `text.ByteSize` writes sizes and rates as TeamSpeak does (`1023 Bytes`, `353.98 KiB`); chat attachments and the file browser now use it too, so they show KiB/MiB with two decimals |
| 9b | … "which chat" enums | done (`5358599`): one `chat.ChatScope` replaces `ConnectionListener.ChatScope`, `ChatLogScope` and `ChatPanel.Target`, and the mappings between them are gone. Android's `ChatKey` also carries the peer, so it goes with the conversation model | | 9b | … "which chat" enums | done (`5358599`): one `chat.ChatScope` replaces `ConnectionListener.ChatScope`, `ChatLogScope` and `ChatPanel.Target`, and the mappings between them are gone. Android's `ChatKey` also carries the peer, so it goes with the conversation model |
| 9c | … the conversation model (Swing `ChatPanel.Tab`, Android `Chats`) | done: `session.ChatFeed` decides which conversation a message, history or server event goes to and renders it, and the frontends get the lines through `chat.ChatSink` (`ServerSession.Listener` no longer passes on raw chat events). `chat.ChatKey` replaces Android's own key and `ChatPanel`'s scope and client id. Each frontend still keeps and draws the lines its own way. Fixes Swing labelling our messages with the global nickname instead of the one we have on the server, and linking our name in a private chat to the peer | | 9c | … the conversation model (Swing `ChatPanel.Tab`, Android `Chats`) | done (`a2a1280`): `session.ChatFeed` decides which conversation a message, history or server event goes to and renders it, and the frontends get the lines through `chat.ChatSink` (`ServerSession.Listener` no longer passes on raw chat events). `chat.ChatKey` replaces Android's own key and `ChatPanel`'s scope and client id. Each frontend still keeps and draws the lines its own way. Fixes Swing labelling our messages with the global nickname instead of the one we have on the server, and linking our name in a private chat to the peer |
| 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | open | | 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | done: `ServerNav` holds where the screen is (one saved `ServerPage` for the five pages that replace it, tree or chat, the conversation, and one `Overlay` for the eight sheets and dialogs); `TreeView` and `ChatSearch` the find state of each side; `TreePicking` the long-press selection and moves. The sheets and dialogs are `ServerOverlay`; `VoiceBar` and `ServerSwitcher` have their own files. Only one sheet or dialog shows at a time, so a channel link in a client sheet now replaces it; Find in tree from a sheet honours Only matches; a failed channel deletion's snackbar is no longer cancelled with its dialog |
| 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | open | | 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | open |
| 12 | Swing `ui` package: 118 files, flat | open | | 12 | Swing `ui` package: 118 files, flat | open |
| 13 | `ClientEntry`/`ChannelNode` are bags of public volatile fields; a reader can see a half-applied update | open | | 13 | `ClientEntry`/`ChannelNode` are bags of public volatile fields; a reader can see a half-applied update | open |