Android app-wide stores out of SessionController; screens take only their parts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 20:55:08 +00:00
co-authored by Claude Opus 5.5
parent 78b66ef346
commit 382d76c3d8
27 changed files with 648 additions and 494 deletions
@@ -0,0 +1,33 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
/** What lives as long as the process, wired together once; each screen is handed only the parts it uses. */
class AppParts(context: Context) {
val settings: Settings = Settings.load()
val icons = IconTheme(context, settings)
val pictures = WebPictures(context.cacheDir, settings)
val swipe = SwipePrefs(context)
/** The reasons offered when adding a ban; shared by every server. */
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
private val bookmarkStore = Bookmarks.load()
private val identityStore = IdentityStore.load(settings)
private val contactStore = ContactStore.load()
val identities: IdentityManager = IdentityManager(context, identityStore, settings, bookmarkStore) { bookmarks.refresh() }
val bookmarks: BookmarkManager = BookmarkManager(context, icons, bookmarkStore, identities) { sessions.bookmarkEdited(it) }
val contacts: ContactManager = ContactManager(context, contactStore, settings)
val whisperLists: WhisperListManager = WhisperListManager()
val audio: AudioSetup = AudioSetup(context, settings)
val myTeamSpeak: MyTeamSpeakAccount = MyTeamSpeakAccount(context, pictures,
TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore), bookmarks, identities) { sessions.myTeamSpeakChanged() }
val sessions: SessionController = SessionController(context, settings, identityStore, identities, bookmarks, contacts, audio, myTeamSpeak)
}
@@ -0,0 +1,76 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.sound.SoundNotifier
import eu.lixko.ts3j.client.sound.SoundPack
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The devices and routing audio goes through, the sound packs, and the floating push-to-talk button. */
class AudioSetup internal constructor(private val context: Context, private val settings: Settings) {
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
settings.outputDevice.addListener { soundPlayer.setOutputDevice(it) }
}
/** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) {
routePrefs.save(route)
_route.value = route
audio.setRoute(route)
}
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
private companion object {
const val OVERLAY_ENABLED = "enabled"
}
}
@@ -0,0 +1,99 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.os.Handler
import android.os.Looper
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The bookmarks, as the connect page lists them and home-screen shortcuts lead to them. */
class BookmarkManager internal constructor(
context: Context,
icons: IconTheme,
private val store: Bookmarks,
private val identities: IdentityManager,
/** A saved bookmark changed, for the servers connected with it. */
private val onEdited: (Bookmark) -> Unit,
) {
private val shortcuts = BookmarkShortcuts(context, icons)
private val main = Handler(Looper.getMainLooper())
private val _all = MutableStateFlow(store.all().toList())
val all: StateFlow<List<Bookmark>> = _all
/** Picks up bookmarks added or changed elsewhere, such as by an import. */
fun refresh() {
_all.value = store.all().toList()
}
fun find(id: String): Bookmark? = store.find(id)
internal fun startupBookmarks(): List<Bookmark> = store.startupBookmarks()
internal fun add(bookmark: Bookmark) {
store.add(bookmark)
save()
}
/** A bookmark to [address] as typed into the connect form, not yet saved. */
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark {
val (host, port) = SessionController.parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != identities.nicknameFor(identityId) }.orEmpty()
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
}
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */
fun save(index: Int, edited: Bookmark) {
val all = store.all()
if (index !in all.indices) {
store.add(edited)
} else {
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
all[index] = edited
}
save()
onEdited(edited)
}
fun remove(bookmark: Bookmark) {
val index = store.all().indexOf(bookmark)
if (index < 0) return
store.remove(index)
save()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
main.post {
val all = store.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) save()
}
}
private fun save() {
store.save()
refresh()
shortcuts.sync(_all.value)
}
val canPinShortcuts: Boolean get() = shortcuts.supported
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
fun pinShortcut(bookmark: Bookmark) {
// A bookmark not saved since ids came in has a new one on every load until it is.
store.save()
shortcuts.pin(bookmark)
}
}
@@ -39,6 +39,8 @@ import kotlin.math.roundToInt
class ConnectionService : LifecycleService() { class ConnectionService : LifecycleService() {
private lateinit var sessions: SessionController private lateinit var sessions: SessionController
private lateinit var icons: IconTheme
private lateinit var audio: AudioSetup
private lateinit var wifiLock: WifiManager.WifiLock private lateinit var wifiLock: WifiManager.WifiLock
private lateinit var wifiBackgroundLock: WifiManager.WifiLock private lateinit var wifiBackgroundLock: WifiManager.WifiLock
private lateinit var wakeLock: PowerManager.WakeLock private lateinit var wakeLock: PowerManager.WakeLock
@@ -48,7 +50,10 @@ class ConnectionService : LifecycleService() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
sessions = (application as Ts3Application).sessions val parts = (application as Ts3Application).parts
sessions = parts.sessions
icons = parts.icons
audio = parts.audio
getSystemService(NotificationManager::class.java).createNotificationChannel( getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW) NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
) )
@@ -89,15 +94,15 @@ class ConnectionService : LifecycleService() {
} }
} }
lifecycleScope.launch { lifecycleScope.launch {
sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } } icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
} }
overlay = PttOverlay(this, sessions.icons, sessions::setPushToTalk) overlay = PttOverlay(this, icons, sessions::setPushToTalk)
lifecycleScope.launch { lifecycleScope.launch {
val owner = sessions.micOwner.flatMapLatest { server -> val owner = sessions.micOwner.flatMapLatest { server ->
server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null) server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null)
} }
combine(owner, sessions.onScreen, sessions.pttOverlay) { held, onScreen, enabled -> combine(owner, sessions.onScreen, audio.pttOverlay) { held, onScreen, enabled ->
val (state, tree) = held ?: return@combine null val (state, tree) = held ?: return@combine null
val wanted = enabled && !onScreen && state.connected && state.micActive && val wanted = enabled && !onScreen && state.connected && state.micActive &&
state.inputMode == Settings.InputMode.PUSH_TO_TALK state.inputMode == Settings.InputMode.PUSH_TO_TALK
@@ -203,7 +208,7 @@ class ConnectionService : LifecycleService() {
private fun statusIcon(self: SelfState): Icon { private fun statusIcon(self: SelfState): Icon {
val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt() val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt()
val bitmap = sessions.icons.renderMaterial(key, size, Color.WHITE) val bitmap = icons.renderMaterial(key, size, Color.WHITE)
?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
return Icon.createWithBitmap(bitmap) return Icon.createWithBitmap(bitmap)
} }
@@ -212,7 +217,7 @@ class ConnectionService : LifecycleService() {
private fun largeIcon(self: SelfState): Icon? { private fun largeIcon(self: SelfState): Icon? {
val key = self.iconKey() ?: return null val key = self.iconKey() ?: return null
val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt() val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt()
return sessions.icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500)) return icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500))
?.let(Icon::createWithBitmap) ?.let(Icon::createWithBitmap)
} }
@@ -0,0 +1,53 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
/** The contacts: friends, blocked clients and how each is treated. */
class ContactManager internal constructor(
private val context: Context,
internal val store: ContactStore,
private val settings: Settings,
) {
/** Copies of the contacts, as the store's own entries change in place. */
private val _all = MutableStateFlow(copies())
val all: StateFlow<List<Contact>> = _all
init {
// Mutations report on whichever thread made them, a connection thread included.
store.addListener { _all.value = copies() }
}
private fun copies(): List<Contact> = store.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [save]. */
fun find(uniqueId: String): Contact? = store.find(uniqueId)?.copy()
fun save(contact: Contact) = store.put(contact)
fun remove(uniqueId: String) = store.remove(uniqueId)
/** What a new contact starts with; changed in place, then [saveDefaults]. */
val defaults: ContactDefaults get() = settings.contactDefaults
fun saveDefaults() = settings.save()
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun import(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else store.merge(found)
}
}
@@ -126,6 +126,9 @@ class IdentityManager(
fun nicknameOf(id: String): String = fun nicknameOf(id: String): String =
(store.byId(id) ?: store.byId(settings.defaultIdentityId.get()))?.nickname.orEmpty() (store.byId(id) ?: store.byId(settings.defaultIdentityId.get()))?.nickname.orEmpty()
/** The nickname a connect with [id] goes by: the identity's own, else the global one. */
fun nicknameFor(id: String): String = nicknameOf(id).ifBlank { settings.nickname.get() }
fun setDefault(id: String) { fun setDefault(id: String) {
settings.defaultIdentityId.set(id) settings.defaultIdentityId.set(id)
settings.save() settings.save()
@@ -18,7 +18,7 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent)) if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent))
setContent { setContent {
Ts3Theme { App(sessions) } Ts3Theme { App((application as Ts3Application).parts) }
} }
} }
@@ -0,0 +1,110 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/**
* The myTeamSpeak account the app stays signed in to: what it syncs, and the files shared
* in chat, which are kept in its cloud storage. Its reads block, so they run on [Dispatchers.IO].
*/
class MyTeamSpeakAccount internal constructor(
private val context: Context,
private val pictures: WebPictures,
private val importer: TeamSpeakImporter,
private val bookmarks: BookmarkManager,
private val identities: IdentityManager,
/** Signed in or out, for the servers to pass on. */
private val onSignInChanged: () -> Unit,
) {
val login: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val _signedIn = MutableStateFlow(login.isSignedIn)
val signedIn: StateFlow<Boolean> = _signedIn
/** Files shared in chat. */
internal val attachments = ChatAttachments(login).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signIn(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { login.signIn(email, password) }
.also {
_signedIn.value = true
onSignInChanged()
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetch(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { login.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_signedIn.value = login.isSignedIn
}
suspend fun signOut() {
login.signOut()
_signedIn.value = false
onSignInChanged()
withContext(Dispatchers.IO) { attachments.close() }
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use; contacts announce themselves. */
suspend fun import(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
bookmarks.refresh()
identities.refresh()
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
}
@@ -7,46 +7,23 @@ import android.content.pm.PackageManager
import android.net.Uri import android.net.Uri
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Setting import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.net.HostButton import eu.lixko.ts3j.client.net.HostButton
import eu.lixko.ts3j.client.net.ChannelFiles import eu.lixko.ts3j.client.net.ChannelFiles
import eu.lixko.ts3j.client.session.SelfState import eu.lixko.ts3j.client.session.SelfState
import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.session.Sessions import eu.lixko.ts3j.client.session.Sessions
import eu.lixko.ts3j.client.sound.SoundNotifier
import eu.lixko.ts3j.client.sound.SoundPack
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import eu.lixko.ts3j.client.text.BBCode import eu.lixko.ts3j.client.text.BBCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
/** What the app shows of a connection and the local client on it. */ /** What the app shows of a connection and the local client on it. */
@@ -75,9 +52,6 @@ data class SessionState(
val whisperControls: Boolean = false, val whisperControls: Boolean = false,
) )
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/** Something that happened once, for the UI to tell the user about. */ /** Something that happened once, for the UI to tell the user about. */
sealed interface SessionEvent { sealed interface SessionEvent {
data class Poke(val from: String, val message: String) : SessionEvent data class Poke(val from: String, val message: String) : SessionEvent
@@ -91,26 +65,24 @@ sealed interface SessionEvent {
* keeps the process in the foreground while any is connected. Only one server captures with * keeps the process in the foreground while any is connected. Only one server captures with
* the microphone at a time; [Sessions] hands it over. * the microphone at a time; [Sessions] hands it over.
*/ */
class SessionController(private val context: Context) { class SessionController internal constructor(
private val context: Context,
val settings: Settings = Settings.load() internal val settings: Settings,
val icons = IconTheme(context, settings) internal val identityStore: IdentityStore,
private val shortcuts = BookmarkShortcuts(context, icons) private val identities: IdentityManager,
val pictures = WebPictures(context.cacheDir, settings) private val bookmarks: BookmarkManager,
private val contacts: ContactManager,
private val audioSetup: AudioSetup,
private val myTeamSpeak: MyTeamSpeakAccount,
) {
internal val cacheDir: File get() = context.cacheDir internal val cacheDir: File get() = context.cacheDir
internal fun fileTransfers(files: ChannelFiles) = FileTransfers(context, files) internal fun fileTransfers(files: ChannelFiles) = FileTransfers(context, files)
private val bookmarkStore = Bookmarks.load() internal val audio get() = audioSetup.audio
internal val identityStore = IdentityStore.load(settings) internal val sounds get() = audioSetup.sounds
val identities = IdentityManager(context, identityStore, settings, bookmarkStore) {
_bookmarks.value = bookmarkStore.all().toList()
}
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
internal val notifier = MessageNotifier(context) internal val notifier = MessageNotifier(context)
internal val contactStore = ContactStore.load() internal val contactStore get() = contacts.store
/** The reasons offered when adding a ban; shared by every server. */ internal val attachments get() = myTeamSpeak.attachments
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() } internal suspend fun openShared(uri: Uri) = myTeamSpeak.openShared(uri)
internal val network = NetworkFollower(context) internal val network = NetworkFollower(context)
private val main = Handler(Looper.getMainLooper()) private val main = Handler(Looper.getMainLooper())
@@ -134,13 +106,6 @@ class SessionController(private val context: Context) {
private val _lastEnd = MutableStateFlow<String?>(null) private val _lastEnd = MutableStateFlow<String?>(null)
val lastEnd: StateFlow<String?> = _lastEnd val lastEnd: StateFlow<String?> = _lastEnd
/** Copies of the contacts, as the store's own entries change in place. */
private val _contacts = MutableStateFlow(contactCopies())
val contacts: StateFlow<List<Contact>> = _contacts
private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList())
val bookmarks: StateFlow<List<Bookmark>> = _bookmarks
private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16) private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16)
val events: SharedFlow<SessionEvent> = _events val events: SharedFlow<SessionEvent> = _events
@@ -162,36 +127,13 @@ class SessionController(private val context: Context) {
@Volatile @Volatile
private var watchingLevel = false private var watchingLevel = false
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
val swipe = SwipePrefs(context)
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init { init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
// Mutations report on whichever thread made them, a connection thread included. // Mutations report on whichever thread made them, a connection thread included.
contactStore.addListener { contactStore.addListener { _servers.value.forEach(ServerController::contactsChanged) }
_contacts.value = contactCopies()
_servers.value.forEach(ServerController::contactsChanged)
}
Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer) Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer)
settings.countryFlags.addListener { servers.value.forEach { it.scheduleTree(structure = false) } } settings.countryFlags.addListener { servers.value.forEach { it.scheduleTree(structure = false) } }
} }
/** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */
fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname.get() }
val lastAddress: String get() = settings.lastAddress.get() val lastAddress: String get() = settings.lastAddress.get()
// ---- connection ---- // ---- connection ----
@@ -221,7 +163,7 @@ class SessionController(private val context: Context) {
private fun start(connect: (ServerController) -> Unit) { private fun start(connect: (ServerController) -> Unit) {
val server = ServerController(nextId.incrementAndGet(), this) val server = ServerController(nextId.incrementAndGet(), this)
server.session.setMyTeamSpeakLogin(myTeamSpeak) server.session.setMyTeamSpeakLogin(myTeamSpeak.login)
sessions.add(server.session) sessions.add(server.session)
_servers.update { it + server } _servers.update { it + server }
_current.value = server _current.value = server
@@ -236,8 +178,7 @@ class SessionController(private val context: Context) {
*/ */
fun open(link: ServerLink, identityId: String = "") { fun open(link: ServerLink, identityId: String = "") {
if (link.bookmarkLabel.isNotEmpty()) { if (link.bookmarkLabel.isNotEmpty()) {
bookmarkStore.add(link.toBookmark()) bookmarks.add(link.toBookmark())
saveBookmarks()
} }
val on = _servers.value.firstOrNull { it.session.isOn(link) } val on = _servers.value.firstOrNull { it.session.isOn(link) }
if (on != null) { if (on != null) {
@@ -251,7 +192,7 @@ class SessionController(private val context: Context) {
/** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */ /** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */
fun openBookmark(id: String): ServerLink? { fun openBookmark(id: String): ServerLink? {
val bookmark = bookmarkStore.find(id) val bookmark = bookmarks.find(id)
if (bookmark == null) { if (bookmark == null) {
error("That bookmark no longer exists") error("That bookmark no longer exists")
return null return null
@@ -265,7 +206,7 @@ class SessionController(private val context: Context) {
fun connectStartupBookmarks(opened: ServerLink?) { fun connectStartupBookmarks(opened: ServerLink?) {
if (startedUp) return if (startedUp) return
startedUp = true startedUp = true
for (b in bookmarkStore.startupBookmarks()) { for (b in bookmarks.startupBookmarks()) {
if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) } if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) }
} }
} }
@@ -327,29 +268,12 @@ class SessionController(private val context: Context) {
internal fun talking(transmitting: Boolean) = levels.talking(transmitting) internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
// ---- bookmarks ---- // ---- what the servers share ----
/** A bookmark to [address] as typed into the connect form, not yet saved. */ /** A saved bookmark changed; the servers connected with it take on what applies at once. */
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark { internal fun bookmarkEdited(bookmark: Bookmark) = _servers.value.forEach { it.bookmarkEdited(bookmark) }
val (host, port) = parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != nicknameFor(identityId) }.orEmpty()
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
}
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */ internal fun serverIconChanged(address: String, port: Int, iconId: Long) = bookmarks.serverIconChanged(address, port, iconId)
fun saveBookmark(index: Int, edited: Bookmark) {
val all = bookmarkStore.all()
if (index !in all.indices) {
bookmarkStore.add(edited)
} else {
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
all[index] = edited
}
saveBookmarks()
_servers.value.forEach { it.bookmarkEdited(edited) }
}
/** The channels of a server we are on at [host]:[port], to pick one to join. */ /** The channels of a server we are on at [host]:[port], to pick one to join. */
fun channelPathsAt(host: String, port: Int): List<String> = sessions.connectedTo(host, port)?.channelPaths().orEmpty() fun channelPathsAt(host: String, port: Int): List<String> = sessions.connectedTo(host, port)?.channelPaths().orEmpty()
@@ -357,187 +281,8 @@ class SessionController(private val context: Context) {
/** The channel we are in on the server at [host]:[port]; null when we are not on it. */ /** The channel we are in on the server at [host]:[port]; null when we are not on it. */
fun currentChannelAt(host: String, port: Int): String? = sessions.connectedTo(host, port)?.currentChannelPath() fun currentChannelAt(host: String, port: Int): String? = sessions.connectedTo(host, port)?.currentChannelPath()
fun removeBookmark(bookmark: Bookmark) { /** Signed in or out of myTeamSpeak. */
val index = bookmarkStore.all().indexOf(bookmark) internal fun myTeamSpeakChanged() = _servers.value.forEach { it.session.updateMyTeamSpeak() }
if (index < 0) return
bookmarkStore.remove(index)
saveBookmarks()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
main.post {
val all = bookmarkStore.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) saveBookmarks()
}
}
private fun saveBookmarks() {
bookmarkStore.save()
_bookmarks.value = bookmarkStore.all().toList()
shortcuts.sync(_bookmarks.value)
}
val canPinShortcuts: Boolean get() = shortcuts.supported
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
fun pinShortcut(bookmark: Bookmark) {
// A bookmark not saved since ids came in has a new one on every load until it is.
bookmarkStore.save()
shortcuts.pin(bookmark)
}
// ---- whisper lists ----
private val whisperListStore = WhisperLists.load()
private val _whisperLists = MutableStateFlow(whisperListCopies())
val whisperLists: StateFlow<List<WhisperList>> = _whisperLists
private fun whisperListCopies() = whisperListStore.all().map { it.copy() }
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
fun saveWhisperList(index: Int, list: WhisperList) {
val all = whisperListStore.all()
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
whisperListStore.save()
_whisperLists.value = whisperListCopies()
}
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) {
val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName)
add(list)
saveWhisperList(index, list)
}
fun removeWhisperList(index: Int) {
val all = whisperListStore.all()
if (index !in all.indices) return
all.removeAt(index)
whisperListStore.save()
_whisperLists.value = whisperListCopies()
}
// ---- contacts ----
private fun contactCopies(): List<Contact> = contactStore.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [saveContact]. */
fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy()
fun saveContact(contact: Contact) = contactStore.put(contact)
fun removeContact(uniqueId: String) = contactStore.remove(uniqueId)
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun importContacts(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else contactStore.merge(found)
}
// ---- myTeamSpeak ----
/** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore)
private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn)
val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn
/** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */
internal val attachments = ChatAttachments(myTeamSpeak).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) }
.also {
_myTeamSpeakSignedIn.value = true
_servers.value.forEach { it.session.updateMyTeamSpeak() }
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { myTeamSpeak.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_myTeamSpeakSignedIn.value = myTeamSpeak.isSignedIn
}
suspend fun signOutMyTeamSpeak() {
myTeamSpeak.signOut()
_myTeamSpeakSignedIn.value = false
_servers.value.forEach { it.session.updateMyTeamSpeak() }
withContext(Dispatchers.IO) { attachments.close() }
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use; contacts announce themselves. */
suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
_bookmarks.value = bookmarkStore.all().toList()
identities.refresh()
}
// ---- sound packs ----
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setCountryFlags(shown: Boolean) {
settings.countryFlags.set(shown)
settings.save()
}
/** Puts new client row colours, already set in [settings], into effect. */ /** Puts new client row colours, already set in [settings], into effect. */
fun clientRowColorsChanged() { fun clientRowColorsChanged() {
@@ -545,23 +290,6 @@ class SessionController(private val context: Context) {
servers.value.forEach { it.scheduleTree(structure = false) } servers.value.forEach { it.scheduleTree(structure = false) }
} }
fun setDescriptionPictures(shown: Boolean) {
settings.descriptionPictures.set(shown)
settings.save()
}
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
// ---- the local client ---- // ---- the local client ----
fun hasMicPermission() = fun hasMicPermission() =
@@ -588,16 +316,6 @@ class SessionController(private val context: Context) {
updateLevels() updateLevels()
} }
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
/** Switches between push to talk and voice activation; returns the new mode. */ /** Switches between push to talk and voice activation; returns the new mode. */
fun toggleInputMode(): Settings.InputMode { fun toggleInputMode(): Settings.InputMode {
settings.inputMode.set(if (settings.inputMode.get() == Settings.InputMode.PUSH_TO_TALK) settings.inputMode.set(if (settings.inputMode.get() == Settings.InputMode.PUSH_TO_TALK)
@@ -623,7 +341,6 @@ class SessionController(private val context: Context) {
/** Output device, volume and receive buffer are global, so they go to every connection. */ /** Output device, volume and receive buffer are global, so they go to every connection. */
private fun applyOutputSettings() { private fun applyOutputSettings() {
soundPlayer.setOutputDevice(settings.outputDevice.get())
for (server in _servers.value) { for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume.get()) server.playback?.setMasterVolume(settings.outputVolume.get())
server.playback?.setOutputDevice(settings.outputDevice.get()) server.playback?.setOutputDevice(settings.outputDevice.get())
@@ -631,13 +348,6 @@ class SessionController(private val context: Context) {
} }
} }
/** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) {
routePrefs.save(route)
_route.value = route
audio.setRoute(route)
}
/** Listens to the microphone for the level meter while [on]. */ /** Listens to the microphone for the level meter while [on]. */
fun watchLevel(on: Boolean) { fun watchLevel(on: Boolean) {
watchingLevel = on watchingLevel = on
@@ -665,7 +375,6 @@ class SessionController(private val context: Context) {
companion object { companion object {
const val DEFAULT_PORT = 9987 const val DEFAULT_PORT = 9987
private const val OVERLAY_ENABLED = "enabled"
/** `host[:port]` as typed, the port defaulting to TeamSpeak's. */ /** `host[:port]` as typed, the port defaulting to TeamSpeak's. */
fun parseAddress(address: String): Pair<String, Int> { fun parseAddress(address: String): Pair<String, Int> {
@@ -5,14 +5,16 @@ import eu.lixko.ts3j.client.config.AppDirs
class Ts3Application : Application() { class Ts3Application : Application() {
lateinit var sessions: SessionController lateinit var parts: AppParts
private set private set
val sessions: SessionController get() = parts.sessions
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
// Before any store loads: there is no home directory to find them in. // Before any store loads: there is no home directory to find them in.
AppDirs.init(filesDir, filesDir.toPath().resolve("chats")) AppDirs.init(filesDir, filesDir.toPath().resolve("chats"))
sessions = SessionController(this) parts = AppParts(this)
Thread(sessions::installSoundPacks, "sound-packs").start() Thread(parts.audio::installSoundPacks, "sound-packs").start()
} }
} }
@@ -0,0 +1,41 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The saved whisper lists, shared by every server. */
class WhisperListManager internal constructor() {
private val store = WhisperLists.load()
private val _all = MutableStateFlow(copies())
val all: StateFlow<List<WhisperList>> = _all
private fun copies() = store.all().map { it.copy() }
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
fun save(index: Int, list: WhisperList) {
val all = store.all()
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
saved()
}
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
fun addTo(index: Int, newName: String, add: (WhisperList) -> Unit) {
val list = store.all().getOrNull(index)?.copy() ?: WhisperList(newName)
add(list)
save(index, list)
}
fun remove(index: Int) {
val all = store.all()
if (index !in all.indices) return
all.removeAt(index)
saved()
}
private fun saved() {
store.save()
_all.value = copies()
}
}
@@ -21,13 +21,14 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.AppParts
import eu.lixko.ts3j.client.android.SessionEvent import eu.lixko.ts3j.client.android.SessionEvent
import eu.lixko.ts3j.client.android.TreeSwipe import eu.lixko.ts3j.client.android.TreeSwipe
@Composable @Composable
fun App(vm: SessionController) { fun App(parts: AppParts) {
val current by vm.current.collectAsStateWithLifecycle() val sessions = parts.sessions
val current by sessions.current.collectAsStateWithLifecycle()
// Each server keeps its own screen state (chat open, conversation) while another is shown. // Each server keeps its own screen state (chat open, conversation) while another is shown.
val serverStates = rememberSaveableStateHolder() val serverStates = rememberSaveableStateHolder()
var connectOpen by rememberSaveable { mutableStateOf(false) } var connectOpen by rememberSaveable { mutableStateOf(false) }
@@ -41,8 +42,8 @@ fun App(vm: SessionController) {
var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) } var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) }
var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) } var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) }
LaunchedEffect(vm) { LaunchedEffect(sessions) {
vm.events.collect { event -> sessions.events.collect { event ->
when (event) { when (event) {
is SessionEvent.Poke -> poke = event is SessionEvent.Poke -> poke = event
is SessionEvent.Error -> snackbar.showSnackbar(event.message) is SessionEvent.Error -> snackbar.showSnackbar(event.message)
@@ -59,7 +60,7 @@ fun App(vm: SessionController) {
val context = LocalContext.current val context = LocalContext.current
val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted -> val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo) if (granted[Manifest.permission.RECORD_AUDIO] == true) sessions.current.value?.let(sessions::giveMicrophoneTo)
} }
fun missing(vararg names: String) = fun missing(vararg names: String) =
names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
@@ -72,7 +73,7 @@ fun App(vm: SessionController) {
if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray()) if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray())
} }
val enableMicrophone: () -> Unit = { val enableMicrophone: () -> Unit = {
if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo) if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) sessions.current.value?.let(sessions::giveMicrophoneTo)
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO)) else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
} }
@@ -82,21 +83,21 @@ fun App(vm: SessionController) {
contactDirect = uniqueId != null contactDirect = uniqueId != null
} }
CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) { CompositionLocalProvider(LocalIconTheme provides parts.icons, LocalWebPictures provides parts.pictures) {
val server = current val server = current
val bookmark = editingBookmark val bookmark = editingBookmark
when { when {
bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null }) bookmark != null -> BookmarkScreen(sessions, parts.bookmarks, parts.identities, bookmark, onDone = { editingBookmark = null })
contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId -> contactsOpen -> ContactsScreen(parts.contacts, editingContact, onEdit = { uniqueId ->
if (uniqueId == null && contactDirect) contactsOpen = false if (uniqueId == null && contactDirect) contactsOpen = false
contactDirect = false contactDirect = false
editingContact = uniqueId editingContact = uniqueId
}, onBack = { contactsOpen = false }) }, onBack = { contactsOpen = false })
myTeamSpeakOpen -> MyTeamSpeakScreen(vm, onBack = { myTeamSpeakOpen = false }) myTeamSpeakOpen -> MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { myTeamSpeakOpen = false })
settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false }) settingsOpen -> SettingsScreen(parts, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
server != null && !connectOpen -> { server != null && !connectOpen -> {
val servers by vm.servers.collectAsStateWithLifecycle() val servers by sessions.servers.collectAsStateWithLifecycle()
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle() val treeSwipe by parts.swipe.tree.collectAsStateWithLifecycle()
val serverSwipe = rememberSwipeState() val serverSwipe = rememberSwipeState()
SwipeHost( SwipeHost(
serverSwipe, server, serverSwipe, server,
@@ -104,13 +105,13 @@ fun App(vm: SessionController) {
if (treeSwipe != TreeSwipe.SERVERS) null if (treeSwipe != TreeSwipe.SERVERS) null
else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) } else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) }
}, },
onSwipe = vm::select, onSwipe = sessions::select,
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
) { shown -> ) { shown ->
serverStates.SaveableStateProvider(shown.id) { serverStates.SaveableStateProvider(shown.id) {
CompositionLocalProvider(LocalServerImages provides shown.images) { CompositionLocalProvider(LocalServerImages provides shown.images) {
PictureViewerHost(shown) { PictureViewerHost(shown) {
ServerScreen(vm, shown, snackbar, { settingsOpen = true }, openContacts, enableMicrophone, ServerScreen(sessions, parts.whisperLists, parts.myTeamSpeak, parts.swipe, parts.banReasons, shown, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it }, onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it },
serverSwipe = serverSwipe, active = shown == server) serverSwipe = serverSwipe, active = shown == server)
} }
@@ -118,7 +119,7 @@ fun App(vm: SessionController) {
} }
} }
} }
else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking, else -> ConnectScreen(sessions, parts.bookmarks, parts.identities, parts.myTeamSpeak, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking,
onEditBookmark = { editingBookmark = it }, onEditBookmark = { editingBookmark = it },
onBack = if (current != null) ({ connectOpen = false }) else null) onBack = if (current != null) ({ connectOpen = false }) else null)
} }
@@ -17,13 +17,13 @@ import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
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.chat.ChatKey import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.MyTsException import eu.lixko.ts3j.client.myts.MyTsException
import kotlinx.coroutines.launch
import java.io.IOException import java.io.IOException
import kotlinx.coroutines.launch
/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */ /** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */
class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit) class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
@@ -34,15 +34,16 @@ class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
*/ */
@Composable @Composable
fun rememberAttachmentActions( fun rememberAttachmentActions(
vm: SessionController, account: MyTeamSpeakAccount,
server: ServerController, server: ServerController,
snackbar: SnackbarHostState, snackbar: SnackbarHostState,
shown: ChatKey, shown: ChatKey,
): AttachmentActions { ): AttachmentActions {
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() val signedIn by account.signedIn.collectAsStateWithLifecycle()
val key by rememberUpdatedState(shown) val key by rememberUpdatedState(shown)
val viewer = LocalPictureViewer.current val viewer = LocalPictureViewer.current
val pictures = LocalWebPictures.current
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
var saving by rememberSaveable { mutableStateOf<String?>(null) } var saving by rememberSaveable { mutableStateOf<String?>(null) }
@@ -52,7 +53,7 @@ fun rememberAttachmentActions(
if (uri == null || ref == null) return@rememberLauncherForActivityResult if (uri == null || ref == null) return@rememberLauncherForActivityResult
scope.launch { scope.launch {
val error = try { val error = try {
vm.saveAttachment(ref, uri) account.saveAttachment(ref, uri)
null null
} catch (e: MyTsException) { } catch (e: MyTsException) {
e.message e.message
@@ -72,7 +73,7 @@ fun rememberAttachmentActions(
when { when {
!signedIn -> tell(SIGN_IN) !signedIn -> tell(SIGN_IN)
ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) { ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) {
vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull() pictures?.data(href) ?: runCatching { account.downloadAttachment(ref) }.getOrNull()
}) })
else -> { else -> {
saving = href saving = href
@@ -1,7 +1,7 @@
package eu.lixko.ts3j.client.android.ui package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@@ -33,6 +33,8 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.BookmarkManager
import eu.lixko.ts3j.client.android.IdentityManager
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
@@ -64,9 +66,9 @@ val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
/** Every setting of one bookmark, saved only on Save. */ /** Every setting of one bookmark, saved only on Save. */
@Composable @Composable
fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit) { fun BookmarkScreen(sessions: SessionController, bookmarks: BookmarkManager, identityManager: IdentityManager, edit: BookmarkEdit, onDone: () -> Unit) {
val b = edit.bookmark val b = edit.bookmark
val identities by vm.identities.all.collectAsStateWithLifecycle() val identities by identityManager.all.collectAsStateWithLifecycle()
var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) } var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) }
var address by rememberSaveable { var address by rememberSaveable {
mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}") mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}")
@@ -82,7 +84,7 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
val save = { val save = {
val (host, port) = SessionController.parseAddress(address) val (host, port) = SessionController.parseAddress(address)
vm.saveBookmark(edit.index, b.copy().also { bookmarks.save(edit.index, b.copy().also {
it.label = label.trim().ifEmpty { host } it.label = label.trim().ifEmpty { host }
it.address = host it.address = host
it.port = port it.port = port
@@ -114,12 +116,12 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) { identityId = it } IdentityField(identities, identityId) { identityId = it }
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") }, OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
placeholder = { Text(vm.nicknameFor(identityId)) }, singleLine = true) placeholder = { Text(identityManager.nicknameFor(identityId)) }, singleLine = true)
val paths = remember(address) { val paths = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) } SessionController.parseAddress(address).let { (host, port) -> sessions.channelPathsAt(host, port) }
} }
val current = remember(address) { val current = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> vm.currentChannelAt(host, port) } SessionController.parseAddress(address).let { (host, port) -> sessions.currentChannelAt(host, port) }
} }
ChannelField(channel, paths, current) { channel = it } ChannelField(channel, paths, current) { channel = it }
OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(), OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(),
@@ -5,6 +5,7 @@ import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement 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.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -15,18 +16,17 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -50,12 +50,15 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.BookmarkManager
import eu.lixko.ts3j.client.android.IdentityInfo import eu.lixko.ts3j.client.android.IdentityInfo
import eu.lixko.ts3j.client.android.IdentityManager
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.net.IconRepository import eu.lixko.ts3j.client.net.IconRepository
@@ -64,7 +67,10 @@ import eu.lixko.ts3j.client.net.IconRepository
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun ConnectScreen( fun ConnectScreen(
vm: SessionController, sessions: SessionController,
bookmarkManager: BookmarkManager,
identityManager: IdentityManager,
account: MyTeamSpeakAccount,
snackbar: SnackbarHostState, snackbar: SnackbarHostState,
onSettings: () -> Unit, onSettings: () -> Unit,
onMyTeamSpeak: () -> Unit, onMyTeamSpeak: () -> Unit,
@@ -73,13 +79,13 @@ fun ConnectScreen(
/** Back to the servers already connected; null when there are none. */ /** Back to the servers already connected; null when there are none. */
onBack: (() -> Unit)?, onBack: (() -> Unit)?,
) { ) {
val lastEnd by vm.lastEnd.collectAsStateWithLifecycle() val lastEnd by sessions.lastEnd.collectAsStateWithLifecycle()
val bookmarks by vm.bookmarks.collectAsStateWithLifecycle() val bookmarks by bookmarkManager.all.collectAsStateWithLifecycle()
val identities by vm.identities.all.collectAsStateWithLifecycle() val identities by identityManager.all.collectAsStateWithLifecycle()
val myTeamSpeakSignedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() val myTeamSpeakSignedIn by account.signedIn.collectAsStateWithLifecycle()
var address by rememberSaveable { mutableStateOf(vm.lastAddress) } var address by rememberSaveable { mutableStateOf(sessions.lastAddress) }
var identityId by rememberSaveable { mutableStateOf("") } var identityId by rememberSaveable { mutableStateOf("") }
var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) } var nickname by rememberSaveable { mutableStateOf(identityManager.nicknameFor("")) }
var password by rememberSaveable { mutableStateOf("") } var password by rememberSaveable { mutableStateOf("") }
if (onBack != null) BackHandler(onBack = onBack) if (onBack != null) BackHandler(onBack = onBack)
@@ -115,18 +121,18 @@ fun ConnectScreen(
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) { IdentityField(identities, identityId) {
identityId = it identityId = it
nickname = vm.nicknameFor(it) nickname = identityManager.nicknameFor(it)
} }
lastEnd?.let { lastEnd?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
} }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button( Button(
onClick = { onConnect { vm.connect(address.trim(), nickname.trim(), password, identityId) } }, onClick = { onConnect { sessions.connect(address.trim(), nickname.trim(), password, identityId) } },
enabled = address.isNotBlank() && nickname.isNotBlank(), enabled = address.isNotBlank() && nickname.isNotBlank(),
) { Text("Connect") } ) { Text("Connect") }
TextButton(onClick = { TextButton(onClick = {
onEditBookmark(BookmarkEdit(-1, vm.newBookmark(address.trim(), nickname.trim(), password, identityId))) onEditBookmark(BookmarkEdit(-1, bookmarkManager.newBookmark(address.trim(), nickname.trim(), password, identityId)))
}, enabled = address.isNotBlank()) { Text("Add bookmark") } }, enabled = address.isNotBlank()) { Text("Add bookmark") }
} }
} }
@@ -144,10 +150,10 @@ fun ConnectScreen(
} }
} }
itemsIndexed(bookmarks) { index, bookmark -> itemsIndexed(bookmarks) { index, bookmark ->
BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } }, BookmarkRow(bookmark, identities, { onConnect { sessions.connect(bookmark) } },
onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) }, onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) },
onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null, onPin = if (bookmarkManager.canPinShortcuts) ({ bookmarkManager.pinShortcut(bookmark) }) else null,
onRemove = { vm.removeBookmark(bookmark) }) onRemove = { bookmarkManager.remove(bookmark) })
} }
} }
} }
@@ -40,14 +40,14 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.ContactManager
import eu.lixko.ts3j.client.contacts.Contact import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactType import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.contacts.NicknameDisplay import eu.lixko.ts3j.client.contacts.NicknameDisplay
import kotlinx.coroutines.launch
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import kotlin.math.roundToInt import kotlin.math.roundToInt
import kotlinx.coroutines.launch
private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
@@ -70,20 +70,20 @@ private val GROUPS = listOf(
* @param editing the unique id of the contact whose page is open, if any * @param editing the unique id of the contact whose page is open, if any
*/ */
@Composable @Composable
fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) { fun ContactsScreen(contacts: ContactManager, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) {
var defaults by rememberSaveable { mutableStateOf(false) } var defaults by rememberSaveable { mutableStateOf(false) }
when { when {
editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) }) editing != null -> return ContactScreen(contacts, editing, onBack = { onEdit(null) })
defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false }) defaults -> return ContactDefaultsScreen(contacts, onBack = { defaults = false })
} }
val contacts by vm.contacts.collectAsStateWithLifecycle() val all by contacts.all.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) } var menu by remember { mutableStateOf(false) }
var imported by remember { mutableStateOf<String?>(null) } var imported by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch { if (uri != null) scope.launch {
imported = runCatching { vm.importContacts(uri) }.fold( imported = runCatching { contacts.import(uri) }.fold(
{ (found, added) -> { (found, added) ->
if (found == 0) "That file holds no contacts." if (found == 0) "That file holds no contacts."
else "Imported $found contacts, $added of them new." else "Imported $found contacts, $added of them new."
@@ -107,14 +107,14 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) ->
}) { padding -> }) { padding ->
LazyColumn(Modifier.padding(padding)) { LazyColumn(Modifier.padding(padding)) {
imported?.let { item { Hint(it) } } imported?.let { item { Hint(it) } }
if (contacts.isEmpty()) { if (all.isEmpty()) {
item { item {
Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " + Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " +
"or import the contacts of TeamSpeak 3 from its settings.db.") "or import the contacts of TeamSpeak 3 from its settings.db.")
} }
} }
for ((type, title) in GROUPS) { for ((type, title) in GROUPS) {
val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() } val group = all.filter { it.type == type }.sortedBy { label(it).lowercase() }
if (group.isEmpty()) continue if (group.isEmpty()) continue
item(key = type) { Section(title) } item(key = type) { Section(title) }
items(group, key = { it.key() }) { contact -> items(group, key = { it.key() }) { contact ->
@@ -131,18 +131,18 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) ->
/** One contact's settings; each is stored as it is changed, the names once the page is left. */ /** One contact's settings; each is stored as it is changed, the names once the page is left. */
@Composable @Composable
private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) { private fun ContactScreen(contacts: ContactManager, uniqueId: String, onBack: () -> Unit) {
val contacts by vm.contacts.collectAsStateWithLifecycle() val all by contacts.all.collectAsStateWithLifecycle()
// A client's unique id may stand for a contact filed under its myTeamSpeak ID. // A client's unique id may stand for a contact filed under its myTeamSpeak ID.
val key = remember(uniqueId) { vm.contact(uniqueId)?.key() ?: uniqueId } val key = remember(uniqueId) { contacts.find(uniqueId)?.key() ?: uniqueId }
val contact = contacts.firstOrNull { it.key() == key } val contact = all.firstOrNull { it.key() == key }
if (contact == null) { if (contact == null) {
LaunchedEffect(Unit) { onBack() } LaunchedEffect(Unit) { onBack() }
return return
} }
// Starts from the stored entry, which may have been seen again since this page opened. // Starts from the stored entry, which may have been seen again since this page opened.
fun edit(change: Contact.() -> Unit) { fun edit(change: Contact.() -> Unit) {
vm.contact(key)?.let { vm.saveContact(it.apply(change)) } contacts.find(key)?.let { contacts.save(it.apply(change)) }
} }
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) } var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) } var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
@@ -211,7 +211,7 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
removing = false removing = false
vm.removeContact(key) contacts.remove(key)
onBack() onBack()
}) { Text("Remove") } }) { Text("Remove") }
}, },
@@ -222,14 +222,14 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
/** What a client starts out with when added as a friend, blocked or neutral. */ /** What a client starts out with when added as a friend, blocked or neutral. */
@Composable @Composable
private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) { private fun ContactDefaultsScreen(contacts: ContactManager, onBack: () -> Unit) {
val defaults = vm.settings.contactDefaults val defaults = contacts.defaults
var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) } var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) }
var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) } var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) }
fun edit(change: ContactDefaults.Entry.() -> Unit) { fun edit(change: ContactDefaults.Entry.() -> Unit) {
val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() } val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() }
defaults.of(tab).copyFrom(changed) defaults.of(tab).copyFrom(changed)
vm.settings.save() contacts.saveDefaults()
entry = changed entry = changed
} }
@@ -42,18 +42,18 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.myts.AccountInfo import eu.lixko.ts3j.client.myts.AccountInfo
import eu.lixko.ts3j.client.myts.MyTeamSpeak import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTsException import eu.lixko.ts3j.client.myts.MyTsException
import eu.lixko.ts3j.client.teamspeak.SyncItem import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import kotlinx.coroutines.launch
import java.io.IOException import java.io.IOException
import java.time.ZoneId import java.time.ZoneId
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle import java.time.format.FormatStyle
import kotlinx.coroutines.launch
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean) private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
@@ -63,8 +63,8 @@ private data class ItemRow(val item: SyncItem, val imported: Boolean, val select
*/ */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
val login = vm.myTeamSpeak val login = account.login
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
var signedIn by remember { mutableStateOf(login.isSignedIn) } var signedIn by remember { mutableStateOf(login.isSignedIn) }
var busy by remember { mutableStateOf(false) } var busy by remember { mutableStateOf(false) }
@@ -77,11 +77,11 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
var rows by remember { mutableStateOf(emptyList<ItemRow>()) } var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
BackHandler(onBack = onBack) BackHandler(onBack = onBack)
fun show(account: MyTeamSpeak.Account) { fun show(fetched: MyTeamSpeak.Account) {
info = account.info() info = fetched.info()
all = account.items() all = fetched.items()
rows = all.filter { it !is SyncItem.Folder && (it !is SyncItem.Contact || TeamSpeakImporter.isImportable(it)) }.map { rows = all.filter { it !is SyncItem.Folder && (it !is SyncItem.Contact || TeamSpeakImporter.isImportable(it)) }.map {
val imported = vm.isImported(it) val imported = account.isImported(it)
ItemRow(it, imported, !imported) ItemRow(it, imported, !imported)
} }
message = if (rows.isEmpty()) "The account holds no bookmarks, identities or contacts." else null message = if (rows.isEmpty()) "The account holds no bookmarks, identities or contacts." else null
@@ -108,7 +108,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
} }
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
if (signedIn) work { show(vm.fetchMyTeamSpeak()) } if (signedIn) work { show(account.fetch()) }
} }
Scaffold( Scaffold(
@@ -118,7 +118,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = { actions = {
if (signedIn) { if (signedIn) {
IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) { IconButton(onClick = { work { show(account.fetch()) } }, enabled = !busy) {
PackIcon("REFRESH", "Refresh") PackIcon("REFRESH", "Refresh")
} }
} }
@@ -146,7 +146,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
Button( Button(
onClick = { onClick = {
work { work {
show(vm.signInMyTeamSpeak(email.trim(), password)) show(account.signIn(email.trim(), password))
password = "" password = ""
} }
}, },
@@ -163,7 +163,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
color = MaterialTheme.colorScheme.onSurfaceVariant) color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
OutlinedButton(onClick = { OutlinedButton(onClick = {
scope.launch { vm.signOutMyTeamSpeak() } scope.launch { account.signOut() }
signedIn = false signedIn = false
rows = emptyList() rows = emptyList()
all = emptyList() all = emptyList()
@@ -219,8 +219,8 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
Button( Button(
onClick = { onClick = {
work { work {
val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item }) val r = account.import(all, rows.filter { it.selected }.map { it.item })
rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) } rows = rows.map { it.copy(imported = account.isImported(it.item), selected = false) }
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " + message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " +
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " + "${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " +
"${count(r.contactsAdded(), "contact", "contacts")}." "${count(r.contactsAdded(), "contact", "contacts")}."
@@ -22,11 +22,10 @@ private const val MAX_BITRATE_KBITS = 160f
/** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */ /** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */
@Composable @Composable
fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { fun NetworkSettingsScreen(settings: Settings, sessions: SessionController, onBack: () -> Unit) {
val settings = vm.settings
fun <T> change(setting: Setting<T>, value: T) { fun <T> change(setting: Setting<T>, value: T) {
setting.set(value) setting.set(value)
vm.applySettings() sessions.applySettings()
} }
var vbr by remember { mutableStateOf(settings.vbr.get()) } var vbr by remember { mutableStateOf(settings.vbr.get()) }
var fec by remember { mutableStateOf(settings.fec.get()) } var fec by remember { mutableStateOf(settings.fec.get()) }
@@ -31,8 +31,8 @@ import kotlinx.coroutines.flow.MutableStateFlow
internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean) internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean)
@Composable @Composable
internal fun rememberPttTarget(vm: SessionController): PttTarget { internal fun rememberPttTarget(sessions: SessionController): PttTarget {
val owner by vm.micOwner.collectAsStateWithLifecycle() val owner by sessions.micOwner.collectAsStateWithLifecycle()
val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle() val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle()
val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle() val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle()
val self = tree.client(state.selfClientId) val self = tree.client(state.selfClientId)
@@ -78,12 +78,12 @@ internal fun PushToTalk(
/** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */ /** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */
@Composable @Composable
fun GiantPttScreen(vm: SessionController, onBack: () -> Unit) { fun GiantPttScreen(sessions: SessionController, onBack: () -> Unit) {
val target = rememberPttTarget(vm) val target = rememberPttTarget(sessions)
SubScreen("Giant PTT", onBack) { padding -> SubScreen("Giant PTT", onBack) { padding ->
val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp) val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp)
if (target.owner != null && target.state.connected) { if (target.owner != null && target.state.connected) {
PushToTalk(target.talking, vm::setForceTransmit, fill, RoundedCornerShape(32.dp), PushToTalk(target.talking, sessions::setForceTransmit, fill, RoundedCornerShape(32.dp),
MaterialTheme.typography.displaySmall) MaterialTheme.typography.displaySmall)
} else { } else {
Box(fill, contentAlignment = Alignment.Center) { Box(fill, contentAlignment = Alignment.Center) {
@@ -13,8 +13,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.WhisperListManager
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
/** Joins [channel], asking for its password first when it is locked. */ /** Joins [channel], asking for its password first when it is locked. */
@@ -26,7 +26,7 @@ internal fun ServerNav.join(server: ServerController, channel: ChannelItem) {
@Composable @Composable
internal fun ServerOverlay( internal fun ServerOverlay(
nav: ServerNav, nav: ServerNav,
vm: SessionController, whisperLists: WhisperListManager,
server: ServerController, server: ServerController,
state: SessionState, state: SessionState,
tree: ServerTree, tree: ServerTree,
@@ -159,9 +159,9 @@ internal fun ServerOverlay(
dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } }, dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } },
) )
} }
is Overlay.AddToWhisperList -> AddToWhisperListDialog(vm, o.name, onDismiss = dismiss) { index, newName -> is Overlay.AddToWhisperList -> AddToWhisperListDialog(whisperLists, o.name, onDismiss = dismiss) { index, newName ->
dismiss() dismiss()
vm.addToWhisperList(index, newName, o.add) whisperLists.addTo(index, newName, o.add)
} }
} }
} }
@@ -30,10 +30,14 @@ import androidx.compose.ui.platform.LocalUriHandler
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.MyTeamSpeakAccount
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.SwipePrefs
import eu.lixko.ts3j.client.android.TreeSwipe import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.android.WhisperListManager
import eu.lixko.ts3j.client.chat.ChatKey import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.config.BanReasonPresets
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
@@ -42,7 +46,11 @@ import eu.lixko.ts3j.client.text.TsLink
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun ServerScreen( fun ServerScreen(
vm: SessionController, sessions: SessionController,
whisperLists: WhisperListManager,
account: MyTeamSpeakAccount,
swipe: SwipePrefs,
banReasons: BanReasonPresets,
server: ServerController, server: ServerController,
snackbar: SnackbarHostState, snackbar: SnackbarHostState,
onSettings: () -> Unit, onSettings: () -> Unit,
@@ -70,8 +78,8 @@ fun ServerScreen(
val conversation by conversationState val conversation by conversationState
val picking = rememberTreePicking(server, treeState, sessionState) val picking = rememberTreePicking(server, treeState, sessionState)
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle() val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle() val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
// The chat lies to the right of the tree. // The chat lies to the right of the tree.
val chatBesideTree = treeSwipe == TreeSwipe.CHAT val chatBesideTree = treeSwipe == TreeSwipe.CHAT
val pageSwipe = rememberSwipeState() val pageSwipe = rememberSwipeState()
@@ -90,12 +98,12 @@ fun ServerScreen(
} }
val uriHandler = LocalUriHandler.current val uriHandler = LocalUriHandler.current
val attachments = rememberAttachmentActions(vm, server, snackbar, conversation.key) val attachments = rememberAttachmentActions(account, server, snackbar, conversation.key)
val onLink: (String) -> Unit = { href -> val onLink: (String) -> Unit = { href ->
val ref = TsLink.parse(href) val ref = TsLink.parse(href)
when { when {
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 { sessions.open(it) }
ref == null -> runCatching { uriHandler.openUri(href) } ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false) ref.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false)
else -> nav.overlay = Overlay.Channel(ref.id) else -> nav.overlay = Overlay.Channel(ref.id)
@@ -111,8 +119,8 @@ fun ServerScreen(
when (val page = nav.page) { when (val page = nav.page) {
ServerPage.Main -> {} ServerPage.Main -> {}
ServerPage.BanList -> return BanListScreen(server, vm.banReasons, onBack = nav::back) ServerPage.BanList -> return BanListScreen(server, banReasons, onBack = nav::back)
ServerPage.WhisperLists -> return WhisperListsScreen(vm, server, onBack = nav::back) ServerPage.WhisperLists -> return WhisperListsScreen(whisperLists, server, onBack = nav::back)
is ServerPage.EditChannel -> return ChannelEditScreen(server, page.edit, onDone = nav::back) is ServerPage.EditChannel -> return ChannelEditScreen(server, page.edit, onDone = nav::back)
is ServerPage.Files -> return FilesScreen(server, page.channelId, page.name, page.password, onBack = nav::back) is ServerPage.Files -> return FilesScreen(server, page.channelId, page.name, page.password, onBack = nav::back)
is ServerPage.ConnectionInfo -> return ConnectionInfoScreen(server, page.clientId, tree.client(page.clientId), onBack = nav::back) is ServerPage.ConnectionInfo -> return ConnectionInfoScreen(server, page.clientId, tree.client(page.clientId), onBack = nav::back)
@@ -140,11 +148,11 @@ fun ServerScreen(
} }
} else { } else {
TopAppBar( TopAppBar(
title = { ServerSwitcher(vm, server, state, onConnectOther) }, title = { ServerSwitcher(sessions, server, state, onConnectOther) },
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) { nav.page = ServerPage.WhisperLists } if (state.connected && state.whisperControls) WhisperMenu(whisperLists, 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") }
}, },
@@ -153,9 +161,9 @@ fun ServerScreen(
}, },
bottomBar = { bottomBar = {
Column { Column {
val ptt = rememberPttTarget(vm) val ptt = rememberPttTarget(sessions)
WhisperBanner(state) { server.setWhisper(null) } WhisperBanner(state) { server.setWhisper(null) }
VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, nav.showChat, chats.anyUnread) { VoiceBar(state, ptt.owner != null, ptt.talking, sessions, server, onEnableMicrophone, nav.showChat, chats.anyUnread) {
nav.showChat = !nav.showChat nav.showChat = !nav.showChat
} }
} }
@@ -237,5 +245,5 @@ fun ServerScreen(
} }
} }
ServerOverlay(nav, vm, server, state, tree, treeView, picking, snackbar, onLink, onEditContact, onEditBookmark) ServerOverlay(nav, whisperLists, server, state, tree, treeView, picking, snackbar, onLink, onEditContact, onEditBookmark)
} }
@@ -46,8 +46,8 @@ private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier)
/** The server on screen, opening onto the others and connecting to another. */ /** The server on screen, opening onto the others and connecting to another. */
@Composable @Composable
internal fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) { internal fun ServerSwitcher(sessions: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by vm.servers.collectAsStateWithLifecycle() val servers by sessions.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) } var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) { Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true }, Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
@@ -68,7 +68,7 @@ internal fun ServerSwitcher(vm: SessionController, server: ServerController, sta
val otherState by other.state.collectAsStateWithLifecycle() val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem( DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; vm.select(other) }, onClick = { open = false; sessions.select(other) },
leadingIcon = { leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f)) ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
}, },
@@ -16,9 +16,12 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AppParts
import eu.lixko.ts3j.client.android.IconTheme import eu.lixko.ts3j.client.android.IconTheme
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SwipePrefs
import eu.lixko.ts3j.client.android.TreeSwipe import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.config.Settings
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -30,15 +33,15 @@ private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES,
* as there is no dialog to confirm. * as there is no dialog to confirm.
*/ */
@Composable @Composable
fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) { fun SettingsScreen(parts: AppParts, onContacts: () -> Unit, onBack: () -> Unit) {
var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) } var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
when (page) { when (page) {
SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null }) SettingsPage.SOUND -> return SoundSettingsScreen(parts.settings, parts.sessions, parts.audio, onBack = { page = null })
SettingsPage.NETWORK -> return NetworkSettingsScreen(vm, onBack = { page = null }) SettingsPage.NETWORK -> return NetworkSettingsScreen(parts.settings, parts.sessions, onBack = { page = null })
SettingsPage.GIANT_PTT -> return GiantPttScreen(vm, onBack = { page = null }) SettingsPage.GIANT_PTT -> return GiantPttScreen(parts.sessions, onBack = { page = null })
SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null }) SettingsPage.DESIGN -> return DesignScreen(parts.settings, parts.icons, parts.swipe, parts.sessions, onBack = { page = null })
SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null }) SettingsPage.IDENTITIES -> return IdentitiesScreen(parts.identities, onBack = { page = null })
SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null }) SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { page = null })
null -> {} null -> {}
} }
@@ -60,7 +63,7 @@ fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () ->
LinkRow("Identities", "Create, import, export, security level", LinkRow("Identities", "Create, import, export, security level",
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES } "IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
LinkRow("myTeamSpeak", LinkRow("myTeamSpeak",
if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}" if (parts.myTeamSpeak.login.isSignedIn) "Signed in as ${parts.myTeamSpeak.login.username()}"
else "Sign in to bring over your synchronised bookmarks, identities and contacts", else "Sign in to bring over your synchronised bookmarks, identities and contacts",
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK } "MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
} }
@@ -68,49 +71,51 @@ fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () ->
} }
@Composable @Composable
private fun DesignScreen(vm: SessionController, onBack: () -> Unit) { private fun DesignScreen(settings: Settings, icons: IconTheme, swipe: SwipePrefs, sessions: SessionController, onBack: () -> Unit) {
SubScreen("Design", onBack) { padding -> SubScreen("Design", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
IconPackPicker(vm.icons) IconPackPicker(icons)
var pictures by remember { mutableStateOf(vm.settings.descriptionPictures.get()) } var pictures by remember { mutableStateOf(settings.descriptionPictures.get()) }
Toggle("Show pictures in descriptions", pictures) { Toggle("Show pictures in descriptions", pictures) {
pictures = it pictures = it
vm.setDescriptionPictures(it) settings.descriptionPictures.set(it)
settings.save()
} }
Section("Channel tree") Section("Channel tree")
var flags by remember { mutableStateOf(vm.settings.countryFlags.get()) } var flags by remember { mutableStateOf(settings.countryFlags.get()) }
Toggle("Show country flags in the channel tree", flags) { Toggle("Show country flags in the channel tree", flags) {
flags = it flags = it
vm.setCountryFlags(it) settings.countryFlags.set(it)
settings.save()
} }
val colors = vm.settings.clientRowColors val colors = settings.clientRowColors
var any by remember { mutableIntStateOf(colors.any) } var any by remember { mutableIntStateOf(colors.any) }
var talking by remember { mutableIntStateOf(colors.talking) } var talking by remember { mutableIntStateOf(colors.talking) }
var mutedAway by remember { mutableIntStateOf(colors.mutedAway) } var mutedAway by remember { mutableIntStateOf(colors.mutedAway) }
RowColorPicker("Client background", any) { RowColorPicker("Client background", any) {
any = it any = it
colors.any = it colors.any = it
vm.clientRowColorsChanged() sessions.clientRowColorsChanged()
} }
RowColorPicker("While talking", talking) { RowColorPicker("While talking", talking) {
talking = it talking = it
colors.talking = it colors.talking = it
vm.clientRowColorsChanged() sessions.clientRowColorsChanged()
} }
RowColorPicker("Muted / away", mutedAway) { RowColorPicker("Muted / away", mutedAway) {
mutedAway = it mutedAway = it
colors.mutedAway = it colors.mutedAway = it
vm.clientRowColorsChanged() sessions.clientRowColorsChanged()
} }
val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle() val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
Picker("Swipe sideways", listOf( Picker("Swipe sideways", listOf(
TreeSwipe.OFF to "Off", TreeSwipe.OFF to "Off",
TreeSwipe.CHAT to "Channel tree and chat", TreeSwipe.CHAT to "Channel tree and chat",
TreeSwipe.SERVERS to "Connected servers", TreeSwipe.SERVERS to "Connected servers",
), treeSwipe, vm.swipe::setTree) ), treeSwipe, swipe::setTree)
Section("Chat") Section("Chat")
val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle() val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
Toggle("Swipe between chat tabs", chatTabSwipe, vm.swipe::setChatTabs) Toggle("Swipe between chat tabs", chatTabSwipe, swipe::setChatTabs)
} }
} }
} }
@@ -134,4 +139,3 @@ private fun IconPackPicker(theme: IconTheme) {
} }
failed?.let { Hint(it) } failed?.let { Hint(it) }
} }
@@ -30,6 +30,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AudioSetup
import eu.lixko.ts3j.client.android.MicLevel import eu.lixko.ts3j.client.android.MicLevel
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.audio.AudioRoute import eu.lixko.ts3j.client.android.audio.AudioRoute
@@ -43,11 +44,10 @@ private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB")
/** Audio devices, transmission, voice activation, processing and playback. */ /** Audio devices, transmission, voice activation, processing and playback. */
@Composable @Composable
fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { fun SoundSettingsScreen(settings: Settings, sessions: SessionController, audio: AudioSetup, onBack: () -> Unit) {
val settings = vm.settings
fun <T> change(setting: Setting<T>, value: T) { fun <T> change(setting: Setting<T>, value: T) {
setting.set(value) setting.set(value)
vm.applySettings() sessions.applySettings()
} }
var inputMode by remember { mutableStateOf(settings.inputMode.get()) } var inputMode by remember { mutableStateOf(settings.inputMode.get()) }
var vadMode by remember { mutableStateOf(settings.vadMode.get()) } var vadMode by remember { mutableStateOf(settings.vadMode.get()) }
@@ -56,15 +56,15 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) } var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) }
var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) } var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) }
var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) } var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) }
val inputs by vm.inputDevices.collectAsStateWithLifecycle() val inputs by audio.inputDevices.collectAsStateWithLifecycle()
val outputs by vm.outputDevices.collectAsStateWithLifecycle() val outputs by audio.outputDevices.collectAsStateWithLifecycle()
val route by vm.route.collectAsStateWithLifecycle() val route by audio.route.collectAsStateWithLifecycle()
val level by vm.micLevel.collectAsStateWithLifecycle() val level by sessions.micLevel.collectAsStateWithLifecycle()
val packs by vm.soundPacks.collectAsStateWithLifecycle() val packs by audio.soundPacks.collectAsStateWithLifecycle()
var pack by remember { mutableStateOf(vm.soundPack?.id()) } var pack by remember { mutableStateOf(audio.soundPack?.id()) }
LifecycleStartEffect(Unit) { LifecycleStartEffect(Unit) {
vm.watchLevel(true) sessions.watchLevel(true)
onStopOrDispose { vm.watchLevel(false) } onStopOrDispose { sessions.watchLevel(false) }
} }
SubScreen("Sound Settings", onBack) { padding -> SubScreen("Sound Settings", onBack) { padding ->
@@ -81,15 +81,15 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
Picker( Picker(
"Microphone preset", "Microphone preset",
INPUT_PRESETS.map { (preset, label) -> INPUT_PRESETS.map { (preset, label) ->
val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !vm.unprocessedSupported val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !audio.unprocessedSupported
preset to if (unsupported) "$label (not supported here)" else label preset to if (unsupported) "$label (not supported here)" else label
}, },
route.inputPreset(), route.inputPreset(),
) { vm.setRoute(AudioRoute(it, route.usage())) } ) { audio.setRoute(AudioRoute(it, route.usage())) }
Hint(PRESET_HINTS.getValue(route.inputPreset())) Hint(PRESET_HINTS.getValue(route.inputPreset()))
Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp)) Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp))
for ((usage, label) in USAGES) { for ((usage, label) in USAGES) {
Choice(label, route.usage() == usage) { vm.setRoute(AudioRoute(route.inputPreset(), usage)) } Choice(label, route.usage() == usage) { audio.setRoute(AudioRoute(route.inputPreset(), usage)) }
} }
Section("Transmission") Section("Transmission")
@@ -99,11 +99,11 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
change(settings.inputMode, mode) change(settings.inputMode, mode)
} }
} }
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm) if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(audio)
val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC
LevelMeter(level, threshold.takeIf { gated }) LevelMeter(level, threshold.takeIf { gated })
if (!level.live) { if (!level.live) {
Hint(if (vm.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.") Hint(if (sessions.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.")
} }
if (inputMode == Settings.InputMode.VOICE_ACTIVATION) { if (inputMode == Settings.InputMode.VOICE_ACTIVATION) {
@@ -134,7 +134,7 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
val step = it.roundToInt() val step = it.roundToInt()
settings.denoise.set(step > 0) settings.denoise.set(step > 0)
if (step > 0) settings.denoiserLevel.set(step - 1) if (step > 0) settings.denoiserLevel.set(step - 1)
vm.applySettings() sessions.applySettings()
} }
Toggle("Automatic gain control", agc) { Toggle("Automatic gain control", agc) {
agc = it agc = it
@@ -157,7 +157,7 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
Hint("This build of the app came without sound packs.") Hint("This build of the app came without sound packs.")
} else { } else {
Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id -> Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id ->
packs.firstOrNull { it.id() == id }?.let(vm::setSoundPack) packs.firstOrNull { it.id() == id }?.let(audio::setSoundPack)
pack = id pack = id
} }
} }
@@ -210,14 +210,14 @@ private val VAD_MODES = listOf(
/** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */ /** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */
@Composable @Composable
private fun FloatingButtonToggle(vm: SessionController) { private fun FloatingButtonToggle(audio: AudioSetup) {
val context = LocalContext.current val context = LocalContext.current
val enabled by vm.pttOverlay.collectAsStateWithLifecycle() val enabled by audio.pttOverlay.collectAsStateWithLifecycle()
val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (canDrawOverlays(context)) vm.setPttOverlay(true) if (canDrawOverlays(context)) audio.setPttOverlay(true)
} }
Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on -> Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on ->
if (!on || canDrawOverlays(context)) vm.setPttOverlay(on) if (!on || canDrawOverlays(context)) audio.setPttOverlay(on)
else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}"))) else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")))
} }
Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.") Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.")
@@ -43,7 +43,7 @@ internal fun VoiceBar(
/** Whether some server holds the microphone, for push-to-talk to talk on. */ /** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean, captured: Boolean,
talking: Boolean, talking: Boolean,
vm: SessionController, sessions: SessionController,
server: ServerController, server: ServerController,
onEnableMicrophone: () -> Unit, onEnableMicrophone: () -> Unit,
showChat: Boolean, showChat: Boolean,
@@ -56,7 +56,7 @@ internal fun VoiceBar(
BarButton( BarButton(
onClick = { server.setMicMuted(!state.micMuted) }, onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = { onLongClick = {
val mode = vm.toggleInputMode() val mode = sessions.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode." val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode." else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show() Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
@@ -81,7 +81,7 @@ internal fun VoiceBar(
} }
val middle = @Composable { val middle = @Composable {
when { when {
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp)) ptt -> PushToTalk(talking, sessions::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) { !state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null) PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1) Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
@@ -39,8 +39,8 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
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.SessionState import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.WhisperListManager
import eu.lixko.ts3j.client.config.WhisperList import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.net.Whisper import eu.lixko.ts3j.client.net.Whisper
@@ -65,8 +65,8 @@ fun WhisperBanner(state: SessionState, onStop: () -> Unit) {
/** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */ /** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */
@Composable @Composable
fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionState, onManage: () -> Unit) { fun WhisperMenu(whisperLists: WhisperListManager, server: ServerController, state: SessionState, onManage: () -> Unit) {
val lists by vm.whisperLists.collectAsStateWithLifecycle() val lists by whisperLists.all.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) } var open by remember { mutableStateOf(false) }
Box { Box {
IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") } IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") }
@@ -95,8 +95,8 @@ fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionS
/** Picks the whisper list to add something to, or names a new one. */ /** Picks the whisper list to add something to, or names a new one. */
@Composable @Composable
fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { fun AddToWhisperListDialog(whisperLists: WhisperListManager, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) {
val lists by vm.whisperLists.collectAsStateWithLifecycle() val lists by whisperLists.all.collectAsStateWithLifecycle()
var naming by remember { mutableStateOf(false) } var naming by remember { mutableStateOf(false) }
if (naming) { if (naming) {
TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = { TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = {
@@ -123,12 +123,12 @@ fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () ->
/** The saved whisper lists, each opening onto its channels and clients. */ /** The saved whisper lists, each opening onto its channels and clients. */
@Composable @Composable
fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: () -> Unit) { fun WhisperListsScreen(whisperLists: WhisperListManager, server: ServerController, onBack: () -> Unit) {
val lists by vm.whisperLists.collectAsStateWithLifecycle() val lists by whisperLists.all.collectAsStateWithLifecycle()
/** The list being edited: its index, -1 for a new one; null on the overview. */ /** The list being edited: its index, -1 for a new one; null on the overview. */
var editing by rememberSaveable { mutableStateOf<Int?>(null) } var editing by rememberSaveable { mutableStateOf<Int?>(null) }
editing?.let { index -> editing?.let { index ->
WhisperListScreen(vm, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null }) WhisperListScreen(whisperLists, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null })
return return
} }
SubScreen("Whisper lists", onBack = onBack, actions = { SubScreen("Whisper lists", onBack = onBack, actions = {
@@ -156,7 +156,7 @@ fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack:
server.setWhisper(Whisper.of(list)) server.setWhisper(Whisper.of(list))
onBack() onBack()
}) })
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; vm.removeWhisperList(index) }) DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; whisperLists.remove(index) })
} }
} }
}, },
@@ -177,7 +177,7 @@ private fun summary(list: WhisperList): String {
/** One whisper list: its name, channels and clients, saved on Save. */ /** One whisper list: its name, channels and clients, saved on Save. */
@Composable @Composable
private fun WhisperListScreen(vm: SessionController, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) { private fun WhisperListScreen(whisperLists: WhisperListManager, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) {
var name by rememberSaveable { mutableStateOf(saved.name) } var name by rememberSaveable { mutableStateOf(saved.name) }
var list by remember { mutableStateOf(saved.copy()) } var list by remember { mutableStateOf(saved.copy()) }
val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) } val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) }
@@ -186,7 +186,7 @@ private fun WhisperListScreen(vm: SessionController, server: ServerController, i
SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = { SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = {
TextButton(onClick = { TextButton(onClick = {
vm.saveWhisperList(index, list.copy().apply { this.name = name.trim() }) whisperLists.save(index, list.copy().apply { this.name = name.trim() })
onBack() onBack()
}, enabled = name.isNotBlank()) { Text("Save") } }, enabled = name.isNotBlank()) { Text("Save") }
}) { padding -> }) { padding ->
+4 -2
View File
@@ -24,8 +24,10 @@ Items are worked through in the order below. Status: open, done (commit), or clo
| 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 (`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 | | 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 | 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 | | 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | done (`78b66ef`): `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 | in progress, in sub-steps: |
| 11a | … the app-wide stores out of it, and screens on the parts they use | done: `AppParts` wires what lives as long as the process; `BookmarkManager`, `ContactManager`, `WhisperListManager`, `MyTeamSpeakAccount` (sign-in, import, chat attachments) and `AudioSetup` (route, devices, sound packs, floating PTT button) hold what was in `SessionController`, which keeps the servers, the microphone between them and the voice settings (386 lines, with `SessionState` and `SessionEvent`). Leaf screens take only their parts; `App` and the settings hub take `AppParts`. Country flags and description pictures are set on `Settings` directly |
| 11b | … `ServerController` on narrow dependencies instead of the whole `SessionController`, which still forwards the stores to 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 |
| 14 | Core produces English UI copy (status lines, log lines) | open | | 14 | Core produces English UI copy (status lines, log lines) | open |