diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt index d28f679..d9bb2d1 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt @@ -1,16 +1,11 @@ package eu.lixko.ts3j.client.android import androidx.compose.runtime.Immutable +import eu.lixko.ts3j.client.chat.ChatKey +import eu.lixko.ts3j.client.chat.ChatScope import eu.lixko.ts3j.client.text.HtmlText import eu.lixko.ts3j.client.text.TextQuery -/** Which conversation a chat line belongs to. */ -sealed interface ChatKey { - data object Server : ChatKey - data object Channel : ChatKey - data class Private(val clientId: Int) : ChatKey -} - /** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */ @Immutable data class ChatLine(val id: Long, val html: String) { @@ -31,25 +26,25 @@ data class Conversation( /** Every conversation of the session: the server's, the channel's, then the private ones. */ @Immutable data class Chats( - val server: Conversation = Conversation(ChatKey.Server, "Server"), - val channel: Conversation = Conversation(ChatKey.Channel, "Channel"), + val server: Conversation = Conversation(ChatKey.SERVER, "Server"), + val channel: Conversation = Conversation(ChatKey.CHANNEL, "Channel"), val private: List = emptyList(), ) { val all: List get() = listOf(server, channel) + private val anyUnread: Boolean get() = all.any { it.unread } - operator fun get(key: ChatKey): Conversation? = when (key) { - ChatKey.Server -> server - ChatKey.Channel -> channel - is ChatKey.Private -> private.firstOrNull { it.key == key } + operator fun get(key: ChatKey): Conversation? = when (key.scope()) { + ChatScope.SERVER -> server + ChatScope.CHANNEL -> channel + ChatScope.PRIVATE -> private.firstOrNull { it.key == key } } /** Applies [change] to a conversation, opening a private one titled [title] if needed. */ - fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) { - ChatKey.Server -> copy(server = change(server)) - ChatKey.Channel -> copy(channel = change(channel)) - is ChatKey.Private -> { + fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key.scope()) { + ChatScope.SERVER -> copy(server = change(server)) + ChatScope.CHANNEL -> copy(channel = change(channel)) + ChatScope.PRIVATE -> { val existing = private.indexOfFirst { it.key == key } if (existing < 0) { copy(private = private + change(Conversation(key, title))) @@ -59,7 +54,7 @@ data class Chats( } } - fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key }) + fun close(key: ChatKey): Chats = copy(private = private.filter { it.key != key }) companion object { /** As many lines as a log history loads; older ones leave the conversation. */ diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt index 2a4004c..dba8358 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt @@ -1,6 +1,7 @@ package eu.lixko.ts3j.client.android import android.net.Uri +import eu.lixko.ts3j.client.chat.ChatKey import eu.lixko.ts3j.client.chat.ChatScope import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.contacts.ContactType @@ -81,7 +82,7 @@ class ServerController internal constructor( set(value) { field = value if (value != null) markRead(value) - if (value is ChatKey.Private) app.notifier.clear(id, value.clientId) + if (value != null && value.isPrivate) app.notifier.clear(id, value.clientId()) } /** Counts the answers to info requests, for the details on screen to be read again. */ @@ -91,8 +92,8 @@ class ServerController internal constructor( val images = ServerImages(session.icons(), session.avatars()) /** A private chat a notification asked to show, until the UI took it up. */ - private val _chatRequest = MutableStateFlow(null) - val chatRequest: StateFlow = _chatRequest + private val _chatRequest = MutableStateFlow(null) + val chatRequest: StateFlow = _chatRequest private val lineIds = AtomicLong() @@ -386,8 +387,8 @@ class ServerController internal constructor( // ---- chat ---- /** Opens the private chat with a client, loading what was said before. */ - fun openPrivateChat(clientId: Int): ChatKey.Private { - val key = ChatKey.Private(clientId) + fun openPrivateChat(clientId: Int): ChatKey { + val key = ChatKey.privateWith(clientId) val client = session.model().getClient(clientId) if (client != null) { _chats.update { chats -> @@ -398,34 +399,23 @@ class ServerController internal constructor( return key } - fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) } + fun closePrivateChat(key: ChatKey) = _chats.update { it.close(key) } - fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text) + fun send(key: ChatKey, text: String) = session.sendChat(key, text) /** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */ suspend fun sendFile(key: ChatKey, uri: Uri) { app.openShared(uri) - .onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) } + .onSuccess { session.sendAttachment(key, app.attachments, it.data, it.size, it.name) } .onFailure { app.error(it.message ?: "Could not read the file") } } - private fun scope(key: ChatKey) = when (key) { - ChatKey.Server -> ChatScope.SERVER - ChatKey.Channel -> ChatScope.CHANNEL - is ChatKey.Private -> ChatScope.PRIVATE - } - - private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0 - - /** Where files shared on this server lie; empty before it is known. */ - private val room: String get() = session.serverUniqueId().orEmpty() - fun markRead(key: ChatKey) { if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } } } internal fun requestChat(clientId: Int) { - _chatRequest.value = ChatKey.Private(clientId) + _chatRequest.value = ChatKey.privateWith(clientId) } fun chatRequestHandled() { @@ -434,22 +424,21 @@ class ServerController internal constructor( /** Answers a private message from its notification. */ internal fun reply(clientId: Int, text: String) { - if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId) + if (session.isConnected) send(ChatKey.privateWith(clientId), text) else app.notifier.clear(id, clientId) } - private fun append(key: ChatKey, title: String, html: String) { - if (html.isEmpty()) return + private fun addLine(key: ChatKey, title: String, html: String) { val line = ChatLine(lineIds.incrementAndGet(), html) _chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } } } - private fun setHistory(key: ChatKey, title: String, entries: List) { - val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() } - .map { ChatLine(lineIds.incrementAndGet(), it) } + private fun replaceLines(key: ChatKey, title: String, html: List) { + val lines = html.map { ChatLine(lineIds.incrementAndGet(), it) } _chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } } } - private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text)) + /** One of this app's own notices, in the server chat. */ + private fun system(text: String) = addLine(ChatKey.SERVER, "", ChatHtml.system(text)) // ---- snapshots ---- @@ -491,30 +480,33 @@ class ServerController internal constructor( if (structureChanged.getAndSet(false)) roots = session.model().buildTree() _tree.value = ServerTree.of(roots, session.model(), session.contacts().store(), app.settings.colorContacts.get(), app.settings.countryFlags.get(), app.settings.clientRowColors) - val serverName = if (session.isConnected) session.model().serverName.orEmpty() else "" - val channelName = session.currentChannel()?.name.orEmpty() - _chats.update { - it.copy( - server = it.server.copy(title = serverName.ifBlank { "Server" }), - channel = it.channel.copy(title = channelName.ifBlank { "Channel" }), - ) - } refresh() } } private inner class Listener : ServerSession.Listener { override fun onSessionChanged() = refresh() - override fun onSystemMessage(text: String) = system(text) - override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) { - val self = session.model().getClient(session.selfClientId())?.nickname ?: app.settings.nickname.get() - val html = ChatHtml.message(session.selfClientId(), session.selfUniqueId(), "$self (you)", text, room) - append(key(scope, peerClientId), peerName, html) - if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text)) + override fun append(key: ChatKey, title: String, html: String) = addLine(key, title, html) + + override fun setHistory(key: ChatKey, title: String, html: List) = replaceLines(key, title, html) + + override fun rename(key: ChatKey, name: String) = _chats.update { + when (key.scope()) { + ChatScope.SERVER -> it.copy(server = it.server.copy(title = name.ifBlank { "Server" })) + ChatScope.CHANNEL -> it.copy(channel = it.channel.copy(title = name.ifBlank { "Channel" })) + else -> it + } } - override fun onStatus(status: String) {} + override fun closePrivateChats() = _chats.update { it.copy(private = emptyList()) } + + override fun onPrivateMessage(fromClientId: Int, fromName: String, message: String) { + if (!app.foreground) app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message)) + } + + override fun onPrivateMessageSent(toClientId: Int, message: String) = + app.notifier.sent(id, toClientId, ChatHtml.plainMessage(message)) override fun onConnected() { network.onConnected() @@ -525,7 +517,6 @@ class ServerController internal constructor( override fun onDisconnected(reason: String?) { network.onDisconnected() app.notifier.clearServer(id) - _chats.update { it.copy(private = emptyList()) } app.disconnected(this@ServerController) scheduleTree(structure = true) refresh() @@ -548,20 +539,6 @@ class ServerController internal constructor( override fun onIconsUpdated() = images.loaded() - override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) { - append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room)) - if (scope == ChatScope.PRIVATE && !app.foreground) { - app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message)) - } - } - - override fun onChatHistory(scope: ChatScope, htmlEntries: List) { - if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries) - } - - override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List) = - setHistory(ChatKey.Private(clientId), nickname, htmlEntries) - override fun onTalkStateChanged(clientId: Int, talking: Boolean) { if (clientId == session.selfClientId() && micOwner) app.talking(talking) scheduleTree(structure = false) @@ -570,16 +547,8 @@ class ServerController internal constructor( override fun onError(message: String) = app.error(message) override fun onPoke(fromName: String, message: String) = app.poked(fromName, message) - - override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message)) - override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room)) } - private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) { - ChatScope.SERVER -> ChatKey.Server - ChatScope.CHANNEL -> ChatKey.Channel - ChatScope.PRIVATE -> ChatKey.Private(peerClientId) - } private companion object { const val TREE_FRAME_MS = 30L diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt index a4f08e7..0df1677 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt @@ -17,9 +17,9 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.lifecycle.compose.collectAsStateWithLifecycle -import eu.lixko.ts3j.client.android.ChatKey import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.chat.ChatKey import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.myts.MyTsException import kotlinx.coroutines.launch diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt index 3b92fc1..5810543 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt @@ -49,11 +49,11 @@ import androidx.compose.ui.input.key.type import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp -import eu.lixko.ts3j.client.android.ChatKey import eu.lixko.ts3j.client.android.ChatLine import eu.lixko.ts3j.client.android.ChatMatch import eu.lixko.ts3j.client.android.Chats import eu.lixko.ts3j.client.android.Conversation +import eu.lixko.ts3j.client.chat.ChatKey import eu.lixko.ts3j.client.text.TextQuery import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter @@ -65,7 +65,7 @@ fun ChatPane( selected: Conversation, canSend: Boolean, onSelect: (ChatKey) -> Unit, - onClose: (ChatKey.Private) -> Unit, + onClose: (ChatKey) -> Unit, onSend: (String) -> Unit, /** Picks a file to share in [selected]. */ onAttach: () -> Unit, @@ -162,7 +162,7 @@ private fun ConversationChip( conversation: Conversation, selected: Boolean, onSelect: (ChatKey) -> Unit, - onClose: (ChatKey.Private) -> Unit, + onClose: (ChatKey) -> Unit, ) { val key = conversation.key FilterChip( @@ -170,7 +170,7 @@ private fun ConversationChip( onClick = { onSelect(key) }, label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, leadingIcon = if (conversation.unread) ({ Badge() }) else null, - trailingIcon = if (key is ChatKey.Private) ({ + trailingIcon = if (key.isPrivate) ({ Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) }) }) else null, ) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt index 9e5d6e9..2d2fa95 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt @@ -73,7 +73,6 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import eu.lixko.ts3j.client.android.ChannelItem -import eu.lixko.ts3j.client.android.ChatKey import eu.lixko.ts3j.client.android.ChatMatch import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.SessionController @@ -81,6 +80,8 @@ 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.findIn +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 @@ -90,17 +91,17 @@ import kotlinx.coroutines.launch private val ChatKeySaver = Saver( save = { key -> - when (key) { - ChatKey.Server -> "server" - ChatKey.Channel -> "channel" - is ChatKey.Private -> "private:${key.clientId}" + 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.Private(saved.substringAfter(':').toInt()) - else -> ChatKey.Channel + saved == "server" -> ChatKey.SERVER + saved.startsWith("private:") -> ChatKey.privateWith(saved.substringAfter(':').toInt()) + else -> ChatKey.CHANNEL } }, ) @@ -144,7 +145,7 @@ fun ServerScreen( var showChat by rememberSaveable { mutableStateOf(false) } // Out here, so the tree keeps its place while the chat or another screen replaces it. val treeList = rememberLazyListState() - var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf(ChatKey.Channel) } + var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf(ChatKey.CHANNEL) } val conversation = chats[chatKey] ?: chats.channel var clientSheet by remember { mutableStateOf(null) } var clientSheetFromTree by remember { mutableStateOf(false) } @@ -418,7 +419,7 @@ fun ServerScreen( canSend = state.connected, onSelect = { chatKey = it }, onClose = { key -> - if (chatKey == key) chatKey = ChatKey.Channel + if (chatKey == key) chatKey = ChatKey.CHANNEL server.closePrivateChat(key) }, onSend = { server.send(conversation.key, it) }, diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md index a99f614..3daf764 100644 --- a/ts3-client/AUDIT-STRUCTURE.md +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -20,10 +20,10 @@ Items are worked through in the order below. Status: open, done (commit), or clo | 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | done (`f7cf040`): `MainCommands` holds each command once, acting on the server on screen or, for hotkeys, on a list of sessions; the menu, toolbar and hotkeys call it directly and both `Listener` interfaces are gone. The menu's mute items no longer click the toolbar's buttons, and the menu's commander toggle now repaints the toolbar and tray | | 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding | done (`e214f21`): the five extend `AbstractServerListDialog`, which lays out the toolbar, list, status line and Reload/Close, follows the server's name, binds F5/Ctrl+W/Escape, guards loading, reloads after a change and reports its failure; `ServerTab` keeps them in one map. All five now take F5, show load failures in red, and keep the status line's height; the ban list's own placeholder field is FlatLaf's. The table models stay per dialog: their rows and columns share nothing | | 8 | `Settings`: 58 public fields, each key spelled twice (load and save), no change notification, so callers fan changes out by hand | done (`203082d`): each value is a `Setting` (`get`/`set`, listeners), declared once with its key, type and range, and loaded and saved from that list. Output device, volume and receive buffer reach every connection, and the status bar and master volume slider follow their toggles, through listeners instead of calls at each place that changes them; Android puts output settings and country flags into effect the same way. `SplitRatio` takes the setting itself. The sections with their own load/store (row colours, server log, notifications, contact defaults) are unchanged. The Playback page now previews the voice volume with the master volume applied, as Apply sets it | -| 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 | in progress, in sub-steps: | -| 9a | … byte-size formatters | done: `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: 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`) | open | +| 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 | +| 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 | | 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | 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 | diff --git a/ts3-client/README.md b/ts3-client/README.md index 3f4f434..73da13f 100644 --- a/ts3-client/README.md +++ b/ts3-client/README.md @@ -228,6 +228,7 @@ core/ eu.lixko.ts3j.client ├── session │ ├── ServerSession one server tab's state and actions, whatever the frontend; │ │ the frontends' only way in to a server +│ ├── ChatFeed turns chat events into the lines of each conversation │ └── Sessions what the servers share: the microphone, away state, nickname ├── net │ ├── TeamspeakConnection ties socket + audio + model; the connection lifecycle @@ -239,7 +240,7 @@ core/ eu.lixko.ts3j.client │ ├── ClientContacts the contact list applied to a server's clients │ ├── IconRepository server icons (avatar/ holds the client avatar cache) │ ├── filetransfer the file transfer protocol -│ └── ConnectionListener frontend callbacks +│ └── ConnectionListener what the connection tells its session ├── audio the voice pipelines every platform shares │ ├── AudioBackend/AudioIo what a platform supplies: devices, lines, Opus │ ├── CaptureVoiceInput capture → processing → VAD/PTT gate → Opus encode @@ -249,7 +250,7 @@ core/ eu.lixko.ts3j.client │ ├── processing port of TS3's WebRTC capture chain: HPF, NS, transients, AGC2 │ ├── vad port of WebRTC's rnn_vad speech detector │ └── opus codec interfaces -├── chat ChatScope: the server, channel or a private chat +├── chat ChatKey/ChatScope: which conversation; ChatSink: where its lines go ├── chatlog TS3-compatible chat logs, shared with the TS3 client by default ├── contacts friends and blocked clients, in TS3's own record format ├── text BBCode, TeamSpeak links, chat search, byte sizes diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chat/ChatKey.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chat/ChatKey.java new file mode 100644 index 0000000..cb26be2 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chat/ChatKey.java @@ -0,0 +1,30 @@ +package eu.lixko.ts3j.client.chat; + +/** + * One conversation on a server: its server chat, its channel chat, or the private chat with a + * client. + * + * @param clientId the peer of a private chat; 0 for the others + */ +public record ChatKey(ChatScope scope, int clientId) { + + public static final ChatKey SERVER = new ChatKey(ChatScope.SERVER, 0); + public static final ChatKey CHANNEL = new ChatKey(ChatScope.CHANNEL, 0); + + public static ChatKey privateWith(int clientId) { + return new ChatKey(ChatScope.PRIVATE, clientId); + } + + /** The conversation a message in {@code scope} belongs to; {@code peerClientId} counts only for a private one. */ + public static ChatKey of(ChatScope scope, int peerClientId) { + return switch (scope) { + case SERVER -> SERVER; + case CHANNEL -> CHANNEL; + case PRIVATE -> privateWith(peerClientId); + }; + } + + public boolean isPrivate() { + return scope == ChatScope.PRIVATE; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chat/ChatSink.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chat/ChatSink.java new file mode 100644 index 0000000..3a3bd8e --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chat/ChatSink.java @@ -0,0 +1,30 @@ +package eu.lixko.ts3j.client.chat; + +import java.util.List; + +/** + * Where a server's chat lines go, already rendered as {@link eu.lixko.ts3j.client.text.ChatHtml} + * HTML. The frontend keeps and shows them; calls arrive on connection threads. + */ +public interface ChatSink { + + /** + * Adds a line to a conversation, opening a private one if it is not open. + * + * @param title the peer's name for a private chat; empty for the server and channel chats + */ + void append(ChatKey key, String title, String html); + + /** Replaces a conversation's lines with what its log held, opening a private one if needed. */ + void setHistory(ChatKey key, String title, List html); + + /** + * The server's or the channel's name, which their conversations go by. + * + * @param name blank while there is none, e.g. when not connected + */ + void rename(ChatKey key, String name); + + /** Leaving the server ends its private chats. */ + void closePrivateChats(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java index c844594..f23736d 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java @@ -4,10 +4,7 @@ import eu.lixko.ts3j.client.chat.ChatScope; import java.util.List; -/** - * UI-facing callbacks fired by {@link TeamspeakConnection}. Implementations are - * responsible for marshalling to the Swing EDT. - */ +/** What a {@link TeamspeakConnection} tells its session; calls arrive on connection threads. */ public interface ConnectionListener { void onStatus(String status); diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ChatFeed.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ChatFeed.java new file mode 100644 index 0000000..7fa3877 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ChatFeed.java @@ -0,0 +1,75 @@ +package eu.lixko.ts3j.client.session; + +import eu.lixko.ts3j.client.chat.ChatKey; +import eu.lixko.ts3j.client.chat.ChatScope; +import eu.lixko.ts3j.client.chat.ChatSink; +import eu.lixko.ts3j.client.text.ChatHtml; + +import java.util.List; +import java.util.function.Supplier; + +/** Turns a session's chat events into the lines of its conversations. */ +final class ChatFeed { + + private final ChatSink sink; + /** The server's unique id, where files shared in its chats lie; empty before it is known. */ + private final Supplier room; + private String serverName = ""; + private String channelName = ""; + + ChatFeed(ChatSink sink, Supplier room) { + this.sink = sink; + this.room = room; + } + + /** Someone else's message; a private one goes to the chat with its sender. */ + void received(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { + sink.append(ChatKey.of(scope, fromClientId), fromName, + ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room.get())); + } + + /** A message we sent; a private one goes to the chat with {@code peerClientId}. */ + void sent(ChatScope scope, int peerClientId, String peerName, int selfId, String selfUniqueId, String selfName, + String message) { + sink.append(ChatKey.of(scope, peerClientId), peerName, + ChatHtml.message(selfId, selfUniqueId, selfName + " (you)", message, room.get())); + } + + void history(ChatKey key, String title, List logEntries) { + String room = this.room.get(); + List lines = logEntries.stream().map(e -> ChatHtml.logEntry(e, room)).filter(l -> !l.isEmpty()) + .toList(); + sink.setHistory(key, title, lines); + } + + /** One of the chat's own notices: connection progress, errors, pokes. */ + void system(String text) { + sink.append(ChatKey.SERVER, "", ChatHtml.system(text)); + } + + void serverLog(String text) { + sink.append(ChatKey.SERVER, "", ChatHtml.serverLog(text)); + } + + void serverLogHtml(String html) { + String line = ChatHtml.logEntry(html, room.get()); + if (!line.isEmpty()) sink.append(ChatKey.SERVER, "", line); + } + + /** Where we are now; the server and channel chats are renamed when it changed. */ + synchronized void names(String server, String channel) { + if (!server.equals(serverName)) { + serverName = server; + sink.rename(ChatKey.SERVER, server); + } + if (!channel.equals(channelName)) { + channelName = channel; + sink.rename(ChatKey.CHANNEL, channel); + } + } + + synchronized void disconnected() { + sink.closePrivateChats(); + names("", ""); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java index 4ed304b..51f14c8 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java @@ -1,7 +1,9 @@ package eu.lixko.ts3j.client.session; import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.chat.ChatKey; import eu.lixko.ts3j.client.chat.ChatScope; +import eu.lixko.ts3j.client.chat.ChatSink; import eu.lixko.ts3j.client.config.Bookmark; import eu.lixko.ts3j.client.config.IdentityEntry; import eu.lixko.ts3j.client.config.IdentityStore; @@ -48,6 +50,7 @@ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -66,25 +69,45 @@ import java.util.stream.Collectors; */ public final class ServerSession { - /** Everything a {@link ConnectionListener} hears, plus what the session adds. */ - public interface Listener extends ConnectionListener { + /** What a frontend hears of the session; the chat's lines come through {@link ChatSink}. */ + public interface Listener extends ChatSink { - /** - * The session's title, status, connecting state or self flags changed. Also - * delivers what {@link #onStatus} does, so frontends usually only need this one. - */ + /** The session's title, status, connecting state or self flags changed. */ void onSessionChanged(); - /** A line for the chat's own log: connection progress, errors, pokes. */ - void onSystemMessage(String text); + void onConnected(); - /** - * The local client sent a chat message. - * - * @param peerClientId the recipient of a private message, else 0 - * @param peerName the recipient's display name for a private message, else empty - */ - void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text); + void onDisconnected(String reason); + + /** The channel/client model changed and any tree view should be rebuilt. */ + void onModelChanged(); + + /** On-demand channel/client details finished loading; refresh any info view. */ + void onInfoUpdated(); + + /** A group icon finished downloading; repaint anything showing icons. */ + void onIconsUpdated(); + + /** A client (possibly the local one) started or stopped talking. */ + void onTalkStateChanged(int clientId, boolean talking); + + /** Also told in the chat and the status. */ + void onError(String message); + + /** Someone poked the local client; also told in the chat. */ + void onPoke(String fromName, String message); + + /** Our offline message inbox's unread count changed, or became known on connecting. */ + default void onUnreadMessagesChanged(int unread) { + } + + /** A private message came in, e.g. for a notification; its line comes through {@link #append}. */ + default void onPrivateMessage(int fromClientId, String fromName, String message) { + } + + /** We sent a private message; its line comes through {@link #append}. */ + default void onPrivateMessageSent(int toClientId, String message) { + } /** * The server's icon is known or changed (0: it has none), and is on its way to the @@ -97,6 +120,7 @@ public final class ServerSession { private final Settings settings; private final IdentityStore identities; private final Listener listener; + private final ChatFeed chat; private final TeamspeakConnection conn; private final OwnClient own; private final Recording recording; @@ -130,6 +154,7 @@ public final class ServerSession { this.identities = identities; this.listener = listener; this.conn = new TeamspeakConnection(settings, audio, new Events(), sounds, contacts); + this.chat = new ChatFeed(listener, () -> Objects.requireNonNullElse(conn.serverUniqueId(), "")); this.own = conn.ownClient(); this.recording = conn.recording(); } @@ -254,7 +279,7 @@ public final class ServerSession { lastTarget = new Target(address, port, nickname, password, channelPassword); lastChannelPath = channel == null ? "" : channel; title = address + ":" + port; - listener.onSystemMessage("Connecting to " + address + ":" + port + chat.system("Connecting to " + address + ":" + port + (channel == null || channel.isBlank() ? "" : " (channel \"" + channel + "\")") + " …"); setStatus("Loading identity…"); @@ -270,7 +295,7 @@ public final class ServerSession { return; } this.identityId = entry.getId(); - listener.onSystemMessage("Using identity \"" + entry.getName() + "\"."); + chat.system("Using identity \"" + entry.getName() + "\"."); conn.connect(address, port, nicknameFor(nickname, entry), entry.getPhoneticNickname(), password, entry.getIdentity(), channel, channelPassword); }, "identity-resolve").start(); @@ -619,17 +644,17 @@ public final class ServerSession { if (dir != null) Files.createDirectories(dir); rec = recording.start(mode, file); } catch (IOException | RuntimeException e) { - listener.onSystemMessage("Failed to start recording: " + e.getMessage()); + chat.system("Failed to start recording: " + e.getMessage()); return; } boolean multitrack = mode == VoiceRecorder.Mode.MULTITRACK; - listener.onSystemMessage((multitrack ? "Started multitrack recording: " : "Started recording: ") + file); + chat.system((multitrack ? "Started multitrack recording: " : "Started recording: ") + file); rec.whenDone().whenComplete((files, error) -> { if (error != null) { Throwable cause = error.getCause() != null ? error.getCause() : error; - listener.onSystemMessage("Recording failed: " + cause.getMessage()); + chat.system("Recording failed: " + cause.getMessage()); } else { - listener.onSystemMessage((multitrack ? "Stopped multitrack recording: " : "Stopped recording: ") + chat.system((multitrack ? "Stopped multitrack recording: " : "Stopped recording: ") + files.stream().map(Path::toString).collect(Collectors.joining(", "))); } listener.onSessionChanged(); @@ -644,53 +669,45 @@ public final class ServerSession { // ---- chat ---- - /** - * Sends a chat message and reports it back through {@link Listener#onOwnChat}. - * - * @param clientId the recipient of a private message; ignored otherwise - */ - public void sendChat(ChatScope scope, int clientId, String text) { + /** Sends a chat message, which then shows in the conversation like any other. */ + public void sendChat(ChatKey key, String text) { if (!conn.isConnected()) { - listener.onSystemMessage("Not connected."); + chat.system("Not connected."); return; } - switch (scope) { - case SERVER -> { - conn.sendServerMessage(text); - listener.onOwnChat(scope, 0, "", text); - } - case PRIVATE -> { - conn.sendPrivateMessage(clientId, text); - listener.onOwnChat(scope, clientId, peerName(clientId), text); - } - default -> { - conn.sendChannelMessage(text); - listener.onOwnChat(scope, 0, "", text); - } + switch (key.scope()) { + case SERVER -> conn.sendServerMessage(text); + case CHANNEL -> conn.sendChannelMessage(text); + case PRIVATE -> conn.sendPrivateMessage(key.clientId(), text); } + ClientEntry self = own.entry(); + String selfName = self != null ? self.nickname : settings.nickname.get(); + String peerName = key.isPrivate() ? peerName(key.clientId()) : ""; + chat.sent(key.scope(), key.clientId(), peerName, selfClientId(), selfUniqueId(), selfName, text); + if (key.isPrivate()) listener.onPrivateMessageSent(key.clientId(), text); } /** * Shares a file in a chat as TeamSpeak 6 does: stores it in this user's myTeamSpeak * cloud storage, then sends the message pointing to it. Runs in the background; a failure - * is reported through {@link Listener#onSystemMessage}. + * is told in the chat. * * @param data read and closed in the background */ - public void sendAttachment(ChatScope scope, int clientId, ChatAttachments attachments, + public void sendAttachment(ChatKey key, ChatAttachments attachments, InputStream data, long size, String fileName) { String room = conn.serverUniqueId(); if (!conn.isConnected() || room == null) { closeQuietly(data); - listener.onSystemMessage("Not connected."); + chat.system("Not connected."); return; } Thread t = new Thread(() -> { try (InputStream in = data) { ChatAttachment attachment = attachments.upload(in, size, fileName, room); - sendChat(scope, clientId, attachment.toMessage()); + sendChat(key, attachment.toMessage()); } catch (IOException | MyTsException e) { - listener.onSystemMessage("Could not share " + fileName + ": " + e.getMessage()); + chat.system("Could not share " + fileName + ": " + e.getMessage()); } }, "ts3-attachment-upload"); t.setDaemon(true); @@ -709,7 +726,7 @@ public final class ServerSession { return c != null ? conn.contacts().displayName(c) : "Client " + clientId; } - /** Hands {@link Listener#onPrivateChatHistory} what was said with a client before. */ + /** Loads what was said with a client before, into their private chat through {@link ChatSink#setHistory}. */ public void loadPrivateChatHistory(int clientId, String uniqueId) { conn.loadPrivateChatHistory(clientId, uniqueId); } @@ -839,12 +856,11 @@ public final class ServerSession { private void setStatus(String text) { status = text; - listener.onStatus(text); listener.onSessionChanged(); } private void reportError(String message) { - listener.onSystemMessage("Error: " + message); + chat.system("Error: " + message); listener.onError(message); setStatus(message); } @@ -855,8 +871,8 @@ public final class ServerSession { Target target = lastTarget; if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return; Replies.handle(conn.privilegeKeys().use(link.token), Runnable::run, - () -> listener.onSystemMessage("Privilege key used."), - failure -> listener.onSystemMessage("Could not use the privilege key: " + failure.getMessage())); + () -> chat.system("Privilege key used."), + failure -> chat.system("Could not use the privilege key: " + failure.getMessage())); } private void checkServerIcon() { @@ -881,7 +897,7 @@ public final class ServerSession { connecting = false; reconnects.connected(); listener.onConnected(); - listener.onSystemMessage("Connected."); + chat.system("Connected."); listener.onSessionChanged(); checkServerIcon(); useConnectToken(); @@ -895,8 +911,9 @@ public final class ServerSession { whisperTargets = null; serverIconId = -1; conn.getModel().clear(); + chat.disconnected(); listener.onDisconnected(reason); - listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason)); + chat.system("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason)); reconnects.disconnected(conn.wasDropped(), conn.getConnectErrorId()); listener.onSessionChanged(); } @@ -913,6 +930,10 @@ public final class ServerSession { } checkServerIcon(); updateWhisperTargets(); + if (conn.isConnected()) { + ChannelNode here = currentChannel(); + chat.names(Objects.requireNonNullElse(name, ""), here == null ? "" : here.name); + } listener.onModelChanged(); } @@ -930,17 +951,18 @@ public final class ServerSession { @Override public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { String name = conn.contacts().store().displayName(fromUniqueId, fromName); - listener.onChat(scope, fromClientId, fromUniqueId, name, message); + chat.received(scope, fromClientId, fromUniqueId, name, message); + if (scope == ChatScope.PRIVATE) listener.onPrivateMessage(fromClientId, name, message); } @Override public void onChatHistory(ChatScope scope, List htmlEntries) { - listener.onChatHistory(scope, htmlEntries); + chat.history(ChatKey.of(scope, 0), "", htmlEntries); } @Override public void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { - listener.onPrivateChatHistory(clientId, nickname, htmlEntries); + chat.history(ChatKey.privateWith(clientId), nickname, htmlEntries); } @Override @@ -955,18 +977,18 @@ public final class ServerSession { @Override public void onPoke(String fromName, String message) { - listener.onSystemMessage("You were poked by " + fromName + ": " + message); + chat.system("You were poked by " + fromName + ": " + message); listener.onPoke(fromName, message); } @Override public void onServerLog(String message) { - listener.onServerLog(message); + chat.serverLog(message); } @Override public void onServerLogHtml(String html) { - listener.onServerLogHtml(html); + chat.serverLogHtml(html); } @Override diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ChatFeedTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ChatFeedTest.java new file mode 100644 index 0000000..3799038 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ChatFeedTest.java @@ -0,0 +1,78 @@ +package eu.lixko.ts3j.client.session; + +import eu.lixko.ts3j.client.chat.ChatKey; +import eu.lixko.ts3j.client.chat.ChatScope; +import eu.lixko.ts3j.client.chat.ChatSink; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChatFeedTest { + + private final List calls = new ArrayList<>(); + private final List lines = new ArrayList<>(); + private final ChatFeed feed = new ChatFeed(new ChatSink() { + @Override + public void append(ChatKey key, String title, String html) { + calls.add("append " + key + " " + title); + lines.add(html); + } + + @Override + public void setHistory(ChatKey key, String title, List html) { + calls.add("history " + key + " " + title + " " + html.size()); + } + + @Override + public void rename(ChatKey key, String name) { + calls.add("rename " + key + " " + name); + } + + @Override + public void closePrivateChats() { + calls.add("close"); + } + }, () -> "room"); + + @Test + void aPrivateMessageGoesToTheChatWithItsSender() { + feed.received(ChatScope.PRIVATE, 7, "peerUid", "Alice", "hi"); + assertEquals(List.of("append " + ChatKey.privateWith(7) + " Alice"), calls); + assertTrue(lines.get(0).contains("Alice"), lines.get(0)); + } + + @Test + void ourOwnMessageCarriesOurNameAndIdentity() { + feed.sent(ChatScope.PRIVATE, 7, "Alice", 3, "selfUid", "Me", "hello"); + assertEquals(List.of("append " + ChatKey.privateWith(7) + " Alice"), calls); + assertTrue(lines.get(0).contains("Me (you)"), lines.get(0)); + assertTrue(lines.get(0).contains("selfUid"), lines.get(0)); + } + + @Test + void historyLeavesOutEntriesThatShowNothing() { + feed.history(ChatKey.CHANNEL, "", List.of("

one

", " ", "

two

")); + assertEquals(List.of("history " + ChatKey.CHANNEL + " 2"), calls); + } + + @Test + void conversationsAreRenamedOnlyWhenTheNameChanges() { + feed.names("Server A", "Lobby"); + feed.names("Server A", "Lobby"); + feed.names("Server A", "AFK"); + assertEquals(List.of("rename " + ChatKey.SERVER + " Server A", "rename " + ChatKey.CHANNEL + " Lobby", + "rename " + ChatKey.CHANNEL + " AFK"), calls); + } + + @Test + void leavingClosesPrivateChatsAndForgetsTheNames() { + feed.names("Server A", "Lobby"); + calls.clear(); + feed.disconnected(); + assertEquals(List.of("close", "rename " + ChatKey.SERVER + " ", "rename " + ChatKey.CHANNEL + " "), calls); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java index b86337d..b2d28d0 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java @@ -1,6 +1,6 @@ package eu.lixko.ts3j.client.ui; -import eu.lixko.ts3j.client.chat.ChatScope; +import eu.lixko.ts3j.client.chat.ChatKey; import eu.lixko.ts3j.client.myts.ChatAttachment; import eu.lixko.ts3j.client.myts.ChatAttachments; import eu.lixko.ts3j.client.myts.MyTsException; @@ -45,7 +45,7 @@ final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { } @Override - public void choose(ChatScope scope, int clientId) { + public void choose(ChatKey key) { if (!signedIn()) return; JFileChooser chooser = new JFileChooser(lastDirectory); chooser.setMultiSelectionEnabled(true); @@ -53,11 +53,11 @@ final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { if (chooser.showOpenDialog(host) != JFileChooser.APPROVE_OPTION) return; File[] files = chooser.getSelectedFiles(); if (files.length > 0) lastDirectory = files[0].getParentFile(); - share(scope, clientId, List.of(files)); + share(key, List.of(files)); } @Override - public void share(ChatScope scope, int clientId, List files) { + public void share(ChatKey key, List files) { if (!signedIn()) return; for (File file : files) { if (!file.isFile()) continue; @@ -66,7 +66,7 @@ final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { continue; } try { - session.sendAttachment(scope, clientId, host.attachments(), + session.sendAttachment(key, host.attachments(), new FileInputStream(file), file.length(), file.getName()); } catch (IOException e) { chat.appendSystem("Could not share " + file.getName() + ": " + e.getMessage()); @@ -75,7 +75,7 @@ final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { } @Override - public void share(ChatScope scope, int clientId, BufferedImage image) { + public void share(ChatKey key, BufferedImage image) { if (!signedIn()) return; ByteArrayOutputStream png = new ByteArrayOutputStream(); try { @@ -84,7 +84,7 @@ final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { chat.appendSystem("Could not share the picture: " + e.getMessage()); return; } - session.sendAttachment(scope, clientId, host.attachments(), + session.sendAttachment(key, host.attachments(), new ByteArrayInputStream(png.toByteArray()), png.size(), PASTED_NAME); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java index 69f69d4..a7de698 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java @@ -2,7 +2,7 @@ package eu.lixko.ts3j.client.ui; import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; -import eu.lixko.ts3j.client.chat.ChatScope; +import eu.lixko.ts3j.client.chat.ChatKey; import eu.lixko.ts3j.client.config.Settings; import eu.lixko.ts3j.client.myts.ChatAttachment; import eu.lixko.ts3j.client.net.PictureDownloads; @@ -53,7 +53,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.function.Supplier; /** * Chat area with one tab per conversation (server, current channel and one per @@ -64,8 +63,7 @@ import java.util.function.Supplier; public final class ChatPanel extends JPanel { public interface SendHandler { - /** {@code clientId} is only meaningful for {@link ChatScope#PRIVATE}. */ - void send(ChatScope scope, int clientId, String text); + void send(ChatKey key, String text); } /** Invoked when a client or channel link in the log is clicked. */ @@ -81,11 +79,11 @@ public final class ChatPanel extends JPanel { /** Files shared in the chats, which the host sends, fetches and shows. */ public interface AttachmentHandler { /** Asks which files to share in the conversation. */ - void choose(ChatScope scope, int clientId); + void choose(ChatKey key); - void share(ChatScope scope, int clientId, List files); + void share(ChatKey key, List files); - void share(ChatScope scope, int clientId, BufferedImage image); + void share(ChatKey key, BufferedImage image); /** * A shared file was clicked. @@ -108,8 +106,8 @@ public final class ChatPanel extends JPanel { private static final String NO_SERVER = "Server"; private static final String NO_CHANNEL = "Channel"; - private final Tab serverTab = new Tab(ChatScope.SERVER, 0, NO_SERVER, Icons.server()); - private final Tab channelTab = new Tab(ChatScope.CHANNEL, 0, NO_CHANNEL, Icons.channelChat()); + private final Tab serverTab = new Tab(ChatKey.SERVER, NO_SERVER, Icons.server()); + private final Tab channelTab = new Tab(ChatKey.CHANNEL, NO_CHANNEL, Icons.channelChat()); /** Private chats keyed by the peer's client id. */ private final Map privateTabs = new LinkedHashMap<>(); /** Static-content tabs (e.g. a moved-out description), keyed by caller-chosen id. */ @@ -137,8 +135,6 @@ public final class ChatPanel extends JPanel { private final TextZoom zoom; private final PictureDownloads downloads; private final DescriptionPictures pictures; - /** The server's unique identifier, which shared files are kept under; null while unknown. */ - private final Supplier room; private final JButton attach = new JButton(Icons.of("UPLOAD")); private boolean inputEnabled; private boolean sharingAvailable; @@ -146,12 +142,11 @@ public final class ChatPanel extends JPanel { for (Tab t : allTabs()) t.picturesChanged(); }); - public ChatPanel(TextZoom zoom, Settings settings, PictureDownloads downloads, Supplier room) { + public ChatPanel(TextZoom zoom, Settings settings, PictureDownloads downloads) { super(new BorderLayout()); this.zoom = zoom; this.downloads = downloads; this.pictures = new DescriptionPictures(downloads, settings); - this.room = room; tabs.setFont(Theme.uiFont()); tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); @@ -195,8 +190,8 @@ public final class ChatPanel extends JPanel { attach.setFocusable(false); attach.addActionListener(e -> { Tab tab = selectedTab(); - if (attachmentHandler != null && tab != null && tab.scope != null) { - attachmentHandler.choose(tab.scope, tab.clientId); + if (attachmentHandler != null && tab != null && tab.key != null) { + attachmentHandler.choose(tab.key); } }); @@ -249,16 +244,6 @@ public final class ChatPanel extends JPanel { }); } - /** Names the server tab after the server we are on; blank falls back to "Server". */ - public void setServerName(String name) { - edt(() -> serverTab.setTitle(name == null || name.isBlank() ? NO_SERVER : name)); - } - - /** Names the channel tab after the channel we are in; blank falls back to "Channel". */ - public void setChannelName(String name) { - edt(() -> channelTab.setTitle(name == null || name.isBlank() ? NO_CHANNEL : name)); - } - public void setInputEnabled(boolean enabled) { input.setEnabled(enabled); inputEnabled = enabled; @@ -276,16 +261,16 @@ public final class ChatPanel extends JPanel { @Override public boolean files(List files) { Tab tab = selectedTab(); - if (attachmentHandler == null || tab == null || tab.scope == null) return false; - attachmentHandler.share(tab.scope, tab.clientId, files); + if (attachmentHandler == null || tab == null || tab.key == null) return false; + attachmentHandler.share(tab.key, files); return true; } @Override public boolean image(BufferedImage image) { Tab tab = selectedTab(); - if (attachmentHandler == null || tab == null || tab.scope == null) return false; - attachmentHandler.share(tab.scope, tab.clientId, image); + if (attachmentHandler == null || tab == null || tab.key == null) return false; + attachmentHandler.share(tab.key, image); return true; } }); @@ -293,28 +278,32 @@ public final class ChatPanel extends JPanel { /** Opens (or focuses) the private chat with {@code clientId}. */ public void openPrivateChat(int clientId, String nickname) { - openPrivateChat(clientId, "", nickname); - } - - /** Opens (or focuses) the private chat with {@code clientId}. */ - public void openPrivateChat(int clientId, String uniqueId, String nickname) { edt(() -> { - Tab tab = privateTab(clientId, uniqueId, nickname); + Tab tab = privateTab(clientId, nickname); tabs.setSelectedComponent(tab.scroll); input.requestFocusInWindow(); }); } - public void setServerHistory(List htmlEntries) { - edt(() -> serverTab.setHistory(htmlEntries)); + /** Adds a line to a conversation, opening a private one titled {@code title} if needed. */ + public void append(ChatKey key, String title, String html) { + edt(() -> tab(key, title).append(html)); } - public void setChannelHistory(List htmlEntries) { - edt(() -> channelTab.setHistory(htmlEntries)); + public void setHistory(ChatKey key, String title, List html) { + edt(() -> tab(key, title).setHistory(html)); } - public void setPrivateHistory(int clientId, String nickname, List htmlEntries) { - edt(() -> privateTab(clientId, "", nickname).setHistory(htmlEntries)); + /** Names the server or channel tab; blank falls back to "Server" or "Channel". */ + public void rename(ChatKey key, String name) { + edt(() -> { + switch (key.scope()) { + case SERVER -> serverTab.setTitle(name.isBlank() ? NO_SERVER : name); + case CHANNEL -> channelTab.setTitle(name.isBlank() ? NO_CHANNEL : name); + case PRIVATE -> { + } + } + }); } /** Drops every private chat tab, e.g. after disconnecting. */ @@ -363,8 +352,8 @@ public final class ChatPanel extends JPanel { String text = input.getText().trim(); if (text.isEmpty() || sendHandler == null) return; Tab tab = selectedTab(); - if (tab == null || tab.scope == null) return; - sendHandler.send(tab.scope, tab.clientId, text); + if (tab == null || tab.key == null) return; + sendHandler.send(tab.key, text); input.setText(""); } @@ -375,58 +364,20 @@ public final class ChatPanel extends JPanel { edt(() -> serverTab.append(ChatHtml.system(text))); } - /** - * Server-side events (client joins/leaves/moves, group changes, channel edits, …). - * These lines name clients and channels with TeamSpeak's own links, which stay - * clickable here — everything else in them is literal text. - */ - public void appendServerLog(String text) { - edt(() -> serverTab.append(ChatHtml.serverLog(text))); - } - - public void appendServerLogHtml(String html) { - edt(() -> serverTab.append(ChatHtml.logEntry(html))); - } - - public void appendServerMessage(int fromId, String from, String text) { - appendServerMessage(fromId, "", from, text); - } - - public void appendServerMessage(int fromId, String uniqueId, String from, String text) { - edt(() -> serverTab.appendMessage(fromId, uniqueId, from, text)); - } - - public void appendChannelMessage(int fromId, String from, String text) { - appendChannelMessage(fromId, "", from, text); - } - - public void appendChannelMessage(int fromId, String uniqueId, String from, String text) { - edt(() -> channelTab.appendMessage(fromId, uniqueId, from, text)); - } - - /** Appends to the private chat with {@code peerId}, creating the tab if needed. */ - public void appendPrivateMessage(int peerId, String peerName, int fromId, String from, String text) { - appendPrivateMessage(peerId, "", peerName, fromId, "", from, text); - } - - /** Appends to the private chat with {@code peerId}, creating the tab if needed. */ - public void appendPrivateMessage(int peerId, String peerUniqueId, String peerName, - int fromId, String fromUniqueId, String from, String text) { - edt(() -> privateTab(peerId, peerUniqueId, peerName).appendMessage(fromId, fromUniqueId, from, text)); + private Tab tab(ChatKey key, String title) { + return switch (key.scope()) { + case SERVER -> serverTab; + case CHANNEL -> channelTab; + case PRIVATE -> privateTab(key.clientId(), title); + }; } private Tab privateTab(int clientId, String nickname) { - return privateTab(clientId, "", nickname); - } - - private Tab privateTab(int clientId, String uniqueId, String nickname) { Tab tab = privateTabs.get(clientId); if (tab == null) { - tab = new Tab(ChatScope.PRIVATE, clientId, uniqueId, nickname, Icons.privateChat()); + tab = new Tab(ChatKey.privateWith(clientId), nickname, Icons.privateChat()); privateTabs.put(clientId, tab); addTab(tab, true); - } else { - tab.setClientUniqueId(uniqueId); } return tab; } @@ -442,7 +393,7 @@ public final class ChatPanel extends JPanel { noteTabs.remove(tab.noteKey); if (tab.onClose != null) tab.onClose.run(); } else { - privateTabs.remove(tab.clientId); + privateTabs.remove(tab.key.clientId()); } tabs.remove(tab.scroll); } @@ -494,11 +445,6 @@ public final class ChatPanel extends JPanel { return all; } - private String room() { - String id = room.get(); - return id == null ? "" : id; - } - private void edt(Runnable r) { if (SwingUtilities.isEventDispatchThread()) r.run(); else SwingUtilities.invokeLater(r); @@ -507,9 +453,8 @@ public final class ChatPanel extends JPanel { /** One conversation: its HTML log, its scroll pane and the tab-strip header. */ private final class Tab { - final ChatScope scope; - final int clientId; - private String clientUniqueId; + /** The conversation; null for a static-content tab. */ + final ChatKey key; private String title; final JEditorPane log = HtmlStyles.pane("font-family:sans-serif; font-size:11px; margin:" + HtmlStyles.px(4) + " " + HtmlStyles.px(6) + ";"); @@ -528,24 +473,17 @@ public final class ChatPanel extends JPanel { private String pictureState = ""; private int renderedPictureWidth; - Tab(ChatScope scope, int clientId, String title, Icon icon) { - this(scope, clientId, "", title, icon, null, null); + Tab(ChatKey key, String title, Icon icon) { + this(key, title, icon, null, null); } - Tab(ChatScope scope, int clientId, String clientUniqueId, String title, Icon icon) { - this(scope, clientId, clientUniqueId, title, icon, null, null); - } - - /** A static-content tab: no send scope, closing it runs {@code onClose}. */ + /** A static-content tab: nothing to send to, closing it runs {@code onClose}. */ Tab(String noteKey, Icon icon, String title, Runnable onClose) { - this(null, 0, "", title, icon, noteKey, onClose); + this(null, title, icon, noteKey, onClose); } - private Tab(ChatScope scope, int clientId, String clientUniqueId, String title, - Icon icon, String noteKey, Runnable onClose) { - this.scope = scope; - this.clientId = clientId; - this.clientUniqueId = clientUniqueId == null ? "" : clientUniqueId; + private Tab(ChatKey key, String title, Icon icon, String noteKey, Runnable onClose) { + this.key = key; this.title = title; this.icon = icon; this.noteKey = noteKey; @@ -573,10 +511,6 @@ public final class ChatPanel extends JPanel { return element != null && element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.IMG; } - void setClientUniqueId(String uniqueId) { - if (uniqueId != null && !uniqueId.isBlank()) clientUniqueId = uniqueId; - } - private void onLink(String href, boolean picture) { if (href == null) return; if (ChatAttachment.isHref(href)) { @@ -652,19 +586,10 @@ public final class ChatPanel extends JPanel { titleLabel.setForeground(unread ? Theme.accent() : null); } - void appendMessage(int fromId, String fromUniqueId, String from, String text) { - append(ChatHtml.message(fromId, - fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text, - room())); - } - - void setHistory(List htmlEntries) { + void setHistory(List html) { entries.clear(); pictureUrls.clear(); - if (htmlEntries != null) { - String room = room(); - for (String entry : htmlEntries) add(ChatHtml.logEntry(entry, room)); - } + for (String entry : html) add(entry); render(); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java index 2fffb4d..2a1c042 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java @@ -1,6 +1,6 @@ package eu.lixko.ts3j.client.ui; -import eu.lixko.ts3j.client.chat.ChatScope; +import eu.lixko.ts3j.client.chat.ChatKey; import eu.lixko.ts3j.client.config.Settings; import eu.lixko.ts3j.client.notify.desktop.DesktopNotifications; import eu.lixko.ts3j.client.notify.desktop.DesktopNotifications.Notice; @@ -146,14 +146,14 @@ final class DesktopNotifier { frame.selectTab(tab); if (clientId != null) { var client = tab.session().model().getClient(clientId); - if (client != null) tab.chat().openPrivateChat(clientId, client.uniqueId, client.nickname); + if (client != null) tab.chat().openPrivateChat(clientId, client.nickname); } }); } private void reply(ServerTab tab, int clientId, String text) { SwingUtilities.invokeLater(() -> { - if (tab.session().isConnected()) tab.session().sendChat(ChatScope.PRIVATE, clientId, text); + if (tab.session().isConnected()) tab.session().sendChat(ChatKey.privateWith(clientId), text); }); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java index e047f05..747adc7 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -67,12 +67,12 @@ final class ServerTab { // up front), and the session must exist before the tree/chat panels and the other // tab helpers that read from it — so wiring finishes with an explicit attach() once // everything is built. Nothing fires callbacks before then. - ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this, settings); + ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this); this.session = new ServerSession(settings, identities, audio, sounds, contacts, events); session.setAutoReconnect(true); session.setMyTeamSpeakLogin(host.myTeamSpeakLogin()); this.groupIcons = new GroupIcons(session.icons()); - this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, session::serverUniqueId); + this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures); this.treeActions = new ServerTabTreeActions(host, this, session, chatPanel, infoPanel, groupIcons); this.treePanel = new ServerTreePanel(session.model(), groupIcons, contacts, settings, treeActions); treeActions.attach(treePanel); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java index f583590..82b08eb 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java @@ -1,8 +1,6 @@ package eu.lixko.ts3j.client.ui; -import eu.lixko.ts3j.client.chat.ChatScope; -import eu.lixko.ts3j.client.config.Settings; -import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.chat.ChatKey; import eu.lixko.ts3j.client.session.ServerSession; import javax.swing.JOptionPane; @@ -22,7 +20,6 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { private final MainFrame host; private final ServerTab tab; - private final Settings settings; private final AtomicBoolean modelChangePending = new AtomicBoolean(); @@ -31,10 +28,9 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { private ChatPanel chatPanel; private ServerTabTreeActions treeActions; - ServerTabConnectionEvents(MainFrame host, ServerTab tab, Settings settings) { + ServerTabConnectionEvents(MainFrame host, ServerTab tab) { this.host = host; this.tab = tab; - this.settings = settings; } void attach(ServerSession session, ServerTreePanel treePanel, ChatPanel chatPanel, @@ -54,21 +50,23 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { } @Override - public void onSystemMessage(String text) { - SwingUtilities.invokeLater(() -> chatPanel.appendSystem(text)); + public void append(ChatKey key, String title, String html) { + chatPanel.append(key, title, html); } @Override - public void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text) { - String me = settings.nickname.get() + " (you)"; - int myId = session.selfClientId(); - SwingUtilities.invokeLater(() -> { - switch (scope) { - case SERVER -> chatPanel.appendServerMessage(myId, me, text); - case PRIVATE -> chatPanel.appendPrivateMessage(peerClientId, peerName, myId, me, text); - default -> chatPanel.appendChannelMessage(myId, me, text); - } - }); + public void setHistory(ChatKey key, String title, List html) { + chatPanel.setHistory(key, title, html); + } + + @Override + public void rename(ChatKey key, String name) { + chatPanel.rename(key, name); + } + + @Override + public void closePrivateChats() { + chatPanel.closePrivateChats(); } @Override @@ -79,11 +77,6 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { }); } - @Override - public void onStatus(String text) { - // Reaches the tab through onSessionChanged. - } - @Override public void onConnected() { SwingUtilities.invokeLater(() -> { @@ -99,10 +92,7 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { treePanel.showDisconnected(); treeActions.clearSelection(); chatPanel.setInputEnabled(false); - chatPanel.closePrivateChats(); chatPanel.closeNoteTabs(); - chatPanel.setServerName(null); - chatPanel.setChannelName(null); tab.serverWindowsChanged(false); host.tabDisconnected(tab); }); @@ -118,11 +108,6 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { treeActions.renderInfo(); treeActions.refreshGroupsDialog(); host.refreshHostButton(tab); - if (session.isConnected()) { - ChannelNode channel = session.currentChannel(); - chatPanel.setServerName(session.model().getServerName()); - chatPanel.setChannelName(channel == null ? null : channel.name); - } }); } @@ -145,31 +130,8 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { } @Override - public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { - SwingUtilities.invokeLater(() -> { - switch (scope) { - case PRIVATE -> { - chatPanel.appendPrivateMessage(fromClientId, fromUniqueId, fromName, - fromClientId, fromUniqueId, fromName, message); - host.notifier().privateMessage(tab, fromClientId, fromName, message); - } - case SERVER -> chatPanel.appendServerMessage(fromClientId, fromUniqueId, fromName, message); - default -> chatPanel.appendChannelMessage(fromClientId, fromUniqueId, fromName, message); - } - }); - } - - @Override - public void onChatHistory(ChatScope scope, List htmlEntries) { - SwingUtilities.invokeLater(() -> { - if (scope == ChatScope.SERVER) chatPanel.setServerHistory(htmlEntries); - else if (scope == ChatScope.CHANNEL) chatPanel.setChannelHistory(htmlEntries); - }); - } - - @Override - public void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { - SwingUtilities.invokeLater(() -> chatPanel.setPrivateHistory(clientId, nickname, htmlEntries)); + public void onPrivateMessage(int fromClientId, String fromName, String message) { + SwingUtilities.invokeLater(() -> host.notifier().privateMessage(tab, fromClientId, fromName, message)); } @Override @@ -182,17 +144,7 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { @Override public void onError(String message) { - // Reaches the chat through onSystemMessage and the tab through onSessionChanged. - } - - @Override - public void onServerLog(String message) { - SwingUtilities.invokeLater(() -> chatPanel.appendServerLog(message)); - } - - @Override - public void onServerLogHtml(String html) { - SwingUtilities.invokeLater(() -> chatPanel.appendServerLogHtml(html)); + // Reaches the chat as a line and the tab through onSessionChanged. } @Override diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java index 8b3ae01..aef744d 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java @@ -129,7 +129,7 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { @Override public void openPrivateChat(ClientEntry client) { - chatPanel.openPrivateChat(client.id, client.uniqueId, session.contacts().displayName(client)); + chatPanel.openPrivateChat(client.id, session.contacts().displayName(client)); session.loadPrivateChatHistory(client.id, client.uniqueId); }