diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/AppParts.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/AppParts.kt new file mode 100644 index 0000000..609e4d2 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/AppParts.kt @@ -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) +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/AudioSetup.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/AudioSetup.kt new file mode 100644 index 0000000..673a94d --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/AudioSetup.kt @@ -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 = _route + + private val _inputDevices = MutableStateFlow(audio.io().inputDevices()) + val inputDevices: StateFlow> = _inputDevices + private val _outputDevices = MutableStateFlow(audio.io().outputDevices()) + val outputDevices: StateFlow> = _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> = _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 = _pttOverlay + + fun setPttOverlay(enabled: Boolean) { + overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply() + _pttOverlay.value = enabled + } + + private companion object { + const val OVERLAY_ENABLED = "enabled" + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkManager.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkManager.kt new file mode 100644 index 0000000..5c8fa8a --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkManager.kt @@ -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> = _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 = 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) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt index 55c12a1..eaae2ba 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt @@ -39,6 +39,8 @@ import kotlin.math.roundToInt class ConnectionService : LifecycleService() { private lateinit var sessions: SessionController + private lateinit var icons: IconTheme + private lateinit var audio: AudioSetup private lateinit var wifiLock: WifiManager.WifiLock private lateinit var wifiBackgroundLock: WifiManager.WifiLock private lateinit var wakeLock: PowerManager.WakeLock @@ -48,7 +50,10 @@ class ConnectionService : LifecycleService() { override fun 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( NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW) ) @@ -89,15 +94,15 @@ class ConnectionService : LifecycleService() { } } 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 { val owner = sessions.micOwner.flatMapLatest { server -> 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 wanted = enabled && !onScreen && state.connected && state.micActive && state.inputMode == Settings.InputMode.PUSH_TO_TALK @@ -203,7 +208,7 @@ class ConnectionService : LifecycleService() { private fun statusIcon(self: SelfState): Icon { 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 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.createWithBitmap(bitmap) } @@ -212,7 +217,7 @@ class ConnectionService : LifecycleService() { private fun largeIcon(self: SelfState): Icon? { val key = self.iconKey() ?: return null 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) } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ContactManager.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ContactManager.kt new file mode 100644 index 0000000..582b43b --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ContactManager.kt @@ -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> = _all + + init { + // Mutations report on whichever thread made them, a connection thread included. + store.addListener { _all.value = copies() } + } + + private fun copies(): List = 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 = withContext(Dispatchers.IO) { + val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts) + found.size to if (found.isEmpty()) 0 else store.merge(found) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt index e211314..6514a82 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt @@ -126,6 +126,9 @@ class IdentityManager( fun nicknameOf(id: String): String = (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) { settings.defaultIdentityId.set(id) settings.save() diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt index 76fb333..391d363 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt @@ -18,7 +18,7 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent)) setContent { - Ts3Theme { App(sessions) } + Ts3Theme { App((application as Ts3Application).parts) } } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/MyTeamSpeakAccount.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/MyTeamSpeakAccount.kt new file mode 100644 index 0000000..ab5ebfa --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/MyTeamSpeakAccount.kt @@ -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 = _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, chosen: List): 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 = 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) + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt index a16edda..ddcf30d 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt @@ -7,46 +7,23 @@ import android.content.pm.PackageManager import android.net.Uri import android.os.Handler 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.Bookmarks import eu.lixko.ts3j.client.config.IdentityStore import eu.lixko.ts3j.client.config.Setting 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.ChannelFiles import eu.lixko.ts3j.client.session.SelfState import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.session.ServerSession 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 kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update -import kotlinx.coroutines.withContext import java.io.File -import java.io.IOException -import java.io.InputStream import java.util.concurrent.atomic.AtomicInteger /** What the app shows of a connection and the local client on it. */ @@ -75,9 +52,6 @@ data class SessionState( 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. */ sealed interface 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 * the microphone at a time; [Sessions] hands it over. */ -class SessionController(private val context: Context) { - - val settings: Settings = Settings.load() - val icons = IconTheme(context, settings) - private val shortcuts = BookmarkShortcuts(context, icons) - val pictures = WebPictures(context.cacheDir, settings) +class SessionController internal constructor( + private val context: Context, + internal val settings: Settings, + internal val identityStore: IdentityStore, + private val identities: IdentityManager, + private val bookmarks: BookmarkManager, + private val contacts: ContactManager, + private val audioSetup: AudioSetup, + private val myTeamSpeak: MyTeamSpeakAccount, +) { internal val cacheDir: File get() = context.cacheDir internal fun fileTransfers(files: ChannelFiles) = FileTransfers(context, files) - private val bookmarkStore = Bookmarks.load() - internal val identityStore = IdentityStore.load(settings) - 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 audio get() = audioSetup.audio + internal val sounds get() = audioSetup.sounds internal val notifier = MessageNotifier(context) - internal val contactStore = ContactStore.load() - /** The reasons offered when adding a ban; shared by every server. */ - val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() } + internal val contactStore get() = contacts.store + internal val attachments get() = myTeamSpeak.attachments + internal suspend fun openShared(uri: Uri) = myTeamSpeak.openShared(uri) internal val network = NetworkFollower(context) private val main = Handler(Looper.getMainLooper()) @@ -134,13 +106,6 @@ class SessionController(private val context: Context) { private val _lastEnd = MutableStateFlow(null) val lastEnd: StateFlow = _lastEnd - /** Copies of the contacts, as the store's own entries change in place. */ - private val _contacts = MutableStateFlow(contactCopies()) - val contacts: StateFlow> = _contacts - - private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList()) - val bookmarks: StateFlow> = _bookmarks - private val _events = MutableSharedFlow(extraBufferCapacity = 16) val events: SharedFlow = _events @@ -162,36 +127,13 @@ class SessionController(private val context: Context) { @Volatile private var watchingLevel = false - private val routePrefs = AudioRoutePrefs(context) - private val _route = MutableStateFlow(routePrefs.load()) - val route: StateFlow = _route - - val swipe = SwipePrefs(context) - - private val _inputDevices = MutableStateFlow(audio.io().inputDevices()) - val inputDevices: StateFlow> = _inputDevices - private val _outputDevices = MutableStateFlow(audio.io().outputDevices()) - val outputDevices: StateFlow> = _outputDevices - - val unprocessedSupported: Boolean get() = audio.unprocessedSupported() - 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. - contactStore.addListener { - _contacts.value = contactCopies() - _servers.value.forEach(ServerController::contactsChanged) - } + contactStore.addListener { _servers.value.forEach(ServerController::contactsChanged) } Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer) 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() // ---- connection ---- @@ -221,7 +163,7 @@ class SessionController(private val context: Context) { private fun start(connect: (ServerController) -> Unit) { val server = ServerController(nextId.incrementAndGet(), this) - server.session.setMyTeamSpeakLogin(myTeamSpeak) + server.session.setMyTeamSpeakLogin(myTeamSpeak.login) sessions.add(server.session) _servers.update { it + server } _current.value = server @@ -236,8 +178,7 @@ class SessionController(private val context: Context) { */ fun open(link: ServerLink, identityId: String = "") { if (link.bookmarkLabel.isNotEmpty()) { - bookmarkStore.add(link.toBookmark()) - saveBookmarks() + bookmarks.add(link.toBookmark()) } val on = _servers.value.firstOrNull { it.session.isOn(link) } 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. */ fun openBookmark(id: String): ServerLink? { - val bookmark = bookmarkStore.find(id) + val bookmark = bookmarks.find(id) if (bookmark == null) { error("That bookmark no longer exists") return null @@ -265,7 +206,7 @@ class SessionController(private val context: Context) { fun connectStartupBookmarks(opened: ServerLink?) { if (startedUp) return 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) } } } @@ -327,29 +268,12 @@ class SessionController(private val context: Context) { 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. */ - fun newBookmark(address: String, nickname: String, password: String, identityId: String): 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 } - } + /** A saved bookmark changed; the servers connected with it take on what applies at once. */ + internal fun bookmarkEdited(bookmark: Bookmark) = _servers.value.forEach { it.bookmarkEdited(bookmark) } - /** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */ - 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) } - } + internal fun serverIconChanged(address: String, port: Int, iconId: Long) = bookmarks.serverIconChanged(address, port, iconId) /** The channels of a server we are on at [host]:[port], to pick one to join. */ fun channelPathsAt(host: String, port: Int): List = 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. */ fun currentChannelAt(host: String, port: Int): String? = sessions.connectedTo(host, port)?.currentChannelPath() - fun removeBookmark(bookmark: Bookmark) { - val index = bookmarkStore.all().indexOf(bookmark) - 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> = _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 = 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 = 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 = _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 = 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, chosen: List): 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> = _soundPacks - - val soundPack: SoundPack? get() = sounds.pack() - - fun setCountryFlags(shown: Boolean) { - settings.countryFlags.set(shown) - settings.save() - } + /** Signed in or out of myTeamSpeak. */ + internal fun myTeamSpeakChanged() = _servers.value.forEach { it.session.updateMyTeamSpeak() } /** Puts new client row colours, already set in [settings], into effect. */ fun clientRowColorsChanged() { @@ -545,23 +290,6 @@ class SessionController(private val context: Context) { 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 ---- fun hasMicPermission() = @@ -588,16 +316,6 @@ class SessionController(private val context: Context) { 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 = _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. */ fun toggleInputMode(): Settings.InputMode { 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. */ private fun applyOutputSettings() { - soundPlayer.setOutputDevice(settings.outputDevice.get()) for (server in _servers.value) { server.playback?.setMasterVolume(settings.outputVolume.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]. */ fun watchLevel(on: Boolean) { watchingLevel = on @@ -665,7 +375,6 @@ class SessionController(private val context: Context) { companion object { const val DEFAULT_PORT = 9987 - private const val OVERLAY_ENABLED = "enabled" /** `host[:port]` as typed, the port defaulting to TeamSpeak's. */ fun parseAddress(address: String): Pair { diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt index ba7912c..3275f06 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt @@ -5,14 +5,16 @@ import eu.lixko.ts3j.client.config.AppDirs class Ts3Application : Application() { - lateinit var sessions: SessionController + lateinit var parts: AppParts private set + val sessions: SessionController get() = parts.sessions + override fun onCreate() { super.onCreate() // Before any store loads: there is no home directory to find them in. AppDirs.init(filesDir, filesDir.toPath().resolve("chats")) - sessions = SessionController(this) - Thread(sessions::installSoundPacks, "sound-packs").start() + parts = AppParts(this) + Thread(parts.audio::installSoundPacks, "sound-packs").start() } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/WhisperListManager.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/WhisperListManager.kt new file mode 100644 index 0000000..b8b320f --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/WhisperListManager.kt @@ -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> = _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() + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt index 851c149..8c28263 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt @@ -21,13 +21,14 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext 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.TreeSwipe @Composable -fun App(vm: SessionController) { - val current by vm.current.collectAsStateWithLifecycle() +fun App(parts: AppParts) { + val sessions = parts.sessions + val current by sessions.current.collectAsStateWithLifecycle() // Each server keeps its own screen state (chat open, conversation) while another is shown. val serverStates = rememberSaveableStateHolder() var connectOpen by rememberSaveable { mutableStateOf(false) } @@ -41,8 +42,8 @@ fun App(vm: SessionController) { var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf(null) } var poke by remember { mutableStateOf(null) } - LaunchedEffect(vm) { - vm.events.collect { event -> + LaunchedEffect(sessions) { + sessions.events.collect { event -> when (event) { is SessionEvent.Poke -> poke = event is SessionEvent.Error -> snackbar.showSnackbar(event.message) @@ -59,7 +60,7 @@ fun App(vm: SessionController) { val context = LocalContext.current 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) = names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } @@ -72,7 +73,7 @@ fun App(vm: SessionController) { if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray()) } 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)) } @@ -82,21 +83,21 @@ fun App(vm: SessionController) { 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 bookmark = editingBookmark when { - bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null }) - contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId -> + bookmark != null -> BookmarkScreen(sessions, parts.bookmarks, parts.identities, bookmark, onDone = { editingBookmark = null }) + contactsOpen -> ContactsScreen(parts.contacts, editingContact, onEdit = { uniqueId -> if (uniqueId == null && contactDirect) contactsOpen = false contactDirect = false editingContact = uniqueId }, onBack = { contactsOpen = false }) - myTeamSpeakOpen -> MyTeamSpeakScreen(vm, onBack = { myTeamSpeakOpen = false }) - settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false }) + myTeamSpeakOpen -> MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { myTeamSpeakOpen = false }) + settingsOpen -> SettingsScreen(parts, onContacts = { openContacts(null) }, onBack = { settingsOpen = false }) server != null && !connectOpen -> { - val servers by vm.servers.collectAsStateWithLifecycle() - val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle() + val servers by sessions.servers.collectAsStateWithLifecycle() + val treeSwipe by parts.swipe.tree.collectAsStateWithLifecycle() val serverSwipe = rememberSwipeState() SwipeHost( serverSwipe, server, @@ -104,13 +105,13 @@ fun App(vm: SessionController) { if (treeSwipe != TreeSwipe.SERVERS) null else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) } }, - onSwipe = vm::select, + onSwipe = sessions::select, modifier = Modifier.fillMaxSize(), ) { shown -> serverStates.SaveableStateProvider(shown.id) { CompositionLocalProvider(LocalServerImages provides shown.images) { 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 }, 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 }, onBack = if (current != null) ({ connectOpen = false }) else null) } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt index 0df1677..7709d91 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt @@ -17,13 +17,13 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.MyTeamSpeakAccount import eu.lixko.ts3j.client.android.ServerController -import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.chat.ChatKey import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.myts.MyTsException -import kotlinx.coroutines.launch 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. */ class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit) @@ -34,15 +34,16 @@ class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit) */ @Composable fun rememberAttachmentActions( - vm: SessionController, + account: MyTeamSpeakAccount, server: ServerController, snackbar: SnackbarHostState, shown: ChatKey, ): AttachmentActions { val scope = rememberCoroutineScope() - val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() + val signedIn by account.signedIn.collectAsStateWithLifecycle() val key by rememberUpdatedState(shown) val viewer = LocalPictureViewer.current + val pictures = LocalWebPictures.current val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } var saving by rememberSaveable { mutableStateOf(null) } @@ -52,7 +53,7 @@ fun rememberAttachmentActions( if (uri == null || ref == null) return@rememberLauncherForActivityResult scope.launch { val error = try { - vm.saveAttachment(ref, uri) + account.saveAttachment(ref, uri) null } catch (e: MyTsException) { e.message @@ -72,7 +73,7 @@ fun rememberAttachmentActions( when { !signedIn -> tell(SIGN_IN) 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 -> { saving = href diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt index e9476b8..766d5ca 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt @@ -1,7 +1,7 @@ package eu.lixko.ts3j.client.android.ui -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row 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.unit.dp 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.config.Bookmark @@ -64,9 +66,9 @@ val BookmarkEditSaver = listSaver( /** Every setting of one bookmark, saved only on Save. */ @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 identities by vm.identities.all.collectAsStateWithLifecycle() + val identities by identityManager.all.collectAsStateWithLifecycle() var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) } var address by rememberSaveable { 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 (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.address = host it.port = port @@ -114,12 +116,12 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) IdentityField(identities, identityId) { identityId = it } 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) { - SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) } + SessionController.parseAddress(address).let { (host, port) -> sessions.channelPathsAt(host, port) } } 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 } OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(), diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt index dd1593a..be62ede 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt @@ -5,6 +5,7 @@ import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.itemsIndexed import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.layout.Box import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.Button import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults -import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.Icon -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem 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.buildAnnotatedString 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.PasswordVisualTransformation +import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp 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.IdentityManager +import eu.lixko.ts3j.client.android.MyTeamSpeakAccount import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.net.IconRepository @@ -64,7 +67,10 @@ import eu.lixko.ts3j.client.net.IconRepository @OptIn(ExperimentalMaterial3Api::class) @Composable fun ConnectScreen( - vm: SessionController, + sessions: SessionController, + bookmarkManager: BookmarkManager, + identityManager: IdentityManager, + account: MyTeamSpeakAccount, snackbar: SnackbarHostState, onSettings: () -> Unit, onMyTeamSpeak: () -> Unit, @@ -73,13 +79,13 @@ fun ConnectScreen( /** Back to the servers already connected; null when there are none. */ onBack: (() -> Unit)?, ) { - val lastEnd by vm.lastEnd.collectAsStateWithLifecycle() - val bookmarks by vm.bookmarks.collectAsStateWithLifecycle() - val identities by vm.identities.all.collectAsStateWithLifecycle() - val myTeamSpeakSignedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() - var address by rememberSaveable { mutableStateOf(vm.lastAddress) } + val lastEnd by sessions.lastEnd.collectAsStateWithLifecycle() + val bookmarks by bookmarkManager.all.collectAsStateWithLifecycle() + val identities by identityManager.all.collectAsStateWithLifecycle() + val myTeamSpeakSignedIn by account.signedIn.collectAsStateWithLifecycle() + var address by rememberSaveable { mutableStateOf(sessions.lastAddress) } var identityId by rememberSaveable { mutableStateOf("") } - var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) } + var nickname by rememberSaveable { mutableStateOf(identityManager.nicknameFor("")) } var password by rememberSaveable { mutableStateOf("") } if (onBack != null) BackHandler(onBack = onBack) @@ -115,18 +121,18 @@ fun ConnectScreen( keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) IdentityField(identities, identityId) { identityId = it - nickname = vm.nicknameFor(it) + nickname = identityManager.nicknameFor(it) } lastEnd?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { 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(), ) { Text("Connect") } 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") } } } @@ -144,10 +150,10 @@ fun ConnectScreen( } } itemsIndexed(bookmarks) { index, bookmark -> - BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } }, + BookmarkRow(bookmark, identities, { onConnect { sessions.connect(bookmark) } }, onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) }, - onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null, - onRemove = { vm.removeBookmark(bookmark) }) + onPin = if (bookmarkManager.canPinShortcuts) ({ bookmarkManager.pinShortcut(bookmark) }) else null, + onRemove = { bookmarkManager.remove(bookmark) }) } } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt index c4ec3fd..beb3696 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt @@ -40,14 +40,14 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp 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.ContactDefaults import eu.lixko.ts3j.client.contacts.ContactType import eu.lixko.ts3j.client.contacts.NicknameDisplay -import kotlinx.coroutines.launch import java.time.format.DateTimeFormatter import kotlin.math.roundToInt +import kotlinx.coroutines.launch 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 */ @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) } when { - editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) }) - defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false }) + editing != null -> return ContactScreen(contacts, editing, onBack = { onEdit(null) }) + defaults -> return ContactDefaultsScreen(contacts, onBack = { defaults = false }) } - val contacts by vm.contacts.collectAsStateWithLifecycle() + val all by contacts.all.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() var menu by remember { mutableStateOf(false) } var imported by remember { mutableStateOf(null) } val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) scope.launch { - imported = runCatching { vm.importContacts(uri) }.fold( + imported = runCatching { contacts.import(uri) }.fold( { (found, added) -> if (found == 0) "That file holds no contacts." else "Imported $found contacts, $added of them new." @@ -107,14 +107,14 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> }) { padding -> LazyColumn(Modifier.padding(padding)) { imported?.let { item { Hint(it) } } - if (contacts.isEmpty()) { + if (all.isEmpty()) { item { 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.") } } 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 item(key = type) { Section(title) } 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. */ @Composable -private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) { - val contacts by vm.contacts.collectAsStateWithLifecycle() +private fun ContactScreen(contacts: ContactManager, uniqueId: String, onBack: () -> Unit) { + val all by contacts.all.collectAsStateWithLifecycle() // 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 contact = contacts.firstOrNull { it.key() == key } + val key = remember(uniqueId) { contacts.find(uniqueId)?.key() ?: uniqueId } + val contact = all.firstOrNull { it.key() == key } if (contact == null) { LaunchedEffect(Unit) { onBack() } return } // Starts from the stored entry, which may have been seen again since this page opened. 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 phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) } @@ -211,7 +211,7 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> confirmButton = { TextButton(onClick = { removing = false - vm.removeContact(key) + contacts.remove(key) onBack() }) { 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. */ @Composable -private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) { - val defaults = vm.settings.contactDefaults +private fun ContactDefaultsScreen(contacts: ContactManager, onBack: () -> Unit) { + val defaults = contacts.defaults var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) } var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) } fun edit(change: ContactDefaults.Entry.() -> Unit) { val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() } defaults.of(tab).copyFrom(changed) - vm.settings.save() + contacts.saveDefaults() entry = changed } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt index e056b8a..fed2e2d 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt @@ -42,18 +42,18 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.style.TextOverflow 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.myts.AccountInfo import eu.lixko.ts3j.client.myts.MyTeamSpeak import eu.lixko.ts3j.client.myts.MyTsException import eu.lixko.ts3j.client.teamspeak.SyncItem import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter -import kotlinx.coroutines.launch import java.io.IOException import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.format.FormatStyle +import kotlinx.coroutines.launch 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) @Composable -fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { - val login = vm.myTeamSpeak +fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) { + val login = account.login val scope = rememberCoroutineScope() var signedIn by remember { mutableStateOf(login.isSignedIn) } var busy by remember { mutableStateOf(false) } @@ -77,11 +77,11 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { var rows by remember { mutableStateOf(emptyList()) } BackHandler(onBack = onBack) - fun show(account: MyTeamSpeak.Account) { - info = account.info() - all = account.items() + fun show(fetched: MyTeamSpeak.Account) { + info = fetched.info() + all = fetched.items() 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) } 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) { - if (signedIn) work { show(vm.fetchMyTeamSpeak()) } + if (signedIn) work { show(account.fetch()) } } Scaffold( @@ -118,7 +118,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, actions = { if (signedIn) { - IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) { + IconButton(onClick = { work { show(account.fetch()) } }, enabled = !busy) { PackIcon("REFRESH", "Refresh") } } @@ -146,7 +146,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { Button( onClick = { work { - show(vm.signInMyTeamSpeak(email.trim(), password)) + show(account.signIn(email.trim(), password)) password = "" } }, @@ -163,7 +163,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { color = MaterialTheme.colorScheme.onSurfaceVariant) } OutlinedButton(onClick = { - scope.launch { vm.signOutMyTeamSpeak() } + scope.launch { account.signOut() } signedIn = false rows = emptyList() all = emptyList() @@ -219,8 +219,8 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { Button( onClick = { work { - val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item }) - rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) } + val r = account.import(all, rows.filter { it.selected }.map { it.item }) + rows = rows.map { it.copy(imported = account.isImported(it.item), selected = false) } message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " + "${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " + "${count(r.contactsAdded(), "contact", "contacts")}." diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt index 16de6cf..b2ea249 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt @@ -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. */ @Composable -fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { - val settings = vm.settings +fun NetworkSettingsScreen(settings: Settings, sessions: SessionController, onBack: () -> Unit) { fun change(setting: Setting, value: T) { setting.set(value) - vm.applySettings() + sessions.applySettings() } var vbr by remember { mutableStateOf(settings.vbr.get()) } var fec by remember { mutableStateOf(settings.fec.get()) } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt index 86ef61d..bc60b0a 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt @@ -31,8 +31,8 @@ import kotlinx.coroutines.flow.MutableStateFlow internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean) @Composable -internal fun rememberPttTarget(vm: SessionController): PttTarget { - val owner by vm.micOwner.collectAsStateWithLifecycle() +internal fun rememberPttTarget(sessions: SessionController): PttTarget { + val owner by sessions.micOwner.collectAsStateWithLifecycle() val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle() val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle() 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. */ @Composable -fun GiantPttScreen(vm: SessionController, onBack: () -> Unit) { - val target = rememberPttTarget(vm) +fun GiantPttScreen(sessions: SessionController, onBack: () -> Unit) { + val target = rememberPttTarget(sessions) SubScreen("Giant PTT", onBack) { padding -> val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp) 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) } else { Box(fill, contentAlignment = Alignment.Center) { diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerOverlay.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerOverlay.kt index 1b5f84d..7d014f3 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerOverlay.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerOverlay.kt @@ -13,8 +13,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import eu.lixko.ts3j.client.android.ChannelItem import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerTree -import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionState +import eu.lixko.ts3j.client.android.WhisperListManager import kotlinx.coroutines.launch /** Joins [channel], asking for its password first when it is locked. */ @@ -26,7 +26,7 @@ internal fun ServerNav.join(server: ServerController, channel: ChannelItem) { @Composable internal fun ServerOverlay( nav: ServerNav, - vm: SessionController, + whisperLists: WhisperListManager, server: ServerController, state: SessionState, tree: ServerTree, @@ -159,9 +159,9 @@ internal fun ServerOverlay( 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() - vm.addToWhisperList(index, newName, o.add) + whisperLists.addTo(index, newName, o.add) } } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt index 5782823..cf4e0e6 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt @@ -30,10 +30,14 @@ import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect 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.SessionController +import eu.lixko.ts3j.client.android.SwipePrefs 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.config.BanReasonPresets import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.text.TsLink @@ -42,7 +46,11 @@ import eu.lixko.ts3j.client.text.TsLink @OptIn(ExperimentalMaterial3Api::class) @Composable fun ServerScreen( - vm: SessionController, + sessions: SessionController, + whisperLists: WhisperListManager, + account: MyTeamSpeakAccount, + swipe: SwipePrefs, + banReasons: BanReasonPresets, server: ServerController, snackbar: SnackbarHostState, onSettings: () -> Unit, @@ -70,8 +78,8 @@ fun ServerScreen( val conversation by conversationState val picking = rememberTreePicking(server, treeState, sessionState) - val treeSwipe by vm.swipe.tree.collectAsStateWithLifecycle() - val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle() + val treeSwipe by swipe.tree.collectAsStateWithLifecycle() + val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle() // The chat lies to the right of the tree. val chatBesideTree = treeSwipe == TreeSwipe.CHAT val pageSwipe = rememberSwipeState() @@ -90,12 +98,12 @@ fun ServerScreen( } 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 ref = TsLink.parse(href) when { 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.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false) else -> nav.overlay = Overlay.Channel(ref.id) @@ -111,8 +119,8 @@ fun ServerScreen( when (val page = nav.page) { ServerPage.Main -> {} - ServerPage.BanList -> return BanListScreen(server, vm.banReasons, onBack = nav::back) - ServerPage.WhisperLists -> return WhisperListsScreen(vm, server, onBack = nav::back) + ServerPage.BanList -> return BanListScreen(server, banReasons, 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.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) @@ -140,11 +148,11 @@ fun ServerScreen( } } else { TopAppBar( - title = { ServerSwitcher(vm, server, state, onConnectOther) }, + title = { ServerSwitcher(sessions, server, state, onConnectOther) }, expandedHeight = 48.dp, actions = { 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 = onSettings) { PackIcon("SETTINGS", "Settings") } }, @@ -153,9 +161,9 @@ fun ServerScreen( }, bottomBar = { Column { - val ptt = rememberPttTarget(vm) + val ptt = rememberPttTarget(sessions) 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 } } @@ -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) } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerSwitcher.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerSwitcher.kt index d7738b5..c6bcc29 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerSwitcher.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerSwitcher.kt @@ -46,8 +46,8 @@ private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) /** The server on screen, opening onto the others and connecting to another. */ @Composable -internal fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) { - val servers by vm.servers.collectAsStateWithLifecycle() +internal fun ServerSwitcher(sessions: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) { + val servers by sessions.servers.collectAsStateWithLifecycle() var open by remember { mutableStateOf(false) } Box(Modifier.fillMaxWidth()) { 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() DropdownMenuItem( text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - onClick = { open = false; vm.select(other) }, + onClick = { open = false; sessions.select(other) }, leadingIcon = { ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f)) }, diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt index 9769bcd..21a9d8f 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt @@ -16,9 +16,12 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier 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.SessionController +import eu.lixko.ts3j.client.android.SwipePrefs import eu.lixko.ts3j.client.android.TreeSwipe +import eu.lixko.ts3j.client.config.Settings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch 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. */ @Composable -fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) { +fun SettingsScreen(parts: AppParts, onContacts: () -> Unit, onBack: () -> Unit) { var page by rememberSaveable { mutableStateOf(null) } when (page) { - SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null }) - SettingsPage.NETWORK -> return NetworkSettingsScreen(vm, onBack = { page = null }) - SettingsPage.GIANT_PTT -> return GiantPttScreen(vm, onBack = { page = null }) - SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null }) - SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null }) - SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null }) + SettingsPage.SOUND -> return SoundSettingsScreen(parts.settings, parts.sessions, parts.audio, onBack = { page = null }) + SettingsPage.NETWORK -> return NetworkSettingsScreen(parts.settings, parts.sessions, onBack = { page = null }) + SettingsPage.GIANT_PTT -> return GiantPttScreen(parts.sessions, onBack = { page = null }) + SettingsPage.DESIGN -> return DesignScreen(parts.settings, parts.icons, parts.swipe, parts.sessions, onBack = { page = null }) + SettingsPage.IDENTITIES -> return IdentitiesScreen(parts.identities, onBack = { page = null }) + SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { page = null }) null -> {} } @@ -60,7 +63,7 @@ fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> LinkRow("Identities", "Create, import, export, security level", "IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES } 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", "MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK } } @@ -68,49 +71,51 @@ fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> } @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 -> Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { - IconPackPicker(vm.icons) - var pictures by remember { mutableStateOf(vm.settings.descriptionPictures.get()) } + IconPackPicker(icons) + var pictures by remember { mutableStateOf(settings.descriptionPictures.get()) } Toggle("Show pictures in descriptions", pictures) { pictures = it - vm.setDescriptionPictures(it) + settings.descriptionPictures.set(it) + settings.save() } 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) { 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 talking by remember { mutableIntStateOf(colors.talking) } var mutedAway by remember { mutableIntStateOf(colors.mutedAway) } RowColorPicker("Client background", any) { any = it colors.any = it - vm.clientRowColorsChanged() + sessions.clientRowColorsChanged() } RowColorPicker("While talking", talking) { talking = it colors.talking = it - vm.clientRowColorsChanged() + sessions.clientRowColorsChanged() } RowColorPicker("Muted / away", mutedAway) { 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( TreeSwipe.OFF to "Off", TreeSwipe.CHAT to "Channel tree and chat", TreeSwipe.SERVERS to "Connected servers", - ), treeSwipe, vm.swipe::setTree) + ), treeSwipe, swipe::setTree) Section("Chat") - val chatTabSwipe by vm.swipe.chatTabs.collectAsStateWithLifecycle() - Toggle("Swipe between chat tabs", chatTabSwipe, vm.swipe::setChatTabs) + val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle() + Toggle("Swipe between chat tabs", chatTabSwipe, swipe::setChatTabs) } } } @@ -134,4 +139,3 @@ private fun IconPackPicker(theme: IconTheme) { } failed?.let { Hint(it) } } - diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt index 333e061..d23dd23 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt @@ -30,6 +30,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleStartEffect 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.SessionController 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. */ @Composable -fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { - val settings = vm.settings +fun SoundSettingsScreen(settings: Settings, sessions: SessionController, audio: AudioSetup, onBack: () -> Unit) { fun change(setting: Setting, value: T) { setting.set(value) - vm.applySettings() + sessions.applySettings() } var inputMode by remember { mutableStateOf(settings.inputMode.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 inputDevice by remember { mutableStateOf(settings.inputDevice.get()) } var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) } - val inputs by vm.inputDevices.collectAsStateWithLifecycle() - val outputs by vm.outputDevices.collectAsStateWithLifecycle() - val route by vm.route.collectAsStateWithLifecycle() - val level by vm.micLevel.collectAsStateWithLifecycle() - val packs by vm.soundPacks.collectAsStateWithLifecycle() - var pack by remember { mutableStateOf(vm.soundPack?.id()) } + val inputs by audio.inputDevices.collectAsStateWithLifecycle() + val outputs by audio.outputDevices.collectAsStateWithLifecycle() + val route by audio.route.collectAsStateWithLifecycle() + val level by sessions.micLevel.collectAsStateWithLifecycle() + val packs by audio.soundPacks.collectAsStateWithLifecycle() + var pack by remember { mutableStateOf(audio.soundPack?.id()) } LifecycleStartEffect(Unit) { - vm.watchLevel(true) - onStopOrDispose { vm.watchLevel(false) } + sessions.watchLevel(true) + onStopOrDispose { sessions.watchLevel(false) } } SubScreen("Sound Settings", onBack) { padding -> @@ -81,15 +81,15 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { Picker( "Microphone preset", 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 }, route.inputPreset(), - ) { vm.setRoute(AudioRoute(it, route.usage())) } + ) { audio.setRoute(AudioRoute(it, route.usage())) } Hint(PRESET_HINTS.getValue(route.inputPreset())) Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp)) 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") @@ -99,11 +99,11 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { 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 LevelMeter(level, threshold.takeIf { gated }) 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) { @@ -134,7 +134,7 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { val step = it.roundToInt() settings.denoise.set(step > 0) if (step > 0) settings.denoiserLevel.set(step - 1) - vm.applySettings() + sessions.applySettings() } Toggle("Automatic gain control", agc) { agc = it @@ -157,7 +157,7 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { Hint("This build of the app came without sound packs.") } else { 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 } } @@ -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. */ @Composable -private fun FloatingButtonToggle(vm: SessionController) { +private fun FloatingButtonToggle(audio: AudioSetup) { val context = LocalContext.current - val enabled by vm.pttOverlay.collectAsStateWithLifecycle() + val enabled by audio.pttOverlay.collectAsStateWithLifecycle() 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 -> - 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}"))) } Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.") diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/VoiceBar.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/VoiceBar.kt index 61917ce..e29aa33 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/VoiceBar.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/VoiceBar.kt @@ -43,7 +43,7 @@ internal fun VoiceBar( /** Whether some server holds the microphone, for push-to-talk to talk on. */ captured: Boolean, talking: Boolean, - vm: SessionController, + sessions: SessionController, server: ServerController, onEnableMicrophone: () -> Unit, showChat: Boolean, @@ -56,7 +56,7 @@ internal fun VoiceBar( BarButton( onClick = { server.setMicMuted(!state.micMuted) }, onLongClick = { - val mode = vm.toggleInputMode() + val mode = sessions.toggleInputMode() val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode." else "Switched to voice activation mode." Toast.makeText(context, text, Toast.LENGTH_SHORT).show() @@ -81,7 +81,7 @@ internal fun VoiceBar( } val middle = @Composable { 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) { PackIcon("CAPTURE", null) Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt index cfd1904..e0b4879 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt @@ -39,8 +39,8 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import eu.lixko.ts3j.client.android.ServerController -import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionState +import eu.lixko.ts3j.client.android.WhisperListManager import eu.lixko.ts3j.client.config.WhisperList 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. */ @Composable -fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionState, onManage: () -> Unit) { - val lists by vm.whisperLists.collectAsStateWithLifecycle() +fun WhisperMenu(whisperLists: WhisperListManager, server: ServerController, state: SessionState, onManage: () -> Unit) { + val lists by whisperLists.all.collectAsStateWithLifecycle() var open by remember { mutableStateOf(false) } Box { 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. */ @Composable -fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { - val lists by vm.whisperLists.collectAsStateWithLifecycle() +fun AddToWhisperListDialog(whisperLists: WhisperListManager, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { + val lists by whisperLists.all.collectAsStateWithLifecycle() var naming by remember { mutableStateOf(false) } if (naming) { 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. */ @Composable -fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: () -> Unit) { - val lists by vm.whisperLists.collectAsStateWithLifecycle() +fun WhisperListsScreen(whisperLists: WhisperListManager, server: ServerController, onBack: () -> Unit) { + val lists by whisperLists.all.collectAsStateWithLifecycle() /** The list being edited: its index, -1 for a new one; null on the overview. */ var editing by rememberSaveable { mutableStateOf(null) } 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 } SubScreen("Whisper lists", onBack = onBack, actions = { @@ -156,7 +156,7 @@ fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: server.setWhisper(Whisper.of(list)) 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. */ @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 list by remember { mutableStateOf(saved.copy()) } 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 = { TextButton(onClick = { - vm.saveWhisperList(index, list.copy().apply { this.name = name.trim() }) + whisperLists.save(index, list.copy().apply { this.name = name.trim() }) onBack() }, enabled = name.isNotBlank()) { Text("Save") } }) { padding -> diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md index 4c1ac70..5d0d999 100644 --- a/ts3-client/AUDIT-STRUCTURE.md +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -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 | | 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 | -| 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | done: `ServerNav` holds where the screen is (one saved `ServerPage` for the five pages that replace it, tree or chat, the conversation, and one `Overlay` for the eight sheets and dialogs); `TreeView` and `ChatSearch` the find state of each side; `TreePicking` the long-press selection and moves. The sheets and dialogs are `ServerOverlay`; `VoiceBar` and `ServerSwitcher` have their own files. Only one sheet or dialog shows at a time, so a channel link in a client sheet now replaces it; Find in tree from a sheet honours Only matches; a failed channel deletion's snackbar is no longer cancelled with its dialog | -| 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | open | +| 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 | 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 | | 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 |