Compare commits
221
Commits
v1.0.0
...
f78e4fcd66
@@ -0,0 +1,20 @@
|
|||||||
|
name: test
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: true
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 25
|
||||||
|
cache: maven
|
||||||
|
# Builds ts3j from the submodule along with the client; no test needs a display or libopus.
|
||||||
|
- run: mvn -B -f ts3-client/pom.xml verify
|
||||||
+15
-1
@@ -4,11 +4,15 @@ build/
|
|||||||
out/
|
out/
|
||||||
*.class
|
*.class
|
||||||
|
|
||||||
# The bundled proprietary TeamSpeak 3 client (reference binary, not our source)
|
# Bundled proprietary TeamSpeak clients (reference binaries, not our source)
|
||||||
/TeamSpeak3-Client-linux_amd64/
|
/TeamSpeak3-Client-linux_amd64/
|
||||||
|
/ts6/
|
||||||
|
/ts6-server/
|
||||||
|
/re-android/
|
||||||
|
|
||||||
# Packages
|
# Packages
|
||||||
*.jar
|
*.jar
|
||||||
|
!android/gradle/wrapper/gradle-wrapper.jar
|
||||||
*.war
|
*.war
|
||||||
*.zip
|
*.zip
|
||||||
*.tar.gz
|
*.tar.gz
|
||||||
@@ -34,3 +38,13 @@ release.properties
|
|||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
# Android / Gradle
|
||||||
|
android/.gradle/
|
||||||
|
android/.kotlin/
|
||||||
|
android/**/.cxx/
|
||||||
|
android/local.properties
|
||||||
|
|
||||||
|
# Release signing (keystore.properties points at the key)
|
||||||
|
android/keystore.properties
|
||||||
|
*.jks
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import java.util.Properties
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.compose)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Puts the sound packs of an installed TeamSpeak 3 client into the app's assets, as the
|
||||||
|
* desktop client borrows them from the installation, with the sounds encoded as Opus
|
||||||
|
* (a fifteenth of the WAVs). They are TeamSpeak's and not in the repository; a build
|
||||||
|
* without the client ships no packs.
|
||||||
|
*/
|
||||||
|
abstract class BundleSoundPacks : DefaultTask() {
|
||||||
|
@get:InputFiles
|
||||||
|
@get:PathSensitive(PathSensitivity.RELATIVE)
|
||||||
|
abstract val packs: DirectoryProperty
|
||||||
|
|
||||||
|
/** The desktop code whose libopus does the encoding. */
|
||||||
|
@get:Classpath
|
||||||
|
abstract val encoder: ConfigurableFileCollection
|
||||||
|
|
||||||
|
@get:OutputDirectory
|
||||||
|
abstract val assets: DirectoryProperty
|
||||||
|
|
||||||
|
@get:Inject
|
||||||
|
abstract val exec: ExecOperations
|
||||||
|
|
||||||
|
@TaskAction
|
||||||
|
fun encode() {
|
||||||
|
val out = assets.get().asFile
|
||||||
|
out.deleteRecursively()
|
||||||
|
val source = packs.get().asFile
|
||||||
|
if (!source.isDirectory) {
|
||||||
|
logger.warn("No TeamSpeak 3 sound packs at $source; the app ships without sounds")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exec.javaexec {
|
||||||
|
classpath = encoder
|
||||||
|
mainClass.set("eu.lixko.ts3j.client.audio.desktop.EncodeSoundPacks")
|
||||||
|
jvmArgs("--enable-native-access=ALL-UNNAMED")
|
||||||
|
args(source.path, File(out, "sound").path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val soundPackEncoder: Configuration by configurations.creating {
|
||||||
|
isCanBeConsumed = false
|
||||||
|
attributes {
|
||||||
|
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
|
||||||
|
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val ts3ClientDir: String = providers.gradleProperty("ts3.client.dir")
|
||||||
|
.orElse(providers.environmentVariable("TS3_CLIENT_DIR"))
|
||||||
|
.getOrElse(rootDir.resolve("../TeamSpeak3-Client-linux_amd64").path)
|
||||||
|
|
||||||
|
val bundleSoundPacks = tasks.register<BundleSoundPacks>("bundleSoundPacks") {
|
||||||
|
packs.set(File(ts3ClientDir, "sound"))
|
||||||
|
encoder.from(soundPackEncoder)
|
||||||
|
assets.set(layout.buildDirectory.dir("generated/soundPacks"))
|
||||||
|
}
|
||||||
|
|
||||||
|
androidComponents {
|
||||||
|
onVariants { variant ->
|
||||||
|
variant.sources.assets?.addGeneratedSourceDirectory(bundleSoundPacks, BundleSoundPacks::assets)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Release signing from keystore.properties (storeFile, storePassword, keyAlias, keyPassword),
|
||||||
|
* kept out of the repository; without it the release APK is left unsigned.
|
||||||
|
*/
|
||||||
|
val releaseKeystore = rootDir.resolve("keystore.properties").takeIf { it.isFile }?.let { file ->
|
||||||
|
Properties().apply { file.inputStream().use(::load) }
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "eu.lixko.ts3j.client.android"
|
||||||
|
compileSdk = 37
|
||||||
|
ndkVersion = "30.0.16248370"
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "eu.lixko.ts3j.client"
|
||||||
|
minSdk = 33
|
||||||
|
targetSdk = 36
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "0.1.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
if (releaseKeystore != null) {
|
||||||
|
create("release") {
|
||||||
|
storeFile = file(releaseKeystore.getProperty("storeFile"))
|
||||||
|
storePassword = releaseKeystore.getProperty("storePassword")
|
||||||
|
keyAlias = releaseKeystore.getProperty("keyAlias")
|
||||||
|
keyPassword = releaseKeystore.getProperty("keyPassword")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One APK per ABI for releases; debug builds stay a single APK for both.
|
||||||
|
splits {
|
||||||
|
abi {
|
||||||
|
isEnable = gradle.startParameter.taskNames.any { it.contains("Release") }
|
||||||
|
reset()
|
||||||
|
include("arm64-v8a", "x86_64")
|
||||||
|
isUniversalApk = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
signingConfig = signingConfigs.findByName("release")
|
||||||
|
isMinifyEnabled = true
|
||||||
|
isShrinkResources = true
|
||||||
|
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
androidResources {
|
||||||
|
// The app is English only; drops the libraries' translations.
|
||||||
|
localeFilters += "en"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
packaging {
|
||||||
|
// Compressed in the APK, which then is smaller to send; extracted on install.
|
||||||
|
dex.useLegacyPackaging = true
|
||||||
|
jniLibs.useLegacyPackaging = true
|
||||||
|
resources {
|
||||||
|
// BouncyCastle ships Java 9+ module metadata Android has no use for.
|
||||||
|
excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(project(":audio"))
|
||||||
|
soundPackEncoder(project(":desktop"))
|
||||||
|
|
||||||
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
|
implementation(libs.androidx.compose.ui)
|
||||||
|
implementation(libs.androidx.compose.material3)
|
||||||
|
implementation(libs.androidx.compose.material.icons)
|
||||||
|
implementation(libs.androidx.activity.compose)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||||
|
implementation(libs.androidx.lifecycle.service)
|
||||||
|
implementation(libs.androidsvg)
|
||||||
|
}
|
||||||
Vendored
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# ts3j looks up SRV records through JNDI only where it exists; Android lacks it.
|
||||||
|
-dontwarn javax.naming.**
|
||||||
|
|
||||||
|
# Reached from native code by name.
|
||||||
|
-keepclasseswithmembernames class eu.lixko.ts3j.client.android.audio.** {
|
||||||
|
native <methods>;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ts3j builds protocol handlers and packet bodies reflectively.
|
||||||
|
-keep class com.github.manevolent.ts3j.** { *; }
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||||
|
|
||||||
|
<!-- Speech sound packs talk through the phone's text-to-speech engine. -->
|
||||||
|
<queries>
|
||||||
|
<intent>
|
||||||
|
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||||
|
</intent>
|
||||||
|
</queries>
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name=".Ts3Application"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:theme="@android:style/Theme.Material.NoActionBar">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:label="@string/launcher_name"
|
||||||
|
android:exported="true"
|
||||||
|
android:launchMode="singleTop"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
<!-- TeamSpeak server links from browsers and other apps connect. -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:scheme="ts3server" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".ConnectionService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="mediaPlayback|microphone" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".ReplyReceiver"
|
||||||
|
android:exported="false" />
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import eu.lixko.ts3j.client.android.audio.AudioRoute
|
||||||
|
|
||||||
|
/** Where the Android-only audio choices are kept; the rest live in the shared settings. */
|
||||||
|
class AudioRoutePrefs(context: Context) {
|
||||||
|
|
||||||
|
private val prefs = context.getSharedPreferences("audio", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
fun load(): AudioRoute = AudioRoute(
|
||||||
|
enumOr(prefs.getString(INPUT_PRESET, null), AudioRoute.DEFAULT.inputPreset()),
|
||||||
|
enumOr(prefs.getString(USAGE, null), AudioRoute.DEFAULT.usage()),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun save(route: AudioRoute) {
|
||||||
|
prefs.edit()
|
||||||
|
.putString(INPUT_PRESET, route.inputPreset().name)
|
||||||
|
.putString(USAGE, route.usage().name)
|
||||||
|
.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun <reified E : Enum<E>> enumOr(name: String?, default: E): E =
|
||||||
|
enumValues<E>().firstOrNull { it.name == name } ?: default
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val INPUT_PRESET = "inputPreset"
|
||||||
|
const val USAGE = "usage"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ShortcutInfo
|
||||||
|
import android.content.pm.ShortcutManager
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Rect
|
||||||
|
import android.graphics.drawable.Icon
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.net.IconRepository
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Home-screen shortcuts that connect to a bookmark in one tap. A shortcut names its bookmark by
|
||||||
|
* [Bookmark.id], so editing the bookmark carries over and removing it disables the shortcut.
|
||||||
|
*/
|
||||||
|
internal class BookmarkShortcuts(private val context: Context, private val icons: IconTheme) {
|
||||||
|
|
||||||
|
private val manager = context.getSystemService(ShortcutManager::class.java)
|
||||||
|
|
||||||
|
val supported: Boolean get() = manager?.isRequestPinShortcutSupported == true
|
||||||
|
|
||||||
|
/** Asks the launcher to pin a shortcut; it confirms with the user itself. */
|
||||||
|
fun pin(bookmark: Bookmark) {
|
||||||
|
manager?.requestPinShortcut(info(bookmark), null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pinned shortcuts take on their bookmarks' current names and icons; those of removed ones stop working. */
|
||||||
|
fun sync(bookmarks: List<Bookmark>) {
|
||||||
|
val manager = manager ?: return
|
||||||
|
val byId = bookmarks.associateBy { shortcutId(it.id) }
|
||||||
|
val pinned = manager.pinnedShortcuts
|
||||||
|
val gone = pinned.map { it.id }.filter { it !in byId }
|
||||||
|
if (gone.isNotEmpty()) manager.disableShortcuts(gone, "Bookmark removed")
|
||||||
|
val kept = pinned.mapNotNull { byId[it.id] }
|
||||||
|
if (kept.isNotEmpty()) {
|
||||||
|
manager.enableShortcuts(kept.map { shortcutId(it.id) })
|
||||||
|
manager.updateShortcuts(kept.map(::info))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun info(bookmark: Bookmark): ShortcutInfo =
|
||||||
|
ShortcutInfo.Builder(context, shortcutId(bookmark.id))
|
||||||
|
.setShortLabel(bookmark.displayName())
|
||||||
|
.setLongLabel(listOfNotNull(bookmark.displayName(), bookmark.channel.ifBlank { null }).joinToString(" · "))
|
||||||
|
.setIcon(icon(bookmark.iconId))
|
||||||
|
.setIntent(Intent(context, MainActivity::class.java)
|
||||||
|
.setAction(ACTION_CONNECT)
|
||||||
|
.putExtra(EXTRA_BOOKMARK, bookmark.id))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
/** The server's own icon as last seen there, else the pack's server icon, inside the adaptive icon's safe zone. */
|
||||||
|
private fun icon(iconId: Long): Icon {
|
||||||
|
val art = IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }
|
||||||
|
?: icons.render(listOf("SERVER_GREEN", "BOOKMARK_MANAGER"), ART_PX, 0x202020)
|
||||||
|
val canvas = Bitmap.createBitmap(ADAPTIVE_PX, ADAPTIVE_PX, Bitmap.Config.ARGB_8888)
|
||||||
|
Canvas(canvas).apply {
|
||||||
|
drawColor(BACKGROUND)
|
||||||
|
if (art != null) {
|
||||||
|
val inset = (ADAPTIVE_PX - ART_PX) / 2
|
||||||
|
drawBitmap(art, null, Rect(inset, inset, inset + ART_PX, inset + ART_PX), null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Icon.createWithAdaptiveBitmap(canvas)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ACTION_CONNECT = "eu.lixko.ts3j.client.android.CONNECT_BOOKMARK"
|
||||||
|
const val EXTRA_BOOKMARK = "bookmark"
|
||||||
|
|
||||||
|
/** 108 dp at xxxhdpi; the inner 72 dp always shows, the art sits well within. */
|
||||||
|
private const val ADAPTIVE_PX = 432
|
||||||
|
private const val ART_PX = 192
|
||||||
|
private const val BACKGROUND = 0xFFE8EEF4.toInt()
|
||||||
|
|
||||||
|
private fun shortcutId(bookmarkId: String) = "bookmark:$bookmarkId"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Immutable
|
||||||
|
import eu.lixko.ts3j.client.text.HtmlText
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
|
||||||
|
/** Which conversation a chat line belongs to. */
|
||||||
|
sealed interface ChatKey {
|
||||||
|
data object Server : ChatKey
|
||||||
|
data object Channel : ChatKey
|
||||||
|
data class Private(val clientId: Int) : ChatKey
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */
|
||||||
|
@Immutable
|
||||||
|
data class ChatLine(val id: Long, val html: String) {
|
||||||
|
/** The text to find in. */
|
||||||
|
val plain: String by lazy { HtmlText.plain(html) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Immutable
|
||||||
|
data class Conversation(
|
||||||
|
val key: ChatKey,
|
||||||
|
val title: String,
|
||||||
|
/** The peer's unique id in a private chat, once known. */
|
||||||
|
val uniqueId: String = "",
|
||||||
|
val lines: List<ChatLine> = emptyList(),
|
||||||
|
val unread: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Every conversation of the session: the server's, the channel's, then the private ones. */
|
||||||
|
@Immutable
|
||||||
|
data class Chats(
|
||||||
|
val server: Conversation = Conversation(ChatKey.Server, "Server"),
|
||||||
|
val channel: Conversation = Conversation(ChatKey.Channel, "Channel"),
|
||||||
|
val private: List<Conversation> = emptyList(),
|
||||||
|
) {
|
||||||
|
val all: List<Conversation> get() = listOf(server, channel) + private
|
||||||
|
|
||||||
|
val anyUnread: Boolean get() = all.any { it.unread }
|
||||||
|
|
||||||
|
operator fun get(key: ChatKey): Conversation? = when (key) {
|
||||||
|
ChatKey.Server -> server
|
||||||
|
ChatKey.Channel -> channel
|
||||||
|
is ChatKey.Private -> private.firstOrNull { it.key == key }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies [change] to a conversation, opening a private one titled [title] if needed. */
|
||||||
|
fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) {
|
||||||
|
ChatKey.Server -> copy(server = change(server))
|
||||||
|
ChatKey.Channel -> copy(channel = change(channel))
|
||||||
|
is ChatKey.Private -> {
|
||||||
|
val existing = private.indexOfFirst { it.key == key }
|
||||||
|
if (existing < 0) {
|
||||||
|
copy(private = private + change(Conversation(key, title)))
|
||||||
|
} else {
|
||||||
|
copy(private = private.toMutableList().also { it[existing] = change(it[existing]) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key })
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** As many lines as a log history loads; older ones leave the conversation. */
|
||||||
|
const val MAX_LINES = 1000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Conversation.append(line: ChatLine, read: Boolean): Conversation =
|
||||||
|
copy(lines = (lines + line).takeLast(Chats.MAX_LINES), unread = unread || !read)
|
||||||
|
|
||||||
|
/** The [nth] match of the find bar's query in the line [line]. */
|
||||||
|
data class ChatMatch(val line: Long, val nth: Int)
|
||||||
|
|
||||||
|
/** Every match of [query] in [lines], oldest first; past [limit], only the newest. */
|
||||||
|
fun findIn(lines: List<ChatLine>, query: TextQuery, limit: Int): List<ChatMatch> {
|
||||||
|
if (query.isEmpty) return emptyList()
|
||||||
|
val out = ArrayList<ChatMatch>()
|
||||||
|
for (line in lines) {
|
||||||
|
val m = query.matcher(line.plain) ?: return emptyList()
|
||||||
|
var n = 0
|
||||||
|
while (m.find()) {
|
||||||
|
if (m.end() > m.start()) out += ChatMatch(line.id, n++)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return if (out.size > limit) out.subList(out.size - limit, out.size) else out
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.drawable.Icon
|
||||||
|
import android.net.wifi.WifiManager
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.lifecycle.LifecycleService
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.net.ClientStatus
|
||||||
|
import eu.lixko.ts3j.client.session.SelfState
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.conflate
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
|
import kotlinx.coroutines.flow.flowOf
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the process in the foreground while connected, so the connection and its audio
|
||||||
|
* survive the app leaving the screen, and offers the essentials in its notification.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class ConnectionService : LifecycleService() {
|
||||||
|
|
||||||
|
private lateinit var sessions: SessionController
|
||||||
|
private lateinit var wifiLock: WifiManager.WifiLock
|
||||||
|
private lateinit var wifiBackgroundLock: WifiManager.WifiLock
|
||||||
|
private lateinit var wakeLock: PowerManager.WakeLock
|
||||||
|
private lateinit var overlay: PttOverlay
|
||||||
|
private var foregroundTypes = 0
|
||||||
|
private var shown: ServerController? = null
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
sessions = (application as Ts3Application).sessions
|
||||||
|
getSystemService(NotificationManager::class.java).createNotificationChannel(
|
||||||
|
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
|
||||||
|
)
|
||||||
|
// Voice goes out every 20 ms; Wi-Fi power saving and a sleeping CPU would stretch that.
|
||||||
|
// Low-latency mode only holds while we are in the foreground with the screen on, so the
|
||||||
|
// high-performance lock keeps power saving off the rest of the time.
|
||||||
|
val wifi = getSystemService(WifiManager::class.java)
|
||||||
|
wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "ts3j:voice")
|
||||||
|
.apply { setReferenceCounted(false); acquire() }
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
wifiBackgroundLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ts3j:voice-background")
|
||||||
|
.apply { setReferenceCounted(false); acquire() }
|
||||||
|
wakeLock = getSystemService(PowerManager::class.java)
|
||||||
|
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ts3j:connection")
|
||||||
|
.apply { setReferenceCounted(false); acquire() }
|
||||||
|
|
||||||
|
show(sessions.current.value?.state?.value ?: SessionState(), capturing = false)
|
||||||
|
lifecycleScope.launch {
|
||||||
|
// The server count shows in the notification too.
|
||||||
|
combine(shownServer(), sessions.micOwner, sessions.servers) { shown, owner, _ -> shown to (owner != null) }
|
||||||
|
.conflate()
|
||||||
|
.collect { (shown, capturing) ->
|
||||||
|
if (shown != null) {
|
||||||
|
this@ConnectionService.shown = shown.first
|
||||||
|
show(shown.second, capturing)
|
||||||
|
// Talking flips the icon often, and Android drops updates that come too fast.
|
||||||
|
delay(MIN_UPDATE_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lifecycleScope.launch {
|
||||||
|
sessions.current.flatMapLatest { it?.state ?: flowOf(null) }.collectLatest { state ->
|
||||||
|
if (state == null) {
|
||||||
|
// A reconnect leaves the server briefly; only stop once it stays gone.
|
||||||
|
delay(STOP_DELAY_MS)
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lifecycleScope.launch {
|
||||||
|
sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
overlay = PttOverlay(this, sessions.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 ->
|
||||||
|
val (state, tree) = held ?: return@combine null
|
||||||
|
val wanted = enabled && !onScreen && state.connected && state.micActive &&
|
||||||
|
state.inputMode == Settings.InputMode.PUSH_TO_TALK
|
||||||
|
val status = tree.client(state.selfClientId)?.status
|
||||||
|
when {
|
||||||
|
!wanted -> null
|
||||||
|
state.micMuted -> PttOverlay.Look.MUTED
|
||||||
|
status == ClientStatus.TALKING || status == ClientStatus.COMMANDER_TALKING -> PttOverlay.Look.TALKING
|
||||||
|
else -> PttOverlay.Look.IDLE
|
||||||
|
}
|
||||||
|
}.distinctUntilChanged().collect { look ->
|
||||||
|
if (look == null) overlay.hide() else overlay.show(look)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The server the notification speaks for, as the desktop tray icon does: the one
|
||||||
|
* holding the microphone, or the visible one when nobody is capturing.
|
||||||
|
*/
|
||||||
|
private fun shownServer(): Flow<Pair<ServerController, SessionState>?> =
|
||||||
|
combine(sessions.current, sessions.micOwner) { current, owner -> current to owner }
|
||||||
|
.flatMapLatest { (current, owner) ->
|
||||||
|
combine(current?.state ?: flowOf(null), owner?.state ?: flowOf(null)) { currentState, ownerState ->
|
||||||
|
when {
|
||||||
|
owner != null && ownerState?.connected == true -> owner to ownerState
|
||||||
|
current != null && currentState != null -> current to currentState
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
super.onStartCommand(intent, flags, startId)
|
||||||
|
val server = shown ?: sessions.current.value ?: return START_NOT_STICKY
|
||||||
|
val state = server.state.value
|
||||||
|
when (intent?.action) {
|
||||||
|
ACTION_TOGGLE_MUTE -> server.setMicMuted(!state.micMuted)
|
||||||
|
ACTION_TOGGLE_DEAFEN -> server.setDeafened(!state.deafened)
|
||||||
|
ACTION_DISCONNECT -> server.disconnect()
|
||||||
|
}
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user swiped the app away: they are done with it, connection included. Leaving
|
||||||
|
* properly spares the server a ghost that would hold our identity until it times out.
|
||||||
|
*/
|
||||||
|
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||||
|
super.onTaskRemoved(rootIntent)
|
||||||
|
lifecycleScope.launch(Dispatchers.IO) {
|
||||||
|
sessions.leave()
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
overlay.hide()
|
||||||
|
wifiLock.release()
|
||||||
|
wifiBackgroundLock.release()
|
||||||
|
wakeLock.release()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Posts the notification, re-declaring what the service uses when that changed. */
|
||||||
|
private fun show(state: SessionState, capturing: Boolean) {
|
||||||
|
val types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or
|
||||||
|
if (capturing && hasMicPermission()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0
|
||||||
|
val notification = notification(state)
|
||||||
|
if (types != foregroundTypes) {
|
||||||
|
startForeground(NOTIFICATION_ID, notification, types)
|
||||||
|
foregroundTypes = types
|
||||||
|
} else {
|
||||||
|
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasMicPermission() =
|
||||||
|
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
|
private fun notification(state: SessionState): Notification {
|
||||||
|
val open = PendingIntent.getActivity(
|
||||||
|
this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
|
val others = sessions.servers.value.size - 1
|
||||||
|
return Notification.Builder(this, CHANNEL)
|
||||||
|
.setSmallIcon(statusIcon(state.self))
|
||||||
|
.setLargeIcon(largeIcon(state.self))
|
||||||
|
.setContentTitle(if (others > 0) "${state.title} +$others" else state.title)
|
||||||
|
.setContentText(state.status)
|
||||||
|
.setContentIntent(open)
|
||||||
|
.setOngoing(true)
|
||||||
|
.addAction(action(ACTION_TOGGLE_MUTE, if (state.micMuted) "Unmute" else "Mute"))
|
||||||
|
.addAction(action(ACTION_TOGGLE_DEAFEN, if (state.deafened) "Undeafen" else "Deafen"))
|
||||||
|
.addAction(action(ACTION_DISCONNECT, "Disconnect"))
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The status bar shows only the shape of an icon, which pack art loses, so it is
|
||||||
|
* drawn from the Material pack whatever pack is chosen.
|
||||||
|
*/
|
||||||
|
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)
|
||||||
|
?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
|
||||||
|
return Icon.createWithBitmap(bitmap)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The expanded notification has room for the chosen pack's own art, as the tree draws it. */
|
||||||
|
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))
|
||||||
|
?.let(Icon::createWithBitmap)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun action(action: String, label: String): Notification.Action {
|
||||||
|
val intent = PendingIntent.getService(
|
||||||
|
this, action.hashCode(), Intent(this, ConnectionService::class.java).setAction(action),
|
||||||
|
PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
|
return Notification.Action.Builder(null, label, intent).build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val CHANNEL = "connection"
|
||||||
|
const val NOTIFICATION_ID = 1
|
||||||
|
const val STOP_DELAY_MS = 3_000L
|
||||||
|
const val MIN_UPDATE_MS = 250L
|
||||||
|
const val STATUS_ICON_DP = 24
|
||||||
|
const val LARGE_ICON_DP = 48
|
||||||
|
const val ACTION_TOGGLE_MUTE = "eu.lixko.ts3j.client.android.TOGGLE_MUTE"
|
||||||
|
const val ACTION_TOGGLE_DEAFEN = "eu.lixko.ts3j.client.android.TOGGLE_DEAFEN"
|
||||||
|
const val ACTION_DISCONNECT = "eu.lixko.ts3j.client.android.DISCONNECT"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import eu.lixko.ts3j.client.net.TeamspeakConnection
|
||||||
|
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
|
||||||
|
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
|
||||||
|
/** One upload or download as the file browser shows it. */
|
||||||
|
data class TransferRow(
|
||||||
|
val id: Long,
|
||||||
|
val name: String,
|
||||||
|
val upload: Boolean,
|
||||||
|
val channelId: Int,
|
||||||
|
/** The directory an upload goes into, to list again once it is there. */
|
||||||
|
val directory: String,
|
||||||
|
val transferred: Long,
|
||||||
|
val total: Long,
|
||||||
|
val state: FileTransfer.State,
|
||||||
|
val error: String?,
|
||||||
|
) {
|
||||||
|
val done: Boolean get() = state != FileTransfer.State.PENDING && state != FileTransfer.State.ACTIVE
|
||||||
|
val progress: Float get() = if (total > 0) (transferred.toFloat() / total).coerceIn(0f, 1f) else 0f
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel file transfers of one server. Transfers go through files of our own in the cache,
|
||||||
|
* as the core reads and writes plain files: a download is copied where the user picked once
|
||||||
|
* complete, an upload is copied out of the picked document first. They outlive the browser page.
|
||||||
|
*/
|
||||||
|
class FileTransfers internal constructor(private val context: Context, private val conn: () -> TeamspeakConnection) {
|
||||||
|
|
||||||
|
private val ids = AtomicLong()
|
||||||
|
private val handles = HashMap<Long, FileTransfer>()
|
||||||
|
|
||||||
|
private val _rows = MutableStateFlow(emptyList<TransferRow>())
|
||||||
|
val rows: StateFlow<List<TransferRow>> = _rows
|
||||||
|
|
||||||
|
/** Downloads [file] into the document at [target]. */
|
||||||
|
fun download(channelId: Int, password: String, file: RemoteFile, target: Uri) {
|
||||||
|
val temp = File.createTempFile("download", null, context.cacheDir)
|
||||||
|
val row = add(file.name, upload = false, channelId, file.parentPath, file.size)
|
||||||
|
start(row, temp, onComplete = {
|
||||||
|
context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } }
|
||||||
|
?: throw IOException("Could not write the file")
|
||||||
|
}) { listener -> conn().downloadFile(channelId, password, file.fullPath, temp, listener) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */
|
||||||
|
suspend fun upload(channelId: Int, password: String, directory: String, source: Uri) {
|
||||||
|
val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) }
|
||||||
|
val row = add(name, upload = true, channelId, directory, temp.length())
|
||||||
|
start(row, temp, onComplete = {}) { listener ->
|
||||||
|
conn().uploadFile(channelId, password, directory + name, temp, true, listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel(id: Long) {
|
||||||
|
synchronized(handles) { handles[id] }?.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearFinished() = _rows.update { rows -> rows.filterNot { it.done } }
|
||||||
|
|
||||||
|
private fun add(name: String, upload: Boolean, channelId: Int, directory: String, total: Long): TransferRow {
|
||||||
|
val row = TransferRow(ids.incrementAndGet(), name, upload, channelId, directory, 0, total,
|
||||||
|
FileTransfer.State.PENDING, null)
|
||||||
|
_rows.update { it + row }
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a transfer through [temp], which goes once it is done with; [onComplete] finishes a successful one. */
|
||||||
|
private fun start(row: TransferRow, temp: File, onComplete: () -> Unit,
|
||||||
|
begin: (FileTransfer.Listener) -> FileTransfer) {
|
||||||
|
var lastUpdate = 0L
|
||||||
|
val listener = FileTransfer.Listener { t ->
|
||||||
|
val now = System.nanoTime()
|
||||||
|
// Progress comes per buffer; the list need not redraw that often.
|
||||||
|
if (!t.isDone && now - lastUpdate < UPDATE_NANOS) return@Listener
|
||||||
|
lastUpdate = now
|
||||||
|
var error = t.errorMessage
|
||||||
|
if (t.state == FileTransfer.State.COMPLETED) {
|
||||||
|
error = runCatching(onComplete).exceptionOrNull()?.let { it.message ?: "Could not save the file" }
|
||||||
|
}
|
||||||
|
if (t.isDone) {
|
||||||
|
temp.delete()
|
||||||
|
synchronized(handles) { handles.remove(row.id) }
|
||||||
|
}
|
||||||
|
val state = if (error != null) FileTransfer.State.FAILED else t.state
|
||||||
|
update(row.id) { it.copy(transferred = t.transferredBytes, total = maxOf(t.totalBytes, 0), state = state, error = error) }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val handle = begin(listener)
|
||||||
|
synchronized(handles) { if (!handle.isDone) handles[row.id] = handle }
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
temp.delete()
|
||||||
|
update(row.id) { it.copy(state = FileTransfer.State.FAILED, error = e.message ?: "Not connected") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun update(id: Long, change: (TransferRow) -> TransferRow) =
|
||||||
|
_rows.update { rows -> rows.map { if (it.id == id) change(it) else it } }
|
||||||
|
|
||||||
|
private fun copyIn(uri: Uri): Pair<String, File> {
|
||||||
|
val resolver = context.contentResolver
|
||||||
|
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
|
||||||
|
if (c.moveToFirst()) c.getString(0) else null
|
||||||
|
}?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "file"
|
||||||
|
val temp = File.createTempFile("upload", null, context.cacheDir)
|
||||||
|
try {
|
||||||
|
resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } }
|
||||||
|
?: throw IOException("Could not read the file")
|
||||||
|
} catch (e: IOException) {
|
||||||
|
temp.delete()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
// A server path takes no slashes in a file name.
|
||||||
|
return name.replace('/', '_') to temp
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val UPDATE_NANOS = 200_000_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import android.util.LruCache
|
||||||
|
import com.caverock.androidsvg.RenderOptions
|
||||||
|
import com.caverock.androidsvg.SVG
|
||||||
|
import eu.lixko.ts3j.client.config.AppDirs
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.gfx.IconPack
|
||||||
|
import eu.lixko.ts3j.client.gfx.IconPacks
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The icon packs the app draws with: the Material pack it ships, and TeamSpeak packs
|
||||||
|
* imported into its `gfx` folder, which are the very zips a TeamSpeak 3 install keeps in
|
||||||
|
* its own. Whatever the chosen pack lacks comes from the Material one.
|
||||||
|
*/
|
||||||
|
class IconTheme(private val context: Context, private val settings: Settings) {
|
||||||
|
|
||||||
|
private val folder = File(AppDirs.profile(), "gfx")
|
||||||
|
private val material: IconPack = IconPacks.material()
|
||||||
|
@Volatile
|
||||||
|
private var lookupOrder = listOf(material)
|
||||||
|
private val cache = LruCache<String, Bitmap>(256)
|
||||||
|
|
||||||
|
private val _packs = MutableStateFlow(emptyList<IconPack>())
|
||||||
|
val packs: StateFlow<List<IconPack>> = _packs
|
||||||
|
|
||||||
|
private val _active = MutableStateFlow(material)
|
||||||
|
val active: StateFlow<IconPack> = _active
|
||||||
|
|
||||||
|
init {
|
||||||
|
reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun select(pack: IconPack) {
|
||||||
|
settings.iconPack = pack.id()
|
||||||
|
settings.save()
|
||||||
|
reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copies a pack's zip into the app and switches to it.
|
||||||
|
*
|
||||||
|
* @return the pack, or `null` when the file is no icon pack
|
||||||
|
*/
|
||||||
|
fun import(uri: Uri): IconPack? {
|
||||||
|
folder.mkdirs()
|
||||||
|
val target = File(folder, displayName(uri).substringAfterLast('/').let {
|
||||||
|
if (it.endsWith(".zip", ignoreCase = true)) it else "$it.zip"
|
||||||
|
})
|
||||||
|
val staged = File(folder, target.name + ".part")
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
staged.outputStream().use { input.copyTo(it) }
|
||||||
|
} ?: return null
|
||||||
|
target.delete()
|
||||||
|
staged.renameTo(target)
|
||||||
|
val pack = IconPack.load(target)
|
||||||
|
if (pack == null) {
|
||||||
|
target.delete()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
select(pack)
|
||||||
|
return _active.value
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Draws the first of [keys] the packs have.
|
||||||
|
*
|
||||||
|
* @param rgb the colour for art that paints in the text colour
|
||||||
|
*/
|
||||||
|
fun render(keys: List<String>, size: Int, rgb: Int): Bitmap? = render(lookupOrder, keys, size, rgb)
|
||||||
|
|
||||||
|
/** Draws from the Material pack whatever pack is chosen, for chrome that must stay legible on its own colours. */
|
||||||
|
fun renderMaterial(key: String, size: Int, rgb: Int): Bitmap? = render(listOf(material), listOf(key), size, rgb)
|
||||||
|
|
||||||
|
private fun render(order: List<IconPack>, keys: List<String>, size: Int, rgb: Int): Bitmap? {
|
||||||
|
val cacheKey = "${order.first().id()}/${keys.joinToString(",")}@$size#$rgb"
|
||||||
|
cache.get(cacheKey)?.let { return it }
|
||||||
|
for (key in keys) {
|
||||||
|
for (pack in order) {
|
||||||
|
val data = pack.icon(key, size) ?: continue
|
||||||
|
val bitmap = (if (pack.isVector(key, size)) rasterize(IconPack.withCurrentColor(data, rgb), size)
|
||||||
|
else decode(data, size)) ?: continue
|
||||||
|
cache.put(cacheKey, bitmap)
|
||||||
|
return bitmap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun reload() {
|
||||||
|
val packs = IconPacks.findAll(folder, null)
|
||||||
|
val active = IconPacks.select(packs, settings.iconPack) ?: material
|
||||||
|
lookupOrder = IconPacks.lookupOrder(active, packs, material)
|
||||||
|
cache.evictAll()
|
||||||
|
_packs.value = packs
|
||||||
|
_active.value = active
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun displayName(uri: Uri): String =
|
||||||
|
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
|
||||||
|
if (it.moveToFirst()) it.getString(0) else null
|
||||||
|
} ?: uri.lastPathSegment ?: "iconpack.zip"
|
||||||
|
|
||||||
|
private fun rasterize(svg: ByteArray, size: Int): Bitmap? = try {
|
||||||
|
val document = SVG.getFromString(String(svg, Charsets.UTF_8))
|
||||||
|
if (document.documentViewBox == null && document.documentWidth > 0 && document.documentHeight > 0) {
|
||||||
|
document.setDocumentViewBox(0f, 0f, document.documentWidth, document.documentHeight)
|
||||||
|
}
|
||||||
|
// Otherwise the art keeps the size it was authored at inside the viewport.
|
||||||
|
document.setDocumentWidth("100%")
|
||||||
|
document.setDocumentHeight("100%")
|
||||||
|
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
|
||||||
|
document.renderToCanvas(Canvas(it), RenderOptions().viewPort(0f, 0f, size.toFloat(), size.toFloat()))
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Scales a bitmap icon into the square, keeping the aspect ratio of art that is not. */
|
||||||
|
private fun decode(data: ByteArray, size: Int): Bitmap? {
|
||||||
|
val source = BitmapFactory.decodeByteArray(data, 0, data.size) ?: return null
|
||||||
|
if (source.width == size && source.height == size) return source
|
||||||
|
val factor = minOf(size.toFloat() / source.width, size.toFloat() / source.height)
|
||||||
|
val w = source.width * factor
|
||||||
|
val h = source.height * factor
|
||||||
|
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
|
||||||
|
val left = (size - w) / 2
|
||||||
|
val top = (size - h) / 2
|
||||||
|
Canvas(it).drawBitmap(source, null, RectF(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmarks
|
||||||
|
import eu.lixko.ts3j.client.config.IdentityEntry
|
||||||
|
import eu.lixko.ts3j.client.config.IdentityStore
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancelAndJoin
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
/** What the identity manager shows of one identity. */
|
||||||
|
data class IdentityInfo(
|
||||||
|
val id: String,
|
||||||
|
val name: String,
|
||||||
|
val uniqueId: String,
|
||||||
|
val securityLevel: Int,
|
||||||
|
val isDefault: Boolean,
|
||||||
|
val nickname: String,
|
||||||
|
val phoneticNickname: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A search for a better key offset under way. */
|
||||||
|
data class Improvement(val id: String, val target: Int, val reached: Int)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The identities, as TeamSpeak's Tools → Identities manages them: create, import, export,
|
||||||
|
* rename, remove, pick the default and raise the security level. Raising the level runs
|
||||||
|
* on until it is reached or stopped, whichever page is on screen.
|
||||||
|
*/
|
||||||
|
class IdentityManager(
|
||||||
|
private val context: Context,
|
||||||
|
private val store: IdentityStore,
|
||||||
|
private val settings: Settings,
|
||||||
|
private val bookmarks: Bookmarks,
|
||||||
|
private val onBookmarksChanged: () -> Unit,
|
||||||
|
) {
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
|
||||||
|
private val _all = MutableStateFlow(snapshot())
|
||||||
|
val all: StateFlow<List<IdentityInfo>> = _all
|
||||||
|
|
||||||
|
private val _improving = MutableStateFlow<Improvement?>(null)
|
||||||
|
val improving: StateFlow<Improvement?> = _improving
|
||||||
|
private var improvement: Job? = null
|
||||||
|
|
||||||
|
/** Picks up identities added elsewhere, such as by an import or a first connect. */
|
||||||
|
fun refresh() {
|
||||||
|
_all.value = snapshot()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun snapshot(): List<IdentityInfo> = store.all().map {
|
||||||
|
IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId,
|
||||||
|
it.nickname, it.phoneticNickname)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generates an identity at TeamSpeak's default security level; the first one becomes the default. */
|
||||||
|
suspend fun generate(name: String): IdentityInfo = added {
|
||||||
|
store.generate(name, IdentityStore.DEFAULT_SECURITY_LEVEL)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Imports a TeamSpeak identity file, under the name it carries. */
|
||||||
|
suspend fun importFile(uri: Uri): IdentityInfo = added {
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { store.importStream(it, null) }
|
||||||
|
?: throw IOException("Cannot open the file")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Imports the identities of a TeamSpeak 3 `settings.db`. */
|
||||||
|
suspend fun importFromTeamSpeak(uri: Uri): TeamSpeakImporter.Result = withContext(Dispatchers.IO) {
|
||||||
|
withLocalCopy(context, uri) { TeamSpeakImporter(store, bookmarks, settings).importIdentities(it) }
|
||||||
|
}.also {
|
||||||
|
adoptDefault(null)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun added(create: () -> IdentityEntry): IdentityInfo {
|
||||||
|
val entry = withContext(Dispatchers.IO) { create() }
|
||||||
|
adoptDefault(entry)
|
||||||
|
refresh()
|
||||||
|
return _all.value.first { it.id == entry.id }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Makes [entry], or else the first identity, the default while there is none. */
|
||||||
|
private fun adoptDefault(entry: IdentityEntry?) {
|
||||||
|
if (store.byId(settings.defaultIdentityId) != null) return
|
||||||
|
val fallback = entry ?: store.all().firstOrNull() ?: return
|
||||||
|
settings.defaultIdentityId = fallback.id
|
||||||
|
settings.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Writes the identity out in TeamSpeak's format, for the official client or another device. */
|
||||||
|
suspend fun export(id: String, uri: Uri) = withContext(Dispatchers.IO) {
|
||||||
|
val entry = store.byId(id) ?: return@withContext
|
||||||
|
val out = context.contentResolver.openOutputStream(uri, "wt") ?: throw IOException("Cannot write the file")
|
||||||
|
store.exportTo(entry, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rename(id: String, name: String) {
|
||||||
|
val entry = store.byId(id) ?: return
|
||||||
|
scope.launch(Dispatchers.IO) {
|
||||||
|
store.rename(entry, name)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setNicknames(id: String, nickname: String, phoneticNickname: String) {
|
||||||
|
val entry = store.byId(id) ?: return
|
||||||
|
scope.launch(Dispatchers.IO) {
|
||||||
|
store.setNicknames(entry, nickname, phoneticNickname)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The nickname of the identity a connect with [id] uses; empty when it has none. */
|
||||||
|
fun nicknameOf(id: String): String =
|
||||||
|
(store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty()
|
||||||
|
|
||||||
|
fun setDefault(id: String) {
|
||||||
|
settings.defaultIdentityId = id
|
||||||
|
settings.save()
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes the identity; bookmarks that connected with it fall back to the default. */
|
||||||
|
fun remove(id: String) {
|
||||||
|
val entry = store.byId(id) ?: return
|
||||||
|
scope.launch(Dispatchers.IO) {
|
||||||
|
// Else the search would write the file back once it ends.
|
||||||
|
if (_improving.value?.id == id) improvement?.cancelAndJoin()
|
||||||
|
store.remove(entry, settings, bookmarks)
|
||||||
|
onBookmarksChanged()
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Searches for a key offset reaching [target], keeping the best found when stopped. */
|
||||||
|
fun improve(id: String, target: Int) {
|
||||||
|
if (improvement?.isActive == true) return
|
||||||
|
val entry = store.byId(id) ?: return
|
||||||
|
_improving.value = Improvement(id, target, entry.securityLevel)
|
||||||
|
improvement = scope.launch {
|
||||||
|
try {
|
||||||
|
store.improveSecurity(entry, target) { reached, _ ->
|
||||||
|
_improving.value = Improvement(id, target, reached)
|
||||||
|
isActive
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
// The level reached stays in memory for this run.
|
||||||
|
} finally {
|
||||||
|
_improving.value = null
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopImproving() {
|
||||||
|
improvement?.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioBackend
|
||||||
|
import eu.lixko.ts3j.client.audio.InputLevel
|
||||||
|
import eu.lixko.ts3j.client.audio.VoiceInput
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/** The microphone's level on [InputLevel]'s scale, and whether that would be sent. */
|
||||||
|
data class MicLevel(
|
||||||
|
val db: Double = InputLevel.SILENCE_DB,
|
||||||
|
val transmitting: Boolean = false,
|
||||||
|
/** Whether a microphone is being listened to at all. */
|
||||||
|
val live: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The level meter behind the voice-activation settings. While connected it listens to the
|
||||||
|
* connection's own microphone, so it shows exactly what gets sent; otherwise it runs a test
|
||||||
|
* microphone of its own for as long as someone watches.
|
||||||
|
*/
|
||||||
|
class LevelMonitor(private val settings: Settings, private val audio: AudioBackend) {
|
||||||
|
|
||||||
|
private val _level = MutableStateFlow(MicLevel())
|
||||||
|
val level: StateFlow<MicLevel> = _level
|
||||||
|
|
||||||
|
/** The connection's microphone, when that is the one listened to. */
|
||||||
|
private var borrowed: VoiceInput? = null
|
||||||
|
private var test: VoiceInput? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts or stops listening.
|
||||||
|
*
|
||||||
|
* @param source the connection's microphone while it captures, else null
|
||||||
|
* @param busy whether a connection is under way, which will bring its own microphone
|
||||||
|
*/
|
||||||
|
@Synchronized
|
||||||
|
fun update(watching: Boolean, source: VoiceInput?, busy: Boolean, mayCapture: Boolean) {
|
||||||
|
when {
|
||||||
|
!watching -> release()
|
||||||
|
source != null -> if (borrowed !== source) {
|
||||||
|
release()
|
||||||
|
source.setLevelListener(::onLevel)
|
||||||
|
borrowed = source
|
||||||
|
}
|
||||||
|
busy || !mayCapture -> release()
|
||||||
|
test == null -> startTest()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The own microphone's transmit state, which the connection reports. */
|
||||||
|
fun talking(transmitting: Boolean) {
|
||||||
|
if (borrowed != null) _level.value = _level.value.copy(transmitting = transmitting)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Puts changed voice settings into effect on the test microphone. */
|
||||||
|
@Synchronized
|
||||||
|
fun apply() {
|
||||||
|
test?.let {
|
||||||
|
it.apply(settings)
|
||||||
|
it.setMode(testMode())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startTest() {
|
||||||
|
release()
|
||||||
|
val input = audio.createInput(settings)
|
||||||
|
input.setMode(testMode())
|
||||||
|
input.setLevelListener(::onLevel)
|
||||||
|
input.setTalkListener { _level.value = _level.value.copy(transmitting = it) }
|
||||||
|
try {
|
||||||
|
input.start()
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
return // no microphone to be had; the meter stays idle
|
||||||
|
}
|
||||||
|
test = input
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun release() {
|
||||||
|
borrowed?.setLevelListener(null)
|
||||||
|
borrowed = null
|
||||||
|
test?.stop()
|
||||||
|
test = null
|
||||||
|
_level.value = MicLevel()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onLevel(db: Double) {
|
||||||
|
_level.value = _level.value.copy(db = db, live = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Push-to-talk would never open without the button, and the test is there to tune the gate. */
|
||||||
|
private fun testMode() =
|
||||||
|
if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hands [read] a temporary copy of the document at [uri], for readers that need a file they
|
||||||
|
* can seek in, which a content URI is not.
|
||||||
|
*/
|
||||||
|
internal fun <T> withLocalCopy(context: Context, uri: Uri, read: (File) -> T): T {
|
||||||
|
val copy = File.createTempFile("import", null, context.cacheDir)
|
||||||
|
try {
|
||||||
|
val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open the file")
|
||||||
|
input.use { copy.outputStream().use { out -> it.copyTo(out) } }
|
||||||
|
return read(copy)
|
||||||
|
} finally {
|
||||||
|
copy.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import eu.lixko.ts3j.client.android.ui.App
|
||||||
|
import eu.lixko.ts3j.client.android.ui.Ts3Theme
|
||||||
|
import eu.lixko.ts3j.client.session.ServerLink
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
|
||||||
|
private val sessions get() = (application as Ts3Application).sessions
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
enableEdgeToEdge()
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent))
|
||||||
|
setContent {
|
||||||
|
Ts3Theme { App(sessions) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
handle(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStart() {
|
||||||
|
super.onStart()
|
||||||
|
sessions.foreground = true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStop() {
|
||||||
|
sessions.foreground = false
|
||||||
|
super.onStop()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A notification opens its conversation; a `ts3server://` link or a bookmark shortcut connects, returning where. */
|
||||||
|
private fun handle(intent: Intent): ServerLink? = when (intent.action) {
|
||||||
|
Intent.ACTION_VIEW -> ServerLink.parse(intent.dataString)?.also { sessions.open(it) }
|
||||||
|
BookmarkShortcuts.ACTION_CONNECT -> intent.getStringExtra(BookmarkShortcuts.EXTRA_BOOKMARK)
|
||||||
|
?.let(sessions::openBookmark)
|
||||||
|
else -> {
|
||||||
|
openRequestedChat(intent)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openRequestedChat(intent: Intent) {
|
||||||
|
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
|
||||||
|
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
|
||||||
|
if (serverId >= 0 && clientId >= 0) sessions.requestChat(serverId, clientId)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.app.Person
|
||||||
|
import android.app.RemoteInput
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tells the user about pokes and private messages while the app is out of sight. The
|
||||||
|
* notifications themselves are silent: the sound pack already plays TeamSpeak's own sound
|
||||||
|
* for either, as it does in the app.
|
||||||
|
*/
|
||||||
|
class MessageNotifier(private val context: Context) {
|
||||||
|
|
||||||
|
private val manager = context.getSystemService(NotificationManager::class.java)
|
||||||
|
private val me = Person.Builder().setName("You").build()
|
||||||
|
|
||||||
|
/** What each private conversation's notification shows, by [id] of server and peer. */
|
||||||
|
private val conversations = HashMap<Int, Conversation>()
|
||||||
|
|
||||||
|
private class Conversation(val peer: Person, val messages: MutableList<Notification.MessagingStyle.Message>)
|
||||||
|
|
||||||
|
init {
|
||||||
|
manager.createNotificationChannels(listOf(
|
||||||
|
channel(MESSAGES, R.string.messages_channel),
|
||||||
|
channel(POKES, R.string.pokes_channel),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun channel(id: String, name: Int) =
|
||||||
|
NotificationChannel(id, context.getString(name), NotificationManager.IMPORTANCE_HIGH).apply {
|
||||||
|
setSound(null, null)
|
||||||
|
enableVibration(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun poke(from: String, message: String) {
|
||||||
|
val notification = Notification.Builder(context, POKES)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_notify_chat)
|
||||||
|
.setContentTitle("$from poked you")
|
||||||
|
.setContentText(message.ifBlank { null })
|
||||||
|
.setCategory(Notification.CATEGORY_MESSAGE)
|
||||||
|
.setContentIntent(open(null, null))
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.build()
|
||||||
|
manager.notify(POKE_TAG, from.hashCode(), notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearPokes() {
|
||||||
|
for (active in manager.activeNotifications) {
|
||||||
|
if (active.tag == POKE_TAG) manager.cancel(POKE_TAG, active.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A message the peer sent, which starts the conversation's notification if it had none. */
|
||||||
|
@Synchronized
|
||||||
|
fun received(serverId: Int, clientId: Int, from: String, text: String) {
|
||||||
|
val id = id(serverId, clientId)
|
||||||
|
val conversation = conversations[id]?.takeIf { it.peer.name == from }
|
||||||
|
?: Conversation(Person.Builder().setName(from).setKey("client:$serverId:$clientId").build(), ArrayList())
|
||||||
|
conversations[id] = conversation
|
||||||
|
add(serverId, clientId, conversation, text, conversation.peer, alert = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Our own reply, shown in a conversation already notified of; answers the reply action too. */
|
||||||
|
@Synchronized
|
||||||
|
fun sent(serverId: Int, clientId: Int, text: String) {
|
||||||
|
val conversation = conversations[id(serverId, clientId)] ?: return
|
||||||
|
add(serverId, clientId, conversation, text, me, alert = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun add(serverId: Int, clientId: Int, conversation: Conversation, text: String, sender: Person, alert: Boolean) {
|
||||||
|
conversation.messages += Notification.MessagingStyle.Message(text, System.currentTimeMillis(), sender)
|
||||||
|
if (conversation.messages.size > MAX_MESSAGES) conversation.messages.removeAt(0)
|
||||||
|
val style = Notification.MessagingStyle(me)
|
||||||
|
conversation.messages.forEach(style::addMessage)
|
||||||
|
val notification = Notification.Builder(context, MESSAGES)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_notify_chat)
|
||||||
|
.setStyle(style)
|
||||||
|
.setCategory(Notification.CATEGORY_MESSAGE)
|
||||||
|
.setContentIntent(open(serverId, clientId))
|
||||||
|
.setOnlyAlertOnce(!alert)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.addAction(replyAction(serverId, clientId))
|
||||||
|
.build()
|
||||||
|
manager.notify(MESSAGE_TAG, id(serverId, clientId), notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The conversation came on screen, or ended with the connection. */
|
||||||
|
@Synchronized
|
||||||
|
fun clear(serverId: Int, clientId: Int) {
|
||||||
|
val id = id(serverId, clientId)
|
||||||
|
conversations.remove(id)
|
||||||
|
manager.cancel(MESSAGE_TAG, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's conversations, as its connection ended. */
|
||||||
|
@Synchronized
|
||||||
|
fun clearServer(serverId: Int) {
|
||||||
|
conversations.keys.filter { it ushr 16 == serverId }.forEach { clear(serverId, it and 0xFFFF) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun open(serverId: Int?, clientId: Int?): PendingIntent {
|
||||||
|
val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||||
|
if (serverId != null && clientId != null) {
|
||||||
|
intent.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId)
|
||||||
|
}
|
||||||
|
return PendingIntent.getActivity(context, if (serverId != null && clientId != null) id(serverId, clientId) else -1,
|
||||||
|
intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun replyAction(serverId: Int, clientId: Int): Notification.Action {
|
||||||
|
val intent = Intent(context, ReplyReceiver::class.java)
|
||||||
|
.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId)
|
||||||
|
// Mutable: the system fills the typed reply into it.
|
||||||
|
val pending = PendingIntent.getBroadcast(context, id(serverId, clientId), intent,
|
||||||
|
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||||
|
return Notification.Action.Builder(null, "Reply", pending)
|
||||||
|
.addRemoteInput(RemoteInput.Builder(KEY_REPLY).setLabel("Message").build())
|
||||||
|
.setSemanticAction(Notification.Action.SEMANTIC_ACTION_REPLY)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Client ids are 16 bits, and only unique on their server. */
|
||||||
|
private fun id(serverId: Int, clientId: Int) = serverId shl 16 or clientId
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** The server and the client id of the private chat a notification opens or replies to. */
|
||||||
|
const val EXTRA_SERVER = "eu.lixko.ts3j.client.android.SERVER"
|
||||||
|
const val EXTRA_CHAT = "eu.lixko.ts3j.client.android.CHAT"
|
||||||
|
const val KEY_REPLY = "reply"
|
||||||
|
private const val MESSAGES = "messages"
|
||||||
|
private const val POKES = "pokes"
|
||||||
|
private const val MESSAGE_TAG = "message"
|
||||||
|
private const val POKE_TAG = "poke"
|
||||||
|
private const val MAX_MESSAGES = 25
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
|
import eu.lixko.ts3j.client.session.ServerSession
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the connections on the network Android routes over.
|
||||||
|
*
|
||||||
|
* A TS3 server knows its clients by address, so once the phone moves from Wi-Fi to mobile
|
||||||
|
* data (or back) an old connection is dead weight: it can only time out. This notices the
|
||||||
|
* move, says goodbye over the old network while that still works, and connects again over
|
||||||
|
* the new one, back into the channel we were in. A server that still holds our old
|
||||||
|
* connection may refuse the new one for a while as a clone, so a failed attempt is retried.
|
||||||
|
*
|
||||||
|
* The process's sockets are bound to the network a connection was made over. Otherwise the
|
||||||
|
* old connection would silently follow the new default network, and its goodbye would come
|
||||||
|
* from an address the server does not know. A socket keeps the network it was made on, so
|
||||||
|
* each connection remembers its own.
|
||||||
|
*/
|
||||||
|
class NetworkFollower(context: Context) {
|
||||||
|
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
private val follows = CopyOnWriteArrayList<Follow>()
|
||||||
|
|
||||||
|
/** The system's default network; null while there is none. */
|
||||||
|
@Volatile
|
||||||
|
private var network: Network? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onAvailable(available: Network) {
|
||||||
|
network = available
|
||||||
|
follows.forEach(Follow::reconsider)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLost(lost: Network) {
|
||||||
|
if (network == lost) network = null
|
||||||
|
follows.forEach(Follow::reconsider)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Follows [session] until [Follow.forget]. */
|
||||||
|
fun follow(session: ServerSession, onChange: () -> Unit, system: (String) -> Unit): Follow =
|
||||||
|
Follow(session, onChange, system).also(follows::add)
|
||||||
|
|
||||||
|
/** Binds new sockets to [to], or lets them go by the default network once no connection wants one. */
|
||||||
|
private fun bind(to: Network?) {
|
||||||
|
connectivity.bindProcessToNetwork(to ?: follows.firstNotNullOfOrNull { f -> f.bound.takeIf { f.wanted } })
|
||||||
|
}
|
||||||
|
|
||||||
|
inner class Follow internal constructor(
|
||||||
|
private val session: ServerSession,
|
||||||
|
private val onChange: () -> Unit,
|
||||||
|
private val system: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
/** The network the connection was made over. */
|
||||||
|
@Volatile
|
||||||
|
internal var bound: Network? = null
|
||||||
|
|
||||||
|
/** The user wants to be on the server: from their connect until they, or the server, end it. */
|
||||||
|
@Volatile
|
||||||
|
internal var wanted = false
|
||||||
|
|
||||||
|
private var settle: Job? = null
|
||||||
|
@Volatile
|
||||||
|
private var recovery: Job? = null
|
||||||
|
@Volatile
|
||||||
|
private var attempt: CompletableDeferred<Boolean>? = null
|
||||||
|
|
||||||
|
/** What to show in place of the session's status while getting back on the server. */
|
||||||
|
@Volatile
|
||||||
|
var status: String? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
val isRecovering: Boolean get() = recovery?.isActive == true
|
||||||
|
|
||||||
|
/** Before a connect the user asked for, which goes over the network there is now. */
|
||||||
|
fun connecting() {
|
||||||
|
recovery?.cancel()
|
||||||
|
wanted = true
|
||||||
|
bindHere(connectivity.activeNetwork)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The user leaves the server. */
|
||||||
|
fun leaving() {
|
||||||
|
wanted = false
|
||||||
|
recovery?.cancel()
|
||||||
|
unbind()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The session is thrown away. */
|
||||||
|
fun forget() {
|
||||||
|
leaving()
|
||||||
|
follows.remove(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onConnected() {
|
||||||
|
attempt?.complete(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun onDisconnected() {
|
||||||
|
val pending = attempt
|
||||||
|
when {
|
||||||
|
pending != null -> pending.complete(false)
|
||||||
|
isRecovering -> {}
|
||||||
|
// A socket on a network that went away fails at once, before we hear of the change.
|
||||||
|
wanted && networkGone() -> synchronized(this) {
|
||||||
|
if (!isRecovering) recovery = recover()
|
||||||
|
}
|
||||||
|
// The server let us go (a kick, a shutdown, a failed first connect): leave it at that.
|
||||||
|
else -> {
|
||||||
|
wanted = false
|
||||||
|
unbind()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Waits for the network to settle: a handover often shows several changes in a row. */
|
||||||
|
internal fun reconsider() {
|
||||||
|
synchronized(this) {
|
||||||
|
settle?.cancel()
|
||||||
|
settle = scope.launch {
|
||||||
|
delay(SETTLE_MS)
|
||||||
|
synchronized(this@Follow) {
|
||||||
|
if (wanted && bound != network && !isRecovering) recovery = recover()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun recover() = scope.launch {
|
||||||
|
try {
|
||||||
|
val back = withTimeoutOrNull(GIVE_UP_MS) {
|
||||||
|
system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…")
|
||||||
|
if (session.isBusy) session.connection().disconnectBlocking("Network changed")
|
||||||
|
var retry = RETRY_MS
|
||||||
|
while (true) {
|
||||||
|
val current = awaitNetwork()
|
||||||
|
bindHere(current)
|
||||||
|
show("Reconnecting…")
|
||||||
|
val done = CompletableDeferred<Boolean>()
|
||||||
|
attempt = done
|
||||||
|
session.reconnect()
|
||||||
|
val connected = done.await()
|
||||||
|
attempt = null
|
||||||
|
if (connected) break
|
||||||
|
if (session.connection().connectErrorId == ERROR_BANNED) break
|
||||||
|
show("Reconnecting, retrying soon…")
|
||||||
|
delay(retry)
|
||||||
|
retry = (retry * 2).coerceAtMost(MAX_RETRY_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (session.connection().connectErrorId == ERROR_BANNED) {
|
||||||
|
wanted = false
|
||||||
|
unbind()
|
||||||
|
} else if (back == null) {
|
||||||
|
system("Could not get back on the server.")
|
||||||
|
wanted = false
|
||||||
|
unbind()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
attempt = null
|
||||||
|
status = null
|
||||||
|
onChange()
|
||||||
|
// The network may have moved again while we were busy.
|
||||||
|
reconsider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun networkGone(): Boolean {
|
||||||
|
val on = bound ?: return false
|
||||||
|
return connectivity.getNetworkCapabilities(on) == null || connectivity.activeNetwork != on
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun awaitNetwork(): Network {
|
||||||
|
while (true) {
|
||||||
|
connectivity.activeNetwork?.let { return it }
|
||||||
|
show("Waiting for network…")
|
||||||
|
delay(POLL_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun show(text: String) {
|
||||||
|
status = text
|
||||||
|
onChange()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bindHere(to: Network?) {
|
||||||
|
bound = to
|
||||||
|
bind(to)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unbind() {
|
||||||
|
bound = null
|
||||||
|
bind(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val SETTLE_MS = 1_500L
|
||||||
|
/** The server's refusal for a banned client; asking again will not help. */
|
||||||
|
const val ERROR_BANNED = 3329
|
||||||
|
const val RETRY_MS = 5_000L
|
||||||
|
const val MAX_RETRY_MS = 30_000L
|
||||||
|
const val POLL_MS = 500L
|
||||||
|
const val GIVE_UP_MS = 5 * 60_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.graphics.ImageDecoder
|
||||||
|
import android.graphics.drawable.AnimatedImageDrawable
|
||||||
|
import android.graphics.drawable.BitmapDrawable
|
||||||
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
|
||||||
|
/** An avatar or a picture from a description: still, or moving like an animated GIF. */
|
||||||
|
sealed interface Picture {
|
||||||
|
val width: Int
|
||||||
|
val height: Int
|
||||||
|
|
||||||
|
data class Still(val bitmap: ImageBitmap) : Picture {
|
||||||
|
override val width get() = bitmap.width
|
||||||
|
override val height get() = bitmap.height
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shared by whatever shows it: one animation, drawn wherever it is on screen. */
|
||||||
|
data class Moving(val drawable: AnimatedImageDrawable) : Picture {
|
||||||
|
override val width get() = drawable.intrinsicWidth
|
||||||
|
override val height get() = drawable.intrinsicHeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decodes any image Android knows, no larger than [maxPx] on its longer side; null if it is none. */
|
||||||
|
internal fun decodePicture(data: ByteArray, maxPx: Int): Picture? = try {
|
||||||
|
val drawable = ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ ->
|
||||||
|
val largest = maxOf(info.size.width, info.size.height)
|
||||||
|
if (largest > maxPx) {
|
||||||
|
decoder.setTargetSize(info.size.width * maxPx / largest, info.size.height * maxPx / largest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
when (drawable) {
|
||||||
|
is AnimatedImageDrawable -> Picture.Moving(drawable)
|
||||||
|
is BitmapDrawable -> Picture.Still(drawable.bitmap.asImageBitmap())
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.PixelFormat
|
||||||
|
import android.provider.Settings
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewConfiguration
|
||||||
|
import android.view.WindowManager
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A push-to-talk button floating over other apps. Holding it talks; a double tap whose
|
||||||
|
* second touch is held moves it instead, so moving never transmits more than the first tap.
|
||||||
|
*/
|
||||||
|
class PttOverlay(
|
||||||
|
private val context: Context,
|
||||||
|
private val icons: IconTheme,
|
||||||
|
private val onPressed: (Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
enum class Look { IDLE, TALKING, MUTED }
|
||||||
|
|
||||||
|
private val windows = context.getSystemService(WindowManager::class.java)
|
||||||
|
private val prefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
|
||||||
|
private val size = (SIZE_DP * context.resources.displayMetrics.density).toInt()
|
||||||
|
private var button: Button? = null
|
||||||
|
|
||||||
|
/** Shows the button, or updates it when it is up; nothing while the app may not draw over others. */
|
||||||
|
fun show(look: Look) {
|
||||||
|
button?.let {
|
||||||
|
it.look = look
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!Settings.canDrawOverlays(context)) return
|
||||||
|
val params = WindowManager.LayoutParams(
|
||||||
|
size, size,
|
||||||
|
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
|
||||||
|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
|
||||||
|
PixelFormat.TRANSLUCENT,
|
||||||
|
).apply {
|
||||||
|
gravity = Gravity.TOP or Gravity.START
|
||||||
|
val screen = windows.currentWindowMetrics.bounds
|
||||||
|
x = prefs.getInt(POS_X, screen.width() - size - size / 4)
|
||||||
|
y = prefs.getInt(POS_Y, screen.height() / 2)
|
||||||
|
}
|
||||||
|
val view = Button(params).also { it.look = look }
|
||||||
|
try {
|
||||||
|
windows.addView(view, params)
|
||||||
|
} catch (e: WindowManager.BadTokenException) {
|
||||||
|
// The permission went away since the check.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
button = view
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hide() {
|
||||||
|
val view = button ?: return
|
||||||
|
button = null
|
||||||
|
view.release()
|
||||||
|
windows.removeView(view)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("ViewConstructor")
|
||||||
|
private inner class Button(private val params: WindowManager.LayoutParams) : View(context) {
|
||||||
|
|
||||||
|
var look = Look.IDLE
|
||||||
|
set(value) {
|
||||||
|
field = value
|
||||||
|
restyle()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private val doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout().toLong()
|
||||||
|
private var pressed = false
|
||||||
|
private var dragging = false
|
||||||
|
private var lastTapUp = 0L
|
||||||
|
private var grabX = 0f
|
||||||
|
private var grabY = 0f
|
||||||
|
|
||||||
|
init {
|
||||||
|
contentDescription = "Push to talk"
|
||||||
|
alpha = RESTING_ALPHA
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Half see-through at rest, so it hides less of the app beneath; solid while it talks. */
|
||||||
|
private fun restyle() {
|
||||||
|
alpha = if (pressed || look == Look.TALKING) 1f else RESTING_ALPHA
|
||||||
|
invalidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDraw(canvas: Canvas) {
|
||||||
|
val radius = width / 2f
|
||||||
|
val lit = pressed || look == Look.TALKING
|
||||||
|
paint.color = when {
|
||||||
|
look == Look.MUTED -> MUTED
|
||||||
|
lit -> TALKING
|
||||||
|
else -> IDLE
|
||||||
|
}
|
||||||
|
canvas.drawCircle(radius, radius, radius, paint)
|
||||||
|
if (lit) {
|
||||||
|
paint.color = Color.WHITE
|
||||||
|
paint.style = Paint.Style.STROKE
|
||||||
|
paint.strokeWidth = radius / 12
|
||||||
|
canvas.drawCircle(radius, radius, radius - paint.strokeWidth, paint)
|
||||||
|
paint.style = Paint.Style.FILL
|
||||||
|
}
|
||||||
|
val iconSize = width / 2
|
||||||
|
icon(iconSize)?.let {
|
||||||
|
val offset = (width - iconSize) / 2f
|
||||||
|
canvas.drawBitmap(it, offset, offset, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun icon(size: Int): Bitmap? =
|
||||||
|
icons.renderMaterial(if (look == Look.MUTED) "INPUT_MUTED" else "CAPTURE", size, Color.WHITE)
|
||||||
|
|
||||||
|
@SuppressLint("ClickableViewAccessibility")
|
||||||
|
override fun onTouchEvent(e: MotionEvent): Boolean {
|
||||||
|
when (e.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN -> {
|
||||||
|
dragging = e.eventTime - lastTapUp < doubleTapTimeout
|
||||||
|
if (dragging) {
|
||||||
|
grabX = e.rawX - params.x
|
||||||
|
grabY = e.rawY - params.y
|
||||||
|
} else {
|
||||||
|
press(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_MOVE -> if (dragging) moveTo(e.rawX - grabX, e.rawY - grabY)
|
||||||
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||||
|
val tap = !dragging && e.eventTime - e.downTime < doubleTapTimeout
|
||||||
|
lastTapUp = if (tap) e.eventTime else 0L
|
||||||
|
if (dragging) {
|
||||||
|
dragging = false
|
||||||
|
prefs.edit().putInt(POS_X, params.x).putInt(POS_Y, params.y).apply()
|
||||||
|
} else {
|
||||||
|
press(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun moveTo(x: Float, y: Float) {
|
||||||
|
val screen = windows.currentWindowMetrics.bounds
|
||||||
|
params.x = x.toInt().coerceIn(0, screen.width() - width)
|
||||||
|
params.y = y.toInt().coerceIn(0, screen.height() - height)
|
||||||
|
windows.updateViewLayout(this, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun press(down: Boolean) {
|
||||||
|
if (pressed == down) return
|
||||||
|
pressed = down
|
||||||
|
onPressed(down)
|
||||||
|
restyle()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lets go of the microphone should the button vanish under the finger. */
|
||||||
|
fun release() = press(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val SIZE_DP = 64
|
||||||
|
const val RESTING_ALPHA = 0.5f
|
||||||
|
const val POS_X = "x"
|
||||||
|
const val POS_Y = "y"
|
||||||
|
val IDLE = Color.rgb(0x1C, 0x6F, 0xB8)
|
||||||
|
val TALKING = Color.rgb(0x2E, 0x9B, 0xF0)
|
||||||
|
val MUTED = Color.rgb(0x42, 0x42, 0x42)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.app.RemoteInput
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
|
||||||
|
/** Sends what the user typed into a private message notification. */
|
||||||
|
class ReplyReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
|
||||||
|
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
|
||||||
|
val text = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(MessageNotifier.KEY_REPLY)?.toString()
|
||||||
|
if (serverId < 0 || clientId < 0 || text.isNullOrBlank()) return
|
||||||
|
(context.applicationContext as Ts3Application).sessions.reply(serverId, clientId, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.os.Environment
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import android.webkit.MimeTypeMap
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
/** Puts pictures into the shared Pictures collection, in a TeamSpeak album, where galleries find them. */
|
||||||
|
object SavedPictures {
|
||||||
|
|
||||||
|
/** Saves [data] as [name], its extension following what the data is; false if it could not be. */
|
||||||
|
suspend fun save(context: Context, name: String, data: ByteArray): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
|
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
|
||||||
|
val mime = bounds.outMimeType ?: return@withContext false
|
||||||
|
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(MediaStore.Images.Media.DISPLAY_NAME, if (extension == null) name else "$name.$extension")
|
||||||
|
put(MediaStore.Images.Media.MIME_TYPE, mime)
|
||||||
|
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/TeamSpeak")
|
||||||
|
put(MediaStore.Images.Media.IS_PENDING, 1)
|
||||||
|
}
|
||||||
|
val resolver = context.contentResolver
|
||||||
|
val uri = resolver.insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), values)
|
||||||
|
?: return@withContext false
|
||||||
|
try {
|
||||||
|
resolver.openOutputStream(uri)!!.use { it.write(data) }
|
||||||
|
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
resolver.delete(uri, null, null)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,582 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactType
|
||||||
|
import eu.lixko.ts3j.client.config.WhisperList
|
||||||
|
import eu.lixko.ts3j.client.net.ChannelNode
|
||||||
|
import eu.lixko.ts3j.client.net.ClientEntry
|
||||||
|
import eu.lixko.ts3j.client.net.ChannelSettings
|
||||||
|
import eu.lixko.ts3j.client.net.ConnectionStats
|
||||||
|
import eu.lixko.ts3j.client.net.Details
|
||||||
|
import eu.lixko.ts3j.client.net.GroupChoice
|
||||||
|
import eu.lixko.ts3j.client.net.Whisper
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanEntry
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanRule
|
||||||
|
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
|
||||||
|
import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope
|
||||||
|
import eu.lixko.ts3j.client.session.ServerLink
|
||||||
|
import eu.lixko.ts3j.client.session.ServerSession
|
||||||
|
import eu.lixko.ts3j.client.text.ChatHtml
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
import kotlin.coroutines.suspendCoroutine
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One server the app is on: its [ServerSession], and the snapshots the UI shows of it. Session
|
||||||
|
* callbacks arrive on connection threads and are turned into immutable snapshots.
|
||||||
|
*/
|
||||||
|
class ServerController internal constructor(
|
||||||
|
/** Unique among the servers of this process run. */
|
||||||
|
val id: Int,
|
||||||
|
private val app: SessionController,
|
||||||
|
) {
|
||||||
|
internal val session = ServerSession(
|
||||||
|
app.settings, app.identityStore, app.audio, app.sounds, app.contactStore, Listener()
|
||||||
|
)
|
||||||
|
internal val conn get() = session.connection()
|
||||||
|
private val network = app.network.follow(session, ::refresh, ::system)
|
||||||
|
|
||||||
|
/** Whether this server holds the microphone; set by [SessionController] as it moves. */
|
||||||
|
@Volatile
|
||||||
|
internal var micOwner = false
|
||||||
|
|
||||||
|
/** Set once connecting began, so a session that never started is not taken for one that ended. */
|
||||||
|
@Volatile
|
||||||
|
private var started = false
|
||||||
|
|
||||||
|
/** Set when the user left, so the end needs no telling. */
|
||||||
|
@Volatile
|
||||||
|
internal var left = false
|
||||||
|
|
||||||
|
private val _state = MutableStateFlow(SessionState())
|
||||||
|
val state: StateFlow<SessionState> = _state
|
||||||
|
|
||||||
|
private val _tree = MutableStateFlow(ServerTree())
|
||||||
|
val tree: StateFlow<ServerTree> = _tree
|
||||||
|
|
||||||
|
private val _chats = MutableStateFlow(Chats())
|
||||||
|
val chats: StateFlow<Chats> = _chats
|
||||||
|
|
||||||
|
/** Channels the user folded away in the tree. */
|
||||||
|
private val _collapsed = MutableStateFlow(emptySet<Int>())
|
||||||
|
val collapsed: StateFlow<Set<Int>> = _collapsed
|
||||||
|
|
||||||
|
/** The conversation on screen, whose new lines are read as they come. */
|
||||||
|
@Volatile
|
||||||
|
var viewing: ChatKey? = null
|
||||||
|
set(value) {
|
||||||
|
field = value
|
||||||
|
if (value != null) markRead(value)
|
||||||
|
if (value is ChatKey.Private) app.notifier.clear(id, value.clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Counts the answers to info requests, for the details on screen to be read again. */
|
||||||
|
private val _infoUpdates = MutableStateFlow(0)
|
||||||
|
val infoUpdates: StateFlow<Int> = _infoUpdates
|
||||||
|
|
||||||
|
val images = ServerImages(conn)
|
||||||
|
|
||||||
|
/** A private chat a notification asked to show, until the UI took it up. */
|
||||||
|
private val _chatRequest = MutableStateFlow<ChatKey.Private?>(null)
|
||||||
|
val chatRequest: StateFlow<ChatKey.Private?> = _chatRequest
|
||||||
|
|
||||||
|
private val lineIds = AtomicLong()
|
||||||
|
|
||||||
|
/** Tree snapshots are taken one at a time, at most once per [TREE_FRAME_MS]. */
|
||||||
|
private val treeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default.limitedParallelism(1))
|
||||||
|
private val treePending = AtomicBoolean()
|
||||||
|
private val structureChanged = AtomicBoolean(true)
|
||||||
|
private var roots: List<ChannelNode> = emptyList()
|
||||||
|
|
||||||
|
val isConnected: Boolean get() = session.isConnected
|
||||||
|
internal val isBusy: Boolean get() = session.isBusy || network.isRecovering
|
||||||
|
internal val microphone get() = if (session.isConnected) conn.microphone else null
|
||||||
|
internal val playback get() = if (session.isConnected) conn.playback else null
|
||||||
|
|
||||||
|
/** Not on the server and not trying to get back on it: done with. */
|
||||||
|
internal val ended: Boolean get() = started && !isBusy
|
||||||
|
|
||||||
|
// ---- connection ----
|
||||||
|
|
||||||
|
internal fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
|
||||||
|
channel: String, channelPassword: String) {
|
||||||
|
network.connecting()
|
||||||
|
started = true
|
||||||
|
session.connect(host, port, nickname, password, identityId, channel, channelPassword)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun open(link: ServerLink, identityId: String) {
|
||||||
|
network.connecting()
|
||||||
|
started = true
|
||||||
|
session.open(link, identityId)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bookmark leading back to this server, joining [channelId]; not yet saved. */
|
||||||
|
fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId))
|
||||||
|
|
||||||
|
fun disconnect() {
|
||||||
|
left = true
|
||||||
|
network.leaving()
|
||||||
|
session.disconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Before the app goes away with the connection, which [SessionController.leave] then ends. */
|
||||||
|
internal fun leaving() {
|
||||||
|
left = true
|
||||||
|
network.leaving()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun dispose() {
|
||||||
|
network.forget()
|
||||||
|
treeScope.cancel()
|
||||||
|
session.dispose()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the local client ----
|
||||||
|
|
||||||
|
fun setMicMuted(muted: Boolean) = session.setMicMuted(muted)
|
||||||
|
|
||||||
|
fun setDeafened(deafened: Boolean) = session.setDeafened(deafened)
|
||||||
|
|
||||||
|
fun setAway(away: Boolean) = session.setAway(away, null)
|
||||||
|
|
||||||
|
// ---- channels and clients ----
|
||||||
|
|
||||||
|
fun joinChannel(channelId: Int, password: String? = null) {
|
||||||
|
if (session.isConnected) conn.joinChannel(channelId, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSubscribed(channelId: Int, subscribed: Boolean) {
|
||||||
|
if (session.isConnected) conn.setChannelsSubscribed(listOf(channelId), subscribed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toggleCollapsed(channelId: Int) =
|
||||||
|
_collapsed.update { if (channelId in it) it - channelId else it + channelId }
|
||||||
|
|
||||||
|
fun expand(channelIds: Collection<Int>) = _collapsed.update { it - channelIds.toSet() }
|
||||||
|
|
||||||
|
val canMoveClients: Boolean get() = session.canMoveClients()
|
||||||
|
|
||||||
|
fun moveClient(clientId: Int, channelId: Int) {
|
||||||
|
if (session.isConnected) conn.moveClient(clientId, channelId, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun poke(clientId: Int, message: String) {
|
||||||
|
if (session.isConnected) conn.poke(clientId, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The client's playback volume change in dB; 0 when unchanged. */
|
||||||
|
fun clientVolume(clientId: Int): Double =
|
||||||
|
conn.model.getClient(clientId)?.let { conn.getClientVolumeModifier(it) } ?: 0.0
|
||||||
|
|
||||||
|
fun setClientVolume(clientId: Int, decibels: Double) {
|
||||||
|
conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- whisper ----
|
||||||
|
|
||||||
|
fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper)
|
||||||
|
|
||||||
|
fun whisperToChannel(channelId: Int) = conn.model.getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) }
|
||||||
|
|
||||||
|
fun whisperToClient(clientId: Int) = conn.model.getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) }
|
||||||
|
|
||||||
|
/** The client who whispered to us last, while on the server. */
|
||||||
|
fun lastWhisperer(): ClientEntry? = session.lastWhisperer()
|
||||||
|
|
||||||
|
/** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */
|
||||||
|
fun channelRef(channelId: Int): String? = conn.model.getChannel(channelId)?.let { conn.model.channelPath(it.id) }
|
||||||
|
|
||||||
|
fun clientRef(clientId: Int): WhisperList.Client? =
|
||||||
|
conn.model.getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) }
|
||||||
|
|
||||||
|
/** The clients on the server, for adding to a whisper list; ourselves left out. */
|
||||||
|
fun clientRefs(): List<WhisperList.Client> = if (!session.isConnected) emptyList()
|
||||||
|
else conn.model.allClients().filter { it.id != conn.selfClientId && !it.uniqueId.isNullOrEmpty() }
|
||||||
|
.sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) }
|
||||||
|
|
||||||
|
fun channelPaths(): List<String> = session.channelPaths()
|
||||||
|
|
||||||
|
// ---- channel administration ----
|
||||||
|
|
||||||
|
val canCreateChannels: Boolean get() = session.canCreateChannels()
|
||||||
|
val canEditChannels: Boolean get() = session.canEditChannels()
|
||||||
|
val canDeleteChannels: Boolean get() = session.canDeleteChannels()
|
||||||
|
|
||||||
|
/** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */
|
||||||
|
fun sortChoices(channelId: Int, parentId: Int): List<ChannelNode> =
|
||||||
|
if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId)
|
||||||
|
|
||||||
|
/** A channel's editable properties as the server has them. */
|
||||||
|
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = suspendCoroutine { done ->
|
||||||
|
conn.requestChannelSettings(channelId) { settings, error ->
|
||||||
|
done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Each of these answers null once done, else why not. */
|
||||||
|
suspend fun editChannel(channelId: Int, changes: Map<String, String>): String? =
|
||||||
|
if (changes.isEmpty()) null
|
||||||
|
else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } }
|
||||||
|
|
||||||
|
suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done ->
|
||||||
|
conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes a channel, with its sub-channels and the clients in it moved out. */
|
||||||
|
suspend fun deleteChannel(channelId: Int): String? =
|
||||||
|
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
|
||||||
|
|
||||||
|
// ---- files ----
|
||||||
|
|
||||||
|
val files = app.fileTransfers { conn }
|
||||||
|
|
||||||
|
/** The files in a directory of a channel's repository; empty for an empty one. */
|
||||||
|
suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> =
|
||||||
|
withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } }
|
||||||
|
|
||||||
|
/** Each of these answers null once done, else why not. */
|
||||||
|
suspend fun createDirectory(channelId: Int, password: String, path: String): String? =
|
||||||
|
fileCall { conn.createDirectory(channelId, password, path) }
|
||||||
|
|
||||||
|
suspend fun deleteFile(channelId: Int, password: String, path: String): String? =
|
||||||
|
fileCall { conn.deleteFile(channelId, password, path) }
|
||||||
|
|
||||||
|
suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? =
|
||||||
|
fileCall { conn.renameFile(channelId, password, from, to) }
|
||||||
|
|
||||||
|
private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) {
|
||||||
|
runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- moderation ----
|
||||||
|
|
||||||
|
val canKickFromChannel: Boolean get() = session.canKickFromChannel()
|
||||||
|
val canKickFromServer: Boolean get() = session.canKickFromServer()
|
||||||
|
val canBanClients: Boolean get() = session.canBanClients()
|
||||||
|
val canViewBanList: Boolean get() = session.canViewBanList()
|
||||||
|
val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create")
|
||||||
|
|
||||||
|
/** The longest ban we may hand out in seconds; 0 or -1 for no limit. */
|
||||||
|
val maxBanSeconds: Long get() = conn.model.maxBanSeconds()
|
||||||
|
|
||||||
|
fun kickFromChannel(clientId: Int, reason: String) {
|
||||||
|
if (session.isConnected) conn.kickFromChannel(clientId, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun kickFromServer(clientId: Int, reason: String) {
|
||||||
|
if (session.isConnected) conn.kickFromServer(clientId, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bans a client for [seconds], or for good with 0. */
|
||||||
|
fun ban(clientId: Int, seconds: Long, reason: String) {
|
||||||
|
if (session.isConnected) conn.banClient(clientId, seconds, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun serverGroupChoices(clientId: Int): List<GroupChoice> =
|
||||||
|
conn.model.getClient(clientId)?.let(conn.model::serverGroupChoices).orEmpty()
|
||||||
|
|
||||||
|
fun channelGroupChoices(clientId: Int): List<GroupChoice> =
|
||||||
|
conn.model.getClient(clientId)?.let(conn.model::channelGroupChoices).orEmpty()
|
||||||
|
|
||||||
|
fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) {
|
||||||
|
val client = conn.model.getClient(clientId) ?: return
|
||||||
|
if (session.isConnected) conn.setClientServerGroup(client.databaseId, groupId, assign)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gives a client [groupId] in the channel they are in. */
|
||||||
|
fun setChannelGroup(clientId: Int, groupId: Int) {
|
||||||
|
val client = conn.model.getClient(clientId) ?: return
|
||||||
|
if (session.isConnected) conn.setClientChannelGroup(client.databaseId, client.channelId, groupId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- ban list ----
|
||||||
|
|
||||||
|
/** The server's bans, or why they could not be read. */
|
||||||
|
/** One reading of a client's connection figures, or null when not connected. */
|
||||||
|
suspend fun connectionStats(clientId: Int): ConnectionStats? =
|
||||||
|
if (!session.isConnected) null
|
||||||
|
else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } }
|
||||||
|
|
||||||
|
suspend fun banList(): Result<List<BanEntry>> = suspendCoroutine { done ->
|
||||||
|
conn.requestBanList { bans, error ->
|
||||||
|
done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Each of these answers null once done, else why not. */
|
||||||
|
suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } }
|
||||||
|
|
||||||
|
suspend fun replaceBan(banId: Int, rule: BanRule): String? =
|
||||||
|
suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } }
|
||||||
|
|
||||||
|
suspend fun deleteBans(banIds: Collection<Int>): String? =
|
||||||
|
suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } }
|
||||||
|
|
||||||
|
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId)
|
||||||
|
|
||||||
|
fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId)
|
||||||
|
|
||||||
|
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId)
|
||||||
|
|
||||||
|
/** Uploads [data] as our avatar; null once it is set, else why not. */
|
||||||
|
suspend fun setAvatar(data: ByteArray): String? {
|
||||||
|
if (!session.isConnected) return "Not connected"
|
||||||
|
val file = withContext(Dispatchers.IO) {
|
||||||
|
File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) }
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } }
|
||||||
|
} finally {
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- details ----
|
||||||
|
|
||||||
|
fun serverDetails(): Details? =
|
||||||
|
if (session.isConnected) Details.server(conn.model, "${conn.serverHost}:${conn.serverPort}") else null
|
||||||
|
|
||||||
|
fun channelDetails(channelId: Int): Details? = conn.model.getChannel(channelId)?.let(Details::channel)
|
||||||
|
|
||||||
|
fun clientDetails(clientId: Int): Details? = conn.model.getClient(clientId)?.let {
|
||||||
|
Details.client(it, conn.model, app.contactStore.find(it.uniqueId))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Asks the server for what the channel's details lack; they change once it answers. */
|
||||||
|
fun requestChannelDetails(channelId: Int) {
|
||||||
|
val channel = conn.model.getChannel(channelId) ?: return
|
||||||
|
if (session.isConnected && !channel.descriptionLoaded) conn.requestChannelInfo(channelId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestClientDetails(clientId: Int) {
|
||||||
|
if (session.isConnected) conn.requestClientInfo(clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Files a client on the server as a contact; a new entry takes the type's defaults. */
|
||||||
|
fun addContact(clientId: Int, type: ContactType) {
|
||||||
|
val client = conn.model.getClient(clientId) ?: return
|
||||||
|
app.contactStore.add(client.uniqueId, client.nickname, type, app.settings.contactDefaults)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun contactsChanged() {
|
||||||
|
treeScope.launch { conn.applyContacts() }
|
||||||
|
scheduleTree(structure = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- chat ----
|
||||||
|
|
||||||
|
/** Opens the private chat with a client, loading what was said before. */
|
||||||
|
fun openPrivateChat(clientId: Int): ChatKey.Private {
|
||||||
|
val key = ChatKey.Private(clientId)
|
||||||
|
val client = conn.model.getClient(clientId)
|
||||||
|
if (client != null) {
|
||||||
|
_chats.update { chats ->
|
||||||
|
chats.update(key, conn.displayName(client)) { it.copy(uniqueId = client.uniqueId) }
|
||||||
|
}
|
||||||
|
conn.loadPrivateChatHistory(clientId, client.uniqueId)
|
||||||
|
}
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
|
||||||
|
fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) }
|
||||||
|
|
||||||
|
fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text)
|
||||||
|
|
||||||
|
/** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */
|
||||||
|
suspend fun sendFile(key: ChatKey, uri: Uri) {
|
||||||
|
app.openShared(uri)
|
||||||
|
.onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) }
|
||||||
|
.onFailure { app.error(it.message ?: "Could not read the file") }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scope(key: ChatKey) = when (key) {
|
||||||
|
ChatKey.Server -> ChatScope.SERVER
|
||||||
|
ChatKey.Channel -> ChatScope.CHANNEL
|
||||||
|
is ChatKey.Private -> ChatScope.PRIVATE
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0
|
||||||
|
|
||||||
|
/** Where files shared on this server lie; empty before it is known. */
|
||||||
|
private val room: String get() = conn.serverUniqueId().orEmpty()
|
||||||
|
|
||||||
|
fun markRead(key: ChatKey) {
|
||||||
|
if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun requestChat(clientId: Int) {
|
||||||
|
_chatRequest.value = ChatKey.Private(clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun chatRequestHandled() {
|
||||||
|
_chatRequest.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Answers a private message from its notification. */
|
||||||
|
internal fun reply(clientId: Int, text: String) {
|
||||||
|
if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun append(key: ChatKey, title: String, html: String) {
|
||||||
|
if (html.isEmpty()) return
|
||||||
|
val line = ChatLine(lineIds.incrementAndGet(), html)
|
||||||
|
_chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setHistory(key: ChatKey, title: String, entries: List<String>) {
|
||||||
|
val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() }
|
||||||
|
.map { ChatLine(lineIds.incrementAndGet(), it) }
|
||||||
|
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text))
|
||||||
|
|
||||||
|
// ---- snapshots ----
|
||||||
|
|
||||||
|
private fun snapshotState(): SessionState {
|
||||||
|
val self = conn.model.getClient(conn.selfClientId)
|
||||||
|
return SessionState(
|
||||||
|
title = session.title(),
|
||||||
|
status = network.status ?: session.status(),
|
||||||
|
connected = session.isConnected,
|
||||||
|
busy = isBusy,
|
||||||
|
micActive = micOwner && app.hasMicPermission(),
|
||||||
|
micPermission = app.hasMicPermission(),
|
||||||
|
micMuted = session.isMicMuted,
|
||||||
|
deafened = session.isDeafened,
|
||||||
|
away = session.isAway,
|
||||||
|
selfClientId = if (session.isConnected) conn.selfClientId else 0,
|
||||||
|
channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
|
||||||
|
inputMode = app.settings.inputMode,
|
||||||
|
hostButton = if (session.isConnected) conn.model.hostButton() else null,
|
||||||
|
self = session.selfState(),
|
||||||
|
whisper = session.whisper()?.label,
|
||||||
|
whisperNobody = session.isWhisperingToNobody,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun refresh() {
|
||||||
|
_state.value = snapshotState()
|
||||||
|
app.serverChanged(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes a new tree snapshot soon; [structure] when channels or clients came, went or moved. */
|
||||||
|
internal fun scheduleTree(structure: Boolean) {
|
||||||
|
if (structure) structureChanged.set(true)
|
||||||
|
if (!treePending.compareAndSet(false, true)) return
|
||||||
|
treeScope.launch {
|
||||||
|
delay(TREE_FRAME_MS)
|
||||||
|
treePending.set(false)
|
||||||
|
if (structureChanged.getAndSet(false)) roots = conn.model.buildTree()
|
||||||
|
_tree.value = ServerTree.of(roots, conn.model, conn.contacts, app.settings.colorContacts,
|
||||||
|
app.settings.countryFlags, app.settings.clientRowColors)
|
||||||
|
val serverName = if (session.isConnected) conn.model.serverName.orEmpty() else ""
|
||||||
|
val channelName = session.currentChannel()?.name.orEmpty()
|
||||||
|
_chats.update {
|
||||||
|
it.copy(
|
||||||
|
server = it.server.copy(title = serverName.ifBlank { "Server" }),
|
||||||
|
channel = it.channel.copy(title = channelName.ifBlank { "Channel" }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class Listener : ServerSession.Listener {
|
||||||
|
override fun onSessionChanged() = refresh()
|
||||||
|
override fun onSystemMessage(text: String) = system(text)
|
||||||
|
|
||||||
|
override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) {
|
||||||
|
val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname
|
||||||
|
val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text, room)
|
||||||
|
append(key(scope, peerClientId), peerName, html)
|
||||||
|
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStatus(status: String) {}
|
||||||
|
|
||||||
|
override fun onConnected() {
|
||||||
|
network.onConnected()
|
||||||
|
app.connected(this@ServerController)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDisconnected(reason: String?) {
|
||||||
|
network.onDisconnected()
|
||||||
|
app.notifier.clearServer(id)
|
||||||
|
_chats.update { it.copy(private = emptyList()) }
|
||||||
|
app.disconnected(this@ServerController)
|
||||||
|
scheduleTree(structure = true)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onModelChanged() {
|
||||||
|
scheduleTree(structure = true)
|
||||||
|
// A server edit may have changed it.
|
||||||
|
if (session.isConnected && conn.model.hostButton() != _state.value.hostButton) refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onServerIconChanged(iconId: Long) =
|
||||||
|
app.serverIconChanged(session.address(), session.port(), iconId)
|
||||||
|
|
||||||
|
override fun onInfoUpdated() {
|
||||||
|
_infoUpdates.update { it + 1 }
|
||||||
|
// Avatars announce their arrival as info updates.
|
||||||
|
images.loaded()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onIconsUpdated() = images.loaded()
|
||||||
|
|
||||||
|
override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) {
|
||||||
|
append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room))
|
||||||
|
if (scope == ChatScope.PRIVATE && !app.foreground) {
|
||||||
|
app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onChatHistory(scope: ChatScope, htmlEntries: List<String>) {
|
||||||
|
if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List<String>) =
|
||||||
|
setHistory(ChatKey.Private(clientId), nickname, htmlEntries)
|
||||||
|
|
||||||
|
override fun onTalkStateChanged(clientId: Int, talking: Boolean) {
|
||||||
|
if (clientId == conn.selfClientId && micOwner) app.talking(talking)
|
||||||
|
scheduleTree(structure = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onError(message: String) = app.error(message)
|
||||||
|
|
||||||
|
override fun onPoke(fromName: String, message: String) = app.poked(fromName, message)
|
||||||
|
|
||||||
|
override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message))
|
||||||
|
override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) {
|
||||||
|
ChatScope.SERVER -> ChatKey.Server
|
||||||
|
ChatScope.CHANNEL -> ChatKey.Channel
|
||||||
|
ChatScope.PRIVATE -> ChatKey.Private(peerClientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TREE_FRAME_MS = 30L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import eu.lixko.ts3j.client.net.TeamspeakConnection
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One server's icons and its clients' avatars, decoded once. What is still
|
||||||
|
* downloading reads as null until [version] moves on.
|
||||||
|
*/
|
||||||
|
class ServerImages internal constructor(private val conn: TeamspeakConnection) {
|
||||||
|
|
||||||
|
private val icons = ConcurrentHashMap<Long, ImageBitmap>()
|
||||||
|
private val avatars = ConcurrentHashMap<String, Picture>()
|
||||||
|
|
||||||
|
private val _version = MutableStateFlow(0)
|
||||||
|
val version: StateFlow<Int> = _version
|
||||||
|
|
||||||
|
internal fun loaded() = _version.update { it + 1 }
|
||||||
|
|
||||||
|
fun icon(id: Long): ImageBitmap? {
|
||||||
|
if (id == 0L) return null
|
||||||
|
icons[id]?.let { return it }
|
||||||
|
val bitmap = conn.icons.get(id)?.let { decode(it, ICON_PX) } ?: return null
|
||||||
|
icons[id] = bitmap
|
||||||
|
return bitmap
|
||||||
|
}
|
||||||
|
|
||||||
|
fun avatar(uniqueId: String, flag: String): Picture? {
|
||||||
|
if (flag.isEmpty()) return null
|
||||||
|
avatars[flag]?.let { return it }
|
||||||
|
val picture = conn.avatars.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null
|
||||||
|
avatars[flag] = picture
|
||||||
|
return picture
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The avatar's file as the server keeps it; null while it has none or it is still downloading. */
|
||||||
|
fun avatarData(uniqueId: String, flag: String): ByteArray? =
|
||||||
|
if (flag.isEmpty()) null else conn.avatars.get(uniqueId, flag)?.data()
|
||||||
|
|
||||||
|
/** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */
|
||||||
|
private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? {
|
||||||
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
|
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
|
||||||
|
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||||
|
var sample = 1
|
||||||
|
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2
|
||||||
|
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||||
|
return BitmapFactory.decodeByteArray(data, 0, data.size, options)?.asImageBitmap()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val ICON_PX = 64
|
||||||
|
const val AVATAR_PX = 512
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Immutable
|
||||||
|
import eu.lixko.ts3j.client.config.ClientRowColors
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactStore
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactType
|
||||||
|
import eu.lixko.ts3j.client.net.ChannelNode
|
||||||
|
import eu.lixko.ts3j.client.net.ClientEntry
|
||||||
|
import eu.lixko.ts3j.client.net.ClientStatus
|
||||||
|
import eu.lixko.ts3j.client.net.ServerModel
|
||||||
|
import eu.lixko.ts3j.client.net.Spacers
|
||||||
|
import eu.lixko.ts3j.client.net.TreeMatch
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A copy of the channel tree taken at one moment. The model's own nodes change in place
|
||||||
|
* on connection threads, which Compose cannot observe; these never change.
|
||||||
|
*/
|
||||||
|
@Immutable
|
||||||
|
data class ServerTree(
|
||||||
|
val channels: List<ChannelItem> = emptyList(),
|
||||||
|
/** The server's own icon; 0 for none. */
|
||||||
|
val serverIconId: Long = 0,
|
||||||
|
/** Whether client rows show their country's flag. */
|
||||||
|
val countryFlags: Boolean = false,
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun channel(id: Int): ChannelItem? = find(channels) { it.id == id }
|
||||||
|
|
||||||
|
fun client(id: Int): ClientItem? {
|
||||||
|
var found: ClientItem? = null
|
||||||
|
find(channels) { c -> found = c.clients.firstOrNull { it.id == id }; found != null }
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The channels from the root down to the one [clientId] is in; null when they are not in the tree. */
|
||||||
|
fun pathTo(clientId: Int): List<Int>? {
|
||||||
|
fun walk(items: List<ChannelItem>): List<Int>? {
|
||||||
|
for (c in items) {
|
||||||
|
if (c.clients.any { it.id == clientId }) return listOf(c.id)
|
||||||
|
walk(c.children)?.let { return listOf(c.id) + it }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return walk(channels)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The channels from the root down to [channelId]'s parent; null when it is not in the tree. */
|
||||||
|
fun parentsOf(channelId: Int): List<Int>? {
|
||||||
|
fun walk(items: List<ChannelItem>, above: List<Int>): List<Int>? {
|
||||||
|
for (c in items) {
|
||||||
|
if (c.id == channelId) return above
|
||||||
|
walk(c.children, above + c.id)?.let { return it }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return walk(channels, emptyList())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The ids of what [find] matches, in reading order. */
|
||||||
|
fun hits(find: TreeFind): List<Int> {
|
||||||
|
val out = ArrayList<Int>()
|
||||||
|
fun walk(items: List<ChannelItem>) {
|
||||||
|
for (c in items) {
|
||||||
|
if (find.matches(c)) out += c.id
|
||||||
|
c.clients.forEach { if (find.matches(it)) out += it.id }
|
||||||
|
walk(c.children)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!find.query.isEmpty) walk(channels)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only what [find] matches: a matching channel with its clients, a matching client, and the channels leading to either. */
|
||||||
|
fun only(find: TreeFind): ServerTree {
|
||||||
|
fun keep(c: ChannelItem): ChannelItem? {
|
||||||
|
val matches = find.matches(c)
|
||||||
|
val clients = if (matches) c.clients else c.clients.filter(find::matches)
|
||||||
|
val children = c.children.mapNotNull(::keep)
|
||||||
|
return if (matches || clients.isNotEmpty() || children.isNotEmpty()) c.copy(clients = clients, children = children) else null
|
||||||
|
}
|
||||||
|
return copy(channels = channels.mapNotNull(::keep))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun find(items: List<ChannelItem>, test: (ChannelItem) -> Boolean): ChannelItem? {
|
||||||
|
for (c in items) {
|
||||||
|
if (test(c)) return c
|
||||||
|
find(c.children, test)?.let { return it }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun of(roots: List<ChannelNode>, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
|
||||||
|
countryFlags: Boolean, rowColors: ClientRowColors): ServerTree =
|
||||||
|
ServerTree(
|
||||||
|
roots.map { channel(it, model, contacts, colorContacts, rowColors) },
|
||||||
|
model.serverIconId(),
|
||||||
|
countryFlags,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun channel(c: ChannelNode, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
|
||||||
|
rowColors: ClientRowColors): ChannelItem {
|
||||||
|
val clients = c.clients
|
||||||
|
val spacer = Spacers.parse(c.name)
|
||||||
|
return ChannelItem(
|
||||||
|
id = c.id,
|
||||||
|
name = c.name ?: "",
|
||||||
|
spacer = spacer,
|
||||||
|
iconId = if (spacer == null) c.iconId else 0,
|
||||||
|
locked = c.hasPassword,
|
||||||
|
full = c.maxClients >= 0 && clients.size >= c.maxClients,
|
||||||
|
subscribed = c.subscribed,
|
||||||
|
clients = clients.map { client(it, model, contacts, colorContacts, rowColors) },
|
||||||
|
children = c.children.map { channel(it, model, contacts, colorContacts, rowColors) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun client(c: ClientEntry, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
|
||||||
|
rowColors: ClientRowColors): ClientItem {
|
||||||
|
val contact = contacts.find(c.uniqueId)
|
||||||
|
val away = c.away && c.awayMessage.isNotEmpty() && contact?.ignoreAwayMessage != true
|
||||||
|
val status = ClientStatus.of(c)
|
||||||
|
return ClientItem(
|
||||||
|
id = c.id,
|
||||||
|
uniqueId = c.uniqueId,
|
||||||
|
nickname = c.nickname ?: "",
|
||||||
|
name = contact?.displayName(c.nickname) ?: c.nickname ?: "",
|
||||||
|
awayMessage = if (away) c.awayMessage else "",
|
||||||
|
status = status,
|
||||||
|
background = rowColors.of(status),
|
||||||
|
self = c.self,
|
||||||
|
contactType = contact?.type,
|
||||||
|
highlight = if (colorContacts) contact?.type ?: ContactType.NEUTRAL else ContactType.NEUTRAL,
|
||||||
|
groupIconIds = (model.serverGroupsOf(c.serverGroupIds) + listOfNotNull(model.channelGroup(c.channelGroupId)))
|
||||||
|
.map { it.iconId }.filter { it != 0L },
|
||||||
|
avatarFlag = c.avatarFlag.orEmpty(),
|
||||||
|
country = c.country.orEmpty(),
|
||||||
|
serverGroupIds = c.serverGroupIds.toList(),
|
||||||
|
channelGroupId = c.channelGroupId,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the find bar looks for in the tree: clients, or with [channels] channels. */
|
||||||
|
@Immutable
|
||||||
|
data class TreeFind(val query: TextQuery, val channels: Boolean) {
|
||||||
|
fun matches(c: ChannelItem) = channels && TreeMatch.channel(query, c.name)
|
||||||
|
fun matches(c: ClientItem) = !channels && TreeMatch.client(query, c.nickname, c.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Immutable
|
||||||
|
data class ChannelItem(
|
||||||
|
val id: Int,
|
||||||
|
val name: String,
|
||||||
|
/** Set for a spacer: a cosmetic separator rather than a channel to join. */
|
||||||
|
val spacer: Spacers.Spacer?,
|
||||||
|
val locked: Boolean,
|
||||||
|
val full: Boolean,
|
||||||
|
val subscribed: Boolean,
|
||||||
|
/** 0 for none. */
|
||||||
|
val iconId: Long,
|
||||||
|
val clients: List<ClientItem>,
|
||||||
|
val children: List<ChannelItem>,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Immutable
|
||||||
|
data class ClientItem(
|
||||||
|
val id: Int,
|
||||||
|
val uniqueId: String,
|
||||||
|
val nickname: String,
|
||||||
|
/** The name shown: the contact's own name for them where there is one. */
|
||||||
|
val name: String,
|
||||||
|
val awayMessage: String,
|
||||||
|
val status: ClientStatus,
|
||||||
|
/** The row's background colour, ARGB; 0 for none. */
|
||||||
|
val background: Int,
|
||||||
|
val self: Boolean,
|
||||||
|
/** How the client is filed in the contacts; null when it is not one. */
|
||||||
|
val contactType: ContactType?,
|
||||||
|
/** The contact colour the name is drawn in, NEUTRAL when contacts are not coloured. */
|
||||||
|
val highlight: ContactType,
|
||||||
|
/** The icons of the client's server groups, then of its channel group, as TeamSpeak lines them up. */
|
||||||
|
val groupIconIds: List<Long>,
|
||||||
|
/** The MD5 of the client's avatar; empty for none. */
|
||||||
|
val avatarFlag: String,
|
||||||
|
/** The code of the country the server places the client in; empty when it cannot tell. */
|
||||||
|
val country: String,
|
||||||
|
val serverGroupIds: List<Int>,
|
||||||
|
val channelGroupId: Int,
|
||||||
|
)
|
||||||
@@ -0,0 +1,657 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
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.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.TeamspeakConnection
|
||||||
|
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. */
|
||||||
|
data class SessionState(
|
||||||
|
val title: String = "",
|
||||||
|
val status: String = "Not connected",
|
||||||
|
val connected: Boolean = false,
|
||||||
|
val busy: Boolean = false,
|
||||||
|
/** Whether this server holds the microphone, which only one server can at a time. */
|
||||||
|
val micActive: Boolean = false,
|
||||||
|
val micPermission: Boolean = false,
|
||||||
|
val micMuted: Boolean = false,
|
||||||
|
val deafened: Boolean = false,
|
||||||
|
val away: Boolean = false,
|
||||||
|
val selfClientId: Int = 0,
|
||||||
|
val channelId: Int = 0,
|
||||||
|
val inputMode: Settings.InputMode = Settings.InputMode.VOICE_ACTIVATION,
|
||||||
|
val hostButton: HostButton? = null,
|
||||||
|
/** What the tree shows for the local client, and the connection notification too. */
|
||||||
|
val self: SelfState = SelfState.DISCONNECTED,
|
||||||
|
/** Who the microphone whispers to instead of the channel; null when it talks in the channel. */
|
||||||
|
val whisper: String? = null,
|
||||||
|
/** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */
|
||||||
|
val whisperNobody: 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
|
||||||
|
data class Error(val message: String) : SessionEvent
|
||||||
|
/** A link or shortcut brought a server on screen, in front of whatever page was open. */
|
||||||
|
data object ServerOpened : SessionEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The servers the app is on and what they share, outliving any activity: [ConnectionService]
|
||||||
|
* 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)
|
||||||
|
internal val cacheDir: File get() = context.cacheDir
|
||||||
|
internal fun fileTransfers(conn: () -> TeamspeakConnection) = FileTransfers(context, conn)
|
||||||
|
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 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 network = NetworkFollower(context)
|
||||||
|
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
private val nextId = AtomicInteger()
|
||||||
|
/** Touched on the main thread only, as [Sessions] wants. */
|
||||||
|
private val sessions = Sessions { main.post(::microphoneMoved) }
|
||||||
|
|
||||||
|
private val _servers = MutableStateFlow(emptyList<ServerController>())
|
||||||
|
/** Every server the app is on or getting on, in the order they were connected. */
|
||||||
|
val servers: StateFlow<List<ServerController>> = _servers
|
||||||
|
|
||||||
|
private val _current = MutableStateFlow<ServerController?>(null)
|
||||||
|
/** The server on screen; null when there is none. */
|
||||||
|
val current: StateFlow<ServerController?> = _current
|
||||||
|
|
||||||
|
private val _micOwner = MutableStateFlow<ServerController?>(null)
|
||||||
|
/** The server capturing with the microphone; null when none is. */
|
||||||
|
val micOwner: StateFlow<ServerController?> = _micOwner
|
||||||
|
|
||||||
|
/** Why the last connection that ended did, for the connect form to show; null when it was left. */
|
||||||
|
private val _lastEnd = MutableStateFlow<String?>(null)
|
||||||
|
val lastEnd: StateFlow<String?> = _lastEnd
|
||||||
|
|
||||||
|
/** Copies of the contacts, as the store's own entries change in place. */
|
||||||
|
private val _contacts = MutableStateFlow(contactCopies())
|
||||||
|
val contacts: StateFlow<List<Contact>> = _contacts
|
||||||
|
|
||||||
|
private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList())
|
||||||
|
val bookmarks: StateFlow<List<Bookmark>> = _bookmarks
|
||||||
|
|
||||||
|
private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16)
|
||||||
|
val events: SharedFlow<SessionEvent> = _events
|
||||||
|
|
||||||
|
private val _onScreen = MutableStateFlow(false)
|
||||||
|
val onScreen: StateFlow<Boolean> = _onScreen
|
||||||
|
|
||||||
|
/** Whether the app is on screen; pokes and private messages are notified of while it is not. */
|
||||||
|
var foreground: Boolean
|
||||||
|
get() = _onScreen.value
|
||||||
|
set(value) {
|
||||||
|
_onScreen.value = value
|
||||||
|
if (value) notifier.clearPokes()
|
||||||
|
// The process may be let go of any time once out of sight.
|
||||||
|
else contactStore.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val levels = LevelMonitor(settings, audio)
|
||||||
|
val micLevel: StateFlow<MicLevel> = levels.level
|
||||||
|
@Volatile
|
||||||
|
private var watchingLevel = false
|
||||||
|
|
||||||
|
private val routePrefs = AudioRoutePrefs(context)
|
||||||
|
private val _route = MutableStateFlow(routePrefs.load())
|
||||||
|
val route: StateFlow<AudioRoute> = _route
|
||||||
|
|
||||||
|
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
|
||||||
|
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
|
||||||
|
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
|
||||||
|
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
|
||||||
|
|
||||||
|
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
|
||||||
|
|
||||||
|
init {
|
||||||
|
audio.setRoute(_route.value)
|
||||||
|
audio.addDeviceListener {
|
||||||
|
_inputDevices.value = audio.io().inputDevices()
|
||||||
|
_outputDevices.value = audio.io().outputDevices()
|
||||||
|
}
|
||||||
|
// Mutations report on whichever thread made them, a connection thread included.
|
||||||
|
contactStore.addListener {
|
||||||
|
_contacts.value = contactCopies()
|
||||||
|
_servers.value.forEach(ServerController::contactsChanged)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 }
|
||||||
|
val lastAddress: String get() = settings.lastAddress
|
||||||
|
|
||||||
|
// ---- connection ----
|
||||||
|
|
||||||
|
/** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */
|
||||||
|
fun connect(address: String, nickname: String, password: String = "", identityId: String = "") {
|
||||||
|
val (host, port) = parseAddress(address)
|
||||||
|
settings.lastAddress = address
|
||||||
|
if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname
|
||||||
|
settings.save()
|
||||||
|
start(host, port, nickname, password, identityId, "", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connect(bookmark: Bookmark) {
|
||||||
|
start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password,
|
||||||
|
bookmark.identityId, bookmark.channel, bookmark.channelPassword) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
|
||||||
|
channel: String, channelPassword: String) {
|
||||||
|
start { it.start(host, port, nickname, password, identityId, channel, channelPassword) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun start(connect: (ServerController) -> Unit) {
|
||||||
|
val server = ServerController(nextId.incrementAndGet(), this)
|
||||||
|
sessions.add(server.session)
|
||||||
|
_servers.update { it + server }
|
||||||
|
_current.value = server
|
||||||
|
_lastEnd.value = null
|
||||||
|
context.startForegroundService(Intent(context, ConnectionService::class.java))
|
||||||
|
connect(server)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Goes where a `ts3server://` link leads: on a server we are on already, to the channel it
|
||||||
|
* names; else connects there as another server.
|
||||||
|
*/
|
||||||
|
fun open(link: ServerLink, identityId: String = "") {
|
||||||
|
if (link.bookmarkLabel.isNotEmpty()) {
|
||||||
|
bookmarkStore.add(link.toBookmark())
|
||||||
|
saveBookmarks()
|
||||||
|
}
|
||||||
|
val on = _servers.value.firstOrNull { it.session.isOn(link) }
|
||||||
|
if (on != null) {
|
||||||
|
_current.value = on
|
||||||
|
on.session.follow(link)
|
||||||
|
} else {
|
||||||
|
start { it.open(link, identityId) }
|
||||||
|
}
|
||||||
|
_events.tryEmit(SessionEvent.ServerOpened)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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)
|
||||||
|
if (bookmark == null) {
|
||||||
|
error("That bookmark no longer exists")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return ServerLink.of(bookmark).also { open(it, bookmark.identityId) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private var startedUp = false
|
||||||
|
|
||||||
|
/** Connects the bookmarks flagged for startup, once per process; [opened] is a server the launch already went to. */
|
||||||
|
fun connectStartupBookmarks(opened: ServerLink?) {
|
||||||
|
if (startedUp) return
|
||||||
|
startedUp = true
|
||||||
|
for (b in bookmarkStore.startupBookmarks()) {
|
||||||
|
if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun select(server: ServerController) {
|
||||||
|
if (server in _servers.value) _current.value = server
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Leaves every server before returning, for when the app goes away with the connections. */
|
||||||
|
fun leave() {
|
||||||
|
val servers = _servers.value
|
||||||
|
servers.forEach(ServerController::leaving)
|
||||||
|
ServerSession.shutdownAll(servers.map { it.session })
|
||||||
|
contactStore.flush()
|
||||||
|
attachments.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id }
|
||||||
|
|
||||||
|
/** A server's state changed; one that is done with goes from the list. */
|
||||||
|
internal fun serverChanged(server: ServerController) {
|
||||||
|
if (server.micOwner) updateLevels()
|
||||||
|
if (server.ended) main.post { remove(server) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun remove(server: ServerController) {
|
||||||
|
if (server !in _servers.value || !server.ended) return
|
||||||
|
sessions.remove(server.session)
|
||||||
|
val rest = _servers.value - server
|
||||||
|
_servers.value = rest
|
||||||
|
if (_current.value == server) _current.value = rest.lastOrNull()
|
||||||
|
server.dispose()
|
||||||
|
val reason = server.state.value.status
|
||||||
|
_lastEnd.value = if (server.left) null else reason
|
||||||
|
if (!server.left && rest.isNotEmpty()) error("${server.state.value.title}: $reason")
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun connected(server: ServerController) {
|
||||||
|
// The first connect generates an identity when there was none.
|
||||||
|
identities.refresh()
|
||||||
|
main.post {
|
||||||
|
// Without the permission yet, the UI hands the microphone over once it is granted.
|
||||||
|
if (hasMicPermission()) sessions.connected(server.session)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun disconnected(server: ServerController) {
|
||||||
|
main.post { sessions.disconnected(server.session) }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun error(message: String) {
|
||||||
|
_events.tryEmit(SessionEvent.Error(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun poked(from: String, message: String) {
|
||||||
|
_events.tryEmit(SessionEvent.Poke(from, message))
|
||||||
|
if (!foreground) notifier.poke(from, BBCode.toPlain(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
|
||||||
|
|
||||||
|
// ---- bookmarks ----
|
||||||
|
|
||||||
|
/** 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 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The channels of a server we are on at [host]:[port], to pick one to join. */
|
||||||
|
fun channelPathsAt(host: String, port: Int): List<String> =
|
||||||
|
_servers.value.firstOrNull {
|
||||||
|
it.isConnected && it.session.port() == port && it.session.address().equals(host.trim(), ignoreCase = true)
|
||||||
|
}?.session?.channelPaths().orEmpty()
|
||||||
|
|
||||||
|
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<List<WhisperList>> = _whisperLists
|
||||||
|
|
||||||
|
private fun whisperListCopies() = whisperListStore.all().map { it.copy() }
|
||||||
|
|
||||||
|
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
|
||||||
|
fun saveWhisperList(index: Int, list: WhisperList) {
|
||||||
|
val all = whisperListStore.all()
|
||||||
|
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
|
||||||
|
whisperListStore.save()
|
||||||
|
_whisperLists.value = whisperListCopies()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
|
||||||
|
fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) {
|
||||||
|
val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName)
|
||||||
|
add(list)
|
||||||
|
saveWhisperList(index, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeWhisperList(index: Int) {
|
||||||
|
val all = whisperListStore.all()
|
||||||
|
if (index !in all.indices) return
|
||||||
|
all.removeAt(index)
|
||||||
|
whisperListStore.save()
|
||||||
|
_whisperLists.value = whisperListCopies()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- contacts ----
|
||||||
|
|
||||||
|
private fun contactCopies(): List<Contact> = contactStore.all().map { it.copy() }
|
||||||
|
|
||||||
|
/** A copy of the contact to edit and hand back to [saveContact]. */
|
||||||
|
fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy()
|
||||||
|
|
||||||
|
fun saveContact(contact: Contact) = contactStore.put(contact)
|
||||||
|
|
||||||
|
fun removeContact(uniqueId: String) = contactStore.remove(uniqueId)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
|
||||||
|
*
|
||||||
|
* @return how many contacts the file held and how many of them were new
|
||||||
|
*/
|
||||||
|
suspend fun importContacts(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
|
||||||
|
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
|
||||||
|
found.size to if (found.isEmpty()) 0 else contactStore.merge(found)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- myTeamSpeak ----
|
||||||
|
|
||||||
|
/** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */
|
||||||
|
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
|
||||||
|
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings)
|
||||||
|
|
||||||
|
private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn)
|
||||||
|
val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn
|
||||||
|
|
||||||
|
/** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */
|
||||||
|
internal val attachments = ChatAttachments(myTeamSpeak).also {
|
||||||
|
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account =
|
||||||
|
withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) }
|
||||||
|
.also {
|
||||||
|
_myTeamSpeakSignedIn.value = true
|
||||||
|
// 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
|
||||||
|
withContext(Dispatchers.IO) { attachments.close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches a file shared in chat whole. */
|
||||||
|
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
|
||||||
|
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
|
||||||
|
|
||||||
|
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
|
||||||
|
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
|
||||||
|
val data = downloadAttachment(ref)
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
|
||||||
|
out.use { it.write(data) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file picked to share in chat, or why it cannot be. */
|
||||||
|
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val resolver = context.contentResolver
|
||||||
|
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
|
||||||
|
null, null, null)?.use { c ->
|
||||||
|
if (!c.moveToFirst()) null
|
||||||
|
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
|
||||||
|
} ?: ("" to -1L)
|
||||||
|
when {
|
||||||
|
size < 0 -> throw IOException("Could not read the file's size")
|
||||||
|
size > ChatAttachments.MAX_UPLOAD_BYTES ->
|
||||||
|
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
|
||||||
|
}
|
||||||
|
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
|
||||||
|
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
|
||||||
|
|
||||||
|
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */
|
||||||
|
suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
|
||||||
|
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
|
||||||
|
.also {
|
||||||
|
_bookmarks.value = bookmarkStore.all().toList()
|
||||||
|
identities.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- sound packs ----
|
||||||
|
|
||||||
|
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
|
||||||
|
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
|
||||||
|
|
||||||
|
val soundPack: SoundPack? get() = sounds.pack()
|
||||||
|
|
||||||
|
fun setCountryFlags(shown: Boolean) {
|
||||||
|
settings.countryFlags = shown
|
||||||
|
settings.save()
|
||||||
|
servers.value.forEach { it.scheduleTree(structure = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Puts new client row colours, already set in [settings], into effect. */
|
||||||
|
fun clientRowColorsChanged() {
|
||||||
|
settings.save()
|
||||||
|
servers.value.forEach { it.scheduleTree(structure = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setDescriptionPictures(shown: Boolean) {
|
||||||
|
settings.descriptionPictures = 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() =
|
||||||
|
context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
|
/** Moves the microphone to [server]; needs RECORD_AUDIO granted. */
|
||||||
|
fun giveMicrophoneTo(server: ServerController) {
|
||||||
|
if (server.isConnected) sessions.giveMicrophoneTo(server.session)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens the microphone of the server holding it while push-to-talk is held. */
|
||||||
|
fun setPushToTalk(pressed: Boolean) = sessions.setPushToTalk(pressed)
|
||||||
|
|
||||||
|
/** Transmits on the server holding the microphone while held, past the voice-activation gate too. */
|
||||||
|
fun setForceTransmit(pressed: Boolean) = sessions.setForceTransmit(pressed)
|
||||||
|
|
||||||
|
private fun microphoneMoved() {
|
||||||
|
val owner = sessions.microphoneOwner()
|
||||||
|
for (server in _servers.value) {
|
||||||
|
server.micOwner = server.session == owner
|
||||||
|
server.refresh()
|
||||||
|
}
|
||||||
|
_micOwner.value = _servers.value.firstOrNull { it.micOwner }
|
||||||
|
updateLevels()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
|
||||||
|
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
|
||||||
|
/** Whether push to talk floats a button over other apps while this one is off screen. */
|
||||||
|
val pttOverlay: StateFlow<Boolean> = _pttOverlay
|
||||||
|
|
||||||
|
fun setPttOverlay(enabled: Boolean) {
|
||||||
|
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
|
||||||
|
_pttOverlay.value = enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Switches between push to talk and voice activation; returns the new mode. */
|
||||||
|
fun toggleInputMode(): Settings.InputMode {
|
||||||
|
settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK)
|
||||||
|
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK
|
||||||
|
applySettings()
|
||||||
|
return settings.inputMode
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saves the settings and puts the voice and device ones into effect at once. */
|
||||||
|
fun applySettings() {
|
||||||
|
settings.save()
|
||||||
|
soundPlayer.setOutputDevice(settings.outputDevice)
|
||||||
|
try {
|
||||||
|
for (server in _servers.value) {
|
||||||
|
server.playback?.setMasterVolume(settings.outputVolume)
|
||||||
|
server.playback?.setOutputDevice(settings.outputDevice)
|
||||||
|
server.playback?.setReceiveBuffer(settings.receiveBuffer)
|
||||||
|
server.microphone?.apply(settings)
|
||||||
|
server.refresh()
|
||||||
|
server.scheduleTree(structure = false)
|
||||||
|
}
|
||||||
|
levels.apply()
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
error(e.message ?: "Microphone unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
updateLevels()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateLevels() {
|
||||||
|
val owner = _micOwner.value
|
||||||
|
levels.update(watchingLevel, owner?.microphone, owner?.isBusy == true, hasMicPermission())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- notifications ----
|
||||||
|
|
||||||
|
/** Shows a private chat a notification was tapped for. */
|
||||||
|
fun requestChat(serverId: Int, clientId: Int) {
|
||||||
|
val server = server(serverId) ?: return
|
||||||
|
_current.value = server
|
||||||
|
server.requestChat(clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Answers a private message from its notification. */
|
||||||
|
fun reply(serverId: Int, clientId: Int, text: String) {
|
||||||
|
server(serverId)?.reply(clientId, text) ?: notifier.clear(serverId, clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
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<String, Int> {
|
||||||
|
val host = address.substringBefore(':').trim()
|
||||||
|
val port = address.substringAfter(':', "").trim().toIntOrNull() ?: DEFAULT_PORT
|
||||||
|
return host to port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.AssetManager
|
||||||
|
import eu.lixko.ts3j.client.config.AppDirs
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unpacks the sound packs bundled in the APK into the profile's `sound` folder, where
|
||||||
|
* [eu.lixko.ts3j.client.sound.SoundNotifier] finds packs, as they are read as plain files.
|
||||||
|
* It happens once per installed version of the app; packs of other origins in the
|
||||||
|
* folder are left alone.
|
||||||
|
*/
|
||||||
|
class SoundPackInstaller(private val context: Context) {
|
||||||
|
|
||||||
|
private val root = File(AppDirs.profile(), ASSET_DIR)
|
||||||
|
private val marker = File(root, ".bundled")
|
||||||
|
/** Where a pack is unpacked first, outside [root] so it is never seen half written. */
|
||||||
|
private val staging = File(AppDirs.profile(), ".sound-staging")
|
||||||
|
|
||||||
|
/** @return whether the packs were (re)installed, so the list of them has to be read again */
|
||||||
|
fun install(): Boolean {
|
||||||
|
val version = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime.toString()
|
||||||
|
if (marker.isFile && marker.readText() == version) return false
|
||||||
|
val assets = context.assets
|
||||||
|
for (pack in assets.list(ASSET_DIR).orEmpty()) {
|
||||||
|
staging.deleteRecursively()
|
||||||
|
copy(assets, "$ASSET_DIR/$pack", staging)
|
||||||
|
val target = File(root, pack)
|
||||||
|
target.deleteRecursively()
|
||||||
|
root.mkdirs()
|
||||||
|
check(staging.renameTo(target)) { "Cannot install sound pack $pack" }
|
||||||
|
}
|
||||||
|
root.mkdirs()
|
||||||
|
marker.writeText(version)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copy(assets: AssetManager, path: String, to: File) {
|
||||||
|
val children = assets.list(path).orEmpty()
|
||||||
|
if (children.isEmpty()) {
|
||||||
|
to.parentFile?.mkdirs()
|
||||||
|
assets.open(path).use { input -> to.outputStream().use { input.copyTo(it) } }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
to.mkdirs()
|
||||||
|
for (child in children) copy(assets, "$path/$child", File(to, child))
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val ASSET_DIR = "sound"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.speech.tts.TextToSpeech
|
||||||
|
import eu.lixko.ts3j.client.sound.SoundPlayer
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the phone's text-to-speech to a wave player, for packs that speak their
|
||||||
|
* notifications. Sentences asked for before the engine is up are dropped: they
|
||||||
|
* would come out late, past what they announce.
|
||||||
|
*/
|
||||||
|
class SpeakingSoundPlayer(context: Context, private val waves: SoundPlayer) : SoundPlayer by waves {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var ready = false
|
||||||
|
private val tts = TextToSpeech(context.applicationContext) { status -> ready = status == TextToSpeech.SUCCESS }
|
||||||
|
|
||||||
|
override fun canSpeak() = true
|
||||||
|
|
||||||
|
override fun say(text: String, volume: Double) {
|
||||||
|
if (!ready) return
|
||||||
|
val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, volume.toFloat()) }
|
||||||
|
tts.speak(text, TextToSpeech.QUEUE_ADD, params, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun shutdown() {
|
||||||
|
tts.shutdown()
|
||||||
|
waves.shutdown()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import eu.lixko.ts3j.client.config.AppDirs
|
||||||
|
|
||||||
|
class Ts3Application : Application() {
|
||||||
|
|
||||||
|
lateinit var sessions: SessionController
|
||||||
|
private set
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.util.LruCache
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.net.PictureDownloads
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
|
/** The pictures descriptions show, fetched by core's downloads and decoded while there is room. */
|
||||||
|
class WebPictures(cacheDir: File, private val settings: Settings) {
|
||||||
|
|
||||||
|
sealed interface State {
|
||||||
|
data object Loading : State
|
||||||
|
data object Broken : State
|
||||||
|
data class Shown(val picture: Picture) : State
|
||||||
|
}
|
||||||
|
|
||||||
|
private val downloads = PictureDownloads(File(cacheDir, "pictures"), false)
|
||||||
|
private val decoded = LruCache<String, Picture>(CACHED)
|
||||||
|
private val undecodable = ConcurrentHashMap.newKeySet<String>()
|
||||||
|
|
||||||
|
private val _version = MutableStateFlow(0)
|
||||||
|
/** Moves on whenever a download has come or failed. */
|
||||||
|
val version: StateFlow<Int> = _version
|
||||||
|
|
||||||
|
init {
|
||||||
|
downloads.addListener { _version.update { it + 1 } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches pictures whose addresses start with [scheme] from [source] rather than the web. */
|
||||||
|
fun addSource(scheme: String, source: PictureDownloads.Source) = downloads.addSource(scheme, source)
|
||||||
|
|
||||||
|
/** Asks again for the pictures that could not be had. */
|
||||||
|
fun retryFailed() = downloads.retryFailed()
|
||||||
|
|
||||||
|
/** Whether pictures are shown at all, rather than links to them. */
|
||||||
|
val enabled: Boolean get() = settings.descriptionPictures
|
||||||
|
|
||||||
|
suspend fun state(url: String): State {
|
||||||
|
decoded.get(url)?.let { return State.Shown(it) }
|
||||||
|
if (url in undecodable) return State.Broken
|
||||||
|
val file = downloads.get(url) ?: return if (downloads.failed(url)) State.Broken else State.Loading
|
||||||
|
val picture = withContext(Dispatchers.IO) { decodePicture(file.readBytes(), MAX_PX) }
|
||||||
|
if (picture == null) {
|
||||||
|
undecodable += url
|
||||||
|
return State.Broken
|
||||||
|
}
|
||||||
|
decoded.put(url, picture)
|
||||||
|
return State.Shown(picture)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The picture's file as downloaded; null while it is not there. */
|
||||||
|
suspend fun data(url: String): ByteArray? = withContext(Dispatchers.IO) { downloads.get(url)?.readBytes() }
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val CACHED = 32
|
||||||
|
const val MAX_PX = 1024
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionEvent
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun App(vm: SessionController) {
|
||||||
|
val current by vm.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) }
|
||||||
|
val snackbar = remember { SnackbarHostState() }
|
||||||
|
var settingsOpen by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var contactsOpen by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var myTeamSpeakOpen by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var editingContact by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
// Set when a contact's page was opened from a client, so leaving it goes back there.
|
||||||
|
var contactDirect by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) }
|
||||||
|
var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) }
|
||||||
|
|
||||||
|
LaunchedEffect(vm) {
|
||||||
|
vm.events.collect { event ->
|
||||||
|
when (event) {
|
||||||
|
is SessionEvent.Poke -> poke = event
|
||||||
|
is SessionEvent.Error -> snackbar.showSnackbar(event.message)
|
||||||
|
SessionEvent.ServerOpened -> {
|
||||||
|
connectOpen = false
|
||||||
|
settingsOpen = false
|
||||||
|
contactsOpen = false
|
||||||
|
myTeamSpeakOpen = false
|
||||||
|
editingBookmark = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val context = LocalContext.current
|
||||||
|
val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
|
||||||
|
if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo)
|
||||||
|
}
|
||||||
|
fun missing(vararg names: String) =
|
||||||
|
names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||||
|
|
||||||
|
// The connection runs without either permission, just silent or without its notification.
|
||||||
|
val connectAsking: (() -> Unit) -> Unit = { connect ->
|
||||||
|
connect()
|
||||||
|
connectOpen = false
|
||||||
|
val ask = missing(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray())
|
||||||
|
}
|
||||||
|
val enableMicrophone: () -> Unit = {
|
||||||
|
if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo)
|
||||||
|
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
|
||||||
|
}
|
||||||
|
|
||||||
|
val openContacts: (String?) -> Unit = { uniqueId ->
|
||||||
|
contactsOpen = true
|
||||||
|
editingContact = uniqueId
|
||||||
|
contactDirect = uniqueId != null
|
||||||
|
}
|
||||||
|
|
||||||
|
CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) {
|
||||||
|
val server = current
|
||||||
|
val bookmark = editingBookmark
|
||||||
|
when {
|
||||||
|
bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null })
|
||||||
|
contactsOpen -> ContactsScreen(vm, 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 })
|
||||||
|
server != null && !connectOpen -> {
|
||||||
|
serverStates.SaveableStateProvider(server.id) {
|
||||||
|
CompositionLocalProvider(LocalServerImages provides server.images) {
|
||||||
|
PictureViewerHost(server) {
|
||||||
|
ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
|
||||||
|
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking,
|
||||||
|
onEditBookmark = { editingBookmark = it },
|
||||||
|
onBack = if (current != null) ({ connectOpen = false }) else null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
poke?.let { p ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { poke = null },
|
||||||
|
title = { Text("${p.from} poked you") },
|
||||||
|
text = if (p.message.isNotBlank()) ({ Text(p.message) }) else null,
|
||||||
|
confirmButton = { TextButton(onClick = { poke = null }) { Text("OK") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.webkit.MimeTypeMap
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContract
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachment
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTsException
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
/** 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)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared files for [server]'s chat: a picture opens full size, anything else is saved where
|
||||||
|
* the user picks; sharing picks a file to send into the conversation [shown] gives.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun rememberAttachmentActions(
|
||||||
|
vm: SessionController,
|
||||||
|
server: ServerController,
|
||||||
|
snackbar: SnackbarHostState,
|
||||||
|
shown: ChatKey,
|
||||||
|
): AttachmentActions {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle()
|
||||||
|
val key by rememberUpdatedState(shown)
|
||||||
|
val viewer = LocalPictureViewer.current
|
||||||
|
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
|
||||||
|
|
||||||
|
var saving by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
|
||||||
|
val ref = ChatAttachment.Ref.parse(saving)
|
||||||
|
saving = null
|
||||||
|
if (uri == null || ref == null) return@rememberLauncherForActivityResult
|
||||||
|
scope.launch {
|
||||||
|
val error = try {
|
||||||
|
vm.saveAttachment(ref, uri)
|
||||||
|
null
|
||||||
|
} catch (e: MyTsException) {
|
||||||
|
e.message
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.message
|
||||||
|
}
|
||||||
|
snackbar.showSnackbar(if (error == null) "Saved ${ref.fileName}." else "Could not save ${ref.fileName}: $error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||||
|
if (uri != null) scope.launch { server.sendFile(key, uri) }
|
||||||
|
}
|
||||||
|
|
||||||
|
return AttachmentActions(
|
||||||
|
open = open@{ href ->
|
||||||
|
val ref = ChatAttachment.Ref.parse(href) ?: return@open
|
||||||
|
when {
|
||||||
|
!signedIn -> tell(SIGN_IN)
|
||||||
|
ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) {
|
||||||
|
vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull()
|
||||||
|
})
|
||||||
|
else -> {
|
||||||
|
saving = href
|
||||||
|
saver.launch(ref.fileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
share = { if (signedIn) picker.launch("*/*") else tell(SIGN_IN) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val SIGN_IN = "Sign in to myTeamSpeak to share files"
|
||||||
|
|
||||||
|
/** Asks where to save a file of the given name, typed by its extension. */
|
||||||
|
internal object SaveAs : ActivityResultContract<String, Uri?>() {
|
||||||
|
override fun createIntent(context: Context, input: String): Intent {
|
||||||
|
val extension = input.substringAfterLast('.', "").lowercase()
|
||||||
|
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
|
||||||
|
return Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||||
|
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||||
|
.setType(type)
|
||||||
|
.putExtra(Intent.EXTRA_TITLE, input)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun parseResult(resultCode: Int, intent: Intent?): Uri? =
|
||||||
|
intent?.data.takeIf { resultCode == Activity.RESULT_OK }
|
||||||
|
}
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
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.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.config.BanReasonPresets
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanEntry
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanPattern
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanRule
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/** What the ban list shows instead of itself: a ban's editor, a new or an existing ban's. */
|
||||||
|
private sealed interface BanEdit {
|
||||||
|
data object New : BanEdit
|
||||||
|
data class Existing(val ban: BanEntry) : BanEdit
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's ban list, as TeamSpeak's Ban List window: searchable, own bans apart, add, edit and remove. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: () -> Unit) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val snackbar = remember { SnackbarHostState() }
|
||||||
|
var bans by remember { mutableStateOf<List<BanEntry>?>(null) }
|
||||||
|
var status by remember { mutableStateOf("Loading…") }
|
||||||
|
/** Bumped to read the list again. */
|
||||||
|
var generation by remember { mutableIntStateOf(0) }
|
||||||
|
var query by rememberSaveable { mutableStateOf("") }
|
||||||
|
var onlyOwn by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var shown by remember { mutableStateOf<BanEntry?>(null) }
|
||||||
|
var edit by remember { mutableStateOf<BanEdit?>(null) }
|
||||||
|
|
||||||
|
LaunchedEffect(generation) {
|
||||||
|
status = "Loading…"
|
||||||
|
server.banList()
|
||||||
|
.onSuccess {
|
||||||
|
bans = it
|
||||||
|
status = if (it.size == 1) "1 ban" else "${it.size} bans"
|
||||||
|
}
|
||||||
|
.onFailure {
|
||||||
|
bans = emptyList()
|
||||||
|
status = "Failed to request ban list: ${it.message}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reports a failed change, or re-reads the list to show what the server now holds. */
|
||||||
|
val change = { action: suspend () -> String?, failure: String ->
|
||||||
|
scope.launch {
|
||||||
|
val error = action()
|
||||||
|
if (error != null) snackbar.showSnackbar("$failure: $error")
|
||||||
|
generation++
|
||||||
|
}
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
edit?.let { e ->
|
||||||
|
val existing = (e as? BanEdit.Existing)?.ban
|
||||||
|
BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule ->
|
||||||
|
edit = null
|
||||||
|
if (existing == null) change({ server.addBan(rule) }, "Error adding ban")
|
||||||
|
else change({ server.replaceBan(existing.id, rule) }, "Error editing ban")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen(
|
||||||
|
"Ban list", onBack,
|
||||||
|
actions = {
|
||||||
|
if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") }
|
||||||
|
IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") }
|
||||||
|
},
|
||||||
|
snackbar = snackbar,
|
||||||
|
) { padding ->
|
||||||
|
val needle = query.trim().lowercase(Locale.ROOT)
|
||||||
|
val filtered = remember(bans, needle, onlyOwn) {
|
||||||
|
bans.orEmpty().filter { ban ->
|
||||||
|
(!onlyOwn || server.isOwnBan(ban)) && (needle.isEmpty() || searchText(ban).contains(needle))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Column(Modifier.padding(padding).imePadding().fillMaxSize()) {
|
||||||
|
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(query, { query = it }, Modifier.weight(1f), placeholder = { Text("Search") },
|
||||||
|
singleLine = true, leadingIcon = { PackIcon("SEARCH", null) })
|
||||||
|
FilterChip(onlyOwn, { onlyOwn = !onlyOwn }, label = { Text("Own") })
|
||||||
|
}
|
||||||
|
Text(status, Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
LazyColumn(Modifier.weight(1f)) {
|
||||||
|
items(filtered, key = { it.id }) { ban ->
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(ban.targets(), maxLines = 2, overflow = TextOverflow.Ellipsis) },
|
||||||
|
supportingContent = {
|
||||||
|
Column {
|
||||||
|
if (ban.reason.isNotEmpty()) Text(ban.reason, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text("${ban.invokerName} · ${expiry(ban)}", style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.clickable { shown = ban },
|
||||||
|
)
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
shown?.let { ban ->
|
||||||
|
BanSheet(
|
||||||
|
ban,
|
||||||
|
onDismiss = { shown = null },
|
||||||
|
onEdit = if (server.canEditBan(ban)) ({ shown = null; edit = BanEdit.Existing(ban) }) else null,
|
||||||
|
onDelete = if (server.canDeleteBans(listOf(ban))) ({
|
||||||
|
shown = null
|
||||||
|
change({ server.deleteBans(listOf(ban.id)) }, "Error deleting ban")
|
||||||
|
}) else null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun searchText(ban: BanEntry): String =
|
||||||
|
listOf(ban.targets(), ban.reason, ban.invokerName, date(ban.createdEpochSeconds), expiry(ban))
|
||||||
|
.joinToString("\n").lowercase(Locale.ROOT)
|
||||||
|
|
||||||
|
private val DATE: DateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
|
||||||
|
|
||||||
|
private fun date(epochSeconds: Long): String =
|
||||||
|
if (epochSeconds <= 0) "" else DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault()))
|
||||||
|
|
||||||
|
private fun expiry(ban: BanEntry): String = if (ban.isPermanent) "Never expires" else "Expires ${date(ban.expiresEpochSeconds())}"
|
||||||
|
|
||||||
|
/** Everything about one ban, and what may be done with it. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
private fun BanSheet(ban: BanEntry, onDismiss: () -> Unit, onEdit: (() -> Unit)?, onDelete: (() -> Unit)?) {
|
||||||
|
var confirmDelete by remember { mutableStateOf(false) }
|
||||||
|
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
|
||||||
|
Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Fact("Name", ban.name)
|
||||||
|
Fact("IP", ban.ip)
|
||||||
|
Fact("Unique ID", ban.uid)
|
||||||
|
Fact("Last nickname", ban.lastNickname)
|
||||||
|
Fact("myTeamSpeak ID", ban.mytsid)
|
||||||
|
Fact("Reason", ban.reason)
|
||||||
|
Fact("Creator", ban.invokerName)
|
||||||
|
Fact("Created", date(ban.createdEpochSeconds))
|
||||||
|
Fact("Expires", if (ban.isPermanent) "Never" else date(ban.expiresEpochSeconds()))
|
||||||
|
Fact("Enforced", ban.enforcements.toString())
|
||||||
|
}
|
||||||
|
onEdit?.let { Action("EDIT", "Edit", onClick = it) }
|
||||||
|
onDelete?.let { Action("DELETE", "Delete") { confirmDelete = true } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (confirmDelete && onDelete != null) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { confirmDelete = false },
|
||||||
|
title = { Text("Delete ban?") },
|
||||||
|
text = { Text(ban.targets()) },
|
||||||
|
confirmButton = { TextButton(onClick = { confirmDelete = false; onDelete() }) { Text("Delete") } },
|
||||||
|
dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Fact(label: String, value: String) {
|
||||||
|
if (value.isEmpty()) return
|
||||||
|
Column {
|
||||||
|
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(value, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds a ban, or rewrites [existing]: what it matches, why, and for how long. */
|
||||||
|
@Composable
|
||||||
|
private fun BanEditor(
|
||||||
|
existing: BanEntry?,
|
||||||
|
presets: BanReasonPresets,
|
||||||
|
maxSeconds: Long,
|
||||||
|
onBack: () -> Unit,
|
||||||
|
onSave: (BanRule) -> Unit,
|
||||||
|
) {
|
||||||
|
val decoded = remember { BanPattern.decode(existing?.ip, existing?.name) }
|
||||||
|
var ip by remember { mutableStateOf(decoded.ip) }
|
||||||
|
var name by remember { mutableStateOf(decoded.name) }
|
||||||
|
var pattern by remember { mutableStateOf(if (existing == null) BanPattern.WILDCARD_IPV4 else decoded.pattern) }
|
||||||
|
var uid by remember { mutableStateOf(existing?.uid.orEmpty()) }
|
||||||
|
var mytsid by remember { mutableStateOf(existing?.mytsid.orEmpty()) }
|
||||||
|
var reason by remember { mutableStateOf(existing?.reason.orEmpty()) }
|
||||||
|
val duration = remember { BanDurationState(existing?.durationSeconds ?: DEFAULT_BAN_SECONDS) }
|
||||||
|
|
||||||
|
val rule = BanRule(pattern.ipToRegex(ip), pattern.nameToRegex(name), uid, mytsid, duration.seconds, reason)
|
||||||
|
val ipValid = BanPattern.isValidRegex(rule.ipRegex)
|
||||||
|
val nameValid = BanPattern.isValidRegex(rule.nameRegex)
|
||||||
|
val valid = rule.hasTarget() && ipValid && nameValid && duration.valid
|
||||||
|
|
||||||
|
SubScreen(
|
||||||
|
if (existing == null) "Add ban" else "Edit ban", onBack,
|
||||||
|
actions = { TextButton(onClick = { onSave(rule) }, enabled = valid) { Text("Save") } },
|
||||||
|
) { padding ->
|
||||||
|
Column(
|
||||||
|
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(ip, { ip = it }, Modifier.fillMaxWidth(), label = { Text("IP") }, singleLine = true,
|
||||||
|
isError = !ipValid)
|
||||||
|
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true,
|
||||||
|
isError = !nameValid)
|
||||||
|
PatternField(pattern) { pattern = it }
|
||||||
|
OutlinedTextField(uid, { uid = it }, Modifier.fillMaxWidth(), label = { Text("Unique ID") }, singleLine = true)
|
||||||
|
OutlinedTextField(mytsid, { mytsid = it }, Modifier.fillMaxWidth(), label = { Text("myTeamSpeak ID") },
|
||||||
|
singleLine = true)
|
||||||
|
ReasonField(reason, { reason = it }, presets)
|
||||||
|
BanDurationField(duration, maxSeconds)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How the IP and name are written: wildcards, fixed strings or regular expressions. */
|
||||||
|
@Composable
|
||||||
|
private fun PatternField(pattern: BanPattern, onSelect: (BanPattern) -> Unit) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Interpret as", Modifier.weight(1f))
|
||||||
|
Box {
|
||||||
|
OutlinedButton(onClick = { open = true }) { Text(pattern.label()) }
|
||||||
|
DropdownMenu(open, { open = false }) {
|
||||||
|
for (p in BanPattern.entries) DropdownMenuItem({ Text(p.label()) }, onClick = { open = false; onSelect(p) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The reason, with the saved presets to pick from and the reason typed to save as one. */
|
||||||
|
@Composable
|
||||||
|
private fun ReasonField(reason: String, onChange: (String) -> Unit, presets: BanReasonPresets) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
var saved by remember { mutableStateOf(presets.all().toList()) }
|
||||||
|
Box {
|
||||||
|
Row(verticalAlignment = Alignment.Top) {
|
||||||
|
LimitedField(reason, onChange, "Reason", BanRule.REASON_LIMIT, Modifier.weight(1f))
|
||||||
|
IconButton(onClick = { open = true }, Modifier.padding(top = 8.dp)) { Icon(Icons.Filled.ArrowDropDown, "Presets") }
|
||||||
|
}
|
||||||
|
DropdownMenu(open, { open = false }, Modifier.align(Alignment.TopEnd)) {
|
||||||
|
for (preset in saved) {
|
||||||
|
DropdownMenuItem({ Text(preset, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
onClick = { open = false; onChange(preset.take(BanRule.REASON_LIMIT)) },
|
||||||
|
trailingIcon = {
|
||||||
|
IconButton(onClick = {
|
||||||
|
presets.remove(preset)
|
||||||
|
presets.save()
|
||||||
|
saved = presets.all().toList()
|
||||||
|
}) { PackIcon("DELETE", "Remove preset") }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (saved.isNotEmpty()) HorizontalDivider()
|
||||||
|
DropdownMenuItem({ Text("Save as preset") }, enabled = reason.isNotBlank(), onClick = {
|
||||||
|
open = false
|
||||||
|
presets.add(reason)
|
||||||
|
presets.save()
|
||||||
|
saved = presets.all().toList()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
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.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.listSaver
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.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.SessionController
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
|
||||||
|
/** A bookmark on the edit page: [index] among the saved ones, -1 for a new one. */
|
||||||
|
class BookmarkEdit(val index: Int, val bookmark: Bookmark)
|
||||||
|
|
||||||
|
val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
|
||||||
|
save = { edit ->
|
||||||
|
val b = edit?.bookmark ?: return@listSaver emptyList()
|
||||||
|
listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password,
|
||||||
|
b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id)
|
||||||
|
},
|
||||||
|
restore = { saved ->
|
||||||
|
if (saved.isEmpty()) null
|
||||||
|
else BookmarkEdit(saved[0] as Int, Bookmark(saved[1] as String, saved[2] as String, saved[3] as Int,
|
||||||
|
saved[4] as String, saved[5] as String).apply {
|
||||||
|
identityId = saved[6] as String
|
||||||
|
channel = saved[7] as String
|
||||||
|
channelPassword = saved[8] as String
|
||||||
|
connectOnStartup = saved[9] as Boolean
|
||||||
|
iconId = saved[10] as Long
|
||||||
|
id = saved[11] as String
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Every setting of one bookmark, saved only on Save. */
|
||||||
|
@Composable
|
||||||
|
fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit) {
|
||||||
|
val b = edit.bookmark
|
||||||
|
val identities by vm.identities.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}")
|
||||||
|
}
|
||||||
|
var nickname by rememberSaveable { mutableStateOf(b.nickname.orEmpty()) }
|
||||||
|
var password by rememberSaveable { mutableStateOf(b.password.orEmpty()) }
|
||||||
|
var identityId by rememberSaveable { mutableStateOf(b.identityId.orEmpty()) }
|
||||||
|
var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) }
|
||||||
|
var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) }
|
||||||
|
var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) }
|
||||||
|
|
||||||
|
val save = {
|
||||||
|
val (host, port) = SessionController.parseAddress(address)
|
||||||
|
vm.saveBookmark(edit.index, b.copy().also {
|
||||||
|
it.label = label.trim().ifEmpty { host }
|
||||||
|
it.address = host
|
||||||
|
it.port = port
|
||||||
|
it.nickname = nickname.trim()
|
||||||
|
it.password = password
|
||||||
|
it.identityId = identityId
|
||||||
|
it.channel = channel.trim()
|
||||||
|
it.channelPassword = channelPassword
|
||||||
|
it.connectOnStartup = connectOnStartup
|
||||||
|
})
|
||||||
|
onDone()
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen(if (edit.index < 0) "New bookmark" else "Edit bookmark", onBack = onDone, actions = {
|
||||||
|
TextButton(onClick = save, enabled = address.isNotBlank()) { Text("Save") }
|
||||||
|
}) { padding ->
|
||||||
|
Column(
|
||||||
|
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
OutlinedTextField(label, { label = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true)
|
||||||
|
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
|
||||||
|
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
|
||||||
|
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("Server password") }, singleLine = true,
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
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)
|
||||||
|
val paths = remember(address) {
|
||||||
|
SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) }
|
||||||
|
}
|
||||||
|
ChannelField(channel, paths) { channel = it }
|
||||||
|
OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("Channel password") }, singleLine = true,
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
|
||||||
|
Row(Modifier.fillMaxWidth().clickable { connectOnStartup = !connectOnStartup },
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Connect on startup", Modifier.weight(1f))
|
||||||
|
Switch(connectOnStartup, { connectOnStartup = it })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The channel to join, typed or picked among [paths] of the server when we are on it. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
private fun ChannelField(channel: String, paths: List<String>, onChange: (String) -> Unit) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
// A channel already picked lists them all, for picking another.
|
||||||
|
val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) }
|
||||||
|
val expanded = open && matches.isNotEmpty()
|
||||||
|
ExposedDropdownMenuBox(expanded, { open = it }) {
|
||||||
|
OutlinedTextField(
|
||||||
|
channel, { onChange(it); open = true }, singleLine = true,
|
||||||
|
label = { Text("Channel") },
|
||||||
|
placeholder = { Text("Default") },
|
||||||
|
trailingIcon = if (paths.isEmpty()) null else ({ ExposedDropdownMenuDefaults.TrailingIcon(expanded) }),
|
||||||
|
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
|
||||||
|
)
|
||||||
|
ExposedDropdownMenu(expanded, { open = false }) {
|
||||||
|
for (path in matches) {
|
||||||
|
DropdownMenuItem({ Text(path) }, onClick = {
|
||||||
|
open = false
|
||||||
|
onChange(path)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.net.ChannelCodec
|
||||||
|
import eu.lixko.ts3j.client.net.ChannelSettings
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/** The channel being edited ([channelId] > 0), or one to create below [parentId] (0: the top level). */
|
||||||
|
data class ChannelEdit(val channelId: Int, val parentId: Int = 0)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TeamSpeak's channel editor on one page: name, password, topic and description, then the
|
||||||
|
* channel's type, sorting, audio and limits. Only what changed is sent, as the server refuses
|
||||||
|
* an edit carrying one property we may not change.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> Unit) {
|
||||||
|
val creating = edit.channelId <= 0
|
||||||
|
val snackbar = remember { SnackbarHostState() }
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
/** The channel as the server described it, which changes are measured against. */
|
||||||
|
var original by remember { mutableStateOf<ChannelSettings?>(null) }
|
||||||
|
var edited by remember { mutableStateOf<ChannelSettings?>(null) }
|
||||||
|
var passwordText by remember { mutableStateOf("") }
|
||||||
|
var saving by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
LaunchedEffect(edit) {
|
||||||
|
if (creating) {
|
||||||
|
// Made from a channel's sheet, a channel is usually a throwaway one, as in TeamSpeak;
|
||||||
|
// the server puts a new channel after its siblings.
|
||||||
|
val fresh = ChannelSettings().apply {
|
||||||
|
type = ChannelSettings.Type.TEMPORARY
|
||||||
|
parentId = edit.parentId
|
||||||
|
order = server.sortChoices(0, edit.parentId).lastOrNull()?.id ?: 0
|
||||||
|
}
|
||||||
|
original = fresh
|
||||||
|
edited = fresh.copy()
|
||||||
|
} else {
|
||||||
|
server.channelSettings(edit.channelId)
|
||||||
|
.onSuccess { original = it; edited = it.copy() }
|
||||||
|
.onFailure { snackbar.showSnackbar("Could not read the channel: ${it.message}"); onDone() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val change = { f: ChannelSettings.() -> Unit -> edited = edited?.copy()?.apply(f) }
|
||||||
|
val save = save@{
|
||||||
|
val e = edited ?: return@save
|
||||||
|
val o = original ?: return@save
|
||||||
|
if (e.name.isBlank()) {
|
||||||
|
scope.launch { snackbar.showSnackbar("The channel needs a name.") }
|
||||||
|
return@save
|
||||||
|
}
|
||||||
|
saving = true
|
||||||
|
scope.launch {
|
||||||
|
val trimmed = e.copy().apply { name = name.trim() }
|
||||||
|
val error = if (creating) server.createChannel(edit.parentId, trimmed)
|
||||||
|
else server.editChannel(edit.channelId, trimmed.changesFrom(o))
|
||||||
|
saving = false
|
||||||
|
if (error == null) onDone()
|
||||||
|
else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val title = when {
|
||||||
|
!creating -> "Edit channel"
|
||||||
|
edit.parentId > 0 -> "New sub-channel"
|
||||||
|
else -> "New channel"
|
||||||
|
}
|
||||||
|
SubScreen(title, onBack = onDone, snackbar = snackbar, actions = {
|
||||||
|
TextButton(onClick = save, enabled = edited != null && !saving) { Text(if (creating) "Create" else "Save") }
|
||||||
|
}) { padding ->
|
||||||
|
val e = edited
|
||||||
|
if (e == null) {
|
||||||
|
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||||
|
return@SubScreen
|
||||||
|
}
|
||||||
|
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(e.name, { change { name = it } }, Modifier.fillMaxWidth(), label = { Text("Name") },
|
||||||
|
singleLine = true)
|
||||||
|
OutlinedTextField(passwordText, {
|
||||||
|
passwordText = it
|
||||||
|
change { password = it }
|
||||||
|
}, Modifier.fillMaxWidth(), label = { Text("Password") }, singleLine = true,
|
||||||
|
placeholder = if (e.hasPassword && e.password == null) ({ Text("Unchanged") }) else null,
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
|
||||||
|
if (e.hasPassword && e.password == null) {
|
||||||
|
TextButton(onClick = { change { password = "" } }) { Text("Remove password") }
|
||||||
|
}
|
||||||
|
OutlinedTextField(e.topic, { change { topic = it } }, Modifier.fillMaxWidth(), label = { Text("Topic") },
|
||||||
|
singleLine = true)
|
||||||
|
OutlinedTextField(e.description, { change { description = it } }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("Description") }, minLines = 3, maxLines = 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Channel type")
|
||||||
|
Segments(listOf(
|
||||||
|
ChannelSettings.Type.TEMPORARY to "Temporary",
|
||||||
|
ChannelSettings.Type.SEMI_PERMANENT to "Semi-permanent",
|
||||||
|
ChannelSettings.Type.PERMANENT to "Permanent",
|
||||||
|
), e.type) { change { type = it } }
|
||||||
|
// The default channel cannot stop being one; another has to take over.
|
||||||
|
if (original?.defaultChannel != true) {
|
||||||
|
Toggle("Default channel", e.defaultChannel) { change { defaultChannel = it } }
|
||||||
|
}
|
||||||
|
val siblings = remember(edit) {
|
||||||
|
server.sortChoices(edit.channelId, edit.parentId).filter { it.id != edit.channelId }
|
||||||
|
}
|
||||||
|
Picker("Sort after", listOf(0 to "(first)") + siblings.map { it.id to it.name },
|
||||||
|
e.order.takeIf { o -> o == 0 || siblings.any { it.id == o } } ?: 0) { change { order = it } }
|
||||||
|
NumberField("Needed talk power", e.neededTalkPower, 0..9999) { change { neededTalkPower = it } }
|
||||||
|
|
||||||
|
Section("Audio")
|
||||||
|
val preset = ChannelCodec.Preset.of(e.codec, e.codecQuality)
|
||||||
|
var custom by remember { mutableStateOf(preset == null) }
|
||||||
|
val presets: List<Pair<ChannelCodec.Preset?, String>> =
|
||||||
|
ChannelCodec.Preset.entries.map { it to it.label } + (null to "Custom")
|
||||||
|
Segments(presets, if (custom) null else preset) { picked ->
|
||||||
|
custom = picked == null
|
||||||
|
if (picked != null) change { codec = picked.codec; codecQuality = picked.quality }
|
||||||
|
}
|
||||||
|
if (custom) {
|
||||||
|
Picker("Codec", ChannelCodec.NAMES.indices.map { it to ChannelCodec.NAMES[it] },
|
||||||
|
ChannelCodec.clampCodec(e.codec)) { change { codec = it } }
|
||||||
|
Level("Quality", e.codecQuality.toFloat(), 0f..ChannelCodec.MAX_QUALITY.toFloat(),
|
||||||
|
{ it.roundToInt().toString() }, steps = ChannelCodec.MAX_QUALITY - 1) {
|
||||||
|
change { codecQuality = it.roundToInt() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Hint("Bandwidth: ${ChannelCodec.bandwidthText(e.codec, e.codecQuality)} per talking client")
|
||||||
|
|
||||||
|
Section("Advanced")
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp)) {
|
||||||
|
OutlinedTextField(e.phoneticName, { change { phoneticName = it } }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("Phonetic name") }, singleLine = true)
|
||||||
|
}
|
||||||
|
if (e.type == ChannelSettings.Type.TEMPORARY) {
|
||||||
|
NumberField("Delete delay (seconds)", e.deleteDelay, 0..ChannelSettings.MAX_DELETE_DELAY) {
|
||||||
|
change { deleteDelay = it }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Toggle("Voice encrypted", e.encrypted) { change { encrypted = it } }
|
||||||
|
Text("Max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
|
||||||
|
Segments(listOf(true to "Unlimited", false to "Limited"), e.maxClientsUnlimited) {
|
||||||
|
change { maxClientsUnlimited = it }
|
||||||
|
}
|
||||||
|
if (!e.maxClientsUnlimited) NumberField("Users", e.maxClients, 0..65535) { change { maxClients = it } }
|
||||||
|
Text("Family max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
|
||||||
|
val family = when {
|
||||||
|
e.familyInherited -> FamilyLimit.INHERITED
|
||||||
|
e.familyUnlimited -> FamilyLimit.UNLIMITED
|
||||||
|
else -> FamilyLimit.LIMITED
|
||||||
|
}
|
||||||
|
Segments(FamilyLimit.entries.map { it to it.label }, family) {
|
||||||
|
change {
|
||||||
|
familyInherited = it == FamilyLimit.INHERITED
|
||||||
|
familyUnlimited = it == FamilyLimit.UNLIMITED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (family == FamilyLimit.LIMITED) {
|
||||||
|
NumberField("Users", e.maxFamilyClients, 0..65535) { change { maxFamilyClients = it } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum class FamilyLimit(val label: String) { INHERITED("Inherited"), UNLIMITED("Unlimited"), LIMITED("Limited") }
|
||||||
|
|
||||||
|
/** A whole number within [range]; what does not parse leaves the value alone. */
|
||||||
|
@Composable
|
||||||
|
private fun NumberField(label: String, value: Int, range: IntRange, onChange: (Int) -> Unit) {
|
||||||
|
var text by remember(value) { mutableStateOf(value.toString()) }
|
||||||
|
Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
OutlinedTextField(text, {
|
||||||
|
text = it.filter(Char::isDigit).take(7)
|
||||||
|
text.toIntOrNull()?.let { n -> onChange(n.coerceIn(range)) }
|
||||||
|
}, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.animateColorAsState
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.slideInVertically
|
||||||
|
import androidx.compose.animation.slideOutVertically
|
||||||
|
import androidx.compose.foundation.layout.BoxScope
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.runtime.derivedStateOf
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.combinedClickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.RowScope
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.LazyListState
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.ProvideTextStyle
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.runtime.snapshotFlow
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.rotate
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ChannelItem
|
||||||
|
import eu.lixko.ts3j.client.android.ClientItem
|
||||||
|
import eu.lixko.ts3j.client.android.ServerTree
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactType
|
||||||
|
import eu.lixko.ts3j.client.gfx.IconKeys
|
||||||
|
import eu.lixko.ts3j.client.net.ClientStatus
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
|
||||||
|
/** A channel's or a client's row. */
|
||||||
|
data class TreeRef(val channel: Boolean, val id: Int)
|
||||||
|
|
||||||
|
/** One line of the tree as the list shows it. */
|
||||||
|
private sealed interface TreeRow {
|
||||||
|
val ref: TreeRef
|
||||||
|
val key: String get() = (if (ref.channel) "c" else "u") + ref.id
|
||||||
|
|
||||||
|
data class Channel(val channel: ChannelItem, val depth: Int, val expanded: Boolean, val current: Boolean) : TreeRow {
|
||||||
|
override val ref get() = TreeRef(true, channel.id)
|
||||||
|
val expandable get() = channel.clients.isNotEmpty() || channel.children.isNotEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Client(val client: ClientItem, val depth: Int) : TreeRow {
|
||||||
|
override val ref get() = TreeRef(false, client.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tree's channels and clients in reading order, leaving out what sits in folded channels. */
|
||||||
|
private fun flatten(tree: ServerTree, collapsed: Set<Int>, currentChannel: Int): List<TreeRow> {
|
||||||
|
val rows = ArrayList<TreeRow>()
|
||||||
|
fun add(channel: ChannelItem, depth: Int) {
|
||||||
|
val expanded = channel.id !in collapsed
|
||||||
|
rows += TreeRow.Channel(channel, depth, expanded, channel.id == currentChannel)
|
||||||
|
if (!expanded) return
|
||||||
|
channel.clients.forEach { rows += TreeRow.Client(it, depth + 1) }
|
||||||
|
channel.children.forEach { add(it, depth + 1) }
|
||||||
|
}
|
||||||
|
tree.channels.forEach { add(it, 0) }
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ChannelItem.holdsSelf(): Boolean = clients.any { it.self } || children.any { it.holdsSelf() }
|
||||||
|
|
||||||
|
/** Where the list shows our own client: its row, or the folded channel hiding it; -1 when it shows nowhere. */
|
||||||
|
private fun selfAnchor(rows: List<TreeRow>): Int = rows.indexOfFirst { row ->
|
||||||
|
when (row) {
|
||||||
|
is TreeRow.Client -> row.client.self
|
||||||
|
is TreeRow.Channel -> !row.expanded && row.channel.holdsSelf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which way our own row lies off screen. */
|
||||||
|
private enum class Offscreen { ABOVE, BELOW }
|
||||||
|
|
||||||
|
/** Floats over the tree's edge on the side our own row went off. */
|
||||||
|
@Composable
|
||||||
|
private fun BoxScope.ScrollToSelf(where: Offscreen?, onClick: () -> Unit) {
|
||||||
|
AnimatedVisibility(where == Offscreen.ABOVE, Modifier.align(Alignment.TopCenter).padding(top = 8.dp),
|
||||||
|
enter = slideInVertically { -it * 2 } + fadeIn(), exit = slideOutVertically { -it * 2 } + fadeOut()) {
|
||||||
|
ScrollToSelfChip(up = true, onClick)
|
||||||
|
}
|
||||||
|
AnimatedVisibility(where == Offscreen.BELOW, Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
|
||||||
|
enter = slideInVertically { it * 2 } + fadeIn(), exit = slideOutVertically { it * 2 } + fadeOut()) {
|
||||||
|
ScrollToSelfChip(up = false, onClick)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ScrollToSelfChip(up: Boolean, onClick: () -> Unit) {
|
||||||
|
Surface(onClick = onClick, shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer,
|
||||||
|
shadowElevation = 4.dp) {
|
||||||
|
Row(Modifier.padding(start = 10.dp, end = 14.dp, top = 6.dp, bottom = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(18.dp).rotate(if (up) 180f else 0f))
|
||||||
|
Text("Me", style = MaterialTheme.typography.labelLarge)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ChannelTree(
|
||||||
|
serverName: String,
|
||||||
|
tree: ServerTree,
|
||||||
|
collapsed: Set<Int>,
|
||||||
|
currentChannel: Int,
|
||||||
|
onToggle: (ChannelItem) -> Unit,
|
||||||
|
onChannel: (ChannelItem) -> Unit,
|
||||||
|
onChannelDoubleTap: (ChannelItem) -> Unit,
|
||||||
|
onClient: (ClientItem) -> Unit,
|
||||||
|
onServer: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
/** A row to scroll to and flash, once the channels above it are expanded. */
|
||||||
|
reveal: TreeRef? = null,
|
||||||
|
onRevealed: () -> Unit = {},
|
||||||
|
/** The rows the find bar matched, and the one it is on, which a reveal does not flash. */
|
||||||
|
found: Set<TreeRef> = emptySet(),
|
||||||
|
foundCurrent: TreeRef? = null,
|
||||||
|
listState: LazyListState = rememberLazyListState(),
|
||||||
|
/** Brings our own client into view; its row may sit in folded channels. */
|
||||||
|
onShowSelf: () -> Unit = {},
|
||||||
|
) {
|
||||||
|
val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) }
|
||||||
|
var flashing by remember { mutableStateOf<TreeRef?>(null) }
|
||||||
|
LaunchedEffect(reveal, rows) {
|
||||||
|
val ref = reveal ?: return@LaunchedEffect
|
||||||
|
val index = rows.indexOfFirst { it.ref == ref }
|
||||||
|
if (index < 0) return@LaunchedEffect
|
||||||
|
// Index 0 is the server's row. The row ends up in the middle of the list.
|
||||||
|
val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2
|
||||||
|
listState.animateScrollToItem(index + 1, -middle)
|
||||||
|
if (ref != foundCurrent) flashing = ref
|
||||||
|
onRevealed()
|
||||||
|
}
|
||||||
|
LaunchedEffect(flashing) {
|
||||||
|
if (flashing != null) {
|
||||||
|
delay(1500)
|
||||||
|
flashing = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val anchor = remember(rows) { selfAnchor(rows) }
|
||||||
|
val offscreen by remember(anchor) {
|
||||||
|
derivedStateOf {
|
||||||
|
if (anchor < 0) return@derivedStateOf null
|
||||||
|
val info = listState.layoutInfo
|
||||||
|
val index = anchor + 1 // past the server's row
|
||||||
|
val item = info.visibleItemsInfo.firstOrNull { it.index == index }
|
||||||
|
when {
|
||||||
|
item != null && item.offset >= info.viewportStartOffset &&
|
||||||
|
item.offset + item.size <= info.viewportEndOffset -> null
|
||||||
|
item != null -> if (item.offset < info.viewportStartOffset) Offscreen.ABOVE else Offscreen.BELOW
|
||||||
|
info.visibleItemsInfo.isEmpty() -> null
|
||||||
|
index < info.visibleItemsInfo.first().index -> Offscreen.ABOVE
|
||||||
|
else -> Offscreen.BELOW
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Box(modifier.fillMaxSize()) {
|
||||||
|
LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 4.dp)) {
|
||||||
|
item(key = "server") {
|
||||||
|
RowLayout(depth = 0, onClick = onServer) {
|
||||||
|
PackIcon("SERVER_GREEN", null, size = ICON)
|
||||||
|
Text(serverName, Modifier.weight(1f), fontWeight = FontWeight.Bold, maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis)
|
||||||
|
ServerIcon(tree.serverIconId, size = ICON)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items(rows, key = { it.key }) { row ->
|
||||||
|
val background = rowBackground(
|
||||||
|
when (row.ref) {
|
||||||
|
flashing -> FLASH
|
||||||
|
foundCurrent -> findCurrentColor()
|
||||||
|
in found -> findMatchColor()
|
||||||
|
else -> Color.Transparent
|
||||||
|
},
|
||||||
|
)
|
||||||
|
when (row) {
|
||||||
|
is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap)
|
||||||
|
is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ScrollToSelf(offscreen, onShowSelf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val ICON = 16.dp
|
||||||
|
private val INDENT = 14.dp
|
||||||
|
private val ROW = 26.dp
|
||||||
|
/** Amber, see-through so the row's text keeps its own colour and contrast. */
|
||||||
|
private val FLASH = Color(0x80FFB300)
|
||||||
|
|
||||||
|
/** Fades in fast and out slowly, so a flash is seen. */
|
||||||
|
@Composable
|
||||||
|
private fun rowBackground(target: Color): Color {
|
||||||
|
val color by animateColorAsState(target, tween(if (target == FLASH) 150 else 600), label = "row")
|
||||||
|
return color
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RowLayout(
|
||||||
|
depth: Int,
|
||||||
|
onClick: (() -> Unit)?,
|
||||||
|
background: Color = Color.Transparent,
|
||||||
|
/** The colour under [background], which a flash or find match goes over. */
|
||||||
|
tint: Color = Color.Transparent,
|
||||||
|
onDoubleClick: (() -> Unit)? = null,
|
||||||
|
content: @Composable RowScope.() -> Unit,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(tint)
|
||||||
|
.background(background)
|
||||||
|
.height(ROW)
|
||||||
|
.then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onClick = onClick) else Modifier)
|
||||||
|
.padding(start = 4.dp + INDENT * depth, end = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
ProvideTextStyle(MaterialTheme.typography.bodyMedium, content = { content() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ChannelRow(
|
||||||
|
row: TreeRow.Channel,
|
||||||
|
background: Color,
|
||||||
|
onToggle: (ChannelItem) -> Unit,
|
||||||
|
onChannel: (ChannelItem) -> Unit,
|
||||||
|
onDoubleTap: (ChannelItem) -> Unit,
|
||||||
|
) {
|
||||||
|
val channel = row.channel
|
||||||
|
val spacer = channel.spacer
|
||||||
|
RowLayout(row.depth, onClick = { onChannel(channel) }, background = background,
|
||||||
|
onDoubleClick = if (spacer == null) ({ onDoubleTap(channel) }) else null) {
|
||||||
|
Box(
|
||||||
|
Modifier.fillMaxHeight().width(ICON + 4.dp)
|
||||||
|
.then(if (row.expandable) Modifier.clickable { onToggle(channel) } else Modifier),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
if (row.expandable) {
|
||||||
|
Icon(Icons.Filled.KeyboardArrowDown, if (row.expanded) "Collapse" else "Expand",
|
||||||
|
Modifier.size(ICON + 2.dp).rotate(if (row.expanded) 0f else -90f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (spacer != null) {
|
||||||
|
SpacerLabel(spacer.align(), spacer.caption().orEmpty(), Modifier.weight(1f))
|
||||||
|
} else {
|
||||||
|
PackIcon(IconKeys.channel(channel.locked, channel.full, channel.subscribed).asList(), null, size = ICON)
|
||||||
|
Text(
|
||||||
|
channel.name,
|
||||||
|
Modifier.weight(1f),
|
||||||
|
color = if (row.current) MaterialTheme.colorScheme.primary else Color.Unspecified,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
ServerIcon(channel.iconId, size = ICON)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A spacer's caption, placed as its tag asks; a repeated one of dashes or the like becomes a rule. */
|
||||||
|
@Composable
|
||||||
|
private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) {
|
||||||
|
if (align == '*') {
|
||||||
|
if (caption.isNotEmpty() && caption.all { it in "-_=.~" }) {
|
||||||
|
HorizontalDivider(modifier)
|
||||||
|
} else {
|
||||||
|
Text(caption.repeat(200 / caption.length.coerceAtLeast(1)), modifier, maxLines = 1, overflow = TextOverflow.Clip)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val textAlign = when (align) {
|
||||||
|
'c' -> TextAlign.Center
|
||||||
|
'r' -> TextAlign.End
|
||||||
|
else -> TextAlign.Start
|
||||||
|
}
|
||||||
|
Text(caption, modifier, textAlign = textAlign, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) {
|
||||||
|
val client = row.client
|
||||||
|
RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background)) {
|
||||||
|
Spacer(Modifier.width(ICON + 4.dp))
|
||||||
|
StatusIcon(client.status)
|
||||||
|
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Text(
|
||||||
|
client.name,
|
||||||
|
fontWeight = if (client.self) FontWeight.Bold else FontWeight.Normal,
|
||||||
|
color = when (client.highlight) {
|
||||||
|
ContactType.FRIEND -> StatusColors.friend
|
||||||
|
ContactType.BLOCKED -> StatusColors.blocked
|
||||||
|
else -> Color.Unspecified
|
||||||
|
},
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
if (client.awayMessage.isNotEmpty()) {
|
||||||
|
Text("[${client.awayMessage}]", Modifier.weight(1f, fill = false),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (id in client.groupIconIds) ServerIcon(id, size = ICON)
|
||||||
|
// The country's flag comes last, at the row's edge.
|
||||||
|
if (countryFlags) CountryFlag(client.country)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun StatusIcon(status: ClientStatus, modifier: Modifier = Modifier) {
|
||||||
|
PackIcon(IconKeys.client(status), status.name, modifier, size = ICON)
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.LazyRow
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.Send
|
||||||
|
import androidx.compose.material.icons.filled.AttachFile
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.Badge
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.snapshotFlow
|
||||||
|
import androidx.compose.runtime.mutableStateMapOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.saveable.Saver
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.snapshots.SnapshotStateMap
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.input.key.Key
|
||||||
|
import androidx.compose.ui.input.key.KeyEventType
|
||||||
|
import androidx.compose.ui.input.key.isShiftPressed
|
||||||
|
import androidx.compose.ui.input.key.key
|
||||||
|
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||||
|
import androidx.compose.ui.input.key.type
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.android.ChatLine
|
||||||
|
import eu.lixko.ts3j.client.android.ChatMatch
|
||||||
|
import eu.lixko.ts3j.client.android.Chats
|
||||||
|
import eu.lixko.ts3j.client.android.Conversation
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.flow.filter
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ChatPane(
|
||||||
|
chats: Chats,
|
||||||
|
selected: Conversation,
|
||||||
|
canSend: Boolean,
|
||||||
|
onSelect: (ChatKey) -> Unit,
|
||||||
|
onClose: (ChatKey.Private) -> Unit,
|
||||||
|
onSend: (String) -> Unit,
|
||||||
|
/** Picks a file to share in [selected]. */
|
||||||
|
onAttach: () -> Unit,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
/** The lines to show, when not all of [selected]'s. */
|
||||||
|
lines: List<ChatLine> = selected.lines,
|
||||||
|
find: TextQuery = TextQuery.EMPTY,
|
||||||
|
/** The match the find bar is on. */
|
||||||
|
current: ChatMatch? = null,
|
||||||
|
/** A line to scroll to. */
|
||||||
|
reveal: Long? = null,
|
||||||
|
onRevealed: () -> Unit = {},
|
||||||
|
) {
|
||||||
|
Column(modifier) {
|
||||||
|
LazyRow(
|
||||||
|
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
items(chats.all, key = { it.key.toString() }) { conversation ->
|
||||||
|
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Each conversation opens at its newest line.
|
||||||
|
key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) }
|
||||||
|
// One unsent message per conversation, kept while another one is on screen.
|
||||||
|
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
|
||||||
|
val draftKey = selected.key.toString()
|
||||||
|
val draft = drafts[draftKey].orEmpty()
|
||||||
|
val send = {
|
||||||
|
if (draft.isNotBlank()) {
|
||||||
|
onSend(draft.trim())
|
||||||
|
drafts.remove(draftKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
IconButton(onClick = onAttach, enabled = canSend) {
|
||||||
|
Icon(Icons.Filled.AttachFile, "Share file")
|
||||||
|
}
|
||||||
|
OutlinedTextField(
|
||||||
|
draft, { drafts[draftKey] = it },
|
||||||
|
Modifier.weight(1f).onPreviewKeyEvent { e ->
|
||||||
|
// A hardware keyboard's Enter sends, as on the desktop; Shift+Enter starts a new line.
|
||||||
|
val enter = e.key == Key.Enter && !e.isShiftPressed
|
||||||
|
if (enter && e.type == KeyEventType.KeyDown) send()
|
||||||
|
enter
|
||||||
|
},
|
||||||
|
placeholder = { Text("Message ${selected.title}", maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
enabled = canSend,
|
||||||
|
maxLines = 4,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
|
||||||
|
keyboardActions = KeyboardActions(onSend = { send() }),
|
||||||
|
)
|
||||||
|
IconButton(onClick = send, enabled = canSend && draft.isNotBlank()) {
|
||||||
|
Icon(Icons.AutoMirrored.Filled.Send, "Send")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val DraftsSaver = Saver<SnapshotStateMap<String, String>, HashMap<String, String>>(
|
||||||
|
save = { HashMap(it) },
|
||||||
|
restore = { mutableStateMapOf<String, String>().apply { putAll(it) } },
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ConversationChip(
|
||||||
|
conversation: Conversation,
|
||||||
|
selected: Boolean,
|
||||||
|
onSelect: (ChatKey) -> Unit,
|
||||||
|
onClose: (ChatKey.Private) -> Unit,
|
||||||
|
) {
|
||||||
|
val key = conversation.key
|
||||||
|
FilterChip(
|
||||||
|
selected = selected,
|
||||||
|
onClick = { onSelect(key) },
|
||||||
|
label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
leadingIcon = if (conversation.unread) ({ Badge() }) else null,
|
||||||
|
trailingIcon = if (key is ChatKey.Private) ({
|
||||||
|
Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) })
|
||||||
|
}) else null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The conversation's lines, following new ones while the newest is in view. */
|
||||||
|
@Composable
|
||||||
|
private fun Lines(
|
||||||
|
lines: List<ChatLine>,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
modifier: Modifier,
|
||||||
|
find: TextQuery,
|
||||||
|
current: ChatMatch?,
|
||||||
|
reveal: Long?,
|
||||||
|
onRevealed: () -> Unit,
|
||||||
|
) {
|
||||||
|
val listState = rememberLazyListState(initialFirstVisibleItemIndex = (lines.size - 1).coerceAtLeast(0))
|
||||||
|
val link by rememberUpdatedState(onLink)
|
||||||
|
// Following the end until the user scrolls away from it, so a restored log, new lines
|
||||||
|
// and pictures that load late all keep the newest line in view.
|
||||||
|
var follow by remember { mutableStateOf(true) }
|
||||||
|
LaunchedEffect(listState) {
|
||||||
|
snapshotFlow { listState.isScrollInProgress }.drop(1).filter { !it }
|
||||||
|
.collect { follow = !listState.canScrollForward }
|
||||||
|
}
|
||||||
|
LaunchedEffect(listState) {
|
||||||
|
snapshotFlow { follow && listState.canScrollForward && !listState.isScrollInProgress }.filter { it }
|
||||||
|
.collect { listState.scrollToItem(listState.layoutInfo.totalItemsCount - 1, Int.MAX_VALUE) }
|
||||||
|
}
|
||||||
|
LaunchedEffect(reveal, lines) {
|
||||||
|
val id = reveal ?: return@LaunchedEffect
|
||||||
|
val index = lines.indexOfFirst { it.id == id }
|
||||||
|
if (index < 0) return@LaunchedEffect
|
||||||
|
val info = listState.layoutInfo
|
||||||
|
if (info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
|
||||||
|
// The line's top ends up in the middle of the list.
|
||||||
|
val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2
|
||||||
|
listState.animateScrollToItem(index, -middle)
|
||||||
|
}
|
||||||
|
onRevealed()
|
||||||
|
}
|
||||||
|
LazyColumn(modifier.fillMaxWidth(), state = listState, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) {
|
||||||
|
items(lines, key = { it.id }) { line ->
|
||||||
|
RichText(line.html, { link(it) }, Modifier.padding(vertical = 2.dp), MaterialTheme.typography.bodyMedium,
|
||||||
|
find, if (current?.line == line.id) current.nth else -1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
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.aspectRatio
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.LocalTextStyle
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.produceState
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.AnnotatedString
|
||||||
|
import androidx.compose.ui.text.LinkAnnotation
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.TextLinkStyles
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.fromHtml
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.WebPictures
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachment
|
||||||
|
import eu.lixko.ts3j.client.text.BBCode
|
||||||
|
import eu.lixko.ts3j.client.text.ChatHtml
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTML as [BBCode][eu.lixko.ts3j.client.text.BBCode] and [ChatHtml] write it, with its rules as dividers
|
||||||
|
* and its pictures fetched from the web: Android's HTML parser shows neither, so the text is
|
||||||
|
* split at them.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun RichText(
|
||||||
|
html: String,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
style: TextStyle = LocalTextStyle.current,
|
||||||
|
/** Matches to highlight: [current] is the index of the one the find bar is on, if it is here. */
|
||||||
|
find: TextQuery = TextQuery.EMPTY,
|
||||||
|
current: Int = -1,
|
||||||
|
) {
|
||||||
|
val link by rememberUpdatedState(onLink)
|
||||||
|
val color = linkColor()
|
||||||
|
val parsed = remember(html, color) { split(html) { chatText(it, color) { href -> link(href) } } }
|
||||||
|
val match = findMatchColor()
|
||||||
|
val currentMatch = findCurrentColor()
|
||||||
|
val pieces = remember(parsed, find, current, match, currentMatch) {
|
||||||
|
if (find.isEmpty) parsed else highlight(parsed, find, current, match, currentMatch)
|
||||||
|
}
|
||||||
|
Column(modifier) {
|
||||||
|
for (piece in pieces) {
|
||||||
|
when (piece) {
|
||||||
|
Piece.Rule -> HorizontalDivider(Modifier.padding(vertical = 6.dp))
|
||||||
|
is Piece.Image -> WebPicture(piece, style) { link(it) }
|
||||||
|
// As wide as there is room, for aligned paragraphs to have somewhere to go.
|
||||||
|
is Piece.Text -> if (piece.text.isNotEmpty()) Text(piece.text, Modifier.fillMaxWidth(), style = style)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [pieces] with [find]'s matches behind [match], and the [current]th of them, counting across pieces, behind [currentMatch]. */
|
||||||
|
private fun highlight(pieces: List<Piece>, find: TextQuery, current: Int, match: Color, currentMatch: Color): List<Piece> {
|
||||||
|
var n = 0
|
||||||
|
return pieces.map { piece ->
|
||||||
|
if (piece !is Piece.Text) return@map piece
|
||||||
|
val m = find.matcher(piece.text.text) ?: return@map piece
|
||||||
|
val text = AnnotatedString.Builder(piece.text)
|
||||||
|
while (m.find()) {
|
||||||
|
if (m.end() == m.start()) continue
|
||||||
|
text.addStyle(SpanStyle(background = if (n == current) currentMatch else match), m.start(), m.end())
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
Piece.Text(text.toAnnotatedString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The web pictures descriptions show. */
|
||||||
|
val LocalWebPictures = staticCompositionLocalOf<WebPictures?> { null }
|
||||||
|
|
||||||
|
private sealed interface Piece {
|
||||||
|
data class Text(val text: AnnotatedString) : Piece
|
||||||
|
data object Rule : Piece
|
||||||
|
/** @param href where the picture links to, if it sits in a link */
|
||||||
|
data class Image(val url: String, val href: String?, val align: Alignment.Horizontal) : Piece
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [html] cut at its rules and pictures. Each piece of text is closed where it is cut and the
|
||||||
|
* next reopens what it was in, so an aligned block or a link carries on past a picture.
|
||||||
|
*/
|
||||||
|
private fun split(html: String, text: (String) -> AnnotatedString): List<Piece> {
|
||||||
|
val pieces = ArrayList<Piece>()
|
||||||
|
val divs = ArrayList<String>()
|
||||||
|
var anchor: String? = null
|
||||||
|
var href: String? = null
|
||||||
|
val current = StringBuilder()
|
||||||
|
fun cut() {
|
||||||
|
if (anchor != null) current.append("</a>")
|
||||||
|
repeat(divs.size) { current.append("</div>") }
|
||||||
|
pieces += Piece.Text(text(current.toString()))
|
||||||
|
current.setLength(0)
|
||||||
|
divs.forEach { current.append(it) }
|
||||||
|
anchor?.let { current.append(it) }
|
||||||
|
}
|
||||||
|
var last = 0
|
||||||
|
for (m in CUT_TAG.findAll(html)) {
|
||||||
|
current.append(html, last, m.range.first)
|
||||||
|
last = m.range.last + 1
|
||||||
|
val tag = m.value
|
||||||
|
when {
|
||||||
|
tag.startsWith("<hr", ignoreCase = true) -> {
|
||||||
|
cut()
|
||||||
|
pieces += Piece.Rule
|
||||||
|
}
|
||||||
|
tag.startsWith("<img", ignoreCase = true) -> {
|
||||||
|
cut()
|
||||||
|
pieces += Piece.Image(unescape(m.groupValues[1]), href?.let(::unescape), alignment(divs))
|
||||||
|
}
|
||||||
|
tag.startsWith("<div", ignoreCase = true) -> {
|
||||||
|
divs += tag
|
||||||
|
current.append(tag)
|
||||||
|
}
|
||||||
|
tag.equals("</div>", ignoreCase = true) -> {
|
||||||
|
divs.removeLastOrNull()
|
||||||
|
current.append(tag)
|
||||||
|
}
|
||||||
|
tag.startsWith("<a", ignoreCase = true) -> {
|
||||||
|
anchor = tag
|
||||||
|
href = m.groupValues[2]
|
||||||
|
current.append(tag)
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
anchor = null
|
||||||
|
href = null
|
||||||
|
current.append(tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current.append(html, last, html.length)
|
||||||
|
pieces += Piece.Text(text(current.toString()))
|
||||||
|
return pieces
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where the innermost aligned block puts what is in it. */
|
||||||
|
private fun alignment(divs: List<String>): Alignment.Horizontal {
|
||||||
|
val align = divs.asReversed().firstNotNullOfOrNull { ALIGN.find(it)?.groupValues?.get(1) }
|
||||||
|
return when (align) {
|
||||||
|
"center" -> Alignment.CenterHorizontally
|
||||||
|
"right" -> Alignment.End
|
||||||
|
else -> Alignment.Start
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unescape(s: String) =
|
||||||
|
s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A picture at its own size, a pixel to a dp as TeamSpeak shows it, narrowed to fit. With
|
||||||
|
* pictures turned off, or when one cannot be had, its address as a link behind a picture icon.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun WebPicture(image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) {
|
||||||
|
val pictures = LocalWebPictures.current
|
||||||
|
Column(Modifier.fillMaxWidth().padding(vertical = 2.dp), horizontalAlignment = image.align) {
|
||||||
|
if (pictures == null || !pictures.enabled) {
|
||||||
|
PictureLink("ICONVIEWER", image, style, onLink)
|
||||||
|
return@Column
|
||||||
|
}
|
||||||
|
val version by pictures.version.collectAsStateWithLifecycle()
|
||||||
|
val state by produceState<WebPictures.State>(WebPictures.State.Loading, image.url, version) {
|
||||||
|
value = pictures.state(image.url)
|
||||||
|
}
|
||||||
|
when (val shown = state) {
|
||||||
|
WebPictures.State.Loading -> PackIcon("LOADING_IMAGE", "Loading picture", size = 16.dp)
|
||||||
|
WebPictures.State.Broken -> PictureLink("BROKEN_IMAGE", image, style, onLink)
|
||||||
|
is WebPictures.State.Shown -> {
|
||||||
|
val picture = shown.picture
|
||||||
|
val viewer = LocalPictureViewer.current
|
||||||
|
Image(
|
||||||
|
rememberPicturePainter(picture),
|
||||||
|
null,
|
||||||
|
Modifier
|
||||||
|
.widthIn(max = picture.width.dp)
|
||||||
|
.aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1))
|
||||||
|
.then(if (viewer != null) Modifier.clickable {
|
||||||
|
viewer(viewedPicture(image, onLink) { pictures.data(image.url) })
|
||||||
|
} else if (image.href != null) Modifier.clickable { onLink(image.href) } else Modifier),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [image] to open full size; a file shared in chat has no address to copy or link to follow but itself. */
|
||||||
|
private fun viewedPicture(image: Piece.Image, onLink: (String) -> Unit, read: suspend () -> ByteArray?): ViewedPicture {
|
||||||
|
val attachment = ChatAttachment.Ref.parse(image.url)
|
||||||
|
if (attachment != null) return ViewedPicture(attachment.fileName.substringBeforeLast('.'), read = read)
|
||||||
|
val openLink = image.href?.let { href -> { onLink(href) } }
|
||||||
|
return ViewedPicture(pictureName(image.url), image.url, openLink, read = read)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The picture's address as a link behind [iconKey], then the link it sat in, if any, so neither is lost. */
|
||||||
|
@Composable
|
||||||
|
private fun PictureLink(iconKey: String, image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) {
|
||||||
|
val color = linkColor()
|
||||||
|
val text = remember(image, color) {
|
||||||
|
val links = listOfNotNull(image.url, image.href?.takeIf { it != image.url })
|
||||||
|
chatText(links.joinToString(" ") { "<a href=\"${BBCode.escape(it)}\">${BBCode.escape(linkText(it))}</a>" }, color, onLink)
|
||||||
|
}
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
PackIcon(iconKey, "Picture", size = 16.dp)
|
||||||
|
Text(text, style = style)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A shared file goes by its name, anything else by its address. */
|
||||||
|
private fun linkText(url: String): String = ChatAttachment.Ref.parse(url)?.fileName ?: BBCode.shortAddress(url)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTML without rules as styled text. Android's parser knows no stylesheets, tables,
|
||||||
|
* numbered lists, font sizes or `align`, so the classes [ChatHtml] marks lines with become
|
||||||
|
* inline colours, table rows lines of their cells, numbered items numbered lines, sizes
|
||||||
|
* `<big>`/`<small>`, and alignment the style it does know.
|
||||||
|
*/
|
||||||
|
fun chatText(html: String, linkColor: Color, onLink: (String) -> Unit): AnnotatedString {
|
||||||
|
val styled = sizes(numbered(CLASS.replace(html) { m ->
|
||||||
|
CLASS_COLORS[m.groupValues[1]]?.let { "style=\"color:$it\"" } ?: ""
|
||||||
|
}))
|
||||||
|
.replace(ALIGN) { m -> "style=\"text-align:${ALIGNS.getValue(m.groupValues[1])}\"" }
|
||||||
|
.replace(CELL_END, " ")
|
||||||
|
.replace(ROW_END, "<br>")
|
||||||
|
val text = AnnotatedString.fromHtml(
|
||||||
|
styled,
|
||||||
|
TextLinkStyles(SpanStyle(color = linkColor, fontWeight = FontWeight.SemiBold)),
|
||||||
|
) { link -> (link as? LinkAnnotation.Url)?.let { onLink(it.url) } }
|
||||||
|
// Block elements leave line breaks around the text.
|
||||||
|
val start = text.text.indexOfFirst { !it.isWhitespace() }.coerceAtLeast(0)
|
||||||
|
val end = text.text.indexOfLast { !it.isWhitespace() } + 1
|
||||||
|
return if (end <= start) AnnotatedString("") else text.subSequence(start, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Numbers the items of each `<ol>`, innermost first. */
|
||||||
|
private fun numbered(html: String): String {
|
||||||
|
var out = html
|
||||||
|
while (true) {
|
||||||
|
val list = INNER_OL.find(out) ?: return out
|
||||||
|
val letters = list.groupValues[1].isNotEmpty()
|
||||||
|
var n = 0
|
||||||
|
val items = LI.replace(list.groupValues[2]) { m ->
|
||||||
|
if (m.value.startsWith("</")) "" else {
|
||||||
|
n++
|
||||||
|
"<br>" + (if (letters) ('a' + (n - 1) % 26).toString() else n.toString()) + ". "
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = out.replaceRange(list.range, "<div>$items</div>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns each font-size span into `<big>`s or `<small>` (or a plain span), closing it alike.
|
||||||
|
* Sizes are TeamSpeak's, around its 11 px text.
|
||||||
|
*/
|
||||||
|
private fun sizes(html: String): String {
|
||||||
|
val closes = ArrayDeque<String>()
|
||||||
|
return SPAN.replace(html) { m ->
|
||||||
|
if (m.value.startsWith("</")) {
|
||||||
|
closes.removeLastOrNull() ?: m.value
|
||||||
|
} else {
|
||||||
|
val px = m.groupValues[1].toIntOrNull()
|
||||||
|
val tags = when {
|
||||||
|
px == null -> listOf("span")
|
||||||
|
px >= BIGGER_PX -> listOf("big", "big")
|
||||||
|
px >= BIG_PX -> listOf("big")
|
||||||
|
px <= SMALL_PX -> listOf("small")
|
||||||
|
else -> listOf("span")
|
||||||
|
}
|
||||||
|
closes.addLast(tags.reversed().joinToString("") { "</$it>" })
|
||||||
|
if (px == null) m.value else tags.joinToString("") { "<$it>" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val BIGGER_PX = 18
|
||||||
|
private const val BIG_PX = 13
|
||||||
|
private const val SMALL_PX = 9
|
||||||
|
|
||||||
|
private val INNER_OL = Regex("<ol( type=\"a\")?>((?:(?!<ol[ >]).)*?)</ol>", RegexOption.DOT_MATCHES_ALL)
|
||||||
|
private val LI = Regex("</?li>")
|
||||||
|
private val SPAN = Regex("<span style=\"font-size:(\\d+)px\">|<span[^>]*>|</span>")
|
||||||
|
private val ALIGNS = mapOf("left" to "start", "justify" to "start", "center" to "center", "right" to "end")
|
||||||
|
|
||||||
|
/** Where the text is cut, and what it has to carry across: aligned blocks and links. */
|
||||||
|
private val CUT_TAG = Regex(
|
||||||
|
"<hr\\s*/?>|<img src=\"([^\"]*)\">|<div[^>]*>|</div>|<a [^>]*href=\"([^\"]*)\"[^>]*>|</a>",
|
||||||
|
RegexOption.IGNORE_CASE,
|
||||||
|
)
|
||||||
|
private val CLASS = Regex("class=\"([a-z]+)\"")
|
||||||
|
private val ALIGN = Regex("align=\"(left|center|right|justify)\"")
|
||||||
|
private val CELL_END = Regex("</t[dh]>")
|
||||||
|
private val ROW_END = Regex("</tr>")
|
||||||
|
|
||||||
|
private val CLASS_COLORS = mapOf(
|
||||||
|
ChatHtml.MUTED_CLASS to "#8c8c8c",
|
||||||
|
ChatHtml.EVENT_CLASS to "#7a8fa6",
|
||||||
|
)
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
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.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
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.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
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
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.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.IdentityInfo
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.net.IconRepository
|
||||||
|
|
||||||
|
/** Where to connect to: an address typed in, or a bookmark. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ConnectScreen(
|
||||||
|
vm: SessionController,
|
||||||
|
snackbar: SnackbarHostState,
|
||||||
|
onSettings: () -> Unit,
|
||||||
|
onMyTeamSpeak: () -> Unit,
|
||||||
|
onConnect: (() -> Unit) -> Unit,
|
||||||
|
onEditBookmark: (BookmarkEdit) -> Unit,
|
||||||
|
/** 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) }
|
||||||
|
var identityId by rememberSaveable { mutableStateOf("") }
|
||||||
|
var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) }
|
||||||
|
var password by rememberSaveable { mutableStateOf("") }
|
||||||
|
|
||||||
|
if (onBack != null) BackHandler(onBack = onBack)
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text("TeamSpook TS3j") },
|
||||||
|
navigationIcon = {
|
||||||
|
if (onBack != null) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
|
||||||
|
},
|
||||||
|
actions = {
|
||||||
|
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
snackbarHost = { SnackbarHost(snackbar) },
|
||||||
|
) { padding ->
|
||||||
|
LazyColumn(
|
||||||
|
Modifier.padding(padding).imePadding(),
|
||||||
|
contentPadding = PaddingValues(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
item {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
|
||||||
|
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
|
||||||
|
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
|
||||||
|
singleLine = true)
|
||||||
|
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
|
||||||
|
label = { Text("Server password") }, singleLine = true,
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
|
||||||
|
IdentityField(identities, identityId) {
|
||||||
|
identityId = it
|
||||||
|
nickname = vm.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) } },
|
||||||
|
enabled = address.isNotBlank() && nickname.isNotBlank(),
|
||||||
|
) { Text("Connect") }
|
||||||
|
TextButton(onClick = {
|
||||||
|
onEditBookmark(BookmarkEdit(-1, vm.newBookmark(address.trim(), nickname.trim(), password, identityId)))
|
||||||
|
}, enabled = address.isNotBlank()) { Text("Add bookmark") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (bookmarks.isNotEmpty()) {
|
||||||
|
item {
|
||||||
|
Text("Bookmarks", Modifier.padding(top = 16.dp), style = MaterialTheme.typography.titleSmall,
|
||||||
|
color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
item {
|
||||||
|
OutlinedButton(onClick = onMyTeamSpeak, Modifier.padding(top = 16.dp)) {
|
||||||
|
Text(if (myTeamSpeakSignedIn) "Import from myTeamSpeak" else "Sign in to myTeamSpeak")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
itemsIndexed(bookmarks) { index, bookmark ->
|
||||||
|
BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } },
|
||||||
|
onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) },
|
||||||
|
onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null,
|
||||||
|
onRemove = { vm.removeBookmark(bookmark) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The identities to connect with, the default one first as an empty id. */
|
||||||
|
private fun identityChoices(identities: List<IdentityInfo>): List<Pair<String, String>> {
|
||||||
|
val default = identities.firstOrNull { it.isDefault }?.name
|
||||||
|
return listOf("" to (default?.let { "Default ($it)" } ?: "Default")) + identities.map { it.id to it.name }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An id no longer among the identities connects with the default, and shows as such. */
|
||||||
|
private fun shownId(identities: List<IdentityInfo>, id: String) = id.takeIf { i -> identities.any { it.id == i } } ?: ""
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
internal fun IdentityField(identities: List<IdentityInfo>, selected: String, onSelect: (String) -> Unit) {
|
||||||
|
val choices = identityChoices(identities)
|
||||||
|
val shown = shownId(identities, selected)
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
ExposedDropdownMenuBox(open, { open = it }) {
|
||||||
|
OutlinedTextField(
|
||||||
|
choices.first { it.first == shown }.second, {}, readOnly = true, singleLine = true,
|
||||||
|
label = { Text("Identity") },
|
||||||
|
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) },
|
||||||
|
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
|
||||||
|
)
|
||||||
|
ExposedDropdownMenu(open, { open = false }) {
|
||||||
|
for ((id, name) in choices) {
|
||||||
|
DropdownMenuItem({ Text(name) }, onClick = {
|
||||||
|
open = false
|
||||||
|
onSelect(id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's icon as last seen there, else the pack's bookmark icon. */
|
||||||
|
@Composable
|
||||||
|
private fun BookmarkIcon(iconId: Long) {
|
||||||
|
val cached = remember(iconId) {
|
||||||
|
IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }
|
||||||
|
}
|
||||||
|
if (cached != null) Image(cached, null, Modifier.size(24.dp))
|
||||||
|
else PackIcon("BOOKMARK_MANAGER", null)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val AUTOCONNECT = Color(0xFF3A9D4A)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun BookmarkRow(
|
||||||
|
bookmark: Bookmark,
|
||||||
|
identities: List<IdentityInfo>,
|
||||||
|
onConnect: () -> Unit,
|
||||||
|
onEdit: () -> Unit,
|
||||||
|
/** Null when the launcher takes no shortcuts. */
|
||||||
|
onPin: (() -> Unit)?,
|
||||||
|
onRemove: () -> Unit,
|
||||||
|
) {
|
||||||
|
val identity = identities.firstOrNull { it.id == bookmark.identityId }
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
ListItem(
|
||||||
|
headlineContent = {
|
||||||
|
Text(buildAnnotatedString {
|
||||||
|
if (bookmark.connectOnStartup) {
|
||||||
|
withStyle(SpanStyle(color = AUTOCONNECT, fontWeight = FontWeight.Bold)) { append("AC") }
|
||||||
|
append(' ')
|
||||||
|
}
|
||||||
|
append(bookmark.displayName())
|
||||||
|
})
|
||||||
|
},
|
||||||
|
supportingContent = {
|
||||||
|
Text(listOfNotNull(bookmark.hostPort(), bookmark.channel.ifBlank { null }, identity?.name)
|
||||||
|
.joinToString(" · "))
|
||||||
|
},
|
||||||
|
leadingContent = { BookmarkIcon(bookmark.iconId) },
|
||||||
|
trailingContent = {
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Bookmark options") }
|
||||||
|
DropdownMenu(menu, { menu = false }) {
|
||||||
|
DropdownMenuItem({ Text("Edit") }, onClick = { menu = false; onEdit() })
|
||||||
|
onPin?.let { DropdownMenuItem({ Text("Add to home screen") }, onClick = { menu = false; it() }) }
|
||||||
|
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; onRemove() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.clickable(onClick = onConnect),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.RowScope
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.PrimaryScrollableTabRow
|
||||||
|
import androidx.compose.material3.Tab
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontStyle
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ClientItem
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.net.ConnectionStats
|
||||||
|
import eu.lixko.ts3j.client.net.ConnectionStatsFormat
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
private const val REFRESH_MS = 1000L
|
||||||
|
|
||||||
|
private val TABS = ConnectionStatsFormat.TRAFFIC_TABS.map { it.title() } +
|
||||||
|
listOf(ConnectionStatsFormat.QUOTA_TAB, ConnectionStatsFormat.VOICE_TAB)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A client's connection figures, read again every second while shown, laid out as TeamSpeak's
|
||||||
|
* Connection Info window: name, times, ping and address beside the avatar, then a tab per
|
||||||
|
* traffic category with Total / In / Out columns, Quota, and what our playback made of their voice.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) {
|
||||||
|
var stats by remember { mutableStateOf<ConnectionStats?>(null) }
|
||||||
|
LaunchedEffect(clientId) {
|
||||||
|
while (true) {
|
||||||
|
stats = server.connectionStats(clientId) ?: break
|
||||||
|
delay(REFRESH_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||||
|
val s = stats
|
||||||
|
SubScreen("Connection info", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
|
||||||
|
Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||||
|
Summary(s, client?.nickname ?: "", Modifier.weight(1f))
|
||||||
|
if (client != null && client.avatarFlag.isNotEmpty()) {
|
||||||
|
Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) {
|
||||||
|
TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) }
|
||||||
|
}
|
||||||
|
val traffic = ConnectionStatsFormat.TRAFFIC_TABS
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||||
|
when {
|
||||||
|
tab < traffic.size -> TrafficTable(ConnectionStatsFormat.trafficRows(s, traffic[tab].kind()))
|
||||||
|
tab == traffic.size -> Figures(ConnectionStatsFormat.quotaGroups(s))
|
||||||
|
else -> Figures(listOf(ConnectionStatsFormat.voiceRows(s?.voiceReceived)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val address = ConnectionStatsFormat.copyableAddress(s)
|
||||||
|
val rows = ConnectionStatsFormat.summaryRows(s, nickname)
|
||||||
|
Column(modifier) {
|
||||||
|
rows.forEachIndexed { i, row ->
|
||||||
|
Row(Modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(row.value, textAlign = TextAlign.End)
|
||||||
|
if (i == rows.lastIndex) {
|
||||||
|
IconButton(
|
||||||
|
onClick = {
|
||||||
|
// The system confirms the copy itself.
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText("Client address", address))
|
||||||
|
},
|
||||||
|
enabled = address != null,
|
||||||
|
modifier = Modifier.size(32.dp),
|
||||||
|
) { PackIcon("COPY", "Copy client address", size = 18.dp) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Labelled figures in groups set apart by a rule. */
|
||||||
|
@Composable
|
||||||
|
private fun Figures(groups: List<List<ConnectionStatsFormat.Row>>) {
|
||||||
|
groups.forEachIndexed { g, rows ->
|
||||||
|
if (g > 0) HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||||
|
for (row in rows) {
|
||||||
|
Row(Modifier.padding(vertical = 4.dp)) {
|
||||||
|
Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(row.value, textAlign = TextAlign.End)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun TrafficTable(rows: List<ConnectionStatsFormat.TrafficRow>) {
|
||||||
|
Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
LabelCell("")
|
||||||
|
ConnectionStatsFormat.COLUMNS.forEachIndexed { i, column -> ValueCell(column, i == 0, FontStyle.Italic) }
|
||||||
|
}
|
||||||
|
for (row in rows) {
|
||||||
|
Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
LabelCell(row.label)
|
||||||
|
ValueCell(row.total, narrow = true)
|
||||||
|
ValueCell(row.`in`)
|
||||||
|
ValueCell(row.out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RowScope.LabelCell(text: String) =
|
||||||
|
Text(text, Modifier.weight(1.5f), color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
style = MaterialTheme.typography.bodySmall)
|
||||||
|
|
||||||
|
/** The Total column only ever holds the loss percentage. */
|
||||||
|
@Composable
|
||||||
|
private fun RowScope.ValueCell(text: String, narrow: Boolean = false, fontStyle: FontStyle? = null) =
|
||||||
|
Text(text, Modifier.weight(if (narrow) 0.7f else 1f), style = MaterialTheme.typography.bodySmall, fontStyle = fontStyle,
|
||||||
|
textAlign = TextAlign.End)
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.PrimaryTabRow
|
||||||
|
import androidx.compose.material3.Tab
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
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.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
|
||||||
|
|
||||||
|
private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
|
||||||
|
|
||||||
|
private val DISPLAYS = listOf(
|
||||||
|
NicknameDisplay.ONLY_NICKNAME to "Nickname",
|
||||||
|
NicknameDisplay.ONLY_CUSTOM to "Custom name",
|
||||||
|
NicknameDisplay.BOTH to "Both",
|
||||||
|
)
|
||||||
|
|
||||||
|
private val GROUPS = listOf(
|
||||||
|
ContactType.FRIEND to "Friends",
|
||||||
|
ContactType.BLOCKED to "Blocked",
|
||||||
|
ContactType.NEUTRAL to "Neutral",
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The contact list, grouped as TeamSpeak's Contacts window groups it, with each
|
||||||
|
* contact's own page and the defaults new contacts start out with.
|
||||||
|
*
|
||||||
|
* @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) {
|
||||||
|
var defaults by rememberSaveable { mutableStateOf(false) }
|
||||||
|
when {
|
||||||
|
editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) })
|
||||||
|
defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false })
|
||||||
|
}
|
||||||
|
|
||||||
|
val contacts by vm.contacts.collectAsStateWithLifecycle()
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
var imported by remember { mutableStateOf<String?>(null) }
|
||||||
|
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri != null) scope.launch {
|
||||||
|
imported = runCatching { vm.importContacts(uri) }.fold(
|
||||||
|
{ (found, added) ->
|
||||||
|
if (found == 0) "That file holds no contacts."
|
||||||
|
else "Imported $found contacts, $added of them new."
|
||||||
|
},
|
||||||
|
{ "That file is not a TeamSpeak 3 settings.db." },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen("Contacts", onBack, actions = {
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
|
||||||
|
DropdownMenu(menu, { menu = false }) {
|
||||||
|
DropdownMenuItem({ Text("Defaults for new contacts") }, onClick = { menu = false; defaults = true })
|
||||||
|
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
|
||||||
|
menu = false
|
||||||
|
importer.launch(arrayOf("*/*"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) { padding ->
|
||||||
|
LazyColumn(Modifier.padding(padding)) {
|
||||||
|
imported?.let { item { Hint(it) } }
|
||||||
|
if (contacts.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() }
|
||||||
|
if (group.isEmpty()) continue
|
||||||
|
item(key = type) { Section(title) }
|
||||||
|
items(group, key = { it.uniqueId }) { contact ->
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
|
||||||
|
supportingContent = { Text(lastSeen(contact)) },
|
||||||
|
modifier = Modifier.clickable { onEdit(contact.uniqueId) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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()
|
||||||
|
val contact = contacts.firstOrNull { it.uniqueId == uniqueId }
|
||||||
|
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(uniqueId)?.let { vm.saveContact(it.apply(change)) }
|
||||||
|
}
|
||||||
|
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
|
||||||
|
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
|
||||||
|
var removing by remember { mutableStateOf(false) }
|
||||||
|
val leave = {
|
||||||
|
if (customName.trim() != contact.nickname || phoneticName.trim() != contact.phoneticNickname) {
|
||||||
|
edit {
|
||||||
|
nickname = customName.trim()
|
||||||
|
phoneticNickname = phoneticName.trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onBack()
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen(label(contact), leave, actions = {
|
||||||
|
IconButton(onClick = { removing = true }) { PackIcon(if (contact.type == ContactType.BLOCKED) "REMOVE_FOE" else "REMOVE_FRIEND", "Remove from contacts") }
|
||||||
|
}) { padding ->
|
||||||
|
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
|
||||||
|
OutlinedTextField(customName, { customName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||||
|
label = { Text("Custom nickname") }, singleLine = true)
|
||||||
|
OutlinedTextField(phoneticName, { phoneticName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
label = { Text("Phonetic nickname") }, singleLine = true)
|
||||||
|
|
||||||
|
Section("Contact")
|
||||||
|
Segments(GROUPS.map { (type, _) -> type to type.label() }, contact.type) { edit { type = it } }
|
||||||
|
|
||||||
|
Section("Show as")
|
||||||
|
Segments(DISPLAYS, contact.nicknameDisplay) { edit { nicknameDisplay = it } }
|
||||||
|
|
||||||
|
Section("Ignore")
|
||||||
|
Toggle("Mute", contact.automute) { edit { automute = it } }
|
||||||
|
Toggle("Ignore server and channel chat", contact.ignorePublicMessages) { edit { ignorePublicMessages = it } }
|
||||||
|
Toggle("Ignore private chat", contact.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
|
||||||
|
Toggle("Ignore pokes", contact.ignorePokes) { edit { ignorePokes = it } }
|
||||||
|
Toggle("Hide avatar", contact.ignoreAvatar) { edit { ignoreAvatar = it } }
|
||||||
|
Toggle("Hide away message", contact.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
|
||||||
|
Toggle("Deny whisper", !contact.whisperAllowed) { edit { whisperAllowed = !it } }
|
||||||
|
|
||||||
|
Section("Playback")
|
||||||
|
val volume = if (contact.hasVolumeModifier) contact.volumeModifier.toFloat() else 0f
|
||||||
|
Level("Volume", volume, -30f..20f, ::formatVolume) { db ->
|
||||||
|
val rounded = db.roundToInt().toDouble()
|
||||||
|
edit {
|
||||||
|
hasVolumeModifier = rounded != 0.0
|
||||||
|
volumeModifier = rounded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Details")
|
||||||
|
val context = LocalContext.current
|
||||||
|
LinkRow("Unique ID", contact.uniqueId) {
|
||||||
|
// The system confirms the copy itself.
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId))
|
||||||
|
}
|
||||||
|
ListItem(headlineContent = { Text(lastSeen(contact)) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (removing) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { removing = false },
|
||||||
|
title = { Text("Remove ${label(contact)}?") },
|
||||||
|
text = { Text("Their settings here are forgotten; they show as anyone else again.") },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
removing = false
|
||||||
|
vm.removeContact(uniqueId)
|
||||||
|
onBack()
|
||||||
|
}) { Text("Remove") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
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()
|
||||||
|
entry = changed
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen("Defaults for new contacts", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding)) {
|
||||||
|
PrimaryTabRow(selectedTabIndex = GROUPS.indexOfFirst { it.first == tab }) {
|
||||||
|
for ((type, title) in GROUPS) Tab(tab == type, onClick = { tab = type }, text = { Text(title) })
|
||||||
|
}
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
|
||||||
|
Section("Show as")
|
||||||
|
Segments(DISPLAYS, entry.nicknameDisplay) { edit { nicknameDisplay = it } }
|
||||||
|
Section("Ignore")
|
||||||
|
Toggle("Mute", entry.automute) { edit { automute = it } }
|
||||||
|
Toggle("Ignore server and channel chat", entry.ignorePublicMessages) { edit { ignorePublicMessages = it } }
|
||||||
|
Toggle("Ignore private chat", entry.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
|
||||||
|
Toggle("Ignore pokes", entry.ignorePokes) { edit { ignorePokes = it } }
|
||||||
|
Toggle("Hide avatar", entry.ignoreAvatar) { edit { ignoreAvatar = it } }
|
||||||
|
Toggle("Hide away message", entry.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
|
||||||
|
Toggle("Deny whisper", entry.ignoreWhisper) { edit { ignoreWhisper = it } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId }
|
||||||
|
|
||||||
|
private fun lastSeen(contact: Contact): String {
|
||||||
|
val seen = contact.lastSeen ?: return "Never seen"
|
||||||
|
val where = contact.lastSeenServerName.ifBlank { contact.lastSeenServerAddress }
|
||||||
|
return "Last seen ${SEEN.format(seen)}" + if (where.isNotBlank()) " on $where" else ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun formatVolume(db: Float): String {
|
||||||
|
val rounded = db.roundToInt()
|
||||||
|
return if (rounded == 0) "Unchanged" else "${if (rounded > 0) "+" else ""}$rounded dB"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun typeColor(type: ContactType): Color = when (type) {
|
||||||
|
ContactType.FRIEND -> StatusColors.friend
|
||||||
|
ContactType.BLOCKED -> StatusColors.blocked
|
||||||
|
ContactType.NEUTRAL -> Color.Unspecified
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.animateContentSize
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
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.ExperimentalLayoutApi
|
||||||
|
import androidx.compose.foundation.layout.FlowRow
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clipToBounds
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.layout.Layout
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Constraints
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.net.Details
|
||||||
|
import eu.lixko.ts3j.client.text.BBCode
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The facts of the server, a channel or a client, then its description, for the top of its sheet.
|
||||||
|
* The minor facts wait behind "more…".
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun DetailsSection(details: Details, onLink: (String) -> Unit, modifier: Modifier = Modifier) {
|
||||||
|
var all by rememberSaveable(details.title()) { mutableStateOf(false) }
|
||||||
|
val shown = if (all) details.fields() else details.fields().filterNot { it.minor() }
|
||||||
|
val more = !all && shown.size < details.fields().size
|
||||||
|
Column(modifier.padding(horizontal = 24.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (shown.isNotEmpty() || more) {
|
||||||
|
Column(Modifier.animateContentSize(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||||
|
for (field in shown) Fact(field)
|
||||||
|
if (more) {
|
||||||
|
Text("more…", Modifier.clickable { all = true }.padding(vertical = 2.dp),
|
||||||
|
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
details.description().isNotBlank() -> Description(details.description(), onLink)
|
||||||
|
details.pending() -> Text("Loading description…", style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalLayoutApi::class)
|
||||||
|
@Composable
|
||||||
|
private fun Fact(field: Details.Field) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text(field.label(), Modifier.width(96.dp), style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
if (field.groups().isEmpty()) {
|
||||||
|
Text(field.value(), style = MaterialTheme.typography.bodySmall)
|
||||||
|
} else {
|
||||||
|
// Each group with its icon, as TeamSpeak's info frame lists them.
|
||||||
|
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
// A nameless group shows only its icon, and takes no comma.
|
||||||
|
val lastNamed = field.groups().indexOfLast { it.name.isNotBlank() }
|
||||||
|
field.groups().forEachIndexed { i, group ->
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
ServerIcon(group.iconId, size = 14.dp)
|
||||||
|
if (group.name.isNotBlank()) {
|
||||||
|
Text(group.name.trim() + if (i < lastNamed) "," else "", style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The description in a box that opens up, when there is more of it than fits folded. */
|
||||||
|
@Composable
|
||||||
|
private fun Description(bbcode: String, onLink: (String) -> Unit) {
|
||||||
|
val html = remember(bbcode) { BBCode.toHtml(bbcode, true) }
|
||||||
|
var expanded by rememberSaveable(bbcode) { mutableStateOf(false) }
|
||||||
|
var overflows by remember(bbcode) { mutableStateOf(false) }
|
||||||
|
val expandable = overflows || expanded
|
||||||
|
val background = MaterialTheme.colorScheme.surfaceContainerHigh
|
||||||
|
Surface(
|
||||||
|
Modifier.fillMaxWidth().then(if (expandable) Modifier.clickable { expanded = !expanded } else Modifier),
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
color = background,
|
||||||
|
) {
|
||||||
|
Column(Modifier.animateContentSize().padding(12.dp)) {
|
||||||
|
Box {
|
||||||
|
Folded(FOLDED_HEIGHT, expanded, onOverflow = { overflows = it }) {
|
||||||
|
RichText(html, onLink, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
if (overflows && !expanded) {
|
||||||
|
Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(24.dp)
|
||||||
|
.background(Brush.verticalGradient(listOf(Color.Transparent, background))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (expandable) {
|
||||||
|
Text(if (expanded) "Less" else "More", Modifier.padding(top = 4.dp),
|
||||||
|
style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Its content cut to [height] unless [open], telling whether there is more of it than that. */
|
||||||
|
@Composable
|
||||||
|
private fun Folded(height: Dp, open: Boolean, onOverflow: (Boolean) -> Unit, content: @Composable () -> Unit) {
|
||||||
|
val report by rememberUpdatedState(onOverflow)
|
||||||
|
Layout(content, Modifier.clipToBounds()) { measurables, constraints ->
|
||||||
|
val placeable = measurables.first().measure(constraints.copy(maxHeight = Constraints.Infinity))
|
||||||
|
val limit = height.roundToPx()
|
||||||
|
report(placeable.height > limit)
|
||||||
|
val shown = if (open) placeable.height else minOf(placeable.height, limit)
|
||||||
|
layout(placeable.width, shown) { placeable.place(0, 0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val FOLDED_HEIGHT = 128.dp
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.text.format.DateUtils
|
||||||
|
import android.text.format.Formatter
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
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.TransferRow
|
||||||
|
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
|
||||||
|
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/** A channel's file repository: folders to walk, files to download, upload, rename and delete. */
|
||||||
|
@Composable
|
||||||
|
fun FilesScreen(server: ServerController, channelId: Int, channelName: String, password: String, onBack: () -> Unit) {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val snackbar = remember { SnackbarHostState() }
|
||||||
|
var path by rememberSaveable { mutableStateOf("/") }
|
||||||
|
var files by remember { mutableStateOf<List<RemoteFile>?>(null) }
|
||||||
|
var failure by remember { mutableStateOf<String?>(null) }
|
||||||
|
var reloads by remember { mutableIntStateOf(0) }
|
||||||
|
val transfers by server.files.rows.collectAsStateWithLifecycle()
|
||||||
|
var downloading by remember { mutableStateOf<RemoteFile?>(null) }
|
||||||
|
var creatingFolder by remember { mutableStateOf(false) }
|
||||||
|
var renaming by remember { mutableStateOf<RemoteFile?>(null) }
|
||||||
|
var deleting by remember { mutableStateOf<RemoteFile?>(null) }
|
||||||
|
|
||||||
|
LaunchedEffect(path, reloads) {
|
||||||
|
failure = null
|
||||||
|
server.listFiles(channelId, password, path)
|
||||||
|
.onSuccess { list -> files = list.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) }
|
||||||
|
.onFailure { files = emptyList(); failure = it.message ?: "Could not list the files" }
|
||||||
|
}
|
||||||
|
// An upload into the folder on screen shows up once it is there.
|
||||||
|
val uploadedHere = transfers.count { it.upload && it.channelId == channelId && it.directory == path && it.state == FileTransfer.State.COMPLETED }
|
||||||
|
LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ }
|
||||||
|
|
||||||
|
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
|
||||||
|
val act = { call: suspend () -> String? ->
|
||||||
|
scope.launch {
|
||||||
|
val error = call()
|
||||||
|
if (error != null) snackbar.showSnackbar(error) else reloads++
|
||||||
|
}
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
|
||||||
|
val file = downloading
|
||||||
|
downloading = null
|
||||||
|
if (uri != null && file != null) server.files.download(channelId, password, file, uri)
|
||||||
|
}
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri != null) scope.launch {
|
||||||
|
runCatching { server.files.upload(channelId, password, path, uri) }
|
||||||
|
.onFailure { tell("Could not read the file: ${it.message}") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen(channelName, onBack = { if (path == "/") onBack() else path = parentOf(path) }, snackbar = snackbar, actions = {
|
||||||
|
IconButton(onClick = { creatingFolder = true }) { PackIcon("ADD_FOLDER", "New folder") }
|
||||||
|
IconButton(onClick = { picker.launch(arrayOf("*/*")) }) { PackIcon("UPLOAD", "Upload") }
|
||||||
|
IconButton(onClick = { reloads++ }) { PackIcon(listOf("FILE_REFRESH", "REFRESH"), "Refresh") }
|
||||||
|
}) { padding ->
|
||||||
|
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
IconButton(onClick = { path = parentOf(path) }, enabled = path != "/") { PackIcon("FILE_UP", "Up") }
|
||||||
|
Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||||
|
val list = files
|
||||||
|
when {
|
||||||
|
list == null -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||||
|
list.isEmpty() -> Text(failure ?: "No files", Modifier.align(Alignment.Center).padding(24.dp),
|
||||||
|
color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
else -> LazyColumn {
|
||||||
|
items(list, key = { it.fullPath }) { file ->
|
||||||
|
FileRow(file,
|
||||||
|
onOpen = {
|
||||||
|
if (file.isDirectory) path = file.fullPath + "/"
|
||||||
|
else { downloading = file; saver.launch(file.name) }
|
||||||
|
},
|
||||||
|
onRename = { renaming = file },
|
||||||
|
onDelete = { deleting = file })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (transfers.isNotEmpty()) Transfers(transfers, server.files::cancel, server.files::clearFinished)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (creatingFolder) {
|
||||||
|
TextPrompt("New folder", "Name", "Create", onDismiss = { creatingFolder = false }, onConfirm = { name ->
|
||||||
|
creatingFolder = false
|
||||||
|
if (name.isNotBlank()) act { server.createDirectory(channelId, password, path + name.trim()) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
renaming?.let { file ->
|
||||||
|
TextPrompt("Rename", "Name", "Rename", initial = file.name, onDismiss = { renaming = null }, onConfirm = { name ->
|
||||||
|
renaming = null
|
||||||
|
if (name.isNotBlank() && name != file.name) {
|
||||||
|
act { server.renameFile(channelId, password, file.fullPath, file.parentPath + name.trim()) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
deleting?.let { file ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { deleting = null },
|
||||||
|
title = { Text("Delete ${file.name}?") },
|
||||||
|
text = if (file.isDirectory) ({ Text("Everything in the folder goes with it.") }) else null,
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
deleting = null
|
||||||
|
act { server.deleteFile(channelId, password, file.fullPath) }
|
||||||
|
}) { Text("Delete") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parentOf(path: String): String {
|
||||||
|
val trimmed = path.removeSuffix("/")
|
||||||
|
val slash = trimmed.lastIndexOf('/')
|
||||||
|
return if (slash <= 0) "/" else trimmed.substring(0, slash + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun FileRow(file: RemoteFile, onOpen: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
val modified = if (file.lastModifiedEpochSec > 0) {
|
||||||
|
DateUtils.formatDateTime(context, file.lastModifiedEpochSec * 1000,
|
||||||
|
DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH)
|
||||||
|
} else null
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(file.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
supportingContent = {
|
||||||
|
Text(listOfNotNull(if (file.isDirectory) null else Formatter.formatShortFileSize(context, file.size), modified)
|
||||||
|
.joinToString(" · "))
|
||||||
|
},
|
||||||
|
leadingContent = { PackIcon(if (file.isDirectory) listOf("FOLDER") else listOf("FILE", "FILETRANSFER"), null) },
|
||||||
|
trailingContent = {
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "File options") }
|
||||||
|
DropdownMenu(menu, { menu = false }) {
|
||||||
|
if (!file.isDirectory) DropdownMenuItem({ Text("Download") }, onClick = { menu = false; onOpen() })
|
||||||
|
DropdownMenuItem({ Text("Rename") }, onClick = { menu = false; onRename() })
|
||||||
|
DropdownMenuItem({ Text("Delete") }, onClick = { menu = false; onDelete() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.clickable(onClick = onOpen),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The transfers under way and done, newest last. */
|
||||||
|
@Composable
|
||||||
|
private fun Transfers(rows: List<TransferRow>, onCancel: (Long) -> Unit, onClear: () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
Surface(tonalElevation = 3.dp) {
|
||||||
|
Column(Modifier.fillMaxWidth().heightIn(max = 220.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Transfers", Modifier.weight(1f), style = MaterialTheme.typography.titleSmall)
|
||||||
|
if (rows.any { it.done }) TextButton(onClick = onClear) { Text("Clear finished") }
|
||||||
|
}
|
||||||
|
LazyColumn {
|
||||||
|
items(rows, key = { it.id }) { row ->
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, bottom = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
PackIcon(if (row.upload) "UPLOAD" else "DOWNLOAD", null)
|
||||||
|
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
|
||||||
|
Text(row.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
when (row.state) {
|
||||||
|
FileTransfer.State.PENDING, FileTransfer.State.ACTIVE ->
|
||||||
|
LinearProgressIndicator({ row.progress }, Modifier.fillMaxWidth().padding(vertical = 4.dp))
|
||||||
|
else -> Text(status(row, context), style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (row.state == FileTransfer.State.FAILED) MaterialTheme.colorScheme.error
|
||||||
|
else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!row.done) IconButton(onClick = { onCancel(row.id) }) { Icon(Icons.Default.Close, "Cancel") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun status(row: TransferRow, context: android.content.Context): String = when (row.state) {
|
||||||
|
FileTransfer.State.COMPLETED -> (if (row.upload) "Uploaded" else "Downloaded") + " · " +
|
||||||
|
Formatter.formatShortFileSize(context, row.total)
|
||||||
|
FileTransfer.State.CANCELLED -> "Cancelled"
|
||||||
|
else -> row.error ?: "Failed"
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.text.KeyboardActions
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.Checkbox
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextField
|
||||||
|
import androidx.compose.material3.TextFieldDefaults
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.listSaver
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.input.key.Key
|
||||||
|
import androidx.compose.ui.input.key.KeyEventType
|
||||||
|
import androidx.compose.ui.input.key.isShiftPressed
|
||||||
|
import androidx.compose.ui.input.key.key
|
||||||
|
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||||
|
import androidx.compose.ui.input.key.type
|
||||||
|
import androidx.compose.ui.text.TextRange
|
||||||
|
import androidx.compose.ui.text.input.ImeAction
|
||||||
|
import androidx.compose.ui.text.input.TextFieldValue
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.gfx.IconKeys
|
||||||
|
import eu.lixko.ts3j.client.net.ClientStatus
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
|
||||||
|
/** What the find bar holds: the text, how to match it, and whether it is [open]. */
|
||||||
|
@Stable
|
||||||
|
class FindState(text: String = "", flags: Int = 0) {
|
||||||
|
var open by mutableStateOf(false)
|
||||||
|
var input by mutableStateOf(TextFieldValue(text))
|
||||||
|
var matchCase by mutableStateOf(flags and 1 != 0)
|
||||||
|
var wholeWord by mutableStateOf(flags and 2 != 0)
|
||||||
|
var regex by mutableStateOf(flags and 4 != 0)
|
||||||
|
/** Counts the times it was asked to show, for the field to take the focus each time. */
|
||||||
|
var shown by mutableStateOf(0)
|
||||||
|
private set
|
||||||
|
/** Show only what matches. */
|
||||||
|
var filter by mutableStateOf(flags and 8 != 0)
|
||||||
|
/** In the tree, find channels rather than clients. */
|
||||||
|
var channels by mutableStateOf(flags and 16 != 0)
|
||||||
|
|
||||||
|
/** What is typed, as it is to be matched; empty while the bar is closed. */
|
||||||
|
val query: TextQuery
|
||||||
|
get() = if (open) TextQuery(input.text, matchCase, wholeWord, regex) else TextQuery.EMPTY
|
||||||
|
|
||||||
|
/** [query], but nothing when it is not a valid regular expression. */
|
||||||
|
val usable: TextQuery
|
||||||
|
get() = query.let { if (it.isInvalid) TextQuery.EMPTY else it }
|
||||||
|
|
||||||
|
/** Opens the bar with what it holds selected, to be typed over. */
|
||||||
|
fun show() {
|
||||||
|
input = input.copy(selection = TextRange(0, input.text.length))
|
||||||
|
open = true
|
||||||
|
shown++
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val Saver = listSaver<FindState, Any>(
|
||||||
|
save = {
|
||||||
|
val flags = (if (it.matchCase) 1 else 0) or (if (it.wholeWord) 2 else 0) or (if (it.regex) 4 else 0) or
|
||||||
|
(if (it.filter) 8 else 0) or (if (it.channels) 16 else 0)
|
||||||
|
listOf(it.input.text, flags, it.open)
|
||||||
|
},
|
||||||
|
restore = { FindState(it[0] as String, it[1] as Int).apply { open = it[2] as Boolean } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The find bar, in the place of the top bar: the field, where the view is among the matches,
|
||||||
|
* previous/next, and the options. Enter goes to the next match, Shift+Enter to the previous.
|
||||||
|
*
|
||||||
|
* @param inTree whether it finds in the tree, which offers finding channels instead of clients
|
||||||
|
* @param position the 1-based match the view is on, or 0 for none
|
||||||
|
* @param more whether there are more matches than [total]
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun FindBar(state: FindState, inTree: Boolean, position: Int, total: Int, more: Boolean, onStep: (Int) -> Unit) {
|
||||||
|
val focus = remember { FocusRequester() }
|
||||||
|
LaunchedEffect(state.shown) { focus.requestFocus() }
|
||||||
|
val query = state.query
|
||||||
|
TopAppBar(
|
||||||
|
expandedHeight = 48.dp,
|
||||||
|
navigationIcon = { IconButton(onClick = { state.open = false }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Close") } },
|
||||||
|
title = {
|
||||||
|
TextField(
|
||||||
|
state.input, { state.input = it },
|
||||||
|
Modifier.focusRequester(focus).onPreviewKeyEvent { e ->
|
||||||
|
when {
|
||||||
|
e.key == Key.Enter -> {
|
||||||
|
if (e.type == KeyEventType.KeyDown) onStep(if (e.isShiftPressed) -1 else 1)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
e.key == Key.Escape && e.type == KeyEventType.KeyDown -> {
|
||||||
|
state.open = false
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
placeholder = {
|
||||||
|
Text(if (!inTree) "Find" else if (state.channels) "Find channels" else "Find clients", maxLines = 1)
|
||||||
|
},
|
||||||
|
leadingIcon = if (inTree) ({
|
||||||
|
IconButton(onClick = { state.channels = !state.channels }) {
|
||||||
|
if (state.channels) PackIcon(IconKeys.channel(false, false, true).asList(), "Finding channels", size = 18.dp)
|
||||||
|
else PackIcon(IconKeys.client(ClientStatus.IDLE), "Finding clients", size = 18.dp)
|
||||||
|
}
|
||||||
|
}) else null,
|
||||||
|
trailingIcon = if (state.input.text.isNotEmpty()) ({
|
||||||
|
IconButton(onClick = { state.input = TextFieldValue() }) { Icon(Icons.Filled.Close, "Clear", Modifier.size(18.dp)) }
|
||||||
|
}) else null,
|
||||||
|
isError = query.isInvalid,
|
||||||
|
singleLine = true,
|
||||||
|
textStyle = MaterialTheme.typography.bodyLarge,
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||||
|
keyboardActions = KeyboardActions(onSearch = { onStep(1) }),
|
||||||
|
colors = TextFieldDefaults.colors(
|
||||||
|
focusedContainerColor = Color.Transparent,
|
||||||
|
unfocusedContainerColor = Color.Transparent,
|
||||||
|
errorContainerColor = Color.Transparent,
|
||||||
|
focusedIndicatorColor = Color.Transparent,
|
||||||
|
unfocusedIndicatorColor = Color.Transparent,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
actions = {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
if (!query.isEmpty) {
|
||||||
|
Text(
|
||||||
|
if (query.isInvalid) "!" else "${if (position > 0) "$position/" else ""}$total${if (more) "+" else ""}",
|
||||||
|
Modifier.padding(horizontal = 4.dp),
|
||||||
|
color = if (query.isInvalid || total == 0) MaterialTheme.colorScheme.error
|
||||||
|
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val navigable = total > 1 || (total == 1 && position == 0)
|
||||||
|
IconButton(onClick = { onStep(-1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowUp, "Previous") }
|
||||||
|
IconButton(onClick = { onStep(1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowDown, "Next") }
|
||||||
|
FindOptions(state)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun FindOptions(state: FindState) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
IconButton(onClick = { open = true }) { Icon(Icons.Filled.MoreVert, "Options") }
|
||||||
|
DropdownMenu(open, onDismissRequest = { open = false }) {
|
||||||
|
@Composable
|
||||||
|
fun option(label: String, checked: Boolean, set: (Boolean) -> Unit) = DropdownMenuItem(
|
||||||
|
text = { Text(label) },
|
||||||
|
onClick = { set(!checked) },
|
||||||
|
leadingIcon = { Checkbox(checked, set) },
|
||||||
|
)
|
||||||
|
option("Only matches", state.filter) { state.filter = it }
|
||||||
|
option("Match case", state.matchCase) { state.matchCase = it }
|
||||||
|
option("Whole words", state.wholeWord) { state.wholeWord = it }
|
||||||
|
option("Regular expression", state.regex) { state.regex = it }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.produceState
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.Picture
|
||||||
|
import eu.lixko.ts3j.client.android.WebPictures
|
||||||
|
import eu.lixko.ts3j.client.net.HostButton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The server's host button in the top bar: its own picture fitted to the bar's icons, or
|
||||||
|
* the pack's host button icon while there is none (yet).
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun HostButtonAction(button: HostButton, onOpen: (String) -> Unit) {
|
||||||
|
val label = button.tooltip.ifEmpty { button.url }.ifEmpty { null }
|
||||||
|
val picture = hostPicture(button.gfxUrl)
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.fillMaxHeight()
|
||||||
|
.clickable(enabled = button.url.isNotEmpty()) { onOpen(button.url) }
|
||||||
|
.padding(horizontal = 12.dp),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
if (picture == null) {
|
||||||
|
PackIcon("HOSTER_BUTTON", label)
|
||||||
|
} else {
|
||||||
|
Image(
|
||||||
|
rememberPicturePainter(picture),
|
||||||
|
label,
|
||||||
|
Modifier
|
||||||
|
.widthIn(max = 24.dp * MAX_ASPECT)
|
||||||
|
.height(24.dp)
|
||||||
|
.aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun hostPicture(url: String): Picture? {
|
||||||
|
val pictures = LocalWebPictures.current
|
||||||
|
if (pictures == null || url.isEmpty()) return null
|
||||||
|
val version by pictures.version.collectAsStateWithLifecycle()
|
||||||
|
val state by produceState<WebPictures.State>(WebPictures.State.Loading, url, version) {
|
||||||
|
value = pictures.state(url)
|
||||||
|
}
|
||||||
|
return (state as? WebPictures.State.Shown)?.picture
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keeps a banner-shaped picture from crowding out the server's name. */
|
||||||
|
private const val MAX_ASPECT = 6
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.IdentityInfo
|
||||||
|
import eu.lixko.ts3j.client.android.IdentityManager
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/** Beyond this a search takes years; TeamSpeak's own dialog stops there too. */
|
||||||
|
private const val MAX_SECURITY_LEVEL = 40
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The identities a server knows this client by, as TeamSpeak's Tools → Identities
|
||||||
|
* manages them, with each identity's own page.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun IdentitiesScreen(manager: IdentityManager, onBack: () -> Unit) {
|
||||||
|
var editing by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
editing?.let { id -> return IdentityScreen(manager, id, onBack = { editing = null }) }
|
||||||
|
|
||||||
|
val identities by manager.all.collectAsStateWithLifecycle()
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
var creating by remember { mutableStateOf(false) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var message by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
fun work(failure: String, block: suspend () -> String?) {
|
||||||
|
busy = true
|
||||||
|
scope.launch {
|
||||||
|
message = try {
|
||||||
|
block()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"$failure: ${e.message ?: e}"
|
||||||
|
}
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val fileImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri != null) work("That file is not a TeamSpeak identity") {
|
||||||
|
editing = manager.importFile(uri).id
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val dbImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri != null) work("That file is not a TeamSpeak 3 settings.db") {
|
||||||
|
val r = manager.importFromTeamSpeak(uri)
|
||||||
|
if (r.identities() == 0) "That file holds no identities."
|
||||||
|
else "Imported ${r.identitiesAdded()} of ${r.identities()} identities."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen("Identities", onBack, actions = {
|
||||||
|
IconButton(onClick = { creating = true }, enabled = !busy) { PackIcon("IDENTITY_ADD", "New identity") }
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
|
||||||
|
DropdownMenu(menu, { menu = false }) {
|
||||||
|
DropdownMenuItem({ Text("Import identity file") }, onClick = {
|
||||||
|
menu = false
|
||||||
|
fileImporter.launch(arrayOf("*/*"))
|
||||||
|
})
|
||||||
|
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
|
||||||
|
menu = false
|
||||||
|
dbImporter.launch(arrayOf("*/*"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) { padding ->
|
||||||
|
LazyColumn(Modifier.padding(padding)) {
|
||||||
|
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
|
||||||
|
message?.let { item { Hint(it) } }
|
||||||
|
if (identities.isEmpty()) {
|
||||||
|
item {
|
||||||
|
Hint("No identities. One is created on the first connect.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items(identities, key = { it.id }) { identity ->
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(identity.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
supportingContent = {
|
||||||
|
Text("Security level ${identity.securityLevel}", maxLines = 1)
|
||||||
|
},
|
||||||
|
trailingContent = if (identity.isDefault) ({ PackIcon("IDENTITY_DEFAULT", "Default") }) else null,
|
||||||
|
modifier = Modifier.clickable { editing = identity.id },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (creating) {
|
||||||
|
NewIdentityDialog(onDismiss = { creating = false }) { name ->
|
||||||
|
creating = false
|
||||||
|
work("Could not create the identity") {
|
||||||
|
editing = manager.generate(name).id
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One identity: its name, whether it is the default, its security level and unique ID. */
|
||||||
|
@Composable
|
||||||
|
private fun IdentityScreen(manager: IdentityManager, id: String, onBack: () -> Unit) {
|
||||||
|
val identities by manager.all.collectAsStateWithLifecycle()
|
||||||
|
val improving by manager.improving.collectAsStateWithLifecycle()
|
||||||
|
val identity = identities.firstOrNull { it.id == id }
|
||||||
|
if (identity == null) {
|
||||||
|
LaunchedEffect(Unit) { onBack() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var name by rememberSaveable(id) { mutableStateOf(identity.name) }
|
||||||
|
var nickname by rememberSaveable(id) { mutableStateOf(identity.nickname) }
|
||||||
|
var phonetic by rememberSaveable(id) { mutableStateOf(identity.phoneticNickname) }
|
||||||
|
var removing by remember { mutableStateOf(false) }
|
||||||
|
var raising by remember { mutableStateOf(false) }
|
||||||
|
var message by remember { mutableStateOf<String?>(null) }
|
||||||
|
val leave = {
|
||||||
|
val trimmed = name.trim()
|
||||||
|
if (trimmed.isNotEmpty() && trimmed != identity.name) manager.rename(id, trimmed)
|
||||||
|
if (nickname.trim() != identity.nickname || phonetic.trim() != identity.phoneticNickname) {
|
||||||
|
manager.setNicknames(id, nickname.trim(), phonetic.trim())
|
||||||
|
}
|
||||||
|
onBack()
|
||||||
|
}
|
||||||
|
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
|
||||||
|
if (uri != null) scope.launch {
|
||||||
|
message = runCatching { manager.export(id, uri) }.fold(
|
||||||
|
{ "Exported." },
|
||||||
|
{ "Could not export: ${it.message ?: it}" },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val mine = improving?.takeIf { it.id == id }
|
||||||
|
|
||||||
|
SubScreen(identity.name, leave, actions = {
|
||||||
|
IconButton(onClick = { exporter.launch(fileName(name.ifBlank { identity.name })) }) {
|
||||||
|
PackIcon("IDENTITY_EXPORT", "Export")
|
||||||
|
}
|
||||||
|
IconButton(onClick = { removing = true }) { PackIcon("DELETE", "Remove") }
|
||||||
|
}) { padding ->
|
||||||
|
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
|
||||||
|
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||||
|
label = { Text("Name") }, singleLine = true, isError = name.isBlank())
|
||||||
|
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp),
|
||||||
|
label = { Text("Nickname") }, placeholder = { Text("Global nickname") }, singleLine = true)
|
||||||
|
OutlinedTextField(phonetic, { phonetic = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
label = { Text("Phonetic nickname") }, singleLine = true)
|
||||||
|
message?.let { Hint(it) }
|
||||||
|
|
||||||
|
Section("Use")
|
||||||
|
if (identity.isDefault) {
|
||||||
|
Hint("Default identity")
|
||||||
|
} else {
|
||||||
|
LinkRow("Make default", null, "IDENTITY_DEFAULT") {
|
||||||
|
manager.setDefault(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Security level")
|
||||||
|
if (mine != null) {
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text("Improving to ${mine.target}: reached ${mine.reached}") },
|
||||||
|
supportingContent = { LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) },
|
||||||
|
trailingContent = { TextButton(onClick = manager::stopImproving) { Text("Stop") } },
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
LinkRow("Level ${identity.securityLevel}",
|
||||||
|
if (improving != null) "Another identity is being improved" else "Improve",
|
||||||
|
"SECURITY") { if (improving == null) raising = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Details")
|
||||||
|
val context = LocalContext.current
|
||||||
|
LinkRow("Unique ID", identity.uniqueId) {
|
||||||
|
// The system confirms the copy itself.
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText("Unique ID", identity.uniqueId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raising) {
|
||||||
|
LevelDialog(identity, onDismiss = { raising = false }) { target ->
|
||||||
|
raising = false
|
||||||
|
manager.improve(id, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (removing) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { removing = false },
|
||||||
|
title = { Text("Remove ${identity.name}?") },
|
||||||
|
text = {
|
||||||
|
Text("Server groups and permissions tied to it are lost. Export it first to keep it.")
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
removing = false
|
||||||
|
manager.remove(id)
|
||||||
|
}) { Text("Remove") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun NewIdentityDialog(onDismiss: () -> Unit, onConfirm: (String) -> Unit) {
|
||||||
|
var name by remember { mutableStateOf("") }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("New identity") },
|
||||||
|
text = {
|
||||||
|
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true)
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(onClick = { onConfirm(name.trim()) }, enabled = name.isNotBlank()) { Text("Create") } },
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LevelDialog(identity: IdentityInfo, onDismiss: () -> Unit, onConfirm: (Int) -> Unit) {
|
||||||
|
var text by remember { mutableStateOf((identity.securityLevel + 1).toString()) }
|
||||||
|
val level = text.trim().toIntOrNull()?.takeIf { it in identity.securityLevel + 1..MAX_SECURITY_LEVEL }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("Improve security level") },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
Text("Current level: ${identity.securityLevel}", style = MaterialTheme.typography.bodyMedium)
|
||||||
|
OutlinedTextField(text, { text = it }, Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||||
|
label = { Text("Target level") }, singleLine = true, isError = level == null,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(onClick = { level?.let(onConfirm) }, enabled = level != null) { Text("Start") } },
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fileName(name: String) = name.replace(Regex("[^\\w.-]+"), "_") + ".ini"
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
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.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Checkbox
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.RadioButton
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ClientItem
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.net.GroupChoice
|
||||||
|
import eu.lixko.ts3j.client.net.TeamspeakConnection
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanRule
|
||||||
|
import eu.lixko.ts3j.client.net.ban.BanUnit
|
||||||
|
|
||||||
|
/** Asks to confirm a kick, with an optional reason. */
|
||||||
|
@Composable
|
||||||
|
fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) {
|
||||||
|
var reason by remember { mutableStateOf("") }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(title) },
|
||||||
|
text = { LimitedField(reason, { reason = it }, "Reason", TeamspeakConnection.KICK_REASON_LIMIT) },
|
||||||
|
confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } },
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Asks for a ban's reason and length. */
|
||||||
|
@Composable
|
||||||
|
fun BanPrompt(name: String, maxSeconds: Long, onDismiss: () -> Unit, onBan: (seconds: Long, reason: String) -> Unit) {
|
||||||
|
var reason by remember { mutableStateOf("") }
|
||||||
|
val duration = remember { BanDurationState(DEFAULT_BAN_SECONDS) }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("Ban $name") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
LimitedField(reason, { reason = it }, "Reason", BanRule.REASON_LIMIT)
|
||||||
|
BanDurationField(duration, maxSeconds)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = { onBan(duration.seconds, reason.trim()) }, enabled = duration.valid) { Text("Ban") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Thirty minutes, as the official client starts its ban dialog. */
|
||||||
|
internal const val DEFAULT_BAN_SECONDS = 30 * 60L
|
||||||
|
|
||||||
|
/** A one-line field that takes no more than [limit] characters, counting them as they come. */
|
||||||
|
@Composable
|
||||||
|
internal fun LimitedField(value: String, onChange: (String) -> Unit, label: String, limit: Int, modifier: Modifier = Modifier) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value, { onChange(it.take(limit)) },
|
||||||
|
modifier.fillMaxWidth(),
|
||||||
|
label = { Text(label) },
|
||||||
|
singleLine = true,
|
||||||
|
supportingText = { Text("${value.length}/$limit", Modifier.fillMaxWidth(), textAlign = TextAlign.End) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A ban's length as typed: an amount of a [BanUnit]. */
|
||||||
|
internal class BanDurationState(seconds: Long) {
|
||||||
|
var unit by mutableStateOf(BanUnit.largestFor(seconds))
|
||||||
|
var amount by mutableStateOf(BanUnit.largestFor(seconds).amountOf(seconds).takeIf { it > 0 }?.toString() ?: "30")
|
||||||
|
|
||||||
|
val valid: Boolean get() = unit == BanUnit.PERMANENT || (amount.toLongOrNull() ?: 0) > 0
|
||||||
|
|
||||||
|
/** The length in seconds; 0 for permanent. */
|
||||||
|
val seconds: Long get() = unit.toSeconds(amount.toLongOrNull() ?: 0)
|
||||||
|
|
||||||
|
fun set(seconds: Long) {
|
||||||
|
unit = BanUnit.largestFor(seconds)
|
||||||
|
if (unit != BanUnit.PERMANENT) amount = unit.amountOf(seconds).toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The amount, its unit, and a jump to the longest ban the server lets us hand out. */
|
||||||
|
@Composable
|
||||||
|
internal fun BanDurationField(state: BanDurationState, maxSeconds: Long, modifier: Modifier = Modifier) {
|
||||||
|
var units by remember { mutableStateOf(false) }
|
||||||
|
Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
if (state.unit == BanUnit.PERMANENT) "" else state.amount,
|
||||||
|
{ text -> state.amount = text.filter(Char::isDigit).take(9) },
|
||||||
|
Modifier.width(120.dp),
|
||||||
|
enabled = state.unit != BanUnit.PERMANENT,
|
||||||
|
label = { Text("Duration") },
|
||||||
|
singleLine = true,
|
||||||
|
isError = !state.valid,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
|
)
|
||||||
|
Box(Modifier.weight(1f)) {
|
||||||
|
OutlinedButton(onClick = { units = true }, Modifier.fillMaxWidth()) { Text(state.unit.label()) }
|
||||||
|
DropdownMenu(units, { units = false }) {
|
||||||
|
for (unit in BanUnit.entries) {
|
||||||
|
DropdownMenuItem({ Text(unit.label()) }, onClick = { units = false; state.unit = unit })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (maxSeconds != 0L) TextButton(onClick = { state.set(maxSeconds) }) { Text("Max") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A client's groups to tick: several server groups, or with [single] the one channel group.
|
||||||
|
* Groups we may not assign are listed only when the client is in them, greyed out; a change shows once the server
|
||||||
|
* made it.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun GroupsDialog(
|
||||||
|
title: String,
|
||||||
|
choices: List<GroupChoice>,
|
||||||
|
single: Boolean,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onChange: (groupId: Int, assign: Boolean) -> Unit,
|
||||||
|
) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(title) },
|
||||||
|
text = {
|
||||||
|
CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides Dp.Unspecified) {
|
||||||
|
LazyColumn {
|
||||||
|
items(choices.filter { it.allowed() || it.assigned() }, key = { it.group().id }) { choice ->
|
||||||
|
val group = choice.group()
|
||||||
|
// A client always has one channel group: picking another is the only change.
|
||||||
|
val changeable = choice.allowed() && !(single && choice.assigned())
|
||||||
|
val toggle = { if (changeable) onChange(group.id, !choice.assigned()) }
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth()
|
||||||
|
.clickable(enabled = changeable, onClick = toggle)
|
||||||
|
.alpha(if (choice.allowed()) 1f else 0.38f)
|
||||||
|
.padding(vertical = 6.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
if (single) {
|
||||||
|
RadioButton(choice.assigned(), onClick = toggle, enabled = choice.allowed())
|
||||||
|
} else {
|
||||||
|
Checkbox(choice.assigned(), onCheckedChange = { toggle() }, enabled = choice.allowed())
|
||||||
|
}
|
||||||
|
Box(Modifier.width(24.dp), contentAlignment = Alignment.Center) {
|
||||||
|
if (group.iconId != 0L) ServerIcon(group.iconId)
|
||||||
|
}
|
||||||
|
Text(group.name, Modifier.padding(start = 8.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out. */
|
||||||
|
@Composable
|
||||||
|
fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit) {
|
||||||
|
var kick by remember { mutableStateOf<Boolean?>(null) }
|
||||||
|
var banning by remember { mutableStateOf(false) }
|
||||||
|
var groups by remember { mutableStateOf<Boolean?>(null) }
|
||||||
|
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
|
||||||
|
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
|
||||||
|
|
||||||
|
if (!client.self) {
|
||||||
|
if (server.canKickFromChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false }
|
||||||
|
if (server.canKickFromServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true }
|
||||||
|
if (server.canBanClients) Action("BAN_CLIENT", "Ban") { banning = true }
|
||||||
|
}
|
||||||
|
val showServerGroups = serverGroups.any { it.allowed() }
|
||||||
|
val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() }
|
||||||
|
if (showServerGroups || showChannelGroups) {
|
||||||
|
Row {
|
||||||
|
if (showServerGroups) Action("PERMISSIONS_SERVER_GROUPS", "Server groups", Modifier.weight(1f)) { groups = true }
|
||||||
|
if (showChannelGroups) Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group", Modifier.weight(1f)) { groups = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
kick?.let { fromServer ->
|
||||||
|
KickPrompt(
|
||||||
|
if (fromServer) "Kick ${client.name} from the server?" else "Kick ${client.name} from the channel?",
|
||||||
|
onDismiss = { kick = null },
|
||||||
|
) { reason ->
|
||||||
|
kick = null
|
||||||
|
if (fromServer) server.kickFromServer(client.id, reason) else server.kickFromChannel(client.id, reason)
|
||||||
|
onDone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (banning) {
|
||||||
|
BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason ->
|
||||||
|
banning = false
|
||||||
|
server.ban(client.id, seconds, reason)
|
||||||
|
onDone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groups?.let { ofServer ->
|
||||||
|
GroupsDialog(
|
||||||
|
if (ofServer) "Server groups" else "Channel group",
|
||||||
|
if (ofServer) serverGroups else channelGroups,
|
||||||
|
single = !ofServer,
|
||||||
|
onDismiss = { groups = null },
|
||||||
|
) { groupId, assign ->
|
||||||
|
if (ofServer) server.setServerGroup(client.id, groupId, assign) else server.setChannelGroup(client.id, groupId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Checkbox
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
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.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 kotlinx.coroutines.launch
|
||||||
|
import java.io.IOException
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
|
||||||
|
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The myTeamSpeak account: sign in and out, and pick what the account synchronises to
|
||||||
|
* import. Signing in lasts until signing out; the password itself is not kept.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
|
||||||
|
val login = vm.myTeamSpeak
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var signedIn by remember { mutableStateOf(login.isSignedIn) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
var message by remember { mutableStateOf<String?>(null) }
|
||||||
|
var error by remember { mutableStateOf(false) }
|
||||||
|
var email by remember { mutableStateOf("") }
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
var info by remember { mutableStateOf<AccountInfo?>(null) }
|
||||||
|
var all by remember { mutableStateOf(emptyList<SyncItem>()) }
|
||||||
|
var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
|
||||||
|
BackHandler(onBack = onBack)
|
||||||
|
|
||||||
|
fun show(account: MyTeamSpeak.Account) {
|
||||||
|
info = account.info()
|
||||||
|
all = account.items()
|
||||||
|
rows = all.filter { it !is SyncItem.Folder }.map {
|
||||||
|
val imported = vm.isImported(it)
|
||||||
|
ItemRow(it, imported, !imported)
|
||||||
|
}
|
||||||
|
message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null
|
||||||
|
error = false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun work(block: suspend () -> Unit) {
|
||||||
|
busy = true
|
||||||
|
message = null
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
} catch (e: MyTsException) {
|
||||||
|
message = e.message
|
||||||
|
error = true
|
||||||
|
} catch (e: IOException) {
|
||||||
|
message = "Could not reach myTeamSpeak: ${e.message}"
|
||||||
|
error = true
|
||||||
|
}
|
||||||
|
// A sign-in the server no longer takes has signed out.
|
||||||
|
signedIn = login.isSignedIn
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
if (signedIn) work { show(vm.fetchMyTeamSpeak()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text("myTeamSpeak") },
|
||||||
|
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
|
||||||
|
actions = {
|
||||||
|
if (signedIn) {
|
||||||
|
IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) {
|
||||||
|
PackIcon("REFRESH", "Refresh")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
) { padding ->
|
||||||
|
LazyColumn(
|
||||||
|
Modifier.padding(padding).imePadding(),
|
||||||
|
contentPadding = PaddingValues(vertical = 8.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
|
||||||
|
if (!signedIn) {
|
||||||
|
item {
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text("Sign in to bring over the bookmarks and identities your account synchronises. " +
|
||||||
|
"The app stays signed in; your password itself is not kept.")
|
||||||
|
OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") },
|
||||||
|
singleLine = true, enabled = !busy,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email))
|
||||||
|
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), label = { Text("Password") },
|
||||||
|
singleLine = true, enabled = !busy, visualTransformation = PasswordVisualTransformation(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
work {
|
||||||
|
show(vm.signInMyTeamSpeak(email.trim(), password))
|
||||||
|
password = ""
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = !busy && email.isNotBlank() && password.isNotEmpty(),
|
||||||
|
) { Text("Sign in") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
item {
|
||||||
|
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text("Signed in as ${login.username()}", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(login.email(), style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
OutlinedButton(onClick = {
|
||||||
|
scope.launch { vm.signOutMyTeamSpeak() }
|
||||||
|
signedIn = false
|
||||||
|
rows = emptyList()
|
||||||
|
all = emptyList()
|
||||||
|
info = null
|
||||||
|
message = null
|
||||||
|
}) { Text("Sign out") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
info?.let { details ->
|
||||||
|
item {
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp)) {
|
||||||
|
if (details.userId().isNotEmpty()) Detail("ID", details.userId())
|
||||||
|
if (details.uuid().isNotEmpty()) Detail("UUID", details.uuid())
|
||||||
|
details.created()?.let { Detail("Created", dateFormat.format(it)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rows.isNotEmpty()) {
|
||||||
|
item {
|
||||||
|
Text("Synchronised by the account", Modifier.padding(start = 16.dp, top = 16.dp),
|
||||||
|
style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ((title, section) in listOf(
|
||||||
|
"Identities" to rows.filter { it.item is SyncItem.Identity },
|
||||||
|
"Bookmarks" to rows.filter { it.item is SyncItem.Bookmark },
|
||||||
|
)) {
|
||||||
|
if (section.isEmpty()) continue
|
||||||
|
item {
|
||||||
|
val select = section.any { !it.selected }
|
||||||
|
Row(Modifier.padding(start = 16.dp, top = 8.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(title, Modifier.weight(1f),
|
||||||
|
style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
TextButton(onClick = {
|
||||||
|
rows = rows.map { if (it in section) it.copy(selected = select) else it }
|
||||||
|
}) { Text(if (select) "Select all" else "Deselect all") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items(section, key = { it.item.uuid() }) { row ->
|
||||||
|
val toggle = { rows = rows.map { if (it === row) it.copy(selected = !it.selected) else it } }
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(name(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
supportingContent = { Text(details(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
leadingContent = { Checkbox(row.selected, { toggle() }) },
|
||||||
|
trailingContent = if (row.imported) ({ Text("Imported", style = MaterialTheme.typography.labelMedium) }) else null,
|
||||||
|
modifier = Modifier.clickable(onClick = toggle),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rows.isNotEmpty()) {
|
||||||
|
item {
|
||||||
|
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) }
|
||||||
|
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " +
|
||||||
|
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")}."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = !busy && rows.any { it.selected },
|
||||||
|
modifier = Modifier.padding(horizontal = 16.dp),
|
||||||
|
) { Text("Import selected") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
message?.let { text ->
|
||||||
|
item {
|
||||||
|
Text(text, Modifier.padding(horizontal = 16.dp),
|
||||||
|
color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault())
|
||||||
|
|
||||||
|
/** A labelled value that can be selected and copied. */
|
||||||
|
@Composable
|
||||||
|
private fun Detail(label: String, value: String) {
|
||||||
|
Column(Modifier.padding(top = 8.dp)) {
|
||||||
|
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
SelectionContainer { Text(value, style = MaterialTheme.typography.bodyMedium) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun name(item: SyncItem) = when (item) {
|
||||||
|
is SyncItem.Bookmark -> item.name().ifBlank { item.address() }
|
||||||
|
is SyncItem.Identity -> item.name()
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun details(item: SyncItem) = when (item) {
|
||||||
|
is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port())
|
||||||
|
is SyncItem.Identity -> item.nickname()
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun count(n: Int, one: String, many: String) = "$n ${if (n == 1) one else many}"
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
private const val MIN_BITRATE_KBITS = 8f
|
||||||
|
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 change(edit: Settings.() -> Unit) {
|
||||||
|
settings.edit()
|
||||||
|
vm.applySettings()
|
||||||
|
}
|
||||||
|
var vbr by remember { mutableStateOf(settings.vbr) }
|
||||||
|
var fec by remember { mutableStateOf(settings.fec) }
|
||||||
|
var music by remember { mutableStateOf(settings.music) }
|
||||||
|
var redundancy by remember { mutableStateOf(settings.redundancyDelay) }
|
||||||
|
var copies by remember { mutableStateOf(settings.redundancyCopies) }
|
||||||
|
var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) }
|
||||||
|
|
||||||
|
SubScreen("Network", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
|
||||||
|
Section("Encoder")
|
||||||
|
Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) {
|
||||||
|
change { bitrate = it.roundToInt() * 1000 }
|
||||||
|
}
|
||||||
|
Toggle("Variable bitrate (VBR)", vbr) {
|
||||||
|
vbr = it
|
||||||
|
change { this.vbr = it }
|
||||||
|
}
|
||||||
|
Toggle("Forward error correction (FEC)", fec) {
|
||||||
|
fec = it
|
||||||
|
change { this.fec = it }
|
||||||
|
}
|
||||||
|
Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) {
|
||||||
|
change { complexity = it.roundToInt() }
|
||||||
|
}
|
||||||
|
Toggle("Music codec (stereo, higher fidelity)", music) {
|
||||||
|
music = it
|
||||||
|
change { this.music = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Redundancy")
|
||||||
|
ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) {
|
||||||
|
redundancy = it
|
||||||
|
change { redundancyDelay = it }
|
||||||
|
}
|
||||||
|
if (redundancy > 0) {
|
||||||
|
Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" },
|
||||||
|
steps = Settings.MAX_REDUNDANCY_COPIES - 2) {
|
||||||
|
copies = it.roundToInt()
|
||||||
|
change { redundancyCopies = copies }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Receive")
|
||||||
|
ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) {
|
||||||
|
receiveBuffer = it
|
||||||
|
change { this.receiveBuffer = it }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A slider stepping through the millisecond [choices], starting at the one nearest [ms]. */
|
||||||
|
@Composable
|
||||||
|
private fun ChoiceLevel(label: String, choices: IntArray, ms: Int, onDone: (Int) -> Unit) {
|
||||||
|
val index = choices.indices.minBy { abs(choices[it] - ms) }
|
||||||
|
fun at(position: Float) = choices[position.roundToInt()]
|
||||||
|
Level(label, index.toFloat(), 0f..(choices.size - 1).toFloat(), { at(it).let { v -> if (v == 0) "Off" else "$v ms" } },
|
||||||
|
steps = choices.size - 2) { onDone(at(it)) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.material3.LocalContentColor
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.toArgb
|
||||||
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.IconTheme
|
||||||
|
|
||||||
|
val LocalIconTheme = staticCompositionLocalOf<IconTheme> { error("No icon theme provided") }
|
||||||
|
|
||||||
|
/** An icon of the active pack, named by its TeamSpeak key; art in the text colour takes [LocalContentColor]. */
|
||||||
|
@Composable
|
||||||
|
fun PackIcon(key: String, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) =
|
||||||
|
PackIcon(listOf(key), contentDescription, modifier, size)
|
||||||
|
|
||||||
|
/** The first of [keys] the pack has, for icons packs need not ship in every variant. */
|
||||||
|
@Composable
|
||||||
|
fun PackIcon(keys: List<String>, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) {
|
||||||
|
val theme = LocalIconTheme.current
|
||||||
|
val active by theme.active.collectAsStateWithLifecycle()
|
||||||
|
val pixels = with(LocalDensity.current) { size.roundToPx() }
|
||||||
|
val color = LocalContentColor.current
|
||||||
|
val rgb = color.copy(alpha = 1f).toArgb()
|
||||||
|
val bitmap = remember(keys, pixels, rgb, active) { theme.render(keys, pixels, rgb)?.asImageBitmap() }
|
||||||
|
if (bitmap == null) {
|
||||||
|
Spacer(modifier.size(size))
|
||||||
|
} else {
|
||||||
|
// Disabled controls fade their content colour; the pack's own colours fade with it.
|
||||||
|
Image(bitmap, contentDescription, modifier.size(size), alpha = color.alpha)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
|
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
|
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.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.LocalContentColor
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.CompositionLocalProvider
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.produceState
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.unit.IntSize
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import eu.lixko.ts3j.client.android.Picture
|
||||||
|
import eu.lixko.ts3j.client.android.SavedPictures
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.decodePicture
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
/** A picture to open full size. */
|
||||||
|
class ViewedPicture(
|
||||||
|
/** What to call it when saved, without an extension. */
|
||||||
|
val name: String,
|
||||||
|
/** Where it is on the web; null for an avatar. */
|
||||||
|
val url: String? = null,
|
||||||
|
/** Follows the link it sits in; null when it sits in none. */
|
||||||
|
val openLink: (() -> Unit)? = null,
|
||||||
|
/** Our own avatar, which there is no taking. */
|
||||||
|
val ownAvatar: Boolean = false,
|
||||||
|
/** Its file; null when it is not there. */
|
||||||
|
val read: suspend () -> ByteArray?,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Opens a picture full size; null where nothing can. */
|
||||||
|
val LocalPictureViewer = staticCompositionLocalOf<((ViewedPicture) -> Unit)?> { null }
|
||||||
|
|
||||||
|
/** Lets [content] open pictures full size, over everything, with [server] to take one as our avatar on. */
|
||||||
|
@Composable
|
||||||
|
fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) {
|
||||||
|
var viewed by remember { mutableStateOf<ViewedPicture?>(null) }
|
||||||
|
CompositionLocalProvider(LocalPictureViewer provides { viewed = it }, content = content)
|
||||||
|
val context = LocalContext.current
|
||||||
|
viewed?.let { picture ->
|
||||||
|
PictureViewer(
|
||||||
|
picture,
|
||||||
|
onSteal = if (picture.ownAvatar) null else { data ->
|
||||||
|
val error = server.setAvatar(data)
|
||||||
|
Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
onDismiss = { viewed = null },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A name to save the picture at [url] under: its file's, or "picture" when it has none. */
|
||||||
|
fun pictureName(url: String): String =
|
||||||
|
url.substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/')
|
||||||
|
.substringBeforeLast('.').ifBlank { "picture" }
|
||||||
|
|
||||||
|
/** The picture on black, filling the screen; pinch or double-tap to zoom, tap to hide the bar. */
|
||||||
|
@Composable
|
||||||
|
private fun PictureViewer(
|
||||||
|
picture: ViewedPicture,
|
||||||
|
/** Takes the picture as our avatar; null when it cannot be. */
|
||||||
|
onSteal: (suspend (ByteArray) -> Unit)?,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
val state by produceState<Shown?>(null, picture) {
|
||||||
|
val data = picture.read()
|
||||||
|
value = Shown(data, data?.let { withContext(Dispatchers.Default) { decodePicture(it, MAX_PX) } })
|
||||||
|
}
|
||||||
|
val data = state?.data
|
||||||
|
var bar by remember { mutableStateOf(true) }
|
||||||
|
var scale by remember { mutableFloatStateOf(1f) }
|
||||||
|
var offset by remember { mutableStateOf(Offset.Zero) }
|
||||||
|
var size by remember { mutableStateOf(IntSize.Zero) }
|
||||||
|
fun panTo(target: Offset) {
|
||||||
|
val maxX = size.width * (scale - 1) / 2
|
||||||
|
val maxY = size.height * (scale - 1) / 2
|
||||||
|
offset = Offset(target.x.coerceIn(-maxX, maxX), target.y.coerceIn(-maxY, maxY))
|
||||||
|
}
|
||||||
|
|
||||||
|
Dialog(onDismiss, DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
|
||||||
|
Box(
|
||||||
|
Modifier.fillMaxSize().background(Color.Black).onSizeChanged { size = it }
|
||||||
|
.pointerInput(Unit) {
|
||||||
|
detectTapGestures(
|
||||||
|
onTap = { bar = !bar },
|
||||||
|
onDoubleTap = { scale = if (scale > 1f) 1f else DOUBLE_TAP_SCALE; panTo(Offset.Zero) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.pointerInput(Unit) {
|
||||||
|
detectTransformGestures { _, pan, zoom, _ ->
|
||||||
|
scale = (scale * zoom).coerceIn(1f, MAX_SCALE)
|
||||||
|
panTo(offset + pan)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
val shown = state?.picture
|
||||||
|
when {
|
||||||
|
state == null -> PackIcon("LOADING_IMAGE", "Loading picture")
|
||||||
|
shown == null -> PackIcon("BROKEN_IMAGE", "Broken picture")
|
||||||
|
else -> Image(
|
||||||
|
rememberPicturePainter(shown), null,
|
||||||
|
Modifier.fillMaxSize().graphicsLayer {
|
||||||
|
scaleX = scale
|
||||||
|
scaleY = scale
|
||||||
|
translationX = offset.x
|
||||||
|
translationY = offset.y
|
||||||
|
},
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (bar) {
|
||||||
|
CompositionLocalProvider(LocalContentColor provides Color.White) {
|
||||||
|
Bar(picture, data, onSteal, onDismiss, Modifier.align(Alignment.TopCenter))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Bar(
|
||||||
|
picture: ViewedPicture,
|
||||||
|
data: ByteArray?,
|
||||||
|
onSteal: (suspend (ByteArray) -> Unit)?,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
modifier: Modifier,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
Row(
|
||||||
|
modifier.fillMaxWidth()
|
||||||
|
.background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.6f), Color.Transparent)))
|
||||||
|
.statusBarsPadding(),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
|
||||||
|
Box(Modifier.weight(1f))
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Picture options") }
|
||||||
|
DropdownMenu(menu, onDismissRequest = { menu = false }) {
|
||||||
|
DropdownMenuItem({ Text("Save") }, enabled = data != null, onClick = {
|
||||||
|
menu = false
|
||||||
|
val bytes = data ?: return@DropdownMenuItem
|
||||||
|
scope.launch {
|
||||||
|
val saved = SavedPictures.save(context, picture.name, bytes)
|
||||||
|
Toast.makeText(context, if (saved) "Saved." else "Could not save.", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (onSteal != null) {
|
||||||
|
DropdownMenuItem({ Text("Steal for avatar") }, enabled = data != null, onClick = {
|
||||||
|
menu = false
|
||||||
|
val bytes = data ?: return@DropdownMenuItem
|
||||||
|
scope.launch { onSteal(bytes) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
picture.url?.let { url ->
|
||||||
|
DropdownMenuItem({ Text("Copy URL") }, onClick = {
|
||||||
|
menu = false
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText("URL", url))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
picture.openLink?.let { open ->
|
||||||
|
DropdownMenuItem({ Text("Open link") }, onClick = {
|
||||||
|
menu = false
|
||||||
|
onDismiss()
|
||||||
|
open()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The picture's file, and the picture when the file is one; both null when it is not there. */
|
||||||
|
private class Shown(val data: ByteArray?, val picture: Picture?)
|
||||||
|
|
||||||
|
private const val MAX_PX = 4096
|
||||||
|
private const val MAX_SCALE = 8f
|
||||||
|
private const val DOUBLE_TAP_SCALE = 2.5f
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||||
|
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.Shape
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
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.net.ClientStatus
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
||||||
|
/** What push-to-talk would talk on: the server holding the microphone, which need not be the one on screen. */
|
||||||
|
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()
|
||||||
|
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)
|
||||||
|
val talking = self?.status == ClientStatus.TALKING || self?.status == ClientStatus.COMMANDER_TALKING
|
||||||
|
return PttTarget(owner, state, talking)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Talks while held. */
|
||||||
|
@Composable
|
||||||
|
internal fun PushToTalk(
|
||||||
|
talking: Boolean,
|
||||||
|
onPressed: (Boolean) -> Unit,
|
||||||
|
modifier: Modifier,
|
||||||
|
shape: Shape = RoundedCornerShape(24.dp),
|
||||||
|
textStyle: TextStyle = MaterialTheme.typography.titleMedium,
|
||||||
|
) {
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
Surface(
|
||||||
|
modifier.pointerInput(Unit) {
|
||||||
|
// Held until the finger lifts, wherever it wanders; a tap gesture would end once it left the button.
|
||||||
|
awaitEachGesture {
|
||||||
|
awaitFirstDown()
|
||||||
|
onPressed(true)
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
val event = awaitPointerEvent()
|
||||||
|
event.changes.forEach { it.consume() }
|
||||||
|
} while (event.changes.any { it.pressed })
|
||||||
|
} finally {
|
||||||
|
onPressed(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
shape = shape,
|
||||||
|
color = if (talking) StatusColors.talking else colors.primaryContainer,
|
||||||
|
contentColor = if (talking) Color.White else colors.onPrimaryContainer,
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.Center) {
|
||||||
|
Text(if (talking) "Talking…" else "Hold to talk", style = textStyle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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)
|
||||||
|
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),
|
||||||
|
MaterialTheme.typography.displaySmall)
|
||||||
|
} else {
|
||||||
|
Box(fill, contentAlignment = Alignment.Center) {
|
||||||
|
Text("Not connected",
|
||||||
|
style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Slider
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.config.ClientRowColors
|
||||||
|
|
||||||
|
/** A row background: none, a preset, or a custom colour. [argb] is 0 for none. */
|
||||||
|
@Composable
|
||||||
|
internal fun RowColorPicker(label: String, argb: Int, onChange: (Int) -> Unit) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
var custom by remember { mutableStateOf(false) }
|
||||||
|
Box {
|
||||||
|
Row(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(label)
|
||||||
|
Text(nameOf(argb), style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
Swatch(argb, 28.dp)
|
||||||
|
}
|
||||||
|
DropdownMenu(open, { open = false }) {
|
||||||
|
DropdownMenuItem({ Text("None") }, leadingIcon = { Swatch(0) }, onClick = {
|
||||||
|
open = false
|
||||||
|
onChange(0)
|
||||||
|
})
|
||||||
|
for (p in ClientRowColors.PRESETS) {
|
||||||
|
DropdownMenuItem({ Text(p.name()) }, leadingIcon = { Swatch(p.argb()) }, onClick = {
|
||||||
|
open = false
|
||||||
|
onChange(p.argb())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
DropdownMenuItem({ Text("Custom…") }, onClick = {
|
||||||
|
open = false
|
||||||
|
custom = true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (custom) {
|
||||||
|
CustomColorDialog(if (argb != 0) argb else 0x59808080, onDismiss = { custom = false }) {
|
||||||
|
custom = false
|
||||||
|
onChange(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun nameOf(argb: Int): String =
|
||||||
|
if (argb == 0) "None" else ClientRowColors.presetOf(argb)?.name() ?: "Custom"
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun CustomColorDialog(initial: Int, onDismiss: () -> Unit, onPick: (Int) -> Unit) {
|
||||||
|
var alpha by remember { mutableIntStateOf(initial ushr 24) }
|
||||||
|
var red by remember { mutableIntStateOf(initial shr 16 and 0xFF) }
|
||||||
|
var green by remember { mutableIntStateOf(initial shr 8 and 0xFF) }
|
||||||
|
var blue by remember { mutableIntStateOf(initial and 0xFF) }
|
||||||
|
val argb = (alpha shl 24) or (red shl 16) or (green shl 8) or blue
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("Custom colour") },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
Box(Modifier.fillMaxWidth().height(40.dp).clip(RoundedCornerShape(6.dp))
|
||||||
|
.background(MaterialTheme.colorScheme.surface)) {
|
||||||
|
Box(Modifier.fillMaxWidth().height(40.dp).background(Color(argb)))
|
||||||
|
}
|
||||||
|
Channel("Red", red) { red = it }
|
||||||
|
Channel("Green", green) { green = it }
|
||||||
|
Channel("Blue", blue) { blue = it }
|
||||||
|
Channel("Opacity", alpha) { alpha = it }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton({ onPick(argb) }, enabled = argb != 0) { Text("OK") } },
|
||||||
|
dismissButton = { TextButton(onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Channel(label: String, value: Int, onChange: (Int) -> Unit) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(label, Modifier.width(64.dp), style = MaterialTheme.typography.bodySmall)
|
||||||
|
Slider(value.toFloat(), { onChange(it.toInt()) }, Modifier.weight(1f), valueRange = 0f..255f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The colour over the screen's background, as a row would show it; outlined so "none" shows too. */
|
||||||
|
@Composable
|
||||||
|
private fun Swatch(argb: Int, size: Dp = 20.dp) {
|
||||||
|
val shape = RoundedCornerShape(4.dp)
|
||||||
|
Box(Modifier.size(size).clip(shape).background(MaterialTheme.colorScheme.surface).background(Color(argb))
|
||||||
|
.border(1.dp, MaterialTheme.colorScheme.outline, shape))
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.drawable.AnimatedImageDrawable
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.LocalContentColor
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.graphics.ImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.graphics.drawscope.DrawScope
|
||||||
|
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
|
||||||
|
import androidx.compose.ui.graphics.nativeCanvas
|
||||||
|
import androidx.compose.ui.graphics.painter.BitmapPainter
|
||||||
|
import androidx.compose.ui.graphics.painter.Painter
|
||||||
|
import androidx.compose.ui.graphics.toArgb
|
||||||
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.Picture
|
||||||
|
import eu.lixko.ts3j.client.android.ServerImages
|
||||||
|
import eu.lixko.ts3j.client.gfx.CountryFlags
|
||||||
|
import eu.lixko.ts3j.client.net.IconRepository
|
||||||
|
import java.util.Optional
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/** The images of the server on screen. */
|
||||||
|
val LocalServerImages = staticCompositionLocalOf<ServerImages?> { null }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A group, channel or server icon; nothing while it has none or it is still downloading.
|
||||||
|
* TeamSpeak's default group icons are the pack's, drawn in its style, as on the desktop.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun ServerIcon(id: Long, modifier: Modifier = Modifier, size: Dp = 16.dp) {
|
||||||
|
if (id == 0L) return
|
||||||
|
if (id in 1..IconRepository.MAX_BUNDLED_ID) {
|
||||||
|
val theme = LocalIconTheme.current
|
||||||
|
val active by theme.active.collectAsStateWithLifecycle()
|
||||||
|
val pixels = with(LocalDensity.current) { size.roundToPx() }
|
||||||
|
val rgb = LocalContentColor.current.copy(alpha = 1f).toArgb()
|
||||||
|
val themed = remember(id, pixels, rgb, active) { theme.render(listOf("GROUP_$id"), pixels, rgb)?.asImageBitmap() }
|
||||||
|
if (themed != null) {
|
||||||
|
Image(themed, null, modifier.size(size))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val images = LocalServerImages.current ?: return
|
||||||
|
val version by images.version.collectAsStateWithLifecycle()
|
||||||
|
val bitmap = remember(id, version) { images.icon(id) } ?: return
|
||||||
|
Image(bitmap, null, modifier.size(size))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A client's avatar, moving if it is an animated GIF; nothing while they have none or it is still downloading. */
|
||||||
|
@Composable
|
||||||
|
fun Avatar(uniqueId: String, flag: String, modifier: Modifier = Modifier, size: Dp = 64.dp) {
|
||||||
|
val images = LocalServerImages.current ?: return
|
||||||
|
val version by images.version.collectAsStateWithLifecycle()
|
||||||
|
val picture = remember(flag, version) { images.avatar(uniqueId, flag) } ?: return
|
||||||
|
Image(rememberPicturePainter(picture), "Avatar", modifier.size(size).clip(RoundedCornerShape(8.dp)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draws [picture], playing it while on screen if it moves. */
|
||||||
|
@Composable
|
||||||
|
fun rememberPicturePainter(picture: Picture): Painter = when (picture) {
|
||||||
|
is Picture.Still -> remember(picture) { BitmapPainter(picture.bitmap) }
|
||||||
|
is Picture.Moving -> rememberMovingPainter(picture.drawable)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun rememberMovingPainter(drawable: AnimatedImageDrawable): Painter {
|
||||||
|
val painter = remember(drawable) { MovingPainter(drawable) }
|
||||||
|
DisposableEffect(drawable) {
|
||||||
|
drawable.callback = painter
|
||||||
|
drawable.start()
|
||||||
|
onDispose {
|
||||||
|
drawable.stop()
|
||||||
|
if (drawable.callback === painter) drawable.callback = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return painter
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MovingPainter(private val drawable: AnimatedImageDrawable) : Painter(), Drawable.Callback {
|
||||||
|
/** Read while drawing, so that each new frame draws again. */
|
||||||
|
private var frame by mutableIntStateOf(0)
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
override val intrinsicSize = Size(drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat())
|
||||||
|
|
||||||
|
override fun DrawScope.onDraw() {
|
||||||
|
frame
|
||||||
|
drawIntoCanvas { canvas ->
|
||||||
|
drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt())
|
||||||
|
drawable.draw(canvas.nativeCanvas)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun invalidateDrawable(who: Drawable) {
|
||||||
|
frame++
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
|
||||||
|
main.postAtTime(what, `when`)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
|
||||||
|
main.removeCallbacks(what)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val flags = ConcurrentHashMap<String, Optional<ImageBitmap>>()
|
||||||
|
|
||||||
|
/** The flag of a country, at TeamSpeak's 16×11; nothing for no country or one without a flag. */
|
||||||
|
@Composable
|
||||||
|
fun CountryFlag(code: String, modifier: Modifier = Modifier) {
|
||||||
|
if (code.isEmpty()) return
|
||||||
|
val bitmap = remember(code) {
|
||||||
|
flags.getOrPut(code) {
|
||||||
|
Optional.ofNullable(CountryFlags.png(code)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() })
|
||||||
|
}.orElse(null)
|
||||||
|
} ?: return
|
||||||
|
Image(bitmap, CountryFlags.name(code), modifier.size(16.dp, 11.dp))
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,686 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.combinedClickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.consumeWindowInsets
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Badge
|
||||||
|
import androidx.compose.material3.BadgedBox
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.FilledTonalButton
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.IconToggleButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.MenuDefaults
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.material3.minimumInteractiveComponentSize
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.Saver
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.input.key.Key
|
||||||
|
import androidx.compose.ui.input.key.KeyEventType
|
||||||
|
import androidx.compose.ui.input.key.isCtrlPressed
|
||||||
|
import androidx.compose.ui.input.key.key
|
||||||
|
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||||
|
import androidx.compose.ui.input.key.type
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.platform.LocalUriHandler
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.ChannelItem
|
||||||
|
import eu.lixko.ts3j.client.android.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.android.ChatMatch
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionState
|
||||||
|
import eu.lixko.ts3j.client.android.TreeFind
|
||||||
|
import eu.lixko.ts3j.client.android.findIn
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.config.WhisperList
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachment
|
||||||
|
import eu.lixko.ts3j.client.session.ServerLink
|
||||||
|
import eu.lixko.ts3j.client.text.TsLink
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
private val ChatKeySaver = Saver<ChatKey, String>(
|
||||||
|
save = { key ->
|
||||||
|
when (key) {
|
||||||
|
ChatKey.Server -> "server"
|
||||||
|
ChatKey.Channel -> "channel"
|
||||||
|
is ChatKey.Private -> "private:${key.clientId}"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
restore = { saved ->
|
||||||
|
when {
|
||||||
|
saved == "server" -> ChatKey.Server
|
||||||
|
saved.startsWith("private:") -> ChatKey.Private(saved.substringAfter(':').toInt())
|
||||||
|
else -> ChatKey.Channel
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
private val ChannelEditSaver = Saver<ChannelEdit?, IntArray>(
|
||||||
|
save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } },
|
||||||
|
restore = { ChannelEdit(it[0], it[1]) },
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A channel whose files are browsed, with the password they take. */
|
||||||
|
private data class FilesOf(val channelId: Int, val name: String, val password: String)
|
||||||
|
|
||||||
|
private val FilesOfSaver = Saver<FilesOf?, List<Any>>(
|
||||||
|
save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } },
|
||||||
|
restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) },
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A connection: the channel tree and the chat, with the voice controls underneath. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ServerScreen(
|
||||||
|
vm: SessionController,
|
||||||
|
server: ServerController,
|
||||||
|
snackbar: SnackbarHostState,
|
||||||
|
onSettings: () -> Unit,
|
||||||
|
/** Opens the given client's contact page. */
|
||||||
|
onEditContact: (String) -> Unit,
|
||||||
|
onEnableMicrophone: () -> Unit,
|
||||||
|
onConnectOther: () -> Unit,
|
||||||
|
onEditBookmark: (BookmarkEdit) -> Unit,
|
||||||
|
) {
|
||||||
|
val state by server.state.collectAsStateWithLifecycle()
|
||||||
|
val tree by server.tree.collectAsStateWithLifecycle()
|
||||||
|
val chats by server.chats.collectAsStateWithLifecycle()
|
||||||
|
val collapsed by server.collapsed.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
var showChat by rememberSaveable { mutableStateOf(false) }
|
||||||
|
// Out here, so the tree keeps its place while the chat or another screen replaces it.
|
||||||
|
val treeList = rememberLazyListState()
|
||||||
|
var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf<ChatKey>(ChatKey.Channel) }
|
||||||
|
val conversation = chats[chatKey] ?: chats.channel
|
||||||
|
var clientSheet by remember { mutableStateOf<Int?>(null) }
|
||||||
|
var clientSheetFromTree by remember { mutableStateOf(false) }
|
||||||
|
/** A row to show in the tree. */
|
||||||
|
var reveal by remember { mutableStateOf<TreeRef?>(null) }
|
||||||
|
var channelSheet by remember { mutableStateOf<Int?>(null) }
|
||||||
|
/** A locked channel being joined, while its password is asked for. */
|
||||||
|
var joinLocked by remember { mutableStateOf<Int?>(null) }
|
||||||
|
val join = { channel: ChannelItem ->
|
||||||
|
if (channel.locked) joinLocked = channel.id else server.joinChannel(channel.id)
|
||||||
|
}
|
||||||
|
var serverSheet by remember { mutableStateOf(false) }
|
||||||
|
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
|
||||||
|
var banList by rememberSaveable { mutableStateOf(false) }
|
||||||
|
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
|
||||||
|
var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf<FilesOf?>(null) }
|
||||||
|
/** A locked channel whose files are wanted, while its password is asked for. */
|
||||||
|
var filesLocked by remember { mutableStateOf<Int?>(null) }
|
||||||
|
var deletingChannel by remember { mutableStateOf<Int?>(null) }
|
||||||
|
var whisperLists by rememberSaveable { mutableStateOf(false) }
|
||||||
|
/** What is being added to a whisper list, while the list is picked: its name and how to add it. */
|
||||||
|
var toWhisperList by remember { mutableStateOf<Pair<String, (WhisperList) -> Unit>?>(null) }
|
||||||
|
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||||
|
/** The client to move, while a channel for them is being picked. */
|
||||||
|
var moving by remember { mutableStateOf<Int?>(null) }
|
||||||
|
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
|
||||||
|
LaunchedEffect(chatRequest) {
|
||||||
|
val key = chatRequest ?: return@LaunchedEffect
|
||||||
|
chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId)
|
||||||
|
showChat = true
|
||||||
|
server.chatRequestHandled()
|
||||||
|
}
|
||||||
|
|
||||||
|
val viewing = if (showChat) conversation.key else null
|
||||||
|
LifecycleResumeEffect(viewing) {
|
||||||
|
server.viewing = viewing
|
||||||
|
onPauseOrDispose { server.viewing = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
val uriHandler = LocalUriHandler.current
|
||||||
|
val attachments = rememberAttachmentActions(vm, 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) }
|
||||||
|
ref == null -> runCatching { uriHandler.openUri(href) }
|
||||||
|
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false }
|
||||||
|
else -> channelSheet = ref.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find: in the tree, clients or channels; in the chat, the conversation on screen.
|
||||||
|
val find = rememberSaveable(saver = FindState.Saver) { FindState() }
|
||||||
|
val treeFind = TreeFind(find.usable, find.channels)
|
||||||
|
val treeHits = remember(tree, treeFind) { tree.hits(treeFind) }
|
||||||
|
val treeFiltering = find.filter && !treeFind.query.isEmpty
|
||||||
|
val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree }
|
||||||
|
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
|
||||||
|
var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet<Int>()) }
|
||||||
|
/** The match the tree is on. */
|
||||||
|
var treeAt by remember { mutableStateOf<Int?>(null) }
|
||||||
|
// Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured.
|
||||||
|
val showTreeHit = { id: Int? ->
|
||||||
|
if (id != null) {
|
||||||
|
treeAt = id
|
||||||
|
val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty()
|
||||||
|
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
|
||||||
|
reveal = TreeRef(treeFind.channels, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LaunchedEffect(treeFind, showChat) {
|
||||||
|
treeAt = null
|
||||||
|
if (!showChat) showTreeHit(treeHits.firstOrNull())
|
||||||
|
}
|
||||||
|
|
||||||
|
val chatQuery = find.usable
|
||||||
|
val chatLines = remember(conversation.lines, chatQuery, find.filter) {
|
||||||
|
if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines
|
||||||
|
}
|
||||||
|
val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) }
|
||||||
|
/** The match the chat is on; a new search starts from the newest. */
|
||||||
|
var chatAt by remember { mutableStateOf<ChatMatch?>(null) }
|
||||||
|
var chatReveal by remember { mutableStateOf<Long?>(null) }
|
||||||
|
LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) {
|
||||||
|
chatAt = if (showChat) chatHits.lastOrNull() else null
|
||||||
|
chatReveal = chatAt?.line
|
||||||
|
}
|
||||||
|
|
||||||
|
val step = { delta: Int ->
|
||||||
|
if (showChat && chatHits.isNotEmpty()) {
|
||||||
|
chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)]
|
||||||
|
chatReveal = chatAt?.line
|
||||||
|
} else if (!showChat && treeHits.isNotEmpty()) {
|
||||||
|
showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (banList) {
|
||||||
|
BanListScreen(server, vm.banReasons, onBack = { banList = false })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
channelEdit?.let {
|
||||||
|
ChannelEditScreen(server, it, onDone = { channelEdit = null })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files?.let {
|
||||||
|
FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (whisperLists) {
|
||||||
|
WhisperListsScreen(vm, server, onBack = { whisperLists = false })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connectionInfo?.let { id ->
|
||||||
|
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
BackHandler(showChat) { showChat = false }
|
||||||
|
BackHandler(moving != null && !showChat) { moving = null }
|
||||||
|
BackHandler(find.open) { find.open = false }
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
// A hardware keyboard's Ctrl+F, as on the desktop.
|
||||||
|
modifier = Modifier.onPreviewKeyEvent { e ->
|
||||||
|
val ctrlF = e.isCtrlPressed && e.key == Key.F
|
||||||
|
if (ctrlF && e.type == KeyEventType.KeyDown) find.show()
|
||||||
|
ctrlF
|
||||||
|
},
|
||||||
|
topBar = {
|
||||||
|
if (find.open) {
|
||||||
|
if (showChat) {
|
||||||
|
FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size,
|
||||||
|
chatHits.size == MAX_CHAT_MATCHES, step)
|
||||||
|
} else {
|
||||||
|
FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
TopAppBar(
|
||||||
|
title = { ServerSwitcher(vm, server, state, onConnectOther) },
|
||||||
|
expandedHeight = 48.dp,
|
||||||
|
actions = {
|
||||||
|
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
|
||||||
|
if (state.connected) WhisperMenu(vm, server, state) { whisperLists = true }
|
||||||
|
IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
|
||||||
|
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
bottomBar = {
|
||||||
|
Column {
|
||||||
|
val ptt = rememberPttTarget(vm)
|
||||||
|
WhisperBanner(state) { server.setWhisper(null) }
|
||||||
|
VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) {
|
||||||
|
showChat = !showChat
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
snackbarHost = { SnackbarHost(snackbar) },
|
||||||
|
) { padding ->
|
||||||
|
Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) {
|
||||||
|
if (!showChat) {
|
||||||
|
moving?.let { id ->
|
||||||
|
val client = tree.client(id)
|
||||||
|
if (client == null) {
|
||||||
|
LaunchedEffect(id) { moving = null }
|
||||||
|
} else {
|
||||||
|
MovePrompt(client.name) { moving = null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ChannelTree(
|
||||||
|
serverName = state.title,
|
||||||
|
tree = shownTree,
|
||||||
|
collapsed = if (treeFiltering) filterCollapsed else collapsed,
|
||||||
|
currentChannel = state.channelId,
|
||||||
|
onToggle = {
|
||||||
|
if (!treeFiltering) server.toggleCollapsed(it.id)
|
||||||
|
else if (it.id in filterCollapsed) filterCollapsed -= it.id
|
||||||
|
else filterCollapsed += it.id
|
||||||
|
},
|
||||||
|
onChannel = { channel ->
|
||||||
|
val client = moving
|
||||||
|
when {
|
||||||
|
channel.spacer != null -> {}
|
||||||
|
client != null -> { server.moveClient(client, channel.id); moving = null }
|
||||||
|
else -> channelSheet = channel.id
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onChannelDoubleTap = { channel ->
|
||||||
|
val client = moving
|
||||||
|
when {
|
||||||
|
client != null -> { server.moveClient(client, channel.id); moving = null }
|
||||||
|
channel.id == state.channelId -> {}
|
||||||
|
else -> join(channel)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onClient = { clientSheet = it.id; clientSheetFromTree = true },
|
||||||
|
onServer = { serverSheet = true },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
reveal = reveal,
|
||||||
|
onRevealed = { reveal = null },
|
||||||
|
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
|
||||||
|
foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) },
|
||||||
|
listState = treeList,
|
||||||
|
onShowSelf = {
|
||||||
|
val path = tree.pathTo(state.selfClientId).orEmpty()
|
||||||
|
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
|
||||||
|
reveal = TreeRef(false, state.selfClientId)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
ChatPane(
|
||||||
|
chats = chats,
|
||||||
|
selected = conversation,
|
||||||
|
canSend = state.connected,
|
||||||
|
onSelect = { chatKey = it },
|
||||||
|
onClose = { key ->
|
||||||
|
if (chatKey == key) chatKey = ChatKey.Channel
|
||||||
|
server.closePrivateChat(key)
|
||||||
|
},
|
||||||
|
onSend = { server.send(conversation.key, it) },
|
||||||
|
onAttach = attachments.share,
|
||||||
|
onLink = onLink,
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
lines = chatLines,
|
||||||
|
find = chatQuery,
|
||||||
|
current = chatAt,
|
||||||
|
reveal = chatReveal,
|
||||||
|
onRevealed = { chatReveal = null },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A sheet goes with its client or channel when that leaves the tree.
|
||||||
|
clientSheet?.let { id ->
|
||||||
|
LaunchedEffect(id) { server.requestClientDetails(id) }
|
||||||
|
tree.client(id)?.let { client ->
|
||||||
|
ClientSheet(
|
||||||
|
client = client,
|
||||||
|
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
|
||||||
|
onLink = onLink,
|
||||||
|
away = state.away,
|
||||||
|
initialVolume = remember(id) { server.clientVolume(id) },
|
||||||
|
onDismiss = { clientSheet = null },
|
||||||
|
onMessage = {
|
||||||
|
clientSheet = null
|
||||||
|
chatKey = server.openPrivateChat(id)
|
||||||
|
showChat = true
|
||||||
|
},
|
||||||
|
onPoke = { server.poke(id, it); clientSheet = null },
|
||||||
|
onVolume = { server.setClientVolume(id, it) },
|
||||||
|
onAway = { server.setAway(it); clientSheet = null },
|
||||||
|
onAddContact = { server.addContact(id, it) },
|
||||||
|
onEditContact = { clientSheet = null; onEditContact(client.uniqueId) },
|
||||||
|
onConnectionInfo = { clientSheet = null; connectionInfo = id },
|
||||||
|
onWhisper = { clientSheet = null; server.whisperToClient(id) },
|
||||||
|
onAddToWhisperList = {
|
||||||
|
clientSheet = null
|
||||||
|
server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } }
|
||||||
|
},
|
||||||
|
onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null,
|
||||||
|
onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
|
||||||
|
{ server.moveClient(id, state.channelId); clientSheet = null }
|
||||||
|
} else null,
|
||||||
|
onFindInTree = if (clientSheetFromTree) null else ({
|
||||||
|
clientSheet = null
|
||||||
|
tree.pathTo(id)?.let { server.expand(it) }
|
||||||
|
showChat = false
|
||||||
|
reveal = TreeRef(false, id)
|
||||||
|
}),
|
||||||
|
moderation = { ClientModeration(server, client) { clientSheet = null } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
channelSheet?.let { id ->
|
||||||
|
LaunchedEffect(id) { server.requestChannelDetails(id) }
|
||||||
|
tree.channel(id)?.let { channel ->
|
||||||
|
ChannelSheet(
|
||||||
|
channel = channel,
|
||||||
|
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
|
||||||
|
onLink = onLink,
|
||||||
|
current = id == state.channelId,
|
||||||
|
onDismiss = { channelSheet = null },
|
||||||
|
onJoin = { join(channel); channelSheet = null },
|
||||||
|
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
|
||||||
|
onBookmark = { channelSheet = null; bookmarkHere(id) },
|
||||||
|
onWhisper = { channelSheet = null; server.whisperToChannel(id) },
|
||||||
|
onAddToWhisperList = {
|
||||||
|
channelSheet = null
|
||||||
|
server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } }
|
||||||
|
},
|
||||||
|
onFiles = {
|
||||||
|
channelSheet = null
|
||||||
|
if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "")
|
||||||
|
},
|
||||||
|
onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
|
||||||
|
onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
|
||||||
|
onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
joinLocked?.let { id ->
|
||||||
|
TextPrompt(
|
||||||
|
title = "Join ${tree.channel(id)?.name.orEmpty()}",
|
||||||
|
label = "Channel password",
|
||||||
|
confirm = "Join",
|
||||||
|
password = true,
|
||||||
|
onDismiss = { joinLocked = null },
|
||||||
|
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
filesLocked?.let { id ->
|
||||||
|
TextPrompt(
|
||||||
|
title = "Files of ${tree.channel(id)?.name.orEmpty()}",
|
||||||
|
label = "Channel password",
|
||||||
|
confirm = "Open",
|
||||||
|
password = true,
|
||||||
|
onDismiss = { filesLocked = null },
|
||||||
|
onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
deletingChannel?.let { id ->
|
||||||
|
val channel = tree.channel(id)
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { deletingChannel = null },
|
||||||
|
title = { Text("Delete ${channel?.name.orEmpty()}?") },
|
||||||
|
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
|
||||||
|
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
|
||||||
|
} else null,
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
deletingChannel = null
|
||||||
|
scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } }
|
||||||
|
}) { Text("Delete") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
toWhisperList?.let { (name, add) ->
|
||||||
|
AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName ->
|
||||||
|
toWhisperList = null
|
||||||
|
vm.addToWhisperList(index, newName, add)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (serverSheet) {
|
||||||
|
remember(tree, infoUpdates) { server.serverDetails() }?.let {
|
||||||
|
ServerSheet(it, onLink, onDismiss = { serverSheet = false },
|
||||||
|
onBookmark = { serverSheet = false; bookmarkHere(state.channelId) },
|
||||||
|
onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null,
|
||||||
|
onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** More matches than this nobody steps through one by one. */
|
||||||
|
private const val MAX_CHAT_MATCHES = 5000
|
||||||
|
|
||||||
|
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
|
||||||
|
private fun next(at: Int, delta: Int, size: Int): Int =
|
||||||
|
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
|
||||||
|
|
||||||
|
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
|
||||||
|
@Composable
|
||||||
|
private fun MovePrompt(name: String, onCancel: () -> Unit) {
|
||||||
|
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
PackIcon("CHANNEL_SWITCH", null)
|
||||||
|
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
TextButton(onClick = onCancel) { Text("Cancel") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
|
||||||
|
* microphone is used. Holding the mute button switches between push to talk and voice activation.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
private fun VoiceBar(
|
||||||
|
state: SessionState,
|
||||||
|
/** Whether some server holds the microphone, for push-to-talk to talk on. */
|
||||||
|
captured: Boolean,
|
||||||
|
talking: Boolean,
|
||||||
|
vm: SessionController,
|
||||||
|
server: ServerController,
|
||||||
|
onEnableMicrophone: () -> Unit,
|
||||||
|
showChat: Boolean,
|
||||||
|
unread: Boolean,
|
||||||
|
onChat: () -> Unit,
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
|
||||||
|
val mic = @Composable {
|
||||||
|
BarButton(
|
||||||
|
onClick = { server.setMicMuted(!state.micMuted) },
|
||||||
|
onLongClick = {
|
||||||
|
val mode = vm.toggleInputMode()
|
||||||
|
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
|
||||||
|
else "Switched to voice activation mode."
|
||||||
|
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
enabled = state.connected,
|
||||||
|
) {
|
||||||
|
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
|
||||||
|
else PackIcon("CAPTURE", "Mute microphone")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val deafen = @Composable {
|
||||||
|
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
|
||||||
|
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
|
||||||
|
else PackIcon("PLAYBACK", "Deafen")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Another server holds the microphone.
|
||||||
|
val activate = @Composable {
|
||||||
|
if (state.connected && state.micPermission && !state.micActive) {
|
||||||
|
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val middle = @Composable {
|
||||||
|
when {
|
||||||
|
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
|
||||||
|
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
|
||||||
|
PackIcon("CAPTURE", null)
|
||||||
|
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val away = @Composable {
|
||||||
|
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
|
||||||
|
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val chat = @Composable {
|
||||||
|
IconToggleButton(showChat, { onChat() }) {
|
||||||
|
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
|
||||||
|
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
|
||||||
|
Modifier.alpha(if (showChat) 1f else 0.7f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Surface(tonalElevation = 3.dp) {
|
||||||
|
// The same places whatever shows: sides of three buttons each keep the talk button centred.
|
||||||
|
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Slot { mic() }; Slot { deafen() }; Slot { activate() }
|
||||||
|
}
|
||||||
|
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
|
||||||
|
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Slot { away() }; Slot { chat() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val SLOT = 48.dp
|
||||||
|
private val SIDE = SLOT * 3
|
||||||
|
|
||||||
|
/** One button's place in the bar, kept whether or not the button shows. */
|
||||||
|
@Composable
|
||||||
|
private fun Slot(content: @Composable () -> Unit) {
|
||||||
|
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An icon button that also answers a long press. */
|
||||||
|
@Composable
|
||||||
|
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
|
||||||
|
Box(
|
||||||
|
Modifier
|
||||||
|
.minimumInteractiveComponentSize()
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
|
||||||
|
.alpha(if (enabled) 1f else 0.38f),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) { content() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's own icon, else the pack's server icon. */
|
||||||
|
@Composable
|
||||||
|
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
|
||||||
|
val tree by server.tree.collectAsStateWithLifecycle()
|
||||||
|
val version by server.images.version.collectAsStateWithLifecycle()
|
||||||
|
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
|
||||||
|
if (icon != null) Image(icon, null, modifier.size(24.dp))
|
||||||
|
else PackIcon("SERVER_GREEN", null, modifier)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server on screen, opening onto the others and connecting to another. */
|
||||||
|
@Composable
|
||||||
|
private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
|
||||||
|
val servers by vm.servers.collectAsStateWithLifecycle()
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
Box(Modifier.fillMaxWidth()) {
|
||||||
|
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
ServerLogo(server, Modifier.padding(end = 12.dp))
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
if (!state.connected) {
|
||||||
|
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Icon(Icons.Filled.ArrowDropDown, "Servers")
|
||||||
|
}
|
||||||
|
DropdownMenu(open, onDismissRequest = { open = false }) {
|
||||||
|
for (other in servers) {
|
||||||
|
key(other.id) {
|
||||||
|
val otherState by other.state.collectAsStateWithLifecycle()
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
onClick = { open = false; vm.select(other) },
|
||||||
|
leadingIcon = {
|
||||||
|
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
|
||||||
|
},
|
||||||
|
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
|
||||||
|
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
|
||||||
|
else MenuDefaults.itemColors(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Connect…") },
|
||||||
|
onClick = { open = false; onConnectOther() },
|
||||||
|
leadingIcon = { PackIcon("CONNECT", null) },
|
||||||
|
)
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Disconnect from current") },
|
||||||
|
onClick = { open = false; server.disconnect() },
|
||||||
|
leadingIcon = { PackIcon("DISCONNECT", null) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
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.IconTheme
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES, MY_TEAMSPEAK }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The settings, by category. Every change is saved and put into effect at once,
|
||||||
|
* as there is no dialog to confirm.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) {
|
||||||
|
var page by rememberSaveable { mutableStateOf<SettingsPage?>(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 })
|
||||||
|
null -> {}
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen("Settings", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
|
||||||
|
LinkRow("Contacts", "Friends and blocked users", "CONTACT", onContacts)
|
||||||
|
LinkRow("Sound Settings", "Devices, transmission, voice activation, processing, volume", "PLAYBACK") {
|
||||||
|
page = SettingsPage.SOUND
|
||||||
|
}
|
||||||
|
LinkRow("Network", "Bitrate, error correction, redundancy, buffering", "PING_4") {
|
||||||
|
page = SettingsPage.NETWORK
|
||||||
|
}
|
||||||
|
LinkRow("Giant PTT", "A push-to-talk button filling the screen", "CAPTURE") {
|
||||||
|
page = SettingsPage.GIANT_PTT
|
||||||
|
}
|
||||||
|
LinkRow("Design", "Icon pack, country flags, client colours, description pictures", "GUISETUP") {
|
||||||
|
page = SettingsPage.DESIGN
|
||||||
|
}
|
||||||
|
LinkRow("Identities", "Create, import, export, security level",
|
||||||
|
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
|
||||||
|
LinkRow("myTeamSpeak",
|
||||||
|
if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}"
|
||||||
|
else "Sign in to bring over your synchronised bookmarks and identities",
|
||||||
|
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DesignScreen(vm: SessionController, onBack: () -> Unit) {
|
||||||
|
SubScreen("Design", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
|
||||||
|
IconPackPicker(vm.icons)
|
||||||
|
var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) }
|
||||||
|
Toggle("Show pictures in descriptions", pictures) {
|
||||||
|
pictures = it
|
||||||
|
vm.setDescriptionPictures(it)
|
||||||
|
}
|
||||||
|
Section("Channel tree")
|
||||||
|
var flags by remember { mutableStateOf(vm.settings.countryFlags) }
|
||||||
|
Toggle("Show country flags in the channel tree", flags) {
|
||||||
|
flags = it
|
||||||
|
vm.setCountryFlags(it)
|
||||||
|
}
|
||||||
|
val colors = vm.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()
|
||||||
|
}
|
||||||
|
RowColorPicker("While talking", talking) {
|
||||||
|
talking = it
|
||||||
|
colors.talking = it
|
||||||
|
vm.clientRowColorsChanged()
|
||||||
|
}
|
||||||
|
RowColorPicker("Muted / away", mutedAway) {
|
||||||
|
mutedAway = it
|
||||||
|
colors.mutedAway = it
|
||||||
|
vm.clientRowColorsChanged()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chooses the icon pack, and brings in TeamSpeak packs from a file. */
|
||||||
|
@Composable
|
||||||
|
private fun IconPackPicker(theme: IconTheme) {
|
||||||
|
val packs by theme.packs.collectAsStateWithLifecycle()
|
||||||
|
val active by theme.active.collectAsStateWithLifecycle()
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var failed by remember { mutableStateOf<String?>(null) }
|
||||||
|
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri != null) scope.launch {
|
||||||
|
val pack = withContext(Dispatchers.IO) { runCatching { theme.import(uri) }.getOrNull() }
|
||||||
|
failed = if (pack == null) "That file is not an icon pack." else null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Picker("Icon pack", packs.map { it to it.name() }, active) { theme.select(it) }
|
||||||
|
LinkRow("Import icon pack", "A TeamSpeak 3 pack (.zip), such as those in the gfx folder of a TeamSpeak 3 install") {
|
||||||
|
importer.launch(arrayOf("application/zip", "application/octet-stream"))
|
||||||
|
}
|
||||||
|
failed?.let { Hint(it) }
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.RowScope
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.RadioButton
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SegmentedButton
|
||||||
|
import androidx.compose.material3.SegmentedButtonDefaults
|
||||||
|
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||||
|
import androidx.compose.material3.Slider
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
/** The width a segment needs for a label of a word or two; narrower screens get a list instead. */
|
||||||
|
private val SEGMENT_WIDTH = 110.dp
|
||||||
|
|
||||||
|
/** A full-screen page with a back arrow; the system back gesture leaves it the same way. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
internal fun SubScreen(
|
||||||
|
title: String,
|
||||||
|
onBack: () -> Unit,
|
||||||
|
actions: @Composable RowScope.() -> Unit = {},
|
||||||
|
snackbar: SnackbarHostState? = null,
|
||||||
|
content: @Composable (PaddingValues) -> Unit,
|
||||||
|
) {
|
||||||
|
BackHandler(onBack = onBack)
|
||||||
|
Scaffold(
|
||||||
|
snackbarHost = { snackbar?.let { SnackbarHost(it) } },
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
|
||||||
|
actions = actions,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A row that opens another page, or does one thing when tapped. */
|
||||||
|
@Composable
|
||||||
|
internal fun LinkRow(title: String, summary: String?, iconKey: String? = null, onClick: () -> Unit) {
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(title) },
|
||||||
|
supportingContent = summary?.let { { Text(it) } },
|
||||||
|
leadingContent = iconKey?.let { { PackIcon(it, null) } },
|
||||||
|
modifier = Modifier.clickable(onClick = onClick),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Section(title: String) {
|
||||||
|
Text(title, Modifier.padding(start = 16.dp, top = 24.dp, bottom = 4.dp),
|
||||||
|
style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Choice(label: String, selected: Boolean, onSelect: () -> Unit) {
|
||||||
|
Row(Modifier.fillMaxWidth().clickable(onClick = onSelect).padding(horizontal = 16.dp, vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
RadioButton(selected, onClick = onSelect)
|
||||||
|
Text(label, Modifier.padding(start = 8.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of [options] as a row of segments, or as radio buttons where the segments would not fit. */
|
||||||
|
@Composable
|
||||||
|
internal fun <T> Segments(options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {
|
||||||
|
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||||
|
if (maxWidth - 32.dp < SEGMENT_WIDTH * options.size) {
|
||||||
|
Column { for ((value, label) in options) Choice(label, value == selected) { onSelect(value) } }
|
||||||
|
return@BoxWithConstraints
|
||||||
|
}
|
||||||
|
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) {
|
||||||
|
options.forEachIndexed { index, (value, label) ->
|
||||||
|
SegmentedButton(
|
||||||
|
selected = value == selected,
|
||||||
|
onClick = { onSelect(value) },
|
||||||
|
shape = SegmentedButtonDefaults.itemShape(index, options.size),
|
||||||
|
) { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Toggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
|
||||||
|
Row(Modifier.fillMaxWidth().clickable { onChange(!checked) }.padding(horizontal = 16.dp, vertical = 2.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(label, Modifier.weight(1f))
|
||||||
|
Switch(checked, onChange)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Hint(text: String) {
|
||||||
|
Text(text, Modifier.padding(horizontal = 16.dp, vertical = 2.dp),
|
||||||
|
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of [options], shown as its label and picked from a menu. */
|
||||||
|
@Composable
|
||||||
|
internal fun <T> Picker(label: String, options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
Box {
|
||||||
|
Column(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||||
|
Text(label)
|
||||||
|
Text(options.firstOrNull { it.first == selected }?.second ?: "", style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
DropdownMenu(open, { open = false }) {
|
||||||
|
for ((value, text) in options) {
|
||||||
|
DropdownMenuItem({ Text(text) }, onClick = {
|
||||||
|
open = false
|
||||||
|
onSelect(value)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A slider that applies its value once let go of. */
|
||||||
|
@Composable
|
||||||
|
internal fun Level(
|
||||||
|
label: String,
|
||||||
|
value: Float,
|
||||||
|
range: ClosedFloatingPointRange<Float>,
|
||||||
|
format: (Float) -> String,
|
||||||
|
steps: Int = 0,
|
||||||
|
onChange: (Float) -> Unit = {},
|
||||||
|
onDone: (Float) -> Unit,
|
||||||
|
) {
|
||||||
|
var current by remember(value) { mutableFloatStateOf(value) }
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) {
|
||||||
|
Row {
|
||||||
|
Text(label, Modifier.weight(1f))
|
||||||
|
Text(format(current), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
Slider(current, {
|
||||||
|
current = it
|
||||||
|
onChange(it)
|
||||||
|
}, valueRange = range, steps = steps, onValueChangeFinished = { onDone(current) })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.ListItemDefaults
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Slider
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import eu.lixko.ts3j.client.android.ChannelItem
|
||||||
|
import eu.lixko.ts3j.client.android.ClientItem
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactType
|
||||||
|
import eu.lixko.ts3j.client.net.Details
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/** What can be done with a client: the private chat, a poke, a move, their volume, filing them as a contact. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ClientSheet(
|
||||||
|
client: ClientItem,
|
||||||
|
details: Details?,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
away: Boolean,
|
||||||
|
initialVolume: Double,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onMessage: () -> Unit,
|
||||||
|
onPoke: (String) -> Unit,
|
||||||
|
onVolume: (Double) -> Unit,
|
||||||
|
onAway: (Boolean) -> Unit,
|
||||||
|
onAddContact: (ContactType) -> Unit,
|
||||||
|
onEditContact: () -> Unit,
|
||||||
|
onConnectionInfo: () -> Unit,
|
||||||
|
onWhisper: () -> Unit,
|
||||||
|
onAddToWhisperList: () -> Unit,
|
||||||
|
/** Null when the client cannot be moved. */
|
||||||
|
onMove: (() -> Unit)?,
|
||||||
|
/** Null when the client cannot be moved, or is in our channel already. */
|
||||||
|
onMoveToOwnChannel: (() -> Unit)?,
|
||||||
|
/** Null when the sheet was opened from the tree. */
|
||||||
|
onFindInTree: (() -> Unit)?,
|
||||||
|
/** Kicks, bans and groups, as far as we may use them. */
|
||||||
|
moderation: @Composable () -> Unit = {},
|
||||||
|
) {
|
||||||
|
var poking by remember { mutableStateOf(false) }
|
||||||
|
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
|
||||||
|
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
StatusIcon(client.status)
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
// The country's flag goes before the name, as in TeamSpeak's info frame.
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
CountryFlag(client.country)
|
||||||
|
Text(client.name, style = MaterialTheme.typography.titleLarge)
|
||||||
|
}
|
||||||
|
if (client.name != client.nickname) Text(client.nickname, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
if (client.awayMessage.isNotEmpty()) Text(client.awayMessage, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
val viewer = LocalPictureViewer.current
|
||||||
|
val images = LocalServerImages.current
|
||||||
|
Avatar(client.uniqueId, client.avatarFlag, Modifier.clickable(enabled = viewer != null && images != null) {
|
||||||
|
viewer?.invoke(ViewedPicture("avatar_${client.nickname}", ownAvatar = client.self) {
|
||||||
|
images?.avatarData(client.uniqueId, client.avatarFlag)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
|
||||||
|
onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) }
|
||||||
|
Action("INFO", "Connection info", onClick = onConnectionInfo)
|
||||||
|
if (client.self) {
|
||||||
|
Action("AWAY", if (away) "Back" else "Away") { onAway(!away) }
|
||||||
|
moderation()
|
||||||
|
} else {
|
||||||
|
Action("PLAYER_CHAT", "Send message", onClick = onMessage)
|
||||||
|
Action("POKE", "Poke") { poking = true }
|
||||||
|
Action("PLAYER_WHISPER", "Whisper", onClick = onWhisper)
|
||||||
|
Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList)
|
||||||
|
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
|
||||||
|
onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) }
|
||||||
|
moderation()
|
||||||
|
if (client.contactType == null) {
|
||||||
|
Row {
|
||||||
|
Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) }
|
||||||
|
Action("ADD_FOE", "Block", Modifier.weight(1f)) { onAddContact(ContactType.BLOCKED) }
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact)
|
||||||
|
}
|
||||||
|
var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) }
|
||||||
|
Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB",
|
||||||
|
Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium)
|
||||||
|
Slider(
|
||||||
|
volume, { volume = it.roundToInt().toFloat() },
|
||||||
|
Modifier.padding(horizontal = 24.dp),
|
||||||
|
valueRange = -30f..20f,
|
||||||
|
onValueChangeFinished = { onVolume(volume.toDouble()) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (poking) {
|
||||||
|
TextPrompt(
|
||||||
|
title = "Poke ${client.name}",
|
||||||
|
label = "Message",
|
||||||
|
confirm = "Poke",
|
||||||
|
onDismiss = { poking = false },
|
||||||
|
onConfirm = { poking = false; onPoke(it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ChannelSheet(
|
||||||
|
channel: ChannelItem,
|
||||||
|
details: Details?,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
current: Boolean,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onJoin: () -> Unit,
|
||||||
|
onSubscribe: (Boolean) -> Unit,
|
||||||
|
onBookmark: () -> Unit,
|
||||||
|
onWhisper: () -> Unit,
|
||||||
|
onAddToWhisperList: () -> Unit,
|
||||||
|
onFiles: () -> Unit,
|
||||||
|
/** Each null when we may not. */
|
||||||
|
onCreateSub: (() -> Unit)?,
|
||||||
|
onEdit: (() -> Unit)?,
|
||||||
|
onDelete: (() -> Unit)?,
|
||||||
|
) {
|
||||||
|
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
|
||||||
|
Text(channel.name, Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||||
|
style = MaterialTheme.typography.titleLarge)
|
||||||
|
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
|
||||||
|
if (!current) {
|
||||||
|
Action("CHANNEL_SWITCH", "Join", onClick = onJoin)
|
||||||
|
}
|
||||||
|
if (channel.subscribed) {
|
||||||
|
Action("UNSUBSCRIBE_FROM_CHANNEL", "Unsubscribe") { onSubscribe(false) }
|
||||||
|
} else {
|
||||||
|
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
|
||||||
|
}
|
||||||
|
Action("WHISPER", "Whisper", onClick = onWhisper)
|
||||||
|
Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList)
|
||||||
|
Action("FILETRANSFER", "Browse files", onClick = onFiles)
|
||||||
|
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
|
||||||
|
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
|
||||||
|
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
|
||||||
|
onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server's details: its version, who is on it, its welcome message. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ServerSheet(
|
||||||
|
details: Details,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onBookmark: () -> Unit,
|
||||||
|
onBanList: (() -> Unit)?,
|
||||||
|
onCreateChannel: (() -> Unit)?,
|
||||||
|
) {
|
||||||
|
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
|
||||||
|
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
PackIcon("SERVER_GREEN", null)
|
||||||
|
Text(details.title(), style = MaterialTheme.typography.titleLarge)
|
||||||
|
}
|
||||||
|
DetailsSection(details, onLink)
|
||||||
|
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
|
||||||
|
onCreateChannel?.let { Action("CHANNEL_CREATE", "Create channel", onClick = it) }
|
||||||
|
onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifier.fillMaxWidth(), onClick: () -> Unit) {
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(label) },
|
||||||
|
leadingContent = { PackIcon(iconKey, null) },
|
||||||
|
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
|
||||||
|
modifier = modifier.clickable(onClick = onClick).padding(horizontal = 8.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Asks for one line of text. */
|
||||||
|
@Composable
|
||||||
|
fun TextPrompt(
|
||||||
|
title: String,
|
||||||
|
label: String,
|
||||||
|
confirm: String,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onConfirm: (String) -> Unit,
|
||||||
|
initial: String = "",
|
||||||
|
password: Boolean = false,
|
||||||
|
) {
|
||||||
|
var text by remember { mutableStateOf(initial) }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(title) },
|
||||||
|
text = {
|
||||||
|
OutlinedTextField(text, { text = it }, label = { Text(label) }, singleLine = true,
|
||||||
|
visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None)
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(onClick = { onConfirm(text) }) { Text(confirm) } },
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION
|
||||||
|
import android.provider.Settings.canDrawOverlays
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.geometry.CornerRadius
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
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.MicLevel
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.audio.AudioRoute
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioDevice
|
||||||
|
import eu.lixko.ts3j.client.audio.InputLevel
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
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 change(edit: Settings.() -> Unit) {
|
||||||
|
settings.edit()
|
||||||
|
vm.applySettings()
|
||||||
|
}
|
||||||
|
var inputMode by remember { mutableStateOf(settings.inputMode) }
|
||||||
|
var vadMode by remember { mutableStateOf(settings.vadMode) }
|
||||||
|
var agc by remember { mutableStateOf(settings.agc) }
|
||||||
|
var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) }
|
||||||
|
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) }
|
||||||
|
var inputDevice by remember { mutableStateOf(settings.inputDevice) }
|
||||||
|
var outputDevice by remember { mutableStateOf(settings.outputDevice) }
|
||||||
|
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()) }
|
||||||
|
LifecycleStartEffect(Unit) {
|
||||||
|
vm.watchLevel(true)
|
||||||
|
onStopOrDispose { vm.watchLevel(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
SubScreen("Sound Settings", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
|
||||||
|
Section("Devices")
|
||||||
|
DevicePicker("Microphone", inputs, inputDevice) {
|
||||||
|
inputDevice = it
|
||||||
|
change { this.inputDevice = it }
|
||||||
|
}
|
||||||
|
DevicePicker("Speaker", outputs, outputDevice) {
|
||||||
|
outputDevice = it
|
||||||
|
change { this.outputDevice = it }
|
||||||
|
}
|
||||||
|
Picker(
|
||||||
|
"Microphone preset",
|
||||||
|
INPUT_PRESETS.map { (preset, label) ->
|
||||||
|
val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !vm.unprocessedSupported
|
||||||
|
preset to if (unsupported) "$label (not supported here)" else label
|
||||||
|
},
|
||||||
|
route.inputPreset(),
|
||||||
|
) { vm.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)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Transmission")
|
||||||
|
for ((mode, label) in INPUT_MODES) {
|
||||||
|
Choice(label, inputMode == mode) {
|
||||||
|
inputMode = mode
|
||||||
|
change { this.inputMode = mode }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm)
|
||||||
|
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.")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inputMode == Settings.InputMode.VOICE_ACTIVATION) {
|
||||||
|
Section("Voice activation")
|
||||||
|
for ((mode, label) in VAD_MODES) {
|
||||||
|
Choice(label, vadMode == mode) {
|
||||||
|
vadMode = mode
|
||||||
|
change { this.vadMode = mode }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (vadMode != Settings.VadMode.AUTOMATIC) {
|
||||||
|
Level("Volume threshold", settings.vadThresholdDb.toFloat(), -50f..50f, { "${it.roundToInt()}" },
|
||||||
|
onChange = { threshold = it }) {
|
||||||
|
change { vadThresholdDb = it.roundToInt().toDouble() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (vadMode != Settings.VadMode.VOLUME_GATE) {
|
||||||
|
Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
|
||||||
|
change { speechThreshold = it.toDouble() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Processing")
|
||||||
|
val suppression = if (settings.denoise) settings.denoiserLevel + 1 else 0
|
||||||
|
Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(),
|
||||||
|
{ DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) {
|
||||||
|
val step = it.roundToInt()
|
||||||
|
change {
|
||||||
|
denoise = step > 0
|
||||||
|
if (step > 0) denoiserLevel = step - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Toggle("Automatic gain control", agc) {
|
||||||
|
agc = it
|
||||||
|
change { this.agc = it }
|
||||||
|
}
|
||||||
|
if (agc) {
|
||||||
|
Level("Boost quiet speech", settings.agcBoostDb.toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(),
|
||||||
|
{ "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) {
|
||||||
|
change { agcBoostDb = it.roundToInt() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Playback")
|
||||||
|
Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) {
|
||||||
|
change { outputVolume = it.toDouble() }
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Notification sounds")
|
||||||
|
if (packs.isEmpty()) {
|
||||||
|
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)
|
||||||
|
pack = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
|
||||||
|
change { soundVolume = it.toDouble() }
|
||||||
|
}
|
||||||
|
Toggle("Beep when talking while muted", mutedTalkWarning) {
|
||||||
|
mutedTalkWarning = it
|
||||||
|
change { this.mutedTalkWarning = it }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val INPUT_MODES = listOf(
|
||||||
|
Settings.InputMode.VOICE_ACTIVATION to "Voice activation",
|
||||||
|
Settings.InputMode.PUSH_TO_TALK to "Push to talk",
|
||||||
|
Settings.InputMode.CONTINUOUS to "Continuous",
|
||||||
|
)
|
||||||
|
|
||||||
|
private val INPUT_PRESETS = listOf(
|
||||||
|
AudioRoute.InputPreset.VOICE_RECOGNITION to "Voice recognition",
|
||||||
|
AudioRoute.InputPreset.VOICE_COMMUNICATION to "Voice communication",
|
||||||
|
AudioRoute.InputPreset.UNPROCESSED to "Unprocessed",
|
||||||
|
AudioRoute.InputPreset.VOICE_PERFORMANCE to "Voice performance",
|
||||||
|
AudioRoute.InputPreset.GENERIC to "Generic",
|
||||||
|
AudioRoute.InputPreset.CAMCORDER to "Camcorder",
|
||||||
|
)
|
||||||
|
|
||||||
|
private val PRESET_HINTS = mapOf(
|
||||||
|
AudioRoute.InputPreset.VOICE_RECOGNITION to "Little or no processing by the phone; the client's own does the rest.",
|
||||||
|
AudioRoute.InputPreset.VOICE_COMMUNICATION to
|
||||||
|
"The phone's call processing: echo cancellation, noise suppression and gain. Works best with voices played as a call.",
|
||||||
|
AudioRoute.InputPreset.UNPROCESSED to "The raw microphone signal.",
|
||||||
|
AudioRoute.InputPreset.VOICE_PERFORMANCE to "Low latency and no processing, meant for live performance.",
|
||||||
|
AudioRoute.InputPreset.GENERIC to "The phone's default microphone source, with whatever it applies to it.",
|
||||||
|
AudioRoute.InputPreset.CAMCORDER to "Tuned for recording video, often with the rear microphone.",
|
||||||
|
)
|
||||||
|
|
||||||
|
private val USAGES = listOf(
|
||||||
|
AudioRoute.Usage.MEDIA to "As media (Bluetooth stays in high quality)",
|
||||||
|
AudioRoute.Usage.VOICE_COMMUNICATION to "As a call (lets the phone cancel echo)",
|
||||||
|
)
|
||||||
|
|
||||||
|
private val VAD_MODES = listOf(
|
||||||
|
Settings.VadMode.AUTOMATIC to "Automatic",
|
||||||
|
Settings.VadMode.VOLUME_GATE to "Volume gate",
|
||||||
|
Settings.VadMode.HYBRID to "Hybrid",
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 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) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val enabled by vm.pttOverlay.collectAsStateWithLifecycle()
|
||||||
|
val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||||
|
if (canDrawOverlays(context)) vm.setPttOverlay(true)
|
||||||
|
}
|
||||||
|
Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on ->
|
||||||
|
if (!on || canDrawOverlays(context)) vm.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.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Picks a device by its settings id; one that is not plugged in now still shows as chosen. */
|
||||||
|
@Composable
|
||||||
|
private fun DevicePicker(label: String, devices: List<AudioDevice>, selected: String, onSelect: (String) -> Unit) {
|
||||||
|
val options = devices.map { it.id() to it.label() }.let { list ->
|
||||||
|
if (list.any { it.first == selected }) list else list + (selected to "Not connected")
|
||||||
|
}
|
||||||
|
Picker(label, options, selected, onSelect)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The microphone level, lit while it would be sent, with the volume gate's threshold marked. */
|
||||||
|
@Composable
|
||||||
|
private fun LevelMeter(level: MicLevel, thresholdDb: Float?) {
|
||||||
|
val track = MaterialTheme.colorScheme.surfaceVariant
|
||||||
|
val fill = if (level.transmitting) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline
|
||||||
|
val marker = MaterialTheme.colorScheme.onSurface
|
||||||
|
fun fraction(db: Double) =
|
||||||
|
((db - InputLevel.MIN_DB) / (InputLevel.MAX_DB - InputLevel.MIN_DB)).toFloat().coerceIn(0f, 1f)
|
||||||
|
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||||
|
Row {
|
||||||
|
Text("Microphone level", Modifier.weight(1f))
|
||||||
|
if (level.live) Text("${level.db.roundToInt()}", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
Canvas(Modifier.fillMaxWidth().padding(top = 6.dp).height(12.dp)) {
|
||||||
|
val radius = CornerRadius(size.height / 2)
|
||||||
|
drawRoundRect(track, cornerRadius = radius)
|
||||||
|
if (level.live) {
|
||||||
|
drawRoundRect(fill, size = Size(size.width * fraction(level.db), size.height), cornerRadius = radius)
|
||||||
|
}
|
||||||
|
if (thresholdDb != null) {
|
||||||
|
val x = size.width * fraction(thresholdDb.toDouble())
|
||||||
|
drawLine(marker, Offset(x, -2.dp.toPx()), Offset(x, size.height + 2.dp.toPx()), strokeWidth = 2.dp.toPx())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.dynamicDarkColorScheme
|
||||||
|
import androidx.compose.material3.dynamicLightColorScheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
|
||||||
|
/** Colours that mean the same in either theme, as TeamSpeak uses them. */
|
||||||
|
object StatusColors {
|
||||||
|
val talking = Color(0xFF2E9BF0)
|
||||||
|
val muted = Color(0xFFD9443A)
|
||||||
|
val away = Color(0xFF9E8A2E)
|
||||||
|
val friend = Color(0xFF3A9D4A)
|
||||||
|
val blocked = Color(0xFFD9443A)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Links in chat and descriptions: blue, as links are, whatever the wallpaper's colours. */
|
||||||
|
@Composable
|
||||||
|
fun linkColor(): Color = if (isSystemInDarkTheme()) Color(0xFF7AB4FF) else Color(0xFF1A62D0)
|
||||||
|
|
||||||
|
/** Behind every match of the find bar's query, as on the desktop. */
|
||||||
|
@Composable
|
||||||
|
fun findMatchColor(): Color = if (isSystemInDarkTheme()) Color(0xFF5C4E1A) else Color(0xFFFFEBA3)
|
||||||
|
|
||||||
|
/** Behind the match the find bar is on. */
|
||||||
|
@Composable
|
||||||
|
fun findCurrentColor(): Color = if (isSystemInDarkTheme()) Color(0xFF9C6A12) else Color(0xFFFFB84D)
|
||||||
|
|
||||||
|
/** The system's own (wallpaper) colours, which every supported Android version offers. */
|
||||||
|
@Composable
|
||||||
|
fun Ts3Theme(content: @Composable () -> Unit) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val colors = if (isSystemInDarkTheme()) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||||
|
MaterialTheme(colorScheme = colors, content = content)
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.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.config.WhisperList
|
||||||
|
import eu.lixko.ts3j.client.net.Whisper
|
||||||
|
|
||||||
|
/** Says the microphone whispers instead of talking in the channel, until stopped. */
|
||||||
|
@Composable
|
||||||
|
fun WhisperBanner(state: SessionState, onStop: () -> Unit) {
|
||||||
|
val target = state.whisper ?: return
|
||||||
|
Surface(color = MaterialTheme.colorScheme.tertiaryContainer) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
PackIcon("WHISPER", null)
|
||||||
|
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
|
||||||
|
Text("Whispering to $target", maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
style = MaterialTheme.typography.bodyMedium)
|
||||||
|
if (state.whisperNobody) {
|
||||||
|
Text("Nobody there", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextButton(onClick = onStop) { Text("Stop") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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()
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") }
|
||||||
|
DropdownMenu(open, { open = false }) {
|
||||||
|
val replyTo = remember(open) { server.lastWhisperer() }
|
||||||
|
replyTo?.let { client ->
|
||||||
|
DropdownMenuItem({ Text("Reply to ${client.nickname}") }, leadingIcon = { PackIcon("PLAYER_WHISPER", null) },
|
||||||
|
onClick = { open = false; server.whisperToClient(client.id) })
|
||||||
|
}
|
||||||
|
for (list in lists) {
|
||||||
|
DropdownMenuItem({ Text(list.name.ifBlank { "Unnamed" }) },
|
||||||
|
leadingIcon = { PackIcon("ON_WHISPERLIST", null) },
|
||||||
|
enabled = !list.isEmpty,
|
||||||
|
onClick = { open = false; server.setWhisper(Whisper.of(list)) })
|
||||||
|
}
|
||||||
|
if (state.whisper != null) {
|
||||||
|
DropdownMenuItem({ Text("Stop whispering") }, leadingIcon = { PackIcon("WHISPER", null) },
|
||||||
|
onClick = { open = false; server.setWhisper(null) })
|
||||||
|
}
|
||||||
|
if (replyTo != null || lists.isNotEmpty() || state.whisper != null) HorizontalDivider()
|
||||||
|
DropdownMenuItem({ Text("Whisper lists…") }, leadingIcon = { PackIcon("WHISPERLISTS", null) },
|
||||||
|
onClick = { open = false; onManage() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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()
|
||||||
|
var naming by remember { mutableStateOf(false) }
|
||||||
|
if (naming) {
|
||||||
|
TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = {
|
||||||
|
if (it.isNotBlank()) onPick(-1, it.trim()) else onDismiss()
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text("Add $what to") },
|
||||||
|
text = {
|
||||||
|
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||||
|
lists.forEachIndexed { index, list ->
|
||||||
|
ListItem(headlineContent = { Text(list.name.ifBlank { "Unnamed" }) },
|
||||||
|
modifier = Modifier.clickable { onPick(index, "") })
|
||||||
|
}
|
||||||
|
ListItem(headlineContent = { Text("New list…") }, modifier = Modifier.clickable { naming = true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {},
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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()
|
||||||
|
/** The list being edited: its index, -1 for a new one; null on the overview. */
|
||||||
|
var editing by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||||
|
editing?.let { index ->
|
||||||
|
WhisperListScreen(vm, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
SubScreen("Whisper lists", onBack = onBack, actions = {
|
||||||
|
TextButton(onClick = { editing = -1 }) { Text("New") }
|
||||||
|
}) { padding ->
|
||||||
|
if (lists.isEmpty()) {
|
||||||
|
Box(Modifier.padding(padding).fillMaxWidth().padding(24.dp)) {
|
||||||
|
Text("No whisper lists", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
return@SubScreen
|
||||||
|
}
|
||||||
|
LazyColumn(Modifier.padding(padding)) {
|
||||||
|
itemsIndexed(lists) { index, list ->
|
||||||
|
var menu by remember { mutableStateOf(false) }
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(list.name.ifBlank { "Unnamed" }) },
|
||||||
|
supportingContent = { Text(summary(list)) },
|
||||||
|
leadingContent = { PackIcon("ON_WHISPERLIST", null) },
|
||||||
|
trailingContent = {
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "List options") }
|
||||||
|
DropdownMenu(menu, { menu = false }) {
|
||||||
|
DropdownMenuItem({ Text("Whisper") }, enabled = !list.isEmpty, onClick = {
|
||||||
|
menu = false
|
||||||
|
server.setWhisper(Whisper.of(list))
|
||||||
|
onBack()
|
||||||
|
})
|
||||||
|
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; vm.removeWhisperList(index) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.clickable { editing = index },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun summary(list: WhisperList): String {
|
||||||
|
val parts = listOfNotNull(
|
||||||
|
list.channels.size.takeIf { it > 0 }?.let { if (it == 1) "1 channel" else "$it channels" },
|
||||||
|
list.clients.size.takeIf { it > 0 }?.let { if (it == 1) "1 client" else "$it clients" },
|
||||||
|
)
|
||||||
|
return parts.joinToString(", ").ifEmpty { "Empty" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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) {
|
||||||
|
var name by rememberSaveable { mutableStateOf(saved.name) }
|
||||||
|
var list by remember { mutableStateOf(saved.copy()) }
|
||||||
|
val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) }
|
||||||
|
var addingChannel by remember { mutableStateOf(false) }
|
||||||
|
var addingClient by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
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() })
|
||||||
|
onBack()
|
||||||
|
}, enabled = name.isNotBlank()) { Text("Save") }
|
||||||
|
}) { padding ->
|
||||||
|
LazyColumn(Modifier.padding(padding)) {
|
||||||
|
item {
|
||||||
|
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(16.dp), label = { Text("Name") },
|
||||||
|
singleLine = true)
|
||||||
|
}
|
||||||
|
item { Section("Channels") }
|
||||||
|
items(list.channels) { channel ->
|
||||||
|
RemovableRow("CHANNEL_GREEN", channel) { change { channels.remove(channel) } }
|
||||||
|
}
|
||||||
|
item { LinkRow("Add channel…", null, "CHANNEL_CREATE") { addingChannel = true } }
|
||||||
|
item { Section("Clients") }
|
||||||
|
items(list.clients) { client ->
|
||||||
|
RemovableRow("PLAYER_WHISPER", client.nickname.ifBlank { client.uniqueId }) { change { clients.remove(client) } }
|
||||||
|
}
|
||||||
|
item { LinkRow("Add client…", null, "ADD_FRIEND") { addingClient = true } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (addingChannel) {
|
||||||
|
val paths = remember { server.channelPaths().filter { it !in list.channels } }
|
||||||
|
ChoiceDialog("Add channel", paths, { it }, onDismiss = { addingChannel = false }) {
|
||||||
|
addingChannel = false
|
||||||
|
change { channels.add(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (addingClient) {
|
||||||
|
val online = remember { server.clientRefs().filter { c -> list.clients.none { it.uniqueId == c.uniqueId } } }
|
||||||
|
ChoiceDialog("Add client", online, { it.nickname }, onDismiss = { addingClient = false }) {
|
||||||
|
addingClient = false
|
||||||
|
change { clients.add(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun RemovableRow(iconKey: String, label: String, onRemove: () -> Unit) {
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
leadingContent = { PackIcon(iconKey, null) },
|
||||||
|
trailingContent = { IconButton(onClick = onRemove) { Icon(Icons.Default.Close, "Remove") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Picks one of [choices], of the server on screen; says so when it has none. */
|
||||||
|
@Composable
|
||||||
|
private fun <T> ChoiceDialog(title: String, choices: List<T>, label: (T) -> String, onDismiss: () -> Unit, onPick: (T) -> Unit) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(title) },
|
||||||
|
text = {
|
||||||
|
if (choices.isEmpty()) Text("Nothing to add on this server")
|
||||||
|
else LazyColumn(Modifier.heightIn(max = 400.dp)) {
|
||||||
|
items(choices) { choice ->
|
||||||
|
ListItem(headlineContent = { Text(label(choice), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
modifier = Modifier.clickable { onPick(choice) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {},
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Generated by ts3-client/tools/AppIcon.java; the art sits in the adaptive icon's safe zone. -->
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:aapt="http://schemas.android.com/aapt"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="256"
|
||||||
|
android:viewportHeight="256">
|
||||||
|
<group
|
||||||
|
android:scaleX="0.62"
|
||||||
|
android:scaleY="0.62"
|
||||||
|
android:pivotX="128"
|
||||||
|
android:pivotY="128">
|
||||||
|
<path android:pathData="M128,6.9C68.5,6.9 18.3,48.4 16.1,102.2L16.1,102.2C10.2,104.5 6,110.3 6,117L6,139.5C6,148.4 13.2,155.5 22,155.5L25.4,155.5C30.2,172.1 37.8,178.4 50.3,178.4C53.9,178.4 57.9,177.9 62.3,176.9L62.3,176.9C66.7,176.1 71.5,174.8 76.8,173.4L76.8,173.4C78.5,174.8 80.6,175.7 83,175.7C88.2,175.7 92.5,171.4 92.5,166.2C92.5,161 88.2,156.7 83,156.7C78.8,156.7 75.3,159.4 74,163.1L74,163.1C68.7,164.5 64.2,165.7 60.2,166.5L60.2,166.5C56.2,167.3 52.9,167.9 50.1,167.9C42.8,167.9 38.7,164.2 35.4,152.1L35.4,152.1C39.1,149.2 41.5,144.7 41.5,139.5L41.5,117C41.5,110.3 37.4,104.6 31.6,102.2L31.6,102.2C33.7,58.6 75.1,22.3 128,22.3C180.9,22.3 222.3,58.6 224.4,102.2L224.4,102.2C218.6,104.6 214.5,110.3 214.5,117L214.5,139.5C214.5,148.4 221.6,155.5 230.5,155.5L234,155.5C242.8,155.5 250,148.4 250,139.5L250,117C250,110.3 245.8,104.5 239.9,102.2L239.9,102.2C237.7,48.4 187.5,6.9 128,6.9ZM77,43C74.1,44.7 71.4,46.6 68.8,48.6L68.8,48.6C73.3,53.8 79.5,61 83,66.7C88.1,75 92.5,86.6 94.8,92.8C97.2,98.9 97.2,100.5 97.2,103.4C97.2,106.4 93.5,107.4 94.8,110.5C96.2,113.7 101.9,118.4 105.5,122.4C109,126.3 115,131.1 116.2,134.2C117.3,137.4 115,139.7 112.6,141.3C110.2,142.9 103.3,141.5 101.9,143.7C100.6,145.9 104.9,151.4 104.3,154.4C103.8,157 99.7,158.4 98.6,160.7L98.6,160.7C99.1,162 99.4,163.5 99.5,164.9L99.5,164.9C100.7,167 102.3,169.1 101.9,170.9C101.3,173.9 95.2,176.1 94.8,179.2C94.4,182.4 98.2,186.5 99.6,189.9C101,193.2 103.9,196.4 103.1,199.4C102.3,202.3 97.8,205.1 94.8,207.7C91.9,210.2 87.5,211.4 85.4,214.8C83.2,218.1 83,224 81.8,227.8C80.6,231.5 81.2,234.1 78.3,237.3C75.3,240.4 67.6,244.8 64,246.7C60.5,248.7 58.1,248.7 56.9,249.1L199.1,249.1C197.9,248.7 195.5,248.7 192,246.7C188.4,244.8 180.7,240.4 177.7,237.3C174.8,234.1 175.4,231.5 174.2,227.8C173,224 172.8,218.1 170.6,214.8C168.5,211.4 164.1,210.2 161.2,207.7C158.2,205.1 153.7,202.3 152.9,199.4C152.1,196.4 155,193.2 156.4,189.9C157.8,186.5 161.6,182.4 161.2,179.2C160.8,176.1 154.7,173.9 154.1,170.9C153.5,168 158,164.2 157.6,161.5C157.2,158.7 152.3,157.3 151.7,154.4C151.1,151.4 155.4,145.9 154.1,143.7C152.7,141.5 145.8,142.9 143.4,141.3C141,139.7 138.7,137.4 139.8,134.2C141,131.1 147,126.3 150.5,122.4C154.1,118.4 159.8,113.7 161.2,110.5C162.5,107.4 158.8,106.4 158.8,103.4C158.8,100.5 158.8,98.9 161.2,92.8C163.5,86.6 167.9,75 173,66.7C176.5,61 182.7,53.8 187.2,48.6L187.2,48.6C184.6,46.6 181.9,44.7 179,43Z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient
|
||||||
|
android:type="linear"
|
||||||
|
android:startX="0"
|
||||||
|
android:startY="0"
|
||||||
|
android:endX="154"
|
||||||
|
android:endY="256"
|
||||||
|
android:startColor="#FF4FA3FF"
|
||||||
|
android:endColor="#FF2442B8" />
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
</group>
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@android:color/white" />
|
||||||
|
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||||
|
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">TeamSpook TS3j</string>
|
||||||
|
<string name="launcher_name">TS3J</string>
|
||||||
|
<string name="connection_channel">Connection</string>
|
||||||
|
<string name="messages_channel">Private messages</string>
|
||||||
|
<string name="pokes_channel">Pokes</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.library)
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "eu.lixko.ts3j.client.android.audio"
|
||||||
|
compileSdk = 37
|
||||||
|
ndkVersion = "30.0.16248370"
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 33
|
||||||
|
ndk {
|
||||||
|
abiFilters += listOf("arm64-v8a", "x86_64")
|
||||||
|
}
|
||||||
|
externalNativeBuild {
|
||||||
|
cmake {
|
||||||
|
arguments += "-DANDROID_STL=c++_static"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
externalNativeBuild {
|
||||||
|
cmake {
|
||||||
|
path = file("src/main/cpp/CMakeLists.txt")
|
||||||
|
version = "4.1.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
api(project(":core"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.22)
|
||||||
|
project(ts3audio LANGUAGES C CXX)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
|
|
||||||
|
# Oboe and libopus from source, built static into our one library together with a static
|
||||||
|
# libc++, so the app ships a single small .so per ABI.
|
||||||
|
include(FetchContent)
|
||||||
|
FetchContent_Declare(oboe
|
||||||
|
URL https://github.com/google/oboe/archive/refs/tags/1.11.0.tar.gz
|
||||||
|
URL_HASH SHA256=0ccf2110640a2b4489f1c93a404f2978656b434d8c5dc9cb6258f9cc95c79b15)
|
||||||
|
FetchContent_Declare(opus
|
||||||
|
URL https://github.com/xiph/opus/releases/download/v1.5.2/opus-1.5.2.tar.gz
|
||||||
|
URL_HASH SHA256=65c1d2f78b9f2fb20082c38cbe47c951ad5839345876e46941612ee87f9a7ce1)
|
||||||
|
set(OPUS_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)
|
||||||
|
set(OPUS_BUILD_TESTING OFF CACHE BOOL "" FORCE)
|
||||||
|
set(OPUS_BUILD_SHARED_LIBRARY OFF CACHE BOOL "" FORCE)
|
||||||
|
set(OPUS_INSTALL_PKG_CONFIG_MODULE OFF CACHE BOOL "" FORCE)
|
||||||
|
set(OPUS_INSTALL_CMAKE_CONFIG_MODULE OFF CACHE BOOL "" FORCE)
|
||||||
|
FetchContent_MakeAvailable(oboe opus)
|
||||||
|
|
||||||
|
add_library(ts3audio SHARED audio_line.cpp opus_jni.cpp)
|
||||||
|
target_link_libraries(ts3audio PRIVATE oboe opus log)
|
||||||
|
target_compile_options(ts3audio PRIVATE -Wall -Wextra)
|
||||||
|
|
||||||
|
# Only the JNI entry points are exported; everything else may be dropped.
|
||||||
|
set_target_properties(ts3audio PROPERTIES CXX_VISIBILITY_PRESET hidden C_VISIBILITY_PRESET hidden)
|
||||||
|
foreach(lib oboe opus)
|
||||||
|
target_compile_options(${lib} PRIVATE -ffunction-sections -fdata-sections)
|
||||||
|
endforeach()
|
||||||
|
target_link_options(ts3audio PRIVATE -Wl,--gc-sections -Wl,--exclude-libs,ALL)
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
// An Oboe stream behind the blocking read/write interface of AudioCapture and AudioPlayback.
|
||||||
|
//
|
||||||
|
// The real-time callback never waits and never calls into Java: it only moves samples
|
||||||
|
// between the device and a lock-free ring, which the Java side fills or drains at its own
|
||||||
|
// pace, blocking while the ring is full (playback) or short (capture).
|
||||||
|
|
||||||
|
#include <jni.h>
|
||||||
|
#include <oboe/Oboe.h>
|
||||||
|
#include <android/log.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstring>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr int32_t kSampleRate = 48000;
|
||||||
|
constexpr int32_t kFrameSize = 960; // 20 ms
|
||||||
|
// Capture keeps some slack for a Java thread that is briefly late; playback keeps little,
|
||||||
|
// since everything queued is latency.
|
||||||
|
constexpr int32_t kCaptureFrames = 8;
|
||||||
|
constexpr int32_t kPlaybackFrames = 3;
|
||||||
|
constexpr auto kPollInterval = std::chrono::milliseconds(1);
|
||||||
|
|
||||||
|
const char *kTag = "ts3audio";
|
||||||
|
|
||||||
|
/** Single-producer, single-consumer ring of 16-bit samples. */
|
||||||
|
class SampleRing {
|
||||||
|
public:
|
||||||
|
explicit SampleRing(size_t capacity) : buffer_(capacity) {}
|
||||||
|
|
||||||
|
size_t available() const {
|
||||||
|
return head_.load(std::memory_order_acquire) - tail_.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t space() const { return buffer_.size() - available(); }
|
||||||
|
|
||||||
|
/** Producer side: stores as much of {@code data} as fits. */
|
||||||
|
size_t write(const int16_t *data, size_t count) {
|
||||||
|
size_t head = head_.load(std::memory_order_relaxed);
|
||||||
|
size_t tail = tail_.load(std::memory_order_acquire);
|
||||||
|
size_t n = std::min(count, buffer_.size() - (head - tail));
|
||||||
|
for (size_t i = 0; i < n; i++) buffer_[(head + i) % buffer_.size()] = data[i];
|
||||||
|
head_.store(head + n, std::memory_order_release);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Consumer side: takes up to {@code count} samples. */
|
||||||
|
size_t read(int16_t *data, size_t count) {
|
||||||
|
size_t tail = tail_.load(std::memory_order_relaxed);
|
||||||
|
size_t head = head_.load(std::memory_order_acquire);
|
||||||
|
size_t n = std::min(count, head - tail);
|
||||||
|
for (size_t i = 0; i < n; i++) data[i] = buffer_[(tail + i) % buffer_.size()];
|
||||||
|
tail_.store(tail + n, std::memory_order_release);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<int16_t> buffer_;
|
||||||
|
std::atomic<size_t> head_{0};
|
||||||
|
std::atomic<size_t> tail_{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
class AudioLine : public oboe::AudioStreamDataCallback, public oboe::AudioStreamErrorCallback {
|
||||||
|
public:
|
||||||
|
/** {@code preset} is the input preset of a capture line, {@code usage} a playback line's usage. */
|
||||||
|
AudioLine(bool input, int32_t deviceId, int32_t channels, int32_t preset, int32_t usage)
|
||||||
|
: input_(input), deviceId_(deviceId), channels_(channels), preset_(preset), usage_(usage),
|
||||||
|
ring_(static_cast<size_t>(kFrameSize) * channels * (input ? kCaptureFrames : kPlaybackFrames)) {}
|
||||||
|
|
||||||
|
int32_t channels() const { return channels_; }
|
||||||
|
|
||||||
|
oboe::Result open() {
|
||||||
|
oboe::AudioStreamBuilder builder;
|
||||||
|
builder.setDirection(input_ ? oboe::Direction::Input : oboe::Direction::Output)
|
||||||
|
->setSharingMode(oboe::SharingMode::Shared)
|
||||||
|
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
|
||||||
|
->setFormat(oboe::AudioFormat::I16)
|
||||||
|
->setFormatConversionAllowed(true)
|
||||||
|
->setChannelCount(channels_)
|
||||||
|
->setChannelConversionAllowed(true)
|
||||||
|
->setSampleRate(kSampleRate)
|
||||||
|
->setSampleRateConversionQuality(oboe::SampleRateConversionQuality::Medium)
|
||||||
|
->setDataCallback(this)
|
||||||
|
->setErrorCallback(this);
|
||||||
|
int32_t deviceId = deviceId_.load();
|
||||||
|
if (deviceId > 0) builder.setDeviceId(deviceId);
|
||||||
|
if (input_) {
|
||||||
|
builder.setInputPreset(static_cast<oboe::InputPreset>(preset_.load()));
|
||||||
|
} else {
|
||||||
|
builder.setUsage(static_cast<oboe::Usage>(usage_.load()))->setContentType(oboe::ContentType::Speech);
|
||||||
|
}
|
||||||
|
std::shared_ptr<oboe::AudioStream> stream;
|
||||||
|
oboe::Result result = builder.openStream(stream);
|
||||||
|
if (result != oboe::Result::OK) return result;
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
if (closing_.load()) { // closed while a reopen was under way
|
||||||
|
stream->close();
|
||||||
|
return oboe::Result::ErrorClosed;
|
||||||
|
}
|
||||||
|
if (stream_) stream_->close(); // a concurrent reopen got there first
|
||||||
|
stream_ = stream;
|
||||||
|
if (started_) result = stream_->requestStart();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
oboe::Result start() {
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
started_ = true;
|
||||||
|
return stream_ ? stream_->requestStart() : oboe::Result::ErrorClosed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Moves the line to another device or configuration; the ring and whoever blocks on it stay. */
|
||||||
|
oboe::Result reopen(int32_t deviceId, int32_t preset, int32_t usage) {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
if (closing_.load()) return oboe::Result::ErrorClosed;
|
||||||
|
if (stream_) {
|
||||||
|
stream_->stop();
|
||||||
|
stream_->close();
|
||||||
|
stream_.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
deviceId_.store(deviceId);
|
||||||
|
preset_.store(preset);
|
||||||
|
usage_.store(usage);
|
||||||
|
return open();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Blocks until {@code count} samples are captured; fewer only once closing. */
|
||||||
|
size_t read(int16_t *data, size_t count) {
|
||||||
|
size_t done = 0;
|
||||||
|
while (done < count && !closing_.load()) {
|
||||||
|
done += ring_.read(data + done, count - done);
|
||||||
|
if (done < count) std::this_thread::sleep_for(kPollInterval);
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Blocks until all samples are queued for playback, or the line closes. */
|
||||||
|
void write(const int16_t *data, size_t count) {
|
||||||
|
size_t done = 0;
|
||||||
|
while (done < count && !closing_.load()) {
|
||||||
|
done += ring_.write(data + done, count - done);
|
||||||
|
if (done < count) std::this_thread::sleep_for(kPollInterval);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void close() {
|
||||||
|
closing_.store(true);
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
if (stream_) {
|
||||||
|
stream_->stop();
|
||||||
|
stream_->close();
|
||||||
|
stream_.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
oboe::DataCallbackResult onAudioReady(oboe::AudioStream *, void *audioData, int32_t numFrames) override {
|
||||||
|
auto *samples = static_cast<int16_t *>(audioData);
|
||||||
|
size_t count = static_cast<size_t>(numFrames) * channels_;
|
||||||
|
if (input_) {
|
||||||
|
ring_.write(samples, count); // a reader that fell behind loses the newest audio
|
||||||
|
} else {
|
||||||
|
size_t played = ring_.read(samples, count);
|
||||||
|
if (played < count) std::memset(samples + played, 0, (count - played) * sizeof(int16_t));
|
||||||
|
}
|
||||||
|
return oboe::DataCallbackResult::Continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The device went away (headset unplugged, route changed): follow onto the new one. */
|
||||||
|
void onErrorAfterClose(oboe::AudioStream *, oboe::Result error) override {
|
||||||
|
if (closing_.load()) return;
|
||||||
|
__android_log_print(ANDROID_LOG_INFO, kTag, "stream closed (%s), reopening",
|
||||||
|
oboe::convertToText(error));
|
||||||
|
deviceId_.store(0);
|
||||||
|
open();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
const bool input_;
|
||||||
|
std::atomic<int32_t> deviceId_;
|
||||||
|
const int32_t channels_;
|
||||||
|
std::atomic<int32_t> preset_;
|
||||||
|
std::atomic<int32_t> usage_;
|
||||||
|
SampleRing ring_;
|
||||||
|
std::atomic<bool> closing_{false};
|
||||||
|
std::mutex mutex_;
|
||||||
|
std::shared_ptr<oboe::AudioStream> stream_;
|
||||||
|
bool started_ = false; // guarded by mutex_
|
||||||
|
};
|
||||||
|
|
||||||
|
AudioLine *line(jlong handle) {
|
||||||
|
return reinterpret_cast<AudioLine *>(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
thread_local std::vector<int16_t> scratch;
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
|
||||||
|
JNIEXPORT jlong JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeOpen(JNIEnv *env, jclass, jboolean input, jint deviceId,
|
||||||
|
jint channels, jint preset, jint usage) {
|
||||||
|
auto *created = new AudioLine(input, deviceId, channels, preset, usage);
|
||||||
|
oboe::Result result = created->open();
|
||||||
|
if (result != oboe::Result::OK) {
|
||||||
|
delete created;
|
||||||
|
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return reinterpret_cast<jlong>(created);
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jint JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeChannels(JNIEnv *, jclass, jlong handle) {
|
||||||
|
return line(handle)->channels();
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeStart(JNIEnv *env, jclass, jlong handle) {
|
||||||
|
oboe::Result result = line(handle)->start();
|
||||||
|
if (result != oboe::Result::OK) {
|
||||||
|
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeReopen(JNIEnv *env, jclass, jlong handle, jint deviceId,
|
||||||
|
jint preset, jint usage) {
|
||||||
|
oboe::Result result = line(handle)->reopen(deviceId, preset, usage);
|
||||||
|
if (result != oboe::Result::OK && result != oboe::Result::ErrorClosed) {
|
||||||
|
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jint JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeRead(JNIEnv *env, jclass, jlong handle, jbyteArray buffer,
|
||||||
|
jint offset, jint length) {
|
||||||
|
size_t samples = static_cast<size_t>(length) / sizeof(int16_t);
|
||||||
|
scratch.resize(samples);
|
||||||
|
size_t read = line(handle)->read(scratch.data(), samples);
|
||||||
|
env->SetByteArrayRegion(buffer, offset, static_cast<jsize>(read * sizeof(int16_t)),
|
||||||
|
reinterpret_cast<const jbyte *>(scratch.data()));
|
||||||
|
return static_cast<jint>(read * sizeof(int16_t));
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeWrite(JNIEnv *env, jclass, jlong handle, jbyteArray buffer,
|
||||||
|
jint offset, jint length) {
|
||||||
|
size_t samples = static_cast<size_t>(length) / sizeof(int16_t);
|
||||||
|
scratch.resize(samples);
|
||||||
|
env->GetByteArrayRegion(buffer, offset, static_cast<jsize>(samples * sizeof(int16_t)),
|
||||||
|
reinterpret_cast<jbyte *>(scratch.data()));
|
||||||
|
line(handle)->write(scratch.data(), samples);
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeClose(JNIEnv *, jclass, jlong handle) {
|
||||||
|
line(handle)->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeDelete(JNIEnv *, jclass, jlong handle) {
|
||||||
|
delete line(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // extern "C"
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
// libopus for NativeOpus: handles are the raw encoder/decoder pointers.
|
||||||
|
|
||||||
|
#include <jni.h>
|
||||||
|
#include <opus.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr int kMaxPacketBytes = 4096;
|
||||||
|
|
||||||
|
void throwOpus(JNIEnv *env, const char *call, int error) {
|
||||||
|
std::string message = std::string(call) + " failed: " + opus_strerror(error);
|
||||||
|
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), message.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
OpusEncoder *encoder(jlong handle) { return reinterpret_cast<OpusEncoder *>(handle); }
|
||||||
|
|
||||||
|
OpusDecoder *decoder(jlong handle) { return reinterpret_cast<OpusDecoder *>(handle); }
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
|
||||||
|
JNIEXPORT jlong JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels,
|
||||||
|
jint application) {
|
||||||
|
int error = OPUS_OK;
|
||||||
|
OpusEncoder *created = opus_encoder_create(sampleRate, channels, application, &error);
|
||||||
|
if (error != OPUS_OK) {
|
||||||
|
throwOpus(env, "opus_encoder_create", error);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return reinterpret_cast<jlong>(created);
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderCtl(JNIEnv *env, jclass, jlong handle, jint request,
|
||||||
|
jint value) {
|
||||||
|
int result = opus_encoder_ctl(encoder(handle), request, value);
|
||||||
|
if (result < 0) throwOpus(env, "opus_encoder_ctl", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jbyteArray JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encode(JNIEnv *env, jclass, jlong handle, jfloatArray pcm,
|
||||||
|
jint frameSize) {
|
||||||
|
unsigned char packet[kMaxPacketBytes];
|
||||||
|
jfloat *samples = env->GetFloatArrayElements(pcm, nullptr);
|
||||||
|
int length = opus_encode_float(encoder(handle), samples, frameSize, packet, kMaxPacketBytes);
|
||||||
|
env->ReleaseFloatArrayElements(pcm, samples, JNI_ABORT);
|
||||||
|
if (length < 0) {
|
||||||
|
throwOpus(env, "opus_encode_float", length);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
jbyteArray out = env->NewByteArray(length);
|
||||||
|
env->SetByteArrayRegion(out, 0, length, reinterpret_cast<const jbyte *>(packet));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderDestroy(JNIEnv *, jclass, jlong handle) {
|
||||||
|
opus_encoder_destroy(encoder(handle));
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jlong JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels) {
|
||||||
|
int error = OPUS_OK;
|
||||||
|
OpusDecoder *created = opus_decoder_create(sampleRate, channels, &error);
|
||||||
|
if (error != OPUS_OK) {
|
||||||
|
throwOpus(env, "opus_decoder_create", error);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return reinterpret_cast<jlong>(created);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes {@code packet}, or conceals {@code frameSize} samples when it is null; with {@code fec},
|
||||||
|
* rebuilds the packet before {@code packet} from its error correction copy.
|
||||||
|
*/
|
||||||
|
JNIEXPORT jint JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decode(JNIEnv *env, jclass, jlong handle, jbyteArray packet,
|
||||||
|
jfloatArray out, jint frameSize, jboolean fec) {
|
||||||
|
std::vector<unsigned char> data;
|
||||||
|
if (packet != nullptr) {
|
||||||
|
data.resize(static_cast<size_t>(env->GetArrayLength(packet)));
|
||||||
|
env->GetByteArrayRegion(packet, 0, static_cast<jsize>(data.size()), reinterpret_cast<jbyte *>(data.data()));
|
||||||
|
}
|
||||||
|
jfloat *samples = env->GetFloatArrayElements(out, nullptr);
|
||||||
|
int decoded = opus_decode_float(decoder(handle), packet != nullptr ? data.data() : nullptr,
|
||||||
|
static_cast<opus_int32>(data.size()), samples, frameSize, fec ? 1 : 0);
|
||||||
|
env->ReleaseFloatArrayElements(out, samples, decoded < 0 ? JNI_ABORT : 0);
|
||||||
|
if (decoded < 0) throwOpus(env, "opus_decode_float", decoded);
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderReset(JNIEnv *, jclass, jlong handle) {
|
||||||
|
opus_decoder_ctl(decoder(handle), OPUS_RESET_STATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderDestroy(JNIEnv *, jclass, jlong handle) {
|
||||||
|
opus_decoder_destroy(decoder(handle));
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT jstring JNICALL
|
||||||
|
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_version0(JNIEnv *env, jclass) {
|
||||||
|
return env->NewStringUTF(opus_get_version_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
} // extern "C"
|
||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.audio;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioBackend;
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioIo;
|
||||||
|
import eu.lixko.ts3j.client.audio.StreamingVoiceOutput;
|
||||||
|
import eu.lixko.ts3j.client.audio.opus.OpusCodec;
|
||||||
|
|
||||||
|
/** Android's audio stack: Oboe for the devices, libopus built with the NDK. */
|
||||||
|
public final class AndroidAudioBackend implements AudioBackend {
|
||||||
|
|
||||||
|
private final AndroidAudioIo io;
|
||||||
|
private final OpusCodec opus = new NativeOpus();
|
||||||
|
|
||||||
|
public AndroidAudioBackend(Context context) {
|
||||||
|
this.io = new AndroidAudioIo(context.getApplicationContext());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AudioIo io() {
|
||||||
|
return io;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How the lines meet Android's audio: microphone preset, and media or call playback. */
|
||||||
|
public AudioRoute route() {
|
||||||
|
return io.route();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies at once to the lines that are open. */
|
||||||
|
public void setRoute(AudioRoute route) {
|
||||||
|
io.setRoute(route);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the device offers {@link AudioRoute.InputPreset#UNPROCESSED} truly unprocessed. */
|
||||||
|
public boolean unprocessedSupported() {
|
||||||
|
return io.unprocessedSupported();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs on the main thread whenever an audio device comes or goes. */
|
||||||
|
public void addDeviceListener(Runnable listener) {
|
||||||
|
io.addDeviceListener(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public OpusCodec opus() {
|
||||||
|
return opus;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One low-latency stream for everyone, as mobile audio wants. */
|
||||||
|
@Override
|
||||||
|
public StreamingVoiceOutput.Lines outputLines() {
|
||||||
|
return StreamingVoiceOutput.Lines.SHARED;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String description() {
|
||||||
|
return "Opus " + opus.version() + ", Oboe";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.audio;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.media.AudioDeviceCallback;
|
||||||
|
import android.media.AudioDeviceInfo;
|
||||||
|
import android.media.AudioManager;
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.Looper;
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioCapture;
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioDevice;
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioIo;
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioPlayback;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The device's microphones and speakers, opened through Oboe.
|
||||||
|
*
|
||||||
|
* <p>Android's device ids are handed out anew whenever a device appears, so a Bluetooth
|
||||||
|
* headset has another one each time it reconnects. What the settings keep is the device's
|
||||||
|
* type and address instead, which stay the same, and each open looks the id up.
|
||||||
|
*
|
||||||
|
* <p>Also owns the phone's call state: communication mode and the communication device are
|
||||||
|
* only set while a line needs them, i.e. playback as a call or a headset microphone.
|
||||||
|
*/
|
||||||
|
final class AndroidAudioIo implements AudioIo {
|
||||||
|
|
||||||
|
/** AudioDeviceInfo.TYPE_ECHO_REFERENCE, which the SDK keeps as a system API. */
|
||||||
|
private static final int TYPE_ECHO_REFERENCE = 28;
|
||||||
|
|
||||||
|
private final AudioManager audioManager;
|
||||||
|
private final Set<OboeLine> open = ConcurrentHashMap.newKeySet();
|
||||||
|
/** Reopening streams takes a moment; it happens off the caller's thread, one at a time. */
|
||||||
|
private final ExecutorService reopener = Executors.newSingleThreadExecutor(r -> {
|
||||||
|
Thread t = new Thread(r, "audio-reopen");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
private final List<Runnable> deviceListeners = new ArrayList<>();
|
||||||
|
private volatile AudioRoute route = AudioRoute.DEFAULT;
|
||||||
|
/** Whether this class put the phone into communication mode, and so must take it out. */
|
||||||
|
private boolean inCall;
|
||||||
|
/** The line being opened, which counts towards the call before it exists; null when none is. */
|
||||||
|
private String openingDevice;
|
||||||
|
private boolean openingInput;
|
||||||
|
|
||||||
|
AndroidAudioIo(Context context) {
|
||||||
|
this.audioManager = context.getSystemService(AudioManager.class);
|
||||||
|
audioManager.registerAudioDeviceCallback(new AudioDeviceCallback() {
|
||||||
|
@Override
|
||||||
|
public void onAudioDevicesAdded(AudioDeviceInfo[] added) {
|
||||||
|
returnToDevices(added);
|
||||||
|
notifyDevices();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAudioDevicesRemoved(AudioDeviceInfo[] removed) {
|
||||||
|
notifyDevices();
|
||||||
|
}
|
||||||
|
}, new Handler(Looper.getMainLooper()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- devices ----
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AudioDevice> inputDevices() {
|
||||||
|
return devices(AudioManager.GET_DEVICES_INPUTS, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AudioDevice> outputDevices() {
|
||||||
|
return devices(AudioManager.GET_DEVICES_OUTPUTS, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs on the main thread whenever a device comes or goes. */
|
||||||
|
void addDeviceListener(Runnable listener) {
|
||||||
|
synchronized (deviceListeners) {
|
||||||
|
deviceListeners.add(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyDevices() {
|
||||||
|
synchronized (deviceListeners) {
|
||||||
|
for (Runnable listener : deviceListeners) listener.run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AudioDevice> devices(int flags, boolean input) {
|
||||||
|
Map<String, AudioDevice> out = new LinkedHashMap<>();
|
||||||
|
out.put(AudioDevice.DEFAULT.id(), AudioDevice.DEFAULT);
|
||||||
|
for (AudioDeviceInfo info : audioManager.getDevices(flags)) {
|
||||||
|
String label = label(info, input);
|
||||||
|
if (label != null) out.putIfAbsent(key(info), new AudioDevice(key(info), label));
|
||||||
|
}
|
||||||
|
return new ArrayList<>(out.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the settings store for a device. */
|
||||||
|
private static String key(AudioDeviceInfo info) {
|
||||||
|
return info.getType() + ":" + info.getAddress();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The device's current id, or 0 to let the system choose when it is not there. */
|
||||||
|
private int resolve(String device, int flags) {
|
||||||
|
if (device == null || device.isEmpty()) return 0;
|
||||||
|
for (AudioDeviceInfo info : audioManager.getDevices(flags)) {
|
||||||
|
if (key(info).equals(device)) return info.getId();
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int flags(OboeLine line) {
|
||||||
|
return line.isInput() ? AudioManager.GET_DEVICES_INPUTS : AudioManager.GET_DEVICES_OUTPUTS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A picked device that dropped out took its lines to the default; bring them back. */
|
||||||
|
private void returnToDevices(AudioDeviceInfo[] added) {
|
||||||
|
for (AudioDeviceInfo info : added) {
|
||||||
|
for (OboeLine line : open) {
|
||||||
|
if (key(info).equals(line.device) && info.isSource() == line.isInput()) {
|
||||||
|
reopen(line, info.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- lines ----
|
||||||
|
|
||||||
|
AudioRoute route() {
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes on a new route, moving the lines it concerns over at once. */
|
||||||
|
void setRoute(AudioRoute newRoute) {
|
||||||
|
AudioRoute old = route;
|
||||||
|
route = newRoute;
|
||||||
|
synchronized (this) {
|
||||||
|
updateCall();
|
||||||
|
}
|
||||||
|
for (OboeLine line : open) {
|
||||||
|
boolean affected = line.isInput()
|
||||||
|
? old.inputPreset() != newRoute.inputPreset()
|
||||||
|
: old.usage() != newRoute.usage();
|
||||||
|
if (affected) reopen(line, resolve(line.device, flags(line)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void reopen(OboeLine line, int deviceId) {
|
||||||
|
reopener.execute(() -> {
|
||||||
|
try {
|
||||||
|
line.reopen(deviceId, route);
|
||||||
|
} catch (IllegalStateException ignored) {
|
||||||
|
// The stream could not come back on those terms; the line reads silence until closed.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AudioCapture openCapture(String deviceId, int preferredChannels) {
|
||||||
|
opening(true, deviceId);
|
||||||
|
try {
|
||||||
|
return register(OboeLine.capture(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_INPUTS),
|
||||||
|
preferredChannels, route, this::closed));
|
||||||
|
} finally {
|
||||||
|
opened();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AudioPlayback openPlayback(String deviceId, int preferredChannels) {
|
||||||
|
opening(false, deviceId);
|
||||||
|
try {
|
||||||
|
return register(OboeLine.playback(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_OUTPUTS),
|
||||||
|
preferredChannels, route, this::closed));
|
||||||
|
} finally {
|
||||||
|
opened();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A stream opens on the call as it will be, so the call is set up for it first. */
|
||||||
|
private synchronized void opening(boolean input, String device) {
|
||||||
|
openingInput = input;
|
||||||
|
openingDevice = device == null ? "" : device;
|
||||||
|
updateCall();
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void opened() {
|
||||||
|
openingDevice = null;
|
||||||
|
updateCall();
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized OboeLine register(OboeLine line) {
|
||||||
|
open.add(line);
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void closed() {
|
||||||
|
open.removeIf(line -> !line.isOpen());
|
||||||
|
updateCall();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Puts the phone into communication mode while a line needs it, pointing the call at
|
||||||
|
* the picked device, and leaves it again once none does.
|
||||||
|
*/
|
||||||
|
private void updateCall() {
|
||||||
|
AudioDeviceInfo headsetMic = null;
|
||||||
|
String output = null;
|
||||||
|
List<String> inputs = new ArrayList<>();
|
||||||
|
for (OboeLine line : open) {
|
||||||
|
if (line.isInput()) inputs.add(line.device);
|
||||||
|
else if (output == null) output = line.device;
|
||||||
|
}
|
||||||
|
if (openingDevice != null) {
|
||||||
|
if (openingInput) inputs.add(openingDevice);
|
||||||
|
else if (output == null) output = openingDevice;
|
||||||
|
}
|
||||||
|
for (String input : inputs) {
|
||||||
|
AudioDeviceInfo mic = find(input, AudioManager.GET_DEVICES_INPUTS);
|
||||||
|
if (mic != null && isHeadsetMic(mic)) headsetMic = mic;
|
||||||
|
}
|
||||||
|
// Held while anything is open, the microphone included: a notification sound coming
|
||||||
|
// and going must not take the phone in and out of a call.
|
||||||
|
boolean call = route.usage() == AudioRoute.Usage.VOICE_COMMUNICATION && (!open.isEmpty() || openingDevice != null);
|
||||||
|
boolean needed = headsetMic != null || call;
|
||||||
|
if (needed && !inCall) {
|
||||||
|
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
|
||||||
|
inCall = true;
|
||||||
|
} else if (!needed && inCall) {
|
||||||
|
audioManager.clearCommunicationDevice();
|
||||||
|
audioManager.setMode(AudioManager.MODE_NORMAL);
|
||||||
|
inCall = false;
|
||||||
|
}
|
||||||
|
if (!needed) return;
|
||||||
|
|
||||||
|
// A headset microphone only works over the headset's call link, so it decides.
|
||||||
|
AudioDeviceInfo target = headsetMic != null
|
||||||
|
? communicationDevice(headsetMic.getAddress(), headsetMic.getType())
|
||||||
|
: communicationDevice(find(output, AudioManager.GET_DEVICES_OUTPUTS));
|
||||||
|
if (target != null) audioManager.setCommunicationDevice(target);
|
||||||
|
else audioManager.clearCommunicationDevice();
|
||||||
|
}
|
||||||
|
|
||||||
|
private AudioDeviceInfo find(String device, int flags) {
|
||||||
|
if (device == null || device.isEmpty()) return null;
|
||||||
|
for (AudioDeviceInfo info : audioManager.getDevices(flags)) {
|
||||||
|
if (key(info).equals(device)) return info;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isHeadsetMic(AudioDeviceInfo info) {
|
||||||
|
return info.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || info.getType() == AudioDeviceInfo.TYPE_BLE_HEADSET;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The communication device that is {@code output}, if calls can go there. */
|
||||||
|
private AudioDeviceInfo communicationDevice(AudioDeviceInfo output) {
|
||||||
|
if (output == null) return null;
|
||||||
|
// Calls cannot go over A2DP; the same headset's call profile can.
|
||||||
|
int type = output.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ? AudioDeviceInfo.TYPE_BLUETOOTH_SCO : output.getType();
|
||||||
|
return communicationDevice(output.getAddress(), type);
|
||||||
|
}
|
||||||
|
|
||||||
|
private AudioDeviceInfo communicationDevice(String address, int inputType) {
|
||||||
|
for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) {
|
||||||
|
if (info.getType() == inputType && info.getAddress().equals(address)) return info;
|
||||||
|
}
|
||||||
|
// Wired and USB headsets, and the built-in microphone, have no address in common with an output.
|
||||||
|
for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) {
|
||||||
|
if (info.getType() == inputType) return info;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean unprocessedSupported() {
|
||||||
|
return "true".equals(audioManager.getProperty(AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How a device is offered in the settings, or null for one no user would pick. */
|
||||||
|
private static String label(AudioDeviceInfo info, boolean input) {
|
||||||
|
String product = info.getProductName() == null ? "" : info.getProductName().toString();
|
||||||
|
String address = info.getAddress();
|
||||||
|
switch (info.getType()) {
|
||||||
|
case AudioDeviceInfo.TYPE_BUILTIN_MIC:
|
||||||
|
return "Phone microphone" + (address.isEmpty() ? "" : " (" + address + ")");
|
||||||
|
case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER:
|
||||||
|
return "Phone speaker";
|
||||||
|
case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE:
|
||||||
|
return "Earpiece";
|
||||||
|
case AudioDeviceInfo.TYPE_WIRED_HEADSET:
|
||||||
|
return input ? "Wired headset microphone" : "Wired headset";
|
||||||
|
case AudioDeviceInfo.TYPE_WIRED_HEADPHONES:
|
||||||
|
return "Wired headphones";
|
||||||
|
case AudioDeviceInfo.TYPE_USB_HEADSET:
|
||||||
|
case AudioDeviceInfo.TYPE_USB_DEVICE:
|
||||||
|
case AudioDeviceInfo.TYPE_USB_ACCESSORY:
|
||||||
|
return product + " (USB)";
|
||||||
|
case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP:
|
||||||
|
return product + " (Bluetooth, media quality)";
|
||||||
|
case AudioDeviceInfo.TYPE_BLUETOOTH_SCO:
|
||||||
|
return product + " (Bluetooth, call quality)";
|
||||||
|
case AudioDeviceInfo.TYPE_BLE_HEADSET:
|
||||||
|
case AudioDeviceInfo.TYPE_BLE_SPEAKER:
|
||||||
|
return product + " (Bluetooth LE)";
|
||||||
|
case AudioDeviceInfo.TYPE_HEARING_AID:
|
||||||
|
return product + " (hearing aid)";
|
||||||
|
case AudioDeviceInfo.TYPE_HDMI:
|
||||||
|
case AudioDeviceInfo.TYPE_HDMI_ARC:
|
||||||
|
case AudioDeviceInfo.TYPE_HDMI_EARC:
|
||||||
|
return "HDMI";
|
||||||
|
case AudioDeviceInfo.TYPE_TELEPHONY:
|
||||||
|
case AudioDeviceInfo.TYPE_REMOTE_SUBMIX:
|
||||||
|
case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE:
|
||||||
|
case TYPE_ECHO_REFERENCE:
|
||||||
|
case AudioDeviceInfo.TYPE_FM_TUNER:
|
||||||
|
case AudioDeviceInfo.TYPE_TV_TUNER:
|
||||||
|
case AudioDeviceInfo.TYPE_BUS:
|
||||||
|
case AudioDeviceInfo.TYPE_BLE_BROADCAST:
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return product.isEmpty() ? "Device " + info.getId() : product;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.audio;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How the app's audio meets Android's: which processing the platform applies to the
|
||||||
|
* microphone, and whether playback is media or a call.
|
||||||
|
*/
|
||||||
|
public record AudioRoute(InputPreset inputPreset, Usage usage) {
|
||||||
|
|
||||||
|
/** The client runs TS3's own processing, so by default the platform adds as little as it can. */
|
||||||
|
public static final AudioRoute DEFAULT = new AudioRoute(InputPreset.VOICE_RECOGNITION, Usage.MEDIA);
|
||||||
|
|
||||||
|
/** Oboe's input presets, which are Android's audio sources. */
|
||||||
|
public enum InputPreset {
|
||||||
|
/** Tuned for speech with light or no processing; what the client expects. */
|
||||||
|
VOICE_RECOGNITION(6),
|
||||||
|
/** The platform's call processing: echo cancellation, noise suppression, gain control. */
|
||||||
|
VOICE_COMMUNICATION(7),
|
||||||
|
/** No processing at all, where the device supports it. */
|
||||||
|
UNPROCESSED(9),
|
||||||
|
/** Low latency and no processing, meant for live performance. */
|
||||||
|
VOICE_PERFORMANCE(10),
|
||||||
|
/** The plain microphone source, with whatever the vendor applies to it. */
|
||||||
|
GENERIC(1),
|
||||||
|
CAMCORDER(5);
|
||||||
|
|
||||||
|
final int oboeValue;
|
||||||
|
|
||||||
|
InputPreset(int oboeValue) {
|
||||||
|
this.oboeValue = oboeValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Oboe's playback usages. */
|
||||||
|
public enum Usage {
|
||||||
|
/** Plays like music: stays on A2DP headphones and leaves the phone out of call mode. */
|
||||||
|
MEDIA(1),
|
||||||
|
/**
|
||||||
|
* Plays as a call: Android goes into communication mode, which is what its echo
|
||||||
|
* canceller works against, and Bluetooth headsets switch to their headset profile.
|
||||||
|
*/
|
||||||
|
VOICE_COMMUNICATION(2);
|
||||||
|
|
||||||
|
final int oboeValue;
|
||||||
|
|
||||||
|
Usage(int oboeValue) {
|
||||||
|
this.oboeValue = oboeValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.audio;
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.audio.opus.CtlOpusEncoder;
|
||||||
|
import eu.lixko.ts3j.client.audio.opus.LibOpus;
|
||||||
|
import eu.lixko.ts3j.client.audio.opus.OpusCodec;
|
||||||
|
import eu.lixko.ts3j.client.audio.opus.OpusDecoder;
|
||||||
|
import eu.lixko.ts3j.client.audio.opus.OpusEncoder;
|
||||||
|
|
||||||
|
/** libopus, built into the app with the NDK. */
|
||||||
|
public final class NativeOpus implements OpusCodec {
|
||||||
|
|
||||||
|
static {
|
||||||
|
System.loadLibrary("ts3audio");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) {
|
||||||
|
return new Encoder(encoderCreate(sampleRate, channels, LibOpus.application(application)), frameSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) {
|
||||||
|
return new Decoder(decoderCreate(sampleRate, channels), maxFrameSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String version() {
|
||||||
|
return version0();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Methods may come from different threads, one at a time, so they only share the handle. */
|
||||||
|
private static final class Encoder extends CtlOpusEncoder {
|
||||||
|
private final int frameSize;
|
||||||
|
private long handle;
|
||||||
|
|
||||||
|
Encoder(long handle, int frameSize) {
|
||||||
|
this.handle = handle;
|
||||||
|
this.frameSize = frameSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected synchronized void ctl(int request, int value) {
|
||||||
|
if (handle != 0) encoderCtl(handle, request, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized byte[] encode(float[] pcm) {
|
||||||
|
if (handle == 0) throw new IllegalStateException("encoder closed");
|
||||||
|
return NativeOpus.encode(handle, pcm, frameSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized void close() {
|
||||||
|
if (handle == 0) return;
|
||||||
|
encoderDestroy(handle);
|
||||||
|
handle = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Decoder implements OpusDecoder {
|
||||||
|
private final int maxFrameSize;
|
||||||
|
private long handle;
|
||||||
|
|
||||||
|
Decoder(long handle, int maxFrameSize) {
|
||||||
|
this.handle = handle;
|
||||||
|
this.maxFrameSize = maxFrameSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int decode(byte[] packet, float[] out) {
|
||||||
|
return NativeOpus.decode(live(), packet, out, maxFrameSize, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int conceal(float[] out, int frameSize) {
|
||||||
|
return NativeOpus.decode(live(), null, out, Math.min(frameSize, maxFrameSize), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int recover(byte[] next, float[] out, int frameSize) {
|
||||||
|
return NativeOpus.decode(live(), next, out, Math.min(frameSize, maxFrameSize), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
if (handle != 0) decoderReset(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (handle == 0) return;
|
||||||
|
decoderDestroy(handle);
|
||||||
|
handle = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long live() {
|
||||||
|
if (handle == 0) throw new IllegalStateException("decoder closed");
|
||||||
|
return handle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static native long encoderCreate(int sampleRate, int channels, int application);
|
||||||
|
|
||||||
|
private static native void encoderCtl(long handle, int request, int value);
|
||||||
|
|
||||||
|
private static native byte[] encode(long handle, float[] pcm, int frameSize);
|
||||||
|
|
||||||
|
private static native void encoderDestroy(long handle);
|
||||||
|
|
||||||
|
private static native long decoderCreate(int sampleRate, int channels);
|
||||||
|
|
||||||
|
private static native int decode(long handle, byte[] packet, float[] out, int frameSize, boolean fec);
|
||||||
|
|
||||||
|
private static native void decoderReset(long handle);
|
||||||
|
|
||||||
|
private static native void decoderDestroy(long handle);
|
||||||
|
|
||||||
|
private static native String version0();
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.audio;
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioCapture;
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioPlayback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An Oboe stream, as either an {@link AudioCapture} or an {@link AudioPlayback}. The native
|
||||||
|
* side keeps a ring between the real-time callback and these blocking calls.
|
||||||
|
*/
|
||||||
|
final class OboeLine implements AudioCapture, AudioPlayback {
|
||||||
|
|
||||||
|
static {
|
||||||
|
System.loadLibrary("ts3audio");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Held across native reads and writes, so {@link #close} never frees a line in use. */
|
||||||
|
private final Object io = new Object();
|
||||||
|
private final int channels;
|
||||||
|
private final boolean input;
|
||||||
|
/** The device as the settings name it, to find it again when the line is reopened. */
|
||||||
|
final String device;
|
||||||
|
private final Runnable onClose;
|
||||||
|
private volatile long handle;
|
||||||
|
|
||||||
|
private OboeLine(boolean input, String device, int deviceId, int channels, AudioRoute route, Runnable onClose) {
|
||||||
|
this.input = input;
|
||||||
|
this.device = device;
|
||||||
|
this.onClose = onClose;
|
||||||
|
this.handle = nativeOpen(input, deviceId, channels, route.inputPreset().oboeValue, route.usage().oboeValue);
|
||||||
|
this.channels = nativeChannels(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
static OboeLine capture(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) {
|
||||||
|
return new OboeLine(true, device, deviceId, channels, route, onClose);
|
||||||
|
}
|
||||||
|
|
||||||
|
static OboeLine playback(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) {
|
||||||
|
return new OboeLine(false, device, deviceId, channels, route, onClose);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isInput() {
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isOpen() {
|
||||||
|
return handle != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Moves the open stream onto {@code deviceId} with {@code route}; readers and writers carry on. */
|
||||||
|
void reopen(int deviceId, AudioRoute route) {
|
||||||
|
long h = handle;
|
||||||
|
if (h != 0) nativeReopen(h, deviceId, route.inputPreset().oboeValue, route.usage().oboeValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int channels() {
|
||||||
|
return channels;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void start() {
|
||||||
|
long h = handle;
|
||||||
|
if (h != 0) nativeStart(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int read(byte[] buffer, int offset, int length) {
|
||||||
|
synchronized (io) {
|
||||||
|
long h = handle;
|
||||||
|
return h == 0 ? 0 : nativeRead(h, buffer, offset, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void write(byte[] buffer, int offset, int length) {
|
||||||
|
synchronized (io) {
|
||||||
|
long h = handle;
|
||||||
|
if (h != 0) nativeWrite(h, buffer, offset, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Oboe has no drain; what is queued is at most a few frames and simply plays out. */
|
||||||
|
@Override
|
||||||
|
public void drain() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
long h = handle;
|
||||||
|
if (h == 0) return;
|
||||||
|
nativeClose(h); // wakes a blocked read or write
|
||||||
|
synchronized (io) {
|
||||||
|
if (handle == 0) return;
|
||||||
|
handle = 0;
|
||||||
|
nativeDelete(h);
|
||||||
|
}
|
||||||
|
onClose.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static native long nativeOpen(boolean input, int deviceId, int channels, int preset, int usage);
|
||||||
|
|
||||||
|
private static native void nativeReopen(long handle, int deviceId, int preset, int usage);
|
||||||
|
|
||||||
|
private static native int nativeChannels(long handle);
|
||||||
|
|
||||||
|
private static native void nativeStart(long handle);
|
||||||
|
|
||||||
|
private static native int nativeRead(long handle, byte[] buffer, int offset, int length);
|
||||||
|
|
||||||
|
private static native void nativeWrite(long handle, byte[] buffer, int offset, int length);
|
||||||
|
|
||||||
|
private static native void nativeClose(long handle);
|
||||||
|
|
||||||
|
private static native void nativeDelete(long handle);
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application) apply false
|
||||||
|
alias(libs.plugins.android.library) apply false
|
||||||
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
plugins {
|
||||||
|
`java-library`
|
||||||
|
}
|
||||||
|
|
||||||
|
val ts3ClientDir: String = providers.gradleProperty("ts3.client.dir")
|
||||||
|
.orElse(providers.environmentVariable("TS3_CLIENT_DIR"))
|
||||||
|
.getOrElse(rootDir.resolve("../TeamSpeak3-Client-linux_amd64").path)
|
||||||
|
|
||||||
|
/** TeamSpeak's own icon packs and country flags, proprietary and so taken from an install, as the desktop's build does. */
|
||||||
|
val teamspeakIconPacks = tasks.register<Sync>("teamspeakIconPacks") {
|
||||||
|
into(layout.buildDirectory.dir("generated/iconPacks"))
|
||||||
|
from(File(ts3ClientDir, "gfx")) {
|
||||||
|
include("default.zip", "default_colored_2014.zip", "default_mono_2014.zip", "countries.zip")
|
||||||
|
into("gfx/teamspeak")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceSets["main"].java.setSrcDirs(listOf(rootDir.resolve("../ts3-client/core/src/main/java")))
|
||||||
|
sourceSets["main"].resources.setSrcDirs(listOf(rootDir.resolve("../ts3-client/core/src/main/resources")))
|
||||||
|
sourceSets["main"].resources.srcDir(teamspeakIconPacks)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType<JavaCompile>().configureEach {
|
||||||
|
options.release = 17
|
||||||
|
options.encoding = "UTF-8"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
api(project(":ts3j"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
plugins {
|
||||||
|
`java-library`
|
||||||
|
}
|
||||||
|
|
||||||
|
// The desktop client's platform code, run on the build machine only: its libopus
|
||||||
|
// encodes the sound packs the app ships (see :app's bundleSoundPacks).
|
||||||
|
java {
|
||||||
|
sourceSets["main"].java.setSrcDirs(listOf(rootDir.resolve("../ts3-client/desktop/src/main/java")))
|
||||||
|
sourceSets["main"].resources.setSrcDirs(listOf(rootDir.resolve("../ts3-client/desktop/src/main/resources")))
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType<JavaCompile>().configureEach {
|
||||||
|
// The FFM API it reaches libopus through; the build has to run on JDK 25 or newer.
|
||||||
|
options.release = 25
|
||||||
|
options.encoding = "UTF-8"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(project(":core"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
|
||||||
|
org.gradle.parallel=true
|
||||||
|
org.gradle.configuration-cache=true
|
||||||
|
android.useAndroidX=true
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[versions]
|
||||||
|
agp = "9.4.1"
|
||||||
|
kotlin = "2.4.20"
|
||||||
|
composeBom = "2026.09.00"
|
||||||
|
activityCompose = "1.13.0"
|
||||||
|
lifecycle = "2.11.0"
|
||||||
|
bouncycastle = "1.86"
|
||||||
|
ini4j = "0.5.1"
|
||||||
|
androidsvg = "1.4"
|
||||||
|
|
||||||
|
[libraries]
|
||||||
|
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
|
||||||
|
androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" }
|
||||||
|
androidx-compose-material3 = { module = "androidx.compose.material3:material3" }
|
||||||
|
androidx-compose-material-icons = { module = "androidx.compose.material:material-icons-extended" }
|
||||||
|
androidx-compose-ui = { module = "androidx.compose.ui:ui" }
|
||||||
|
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
|
||||||
|
androidx-lifecycle-service = { module = "androidx.lifecycle:lifecycle-service", version.ref = "lifecycle" }
|
||||||
|
androidsvg = { module = "com.caverock:androidsvg-aar", version.ref = "androidsvg" }
|
||||||
|
bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
|
||||||
|
ini4j = { module = "org.ini4j:ini4j", version.ref = "ini4j" }
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
android-library = { id = "com.android.library", version.ref = "agp" }
|
||||||
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1,9 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
retries=0
|
||||||
|
retryBackOffMs=500
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# gradlew start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh gradlew
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+112
@@ -0,0 +1,112 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem gradlew startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||||
|
setlocal EnableExtensions
|
||||||
|
|
||||||
|
@rem Catch executions from older scripts and ensure they exit cleanly.
|
||||||
|
@rem This can be removed once we can be reasonably confident that few people
|
||||||
|
@rem will be migrating directly to this new wrapper.
|
||||||
|
goto afterSafetyNet
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||||
|
goto exitWithErrorLevel
|
||||||
|
:afterSafetyNet
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
1>&2 echo.
|
||||||
|
1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
1>&2 echo.
|
||||||
|
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
1>&2 echo location of your Java installation.
|
||||||
|
|
||||||
|
"%COMSPEC%" /c exit 1
|
||||||
|
goto exitWithErrorLevel
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
1>&2 echo.
|
||||||
|
1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||||
|
1>&2 echo.
|
||||||
|
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
1>&2 echo location of your Java installation.
|
||||||
|
|
||||||
|
"%COMSPEC%" /c exit 1
|
||||||
|
goto exitWithErrorLevel
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute gradlew
|
||||||
|
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||||
|
@rem which allows us to clear the local environment before executing the java command
|
||||||
|
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
|
||||||
|
|
||||||
|
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
|
||||||
|
:exitWithErrorLevel
|
||||||
|
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||||
|
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "ts3-android"
|
||||||
|
|
||||||
|
// core, ts3j and desktop compile the very sources the desktop's Maven build does.
|
||||||
|
include(":ts3j", ":core", ":desktop", ":audio", ":app")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
plugins {
|
||||||
|
`java-library`
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceSets["main"].java.setSrcDirs(listOf(rootDir.resolve("../ts3j/src/main/java")))
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType<JavaCompile>().configureEach {
|
||||||
|
options.release = 17
|
||||||
|
options.encoding = "UTF-8"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Android ships a BouncyCastle of its own, but under a different package, so they never meet.
|
||||||
|
api(libs.bouncycastle)
|
||||||
|
api(libs.ini4j)
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# Codebase audit — ts3-client
|
||||||
|
|
||||||
|
First audit: 2026-09-11. Revisited and worked through: 2026-09-25. Every finding below was
|
||||||
|
either fixed (commit given) or closed with a reason. Logging (§3) was left out on purpose.
|
||||||
|
|
||||||
|
State after the fixes: `mvn -o test` passes (177 tests: 25 in ts3j, 135 core, 11 desktop,
|
||||||
|
6 swing), on Java 25 and 26. The Android release build (R8 over core and ts3j) passes. The
|
||||||
|
Swing client was run against the test server on Java 25: it connected, loaded the tree and
|
||||||
|
chat logs, and wrote its profile owner-only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Fixed
|
||||||
|
|
||||||
|
### Tests and build
|
||||||
|
| Finding | Commit |
|
||||||
|
|---|---|
|
||||||
|
| The importer test failed on every run after the first. The cause was not the real profile: the POM already points `user.home` at `target/test-home`, but that folder outlives a run, so the first run's identity was still there | `ba5de5a` |
|
||||||
|
| The ts3j DNS test resolved `voice.teamspeak.com` for real and failed when DNS did not answer | ts3j `Test SRV lookup…`, `acb3efa` |
|
||||||
|
| README architecture and features out of date | `51f19c2` |
|
||||||
|
| Java 26 required for no reason; it now needs 25 (LTS), and builds, tests and runs on it | `85c3ae6` |
|
||||||
|
| Missing tests: channel tree, event handler, settings round-trip and migration | `71ac2c8` |
|
||||||
|
|
||||||
|
### Connection lifecycle and threading
|
||||||
|
| Finding | Commit |
|
||||||
|
|---|---|
|
||||||
|
| An action racing a disconnect showed `NullPointerException` as the error; 20 raw threads. Actions now capture the socket and run on a pool that lives as long as the connection | `f350b19` |
|
||||||
|
| `connect()` on a live instance leaked socket and audio; fields shared across threads were not volatile | `d28bb57` |
|
||||||
|
| Permission errors were recognised by substring; now by the server's error id | `d074ffa` |
|
||||||
|
| `HotkeyEngine` locked on another class's list; `Hotkeys.all()` now returns a snapshot | `5b1809c` |
|
||||||
|
| Two quick tab switches could interleave the microphone hand-over | `665316d` |
|
||||||
|
| `MainFrame` was also the app controller: microphone ownership, push-to-talk, away and nickname fan-out moved to `core/session/Sessions` | `bf07f0b` |
|
||||||
|
|
||||||
|
### Model and events
|
||||||
|
| Finding | Commit |
|
||||||
|
|---|---|
|
||||||
|
| `buildTree()` refilled lists shared with the UI; node fields not volatile. Lists are now published whole and unmodifiable. Whether a channel is full is counted from the model | `67f8f46` |
|
||||||
|
| `selfPermissionValue` scanned every permission; `primaryServerGroupName` unused | `8c735a0` |
|
||||||
|
| A cleared avatar, description or away message was ignored | `7cb4f47` |
|
||||||
|
|
||||||
|
### Voice
|
||||||
|
| Finding | Commit |
|
||||||
|
|---|---|
|
||||||
|
| Fixed 60 ms jitter delay instead of TS3's adaptive buffer. The stashed libspeex port is now in `VoiceStream`, driven as TS3 drives it. A simulated 0–60 ms jitter stops concealing after about 3 s | `0083dc8` |
|
||||||
|
| A playback line kept open for every client that ever spoke | `6234ec6` |
|
||||||
|
| A dead playback line silently muted its speaker for the whole session | `12ca585` |
|
||||||
|
| `CaptureVoiceInput.stop()` tore down while the capture loop was still running | `8e9c461` |
|
||||||
|
|
||||||
|
### Chat logs
|
||||||
|
| Finding | Commit |
|
||||||
|
|---|---|
|
||||||
|
| Multi-line messages lost their continuation lines in history | `f9b2f4d` |
|
||||||
|
| History read whole, ever-growing logs; now the last 4 MiB | `a5c4ba1` |
|
||||||
|
| `appendPrivateMessage` duplicated `appendMessage` | `1a3a3e3` |
|
||||||
|
| Logs could not be turned off or moved (new Options → Chat page) | `d7261c9` |
|
||||||
|
| Chat logs only worked with admin rights: the server id came from `serverinfo`, which guests may not use. It turned out to be base64(SHA-1(the server's handshake key)), as the official client derives it. Found while checking the "`serverUniqueId` fallbacks can go" finding | ts3j `Derive the server's unique id…`, `eeccb49` |
|
||||||
|
|
||||||
|
### Persistence, file transfers, UI
|
||||||
|
| Finding | Commit |
|
||||||
|
|---|---|
|
||||||
|
| Profile files (private keys, server passwords) readable by everyone, and truncated by a crash mid-write. Now written privately and atomically, and the profile folder is owner-only | `3cdade9` |
|
||||||
|
| Three copies of the enum parser in `Settings` | `48a0032` |
|
||||||
|
| A stalled file server hung a download forever | `ae8d1f7` |
|
||||||
|
| Collapsed channels reopened on every tree rebuild | `f30cecf` |
|
||||||
|
|
||||||
|
## 2. Closed without a change, or still open
|
||||||
|
|
||||||
|
- **Chat-log folders "may contain `/`"**: they cannot. The value encoded is itself Base64 text,
|
||||||
|
and no 6-bit group of such bytes reaches 62 or 63, the codes for `+` and `/`.
|
||||||
|
- **`rootMessage()` hides the command**: every caller names the action in front of it.
|
||||||
|
- **Not tested:** `TeamspeakConnection`'s lifecycle against a fake socket (the smoke test
|
||||||
|
above covers connect only); the idle release and dead-line replacement in
|
||||||
|
`PerSpeakerPlayout`; the jitter buffer with real voice from another client.
|
||||||
|
- **`git stash@{0}`** ("jitter buffer test") is now fully ported, except FEC decoding (TS3
|
||||||
|
does not use FEC either). It can be dropped.
|
||||||
|
|
||||||
|
## 3. Left out on purpose
|
||||||
|
|
||||||
|
- **Logging.** There are still 60 swallowed exceptions and no log output.
|
||||||
+178
-58
@@ -1,4 +1,4 @@
|
|||||||
# TS3J Client
|
# TeamSpook TS3j
|
||||||
|
|
||||||
A desktop TeamSpeak 3 client built on top of the [`ts3j`](../ts3j) reverse-engineered
|
A desktop TeamSpeak 3 client built on top of the [`ts3j`](../ts3j) reverse-engineered
|
||||||
TS3 protocol library. It looks and behaves like the official TS3 client and focuses
|
TS3 protocol library. It looks and behaves like the official TS3 client and focuses
|
||||||
@@ -10,13 +10,14 @@ TeaVM/CheerpJ) without touching the library:
|
|||||||
|
|
||||||
| Module | Artifact | Responsibility |
|
| Module | Artifact | Responsibility |
|
||||||
|--------|----------|----------------|
|
|--------|----------|----------------|
|
||||||
| `core` | `ts3-client-core` | Frontend-agnostic library: protocol integration, server model, connection orchestration, audio **abstractions**. No UI, no platform audio, no native code. |
|
| `core` | `ts3-client-core` | Frontend-agnostic library: protocol integration, server model, connection orchestration, the voice pipelines and their DSP. No UI, no platform audio API, no native code. |
|
||||||
| `desktop` | `ts3-client-desktop` | Desktop audio backend: Java Sound capture/playback + native Opus via the FFM API (project Panama), implementing the core audio interfaces. |
|
| `desktop` | `ts3-client-desktop` | Desktop audio backend: PipeWire (or Java Sound) capture/playback + native Opus via the FFM API (project Panama), plus the global hotkey hooks. |
|
||||||
| `swing` | `ts3-client-swing` | Swing desktop UI + entry point. Depends on `core` and `desktop`. |
|
| `swing` | `ts3-client-swing` | Swing desktop UI + entry point. Depends on `core` and `desktop`. |
|
||||||
|
|
||||||
The core exposes `AudioBackend` / `VoiceInput` / `VoiceOutput`; the frontend injects
|
The core exposes `AudioBackend` / `VoiceInput` / `VoiceOutput`; the frontend injects
|
||||||
a concrete backend (`JavaSoundAudioBackend`) into `TeamspeakConnection`. A different
|
a concrete backend (`DesktopAudioBackend`) into `TeamspeakConnection`. A different
|
||||||
frontend supplies its own UI and audio backend while reusing `core` unchanged.
|
frontend supplies its own UI and audio backend while reusing `core` unchanged, as the
|
||||||
|
Android app in [`../android`](../android) does.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@@ -28,26 +29,26 @@ frontend supplies its own UI and audio backend while reusing `core` unchanged.
|
|||||||
elsewhere install libopus from your package manager. Encoding at 48 kHz, 20 ms frames.
|
elsewhere install libopus from your package manager. Encoding at 48 kHz, 20 ms frames.
|
||||||
- **Voice Activation Detection (VAD)** with the same three modes as the TS3 client:
|
- **Voice Activation Detection (VAD)** with the same three modes as the TS3 client:
|
||||||
- **Volume Gate** — RMS/dBFS threshold with a live input meter and hangover.
|
- **Volume Gate** — RMS/dBFS threshold with a live input meter and hangover.
|
||||||
- **Automatic** — a dependency-free speech detector (short-term energy + spectral
|
- **Automatic** — a Java port of WebRTC's RNN speech detector (`rnn_vad`), the one the
|
||||||
flatness + dominant frequency against an adaptive noise floor).
|
TS3 client uses, with the same weights.
|
||||||
- **Hybrid** — transmit only when loud enough **and** detected as speech.
|
- **Hybrid** — transmit only when loud enough **and** detected as speech.
|
||||||
- Optional **VAD over Push-To-Talk** (keep detecting voice while PTT is available).
|
- Optional **VAD over Push-To-Talk** (keep detecting voice while PTT is available).
|
||||||
- **Capture pre-processing** — a mini audio-processing chain in the same order as the
|
- **Capture pre-processing** — a Java port of the WebRTC audio-processing stages the TS3
|
||||||
TS3 client's WebRTC APM, applied before activation and encoding (and feeding the VAD):
|
client enables, in its order: high-pass filter → **noise suppression** (WebRTC NS, TS3's
|
||||||
input gain → **high-pass filter** (80 Hz, always-on rumble/DC removal) → **noise
|
four levels) → **typing attenuation** (the transient suppressor, told about key presses)
|
||||||
suppression** → **typing attenuation** → **AGC**:
|
→ **automatic gain control** (AGC2, WebRTC's successor to the AGC1 TS3 uses). Checked
|
||||||
- **Remove background noise** — spectral denoiser (decision-directed Wiener with
|
against WebRTC built from source.
|
||||||
minimum-statistics noise tracking), with an adjustable removal level.
|
- **Boost quiet speech** (0–20 dB) raises AGC2's cap on the amplified noise floor, which
|
||||||
- **Typing attenuation** — detects impulsive keystroke transients (short, broadband,
|
otherwise holds back a distant voice that is barely above the background noise.
|
||||||
high-frequency bursts) and ducks them while leaving sustained speech intact.
|
|
||||||
- **Automatic gain control (AGC)** — normalises mic loudness to a target level
|
|
||||||
(fast attack / slow release, noise-gated so silence is never amplified).
|
|
||||||
- Echo cancellation (WebRTC AEC3) is intentionally omitted — it needs the loudspeaker
|
- Echo cancellation (WebRTC AEC3) is intentionally omitted — it needs the loudspeaker
|
||||||
reference signal and matters mainly for open speakers, not the typical headset.
|
reference signal and matters mainly for open speakers, not the typical headset.
|
||||||
- **Push-to-Talk** — bind any key; transmits only while held (while the app is focused).
|
- **Push-to-Talk** — bind any key or mouse button as a global hotkey; transmits only while held.
|
||||||
- **Continuous** transmission mode.
|
- **Continuous** transmission mode.
|
||||||
- **Playback mixing** — each speaker gets its own Opus decoder and audio line, so
|
- **Adaptive jitter buffer** — a port of the libspeex jitter buffer the TS3 client uses,
|
||||||
multiple simultaneous talkers are mixed and one slow decode never blocks others.
|
set up and driven as it does: the delay follows the measured network jitter, and what it
|
||||||
|
has learned carries over between talk bursts.
|
||||||
|
- **Playback mixing** — each speaker gets their own Opus decoder and audio line (a stream
|
||||||
|
of their own in the PipeWire mixer), so one slow decode never blocks the others.
|
||||||
- **Whisper receive** — targeted voice is decoded and played like normal voice.
|
- **Whisper receive** — targeted voice is decoded and played like normal voice.
|
||||||
- Per-client **mute**, master **deafen**, adjustable mic gain / playback volume.
|
- Per-client **mute**, master **deafen**, adjustable mic gain / playback volume.
|
||||||
- **On-the-fly Opus tuning** — bitrate, complexity, VBR, FEC and voice/music codec
|
- **On-the-fly Opus tuning** — bitrate, complexity, VBR, FEC and voice/music codec
|
||||||
@@ -71,15 +72,76 @@ frontend supplies its own UI and audio backend while reusing `core` unchanged.
|
|||||||
**private chat**, or **locally mute** them.
|
**private chat**, or **locally mute** them.
|
||||||
- **Chat** to the current channel or the whole server; receive channel/server/private
|
- **Chat** to the current channel or the whole server; receive channel/server/private
|
||||||
messages and **pokes**.
|
messages and **pokes**.
|
||||||
|
- **Avatars** — a selected client's avatar is shown in the info panel, fetched from the
|
||||||
|
server's file repository (`/avatar_<id>` in channel 0, verified against the client's
|
||||||
|
`client_flag_avatar` MD5) and cached on disk; **animated GIFs play**. Self → Set
|
||||||
|
avatar… uploads your own picture (PNG/JPEG/GIF/BMP, within the server's
|
||||||
|
`i_client_max_avatar_filesize`) or removes it.
|
||||||
- **Server bookmarks** — quick-connect menu with add/edit/remove management, each
|
- **Server bookmarks** — quick-connect menu with add/edit/remove management, each
|
||||||
optionally pinned to a specific identity.
|
optionally pinned to a specific identity.
|
||||||
- **Identity management** (Tools → Identities) — keep several identities, mark one
|
- **Identity management** (Tools → Identities) — keep several identities, mark one
|
||||||
as the default, pick one per server or per bookmark, rename, raise an identity's
|
as the default, pick one per server or per bookmark, rename, raise an identity's
|
||||||
security level, and import/export TeamSpeak-compatible `.ini` identity files.
|
security level, and import/export TeamSpeak-compatible `.ini` identity files.
|
||||||
|
- **Import from TeamSpeak 3 / myTeamSpeak** — the official client keeps its bookmarks
|
||||||
|
and identities (the data a myTeamSpeak account synchronises) as protobuf
|
||||||
|
`Item_Data` blobs in the `ProtobufItems` table of its `settings.db`. On first run,
|
||||||
|
when this client has no identity of its own yet, it adopts all of them — identities,
|
||||||
|
the default identity and its nickname, and the bookmarks with the identities they
|
||||||
|
connect with; "Import from TeamSpeak 3…" in Manage Bookmarks and in Identities
|
||||||
|
re-imports at any time (additive: known identities and bookmarks are left alone).
|
||||||
|
The schema was recovered from the descriptors embedded in the client binary.
|
||||||
|
- **Contacts** (Tools → Contacts) — TeamSpeak's friend/blocked list: mark a client as
|
||||||
|
**Friend**, **Blocked** or **Neutral** from its context menu (or drag it into the
|
||||||
|
window), give it a custom and a phonetic nickname, choose how the name is shown
|
||||||
|
(custom name and nickname / only custom / only nickname), and per contact **mute
|
||||||
|
automatically**, **ignore** server/channel chat, private chat, pokes and away
|
||||||
|
messages, and **allow or deny whispers**. Friends are coloured green and blocked
|
||||||
|
clients red in the tree (optional), per-type defaults for new contacts are
|
||||||
|
configurable ("Set Defaults"), and the global whisper policy lives in Options →
|
||||||
|
Contacts. The list is stored in `~/.ts3jclient/contacts.txt` in the *exact* record
|
||||||
|
format the official client keeps in the `Contacts` table of its `settings.db`; on
|
||||||
|
first run it is seeded from an installed TeamSpeak 3 client's database (read with a
|
||||||
|
small built-in SQLite reader — no driver needed), and can be re-imported any time.
|
||||||
|
- **Per-client volume** ("Change Volume…") — a dB gain on top of the master volume,
|
||||||
|
remembered in the client's contact entry.
|
||||||
|
- **Ban List** (Tools → Ban List) — the server's bans in a searchable table (Add /
|
||||||
|
Remove / Edit, own-ban filter and highlighting, choosable columns), with the
|
||||||
|
official Add dialog: IP and nickname patterns read as IPv4/IPv6 wildcards, fixed
|
||||||
|
strings or regular expressions, unique id, myTeamSpeak id, reason presets and a
|
||||||
|
duration capped by `i_client_ban_max_bantime`.
|
||||||
- **Self status** — Away (with message) and Channel Commander toggles.
|
- **Self status** — Away (with message) and Channel Commander toggles.
|
||||||
- **Status bar** shows the server name, user count and live ping.
|
- **Status bar** shows the server name, user count and live ping.
|
||||||
- Change your nickname, mute/deafen from the toolbar.
|
- Change your nickname, mute/deafen from the toolbar.
|
||||||
|
|
||||||
|
### Hotkeys
|
||||||
|
- **Global hotkeys**, as in TeamSpeak 3: single keys or combinations (any key can act
|
||||||
|
as the modifier) and mouse buttons including *Mouse 4* / *Mouse 5*, working
|
||||||
|
system-wide rather than only while the window has focus. Configure them in
|
||||||
|
**Options → Hotkeys**.
|
||||||
|
- Per binding you choose whether it **triggers on key down or on key up**, and whether
|
||||||
|
it applies **on the active server** only or to every connected one (checkbox off).
|
||||||
|
Push-to-talk style actions ignore the trigger setting and simply last while held.
|
||||||
|
- The action list is TeamSpeak's own, reverse-engineered from its hotkey dialog:
|
||||||
|
three categories (*Server*, *Self*, *Misc*) and a **"Show advanced actions"**
|
||||||
|
checkbox that reveals the rest, exactly as the original hides all but the everyday
|
||||||
|
actions. Actions this client does not implement are listed but greyed out.
|
||||||
|
- Push-to-talk is one of those hotkeys; the button in **Options → Voice Activation**
|
||||||
|
edits that binding.
|
||||||
|
- On Linux, capture uses **XInput2 raw events**, as TeamSpeak's own client does: no
|
||||||
|
privileges needed and the keystroke is not swallowed. X11's RECORD extension is kept
|
||||||
|
as a fallback for servers without XInput2.
|
||||||
|
- On **Windows**, capture uses **raw input** (`RIDEV_INPUTSINK`) through a message-only
|
||||||
|
window: it observes rather than intercepts, so unlike a low-level keyboard hook it
|
||||||
|
cannot swallow a keystroke or stall the system input queue, and it reports the side
|
||||||
|
buttons and both edges of every key. Bindings are stored as scan codes, so they follow
|
||||||
|
the physical key rather than the layout.
|
||||||
|
- On Wayland the hooks run inside Xwayland, so they see every X11 application, and keys
|
||||||
|
aimed at native Wayland windows only where the compositor forwards them — under KWin
|
||||||
|
that is *System Settings → Window Management → Legacy X11 App Support*, which is why
|
||||||
|
TeamSpeak's hotkeys work there. Where it forwards nothing, the client reads
|
||||||
|
`/dev/input/event*` instead, for which your user has to be in the `input` group.
|
||||||
|
The Hotkeys tab says which backend is in use, or why none is.
|
||||||
|
|
||||||
### Notification sounds
|
### Notification sounds
|
||||||
- **Sound packs** in TeamSpeak's own format: a folder of waves plus a `settings.ini`
|
- **Sound packs** in TeamSpeak's own format: a folder of waves plus a `settings.ini`
|
||||||
mapping actions (`CONNECTION_CONNECTED`, `CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS`, …)
|
mapping actions (`CONNECTION_CONNECTED`, `CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS`, …)
|
||||||
@@ -100,6 +162,11 @@ frontend supplies its own UI and audio backend while reusing `core` unchanged.
|
|||||||
TeamSpeak 3 client (`$TS3_CLIENT_DIR` or the usual install paths) and a folder of
|
TeamSpeak 3 client (`$TS3_CLIENT_DIR` or the usual install paths) and a folder of
|
||||||
your choosing, so the official packs (`default_colored_2014.zip`,
|
your choosing, so the official packs (`default_colored_2014.zip`,
|
||||||
`default_mono_2014.zip`, the legacy `default.zip`) work unchanged.
|
`default_mono_2014.zip`, the legacy `default.zip`) work unchanged.
|
||||||
|
- **Material**, a pack in the same format built from Google's Material icons, ships
|
||||||
|
with the client (`core/src/main/resources/gfx/material`, generated by
|
||||||
|
`tools/material-icon-pack.py`). Its monochrome icons paint with `currentColor`, which
|
||||||
|
follows the theme's text colour; it covers every icon TeamSpeak's own packs do. It is
|
||||||
|
the Android app's default, and the Android app draws TeamSpeak packs too — import one (e.g. `default_colored_2014.zip`) in its settings.
|
||||||
- The pack draws the tree (server, channel, client state), the toolbar, the menus,
|
- The pack draws the tree (server, channel, client state), the toolbar, the menus,
|
||||||
the context menus, the file browser and TeamSpeak's default group icons. Vector
|
the context menus, the file browser and TeamSpeak's default group icons. Vector
|
||||||
art is rasterised at the size it is drawn at; a pack's `FALLBACK` option decides
|
art is rasterised at the size it is drawn at; a pack's `FALLBACK` option decides
|
||||||
@@ -108,19 +175,31 @@ frontend supplies its own UI and audio backend while reusing `core` unchanged.
|
|||||||
- **Pick one in Options → Design**, which also shows a viewer of everything the pack
|
- **Pick one in Options → Design**, which also shows a viewer of everything the pack
|
||||||
contains; switching redraws the window right away.
|
contains; switching redraws the window right away.
|
||||||
|
|
||||||
|
### Display scaling (Linux)
|
||||||
|
- Java2D on X11 (and so under XWayland) only scales by whole numbers, so 125 % or
|
||||||
|
150 % comes out at 100 %. On Linux the client pins Java2D to 1 and hands the full
|
||||||
|
factor to FlatLaf instead, scaling its own sizes and icons to match.
|
||||||
|
- The factor follows the desktop: XSETTINGS `Xft/DPI` (GNOME, Plasma), else KWin's
|
||||||
|
XWayland scale, else `GDK_SCALE`. For crisp text on Wayland, let X11 apps scale
|
||||||
|
themselves (Plasma: *Display Configuration → Legacy Applications → Apply scaling
|
||||||
|
themselves*; GNOME: the `xwayland-native-scaling` mutter feature), otherwise the
|
||||||
|
compositor upscales the window.
|
||||||
|
- **Options → Design → Interface scale** overrides it (after a restart);
|
||||||
|
`-Dflatlaf.uiScale=` or `-Dsun.java2d.uiScale=` on the command line bypasses all this.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
- Java 26+ (developed/tested on Temurin 26)
|
- Java 25+ (the LTS; developed on Temurin 26)
|
||||||
- The native Opus library on the system:
|
- The native Opus library on the system:
|
||||||
- Debian/Ubuntu: `sudo apt install libopus0`
|
- Debian/Ubuntu: `sudo apt install libopus0`
|
||||||
- Arch: `sudo pacman -S opus`
|
- Arch: `sudo pacman -S opus`
|
||||||
- macOS: `brew install opus`
|
- macOS: `brew install opus`
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
The client depends on `ts3j`, so install that into your local Maven repo first:
|
The build compiles `ts3j` from `../ts3j` alongside the client, so make sure the submodule is
|
||||||
|
checked out (`git submodule update --init`):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ../ts3j && mvn -DskipTests install
|
mvn -DskipTests package
|
||||||
cd ../ts3-client && mvn -DskipTests package
|
|
||||||
```
|
```
|
||||||
|
|
||||||
This produces a runnable fat-jar at `swing/target/ts3-client.jar`.
|
This produces a runnable fat-jar at `swing/target/ts3-client.jar`.
|
||||||
@@ -138,42 +217,74 @@ voice activation while watching the live meter.
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
```
|
```
|
||||||
core/ com.ts3client
|
core/ eu.lixko.ts3j.client
|
||||||
├── config.Settings persisted prefs (~/.ts3jclient/settings.properties)
|
├── config the profile (~/.ts3jclient): Settings, Bookmarks, IdentityStore,
|
||||||
├── config.Bookmarks persisted server bookmarks (with per-server identity)
|
│ AwayMessages, …; AppDirs finds it, ProfileFiles writes it
|
||||||
├── config.IdentityStore managed identities (~/.ts3jclient/identities/*.ini)
|
│ privately and all at once
|
||||||
├── audio abstractions + reusable DSP (no platform code)
|
├── session
|
||||||
│ ├── AudioBackend factory for a platform's VoiceInput/VoiceOutput
|
│ ├── ServerSession one server tab's state and actions, whatever the frontend
|
||||||
│ ├── VoiceInput capture source (extends ts3j Microphone) + gating controls
|
│ └── Sessions what the servers share: the microphone, away state, nickname
|
||||||
│ ├── VoiceOutput voice-packet playback sink
|
├── net
|
||||||
│ ├── OpusParameters live-tunable encoder settings
|
│ ├── TeamspeakConnection ties socket + audio + model; runs requests on its own pool
|
||||||
│ └── SpeechDetector feature-based speech-probability VAD (Automatic/Hybrid)
|
│ ├── ConnectionEventHandler server events → model changes, sounds and log lines
|
||||||
|
│ ├── ServerModel channel/client state; ChannelNode/ClientEntry view models
|
||||||
|
│ ├── ChannelAdmin/BanAdmin/AvatarAdmin channel editing, the ban list, our own avatar
|
||||||
|
│ ├── IconRepository server icons (avatar/ holds the client avatar cache)
|
||||||
|
│ ├── filetransfer channel file browsing, up- and downloads
|
||||||
|
│ └── ConnectionListener frontend callbacks
|
||||||
|
├── audio the voice pipelines every platform shares
|
||||||
|
│ ├── AudioBackend/AudioIo what a platform supplies: devices, lines, Opus
|
||||||
|
│ ├── CaptureVoiceInput capture → processing → VAD/PTT gate → Opus encode
|
||||||
|
│ ├── StreamingVoiceOutput per-speaker decode, each through a VoiceStream
|
||||||
|
│ ├── JitterBuffer port of the libspeex jitter buffer TS3 uses
|
||||||
|
│ ├── PerSpeakerPlayout a line per speaker (desktop); MixedPlayout mixes onto one (Android)
|
||||||
|
│ ├── processing port of TS3's WebRTC capture chain: HPF, NS, transients, AGC2
|
||||||
|
│ ├── vad port of WebRTC's rnn_vad speech detector
|
||||||
|
│ └── opus codec interfaces
|
||||||
|
├── chatlog TS3-compatible chat logs, shared with the TS3 client by default
|
||||||
|
├── contacts friends and blocked clients, in TS3's own record format
|
||||||
|
├── text BBCode, TeamSpeak links, chat search
|
||||||
├── gfx
|
├── gfx
|
||||||
│ ├── IconPack an icon pack zip/folder + its settings.ini mapping
|
│ ├── IconPack an icon pack zip/folder/classpath folder + its settings.ini mapping
|
||||||
│ └── IconPacks discovery of installed packs
|
│ ├── IconPacks discovery of installed packs, the shipped Material one, lookup order
|
||||||
|
│ └── IconKeys the icon keys the channel tree asks for
|
||||||
|
├── hotkey
|
||||||
|
│ ├── HotkeyAction catalogue of TeamSpeak's hotkey actions (RE'd from its binary)
|
||||||
|
│ ├── Hotkey/HotkeyCombo one binding: keys, trigger edge, server scope, argument
|
||||||
|
│ ├── Hotkeys persisted bindings (~/.ts3jclient/hotkeys.properties)
|
||||||
|
│ ├── GlobalInputHook platform hook interface: system-wide key/button events
|
||||||
|
│ └── HotkeyEngine held-key tracking, combination matching, recording
|
||||||
├── sound
|
├── sound
|
||||||
│ ├── SoundEvent catalogue of actions (TeamSpeak's own event ids)
|
│ ├── SoundEvent catalogue of actions (TeamSpeak's own event ids)
|
||||||
│ ├── SoundPack a pack folder + its settings.ini mapping
|
│ ├── SoundPack a pack folder + its settings.ini mapping
|
||||||
│ ├── SoundPacks discovery of installed packs
|
│ ├── SoundPacks discovery of installed packs
|
||||||
│ ├── NotificationSettings per-action enabled / important flags
|
│ ├── NotificationSettings per-action enabled / important flags
|
||||||
│ ├── SoundNotifier decides what is heard (pack + config + mute state)
|
│ ├── SoundNotifier decides what is heard (pack + config + mute state)
|
||||||
│ └── SoundPlayer platform hook for rendering a sound
|
│ ├── SoundPlayer renders a sound
|
||||||
└── net
|
│ └── PackSoundPlayer decodes, resamples and mixes sounds onto one line
|
||||||
├── TeamspeakConnection ties socket + audio backend + model, translates events
|
└── teamspeak the official client's own data files
|
||||||
├── ServerModel thread-safe channel/client state
|
├── TeamSpeakSettingsDb locates settings.db; reads Contacts and the ProtobufItems sync store
|
||||||
├── ChannelNode/ClientEntry view models
|
├── SqliteReader minimal read-only SQLite 3 file reader (no driver)
|
||||||
└── ConnectionListener frontend callbacks
|
├── SyncItem a synced bookmark / identity / folder (Item_Data)
|
||||||
|
├── SyncItemDecoder protobuf wire decoding of Item_Data, via ProtobufReader
|
||||||
|
└── TeamSpeakImporter merges synced items into IdentityStore / Bookmarks
|
||||||
|
|
||||||
desktop/ com.ts3client.audio.desktop
|
desktop/ eu.lixko.ts3j.client.audio.desktop + eu.lixko.ts3j.client.hotkey.desktop
|
||||||
├── Opus Panama (FFM) binding to native libopus
|
├── DesktopAudioBackend PipeWire where it runs, Java Sound elsewhere, and native Opus
|
||||||
├── OpusEncoder/OpusDecoder thin codec wrappers
|
├── Opus/NativeOpusCodec Panama (FFM) binding to native libopus
|
||||||
├── AudioDevices device enumeration + line opening (48 kHz/16-bit)
|
├── AudioDevices device enumeration + line opening (48 kHz/16-bit)
|
||||||
├── JavaSoundVoiceInput capture + VAD/PTT gating + Opus encode
|
├── JavaSoundCapture/JavaSoundPlayback Java Sound lines
|
||||||
├── JavaSoundVoiceOutput per-client Opus decode + playback + mixing
|
├── pipewire PipeWire streams through FFM
|
||||||
├── WavSoundPlayer sound-pack playback: decode, resample and mix on one line
|
└── hotkey.desktop
|
||||||
└── JavaSoundAudioBackend wires the above into the core AudioBackend
|
├── XInput2InputHook global key/button capture via XInput2 raw events
|
||||||
|
├── XRecordInputHook the same via X11's RECORD extension, as a fallback
|
||||||
|
├── EvdevInputHook /dev/input fallback for Wayland sessions
|
||||||
|
├── WindowsInputHook the same on Windows: raw input into a message-only window
|
||||||
|
├── RawInput RAWINPUT layout and decoding, split out to be testable
|
||||||
|
├── X11KeyNamer/WindowsKeyNamer layout-aware key labels per platform
|
||||||
|
└── DesktopInputHooks picks the backend that suits the session
|
||||||
|
|
||||||
swing/ com.ts3client
|
swing/ eu.lixko.ts3j.client
|
||||||
├── Main entry point (look & feel, settings, backend injection)
|
├── Main entry point (look & feel, settings, backend injection)
|
||||||
└── ui
|
└── ui
|
||||||
├── MainFrame window: menu, toolbar, tree | chat, status bar
|
├── MainFrame window: menu, toolbar, tree | chat, status bar
|
||||||
@@ -181,9 +292,14 @@ swing/ com.ts3client
|
|||||||
├── Spacers TS3 spacer-channel name parsing/rendering
|
├── Spacers TS3 spacer-channel name parsing/rendering
|
||||||
├── InfoPanel channel description / client group + details view
|
├── InfoPanel channel description / client group + details view
|
||||||
├── ChatPanel chat log + input
|
├── ChatPanel chat log + input
|
||||||
├── SettingsDialog audio + VAD options with live meter
|
├── SettingsDialog the Options dialog: TS3-style page sidebar; one panel per page (ApplicationPanel, …, ChatLogsPanel)
|
||||||
|
├── HotkeysPanel hotkey list (Options → Hotkeys)
|
||||||
|
├── HotkeyDialog add/edit one hotkey: action, combination, trigger, scope
|
||||||
|
├── HotkeyService bindings + engine + input hook, for the dialogs
|
||||||
|
├── HotkeyActions carries a fired hotkey out on the client
|
||||||
├── NotificationsPanel sound pack + per-action sound/important configuration
|
├── NotificationsPanel sound pack + per-action sound/important configuration
|
||||||
├── IconPackPanel icon pack chooser + icon viewer (Options → Design)
|
├── IconPackPanel icon pack chooser + icon viewer (Options → Design)
|
||||||
|
├── DisplayScale interface scale on Linux (fractional, via FlatLaf)
|
||||||
├── ConnectDialog connect form
|
├── ConnectDialog connect form
|
||||||
├── BookmarksDialog manage saved servers
|
├── BookmarksDialog manage saved servers
|
||||||
├── IdentitiesDialog manage identities (new/import/export/improve)
|
├── IdentitiesDialog manage identities (new/import/export/improve)
|
||||||
@@ -195,11 +311,15 @@ swing/ com.ts3client
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Known limitations / next steps
|
## Known limitations / next steps
|
||||||
- The **Automatic/Hybrid** VAD uses a lightweight energy/spectral detector rather
|
|
||||||
than the WebRTC GMM model the official client ships; it is intentionally
|
|
||||||
dependency-free and reusable in the core library.
|
|
||||||
- Whisper is received/played but not yet **sendable** from the UI.
|
- Whisper is received/played but not yet **sendable** from the UI.
|
||||||
- Playback decodes streams as mono; stereo music-bot audio is down-mixed.
|
- Hotkey actions TeamSpeak offers but this client does not perform yet (listed but
|
||||||
- Push-to-talk is captured via Swing key events, so it only works while the app
|
greyed out in the dialog): capture/playback/hotkey profiles and sound packs,
|
||||||
window has focus (no global hotkey).
|
whisper and push-to-whisper, recording, plugins, server groups, talk power, 3D
|
||||||
- No file transfer, avatars, or server/channel administration UI yet.
|
sound, hardware ("local") microphone mute and the channel-traversal variants
|
||||||
|
beyond "Switch to Channel".
|
||||||
|
- Global hotkeys cover Linux and Windows; **macOS has no backend**, so hotkeys there are
|
||||||
|
inert (a `CGEventTap`, which needs Accessibility permission, is the way in). The
|
||||||
|
Windows backend is written but has not been run on Windows — only its decoding is
|
||||||
|
covered by tests.
|
||||||
|
- When no backend can start, push-to-talk does not work at all, not even with the window
|
||||||
|
focused; a focus-scoped fallback hook would restore the pre-hotkey behaviour.
|
||||||
|
|||||||
+28
-2
@@ -5,15 +5,22 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ts3client</groupId>
|
<groupId>eu.lixko.ts3j.client</groupId>
|
||||||
<artifactId>ts3-client-parent</artifactId>
|
<artifactId>ts3-client-parent</artifactId>
|
||||||
<version>0.1.0</version>
|
<version>0.1.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>ts3-client-core</artifactId>
|
<artifactId>ts3-client-core</artifactId>
|
||||||
<name>TS3J Client Core</name>
|
<name>TeamSpook TS3j Core</name>
|
||||||
<description>Frontend-agnostic library: protocol integration, model, audio abstractions</description>
|
<description>Frontend-agnostic library: protocol integration, model, audio abstractions</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- Android runs core too, and it only knows Java 17. -->
|
||||||
|
<maven.compiler.release>17</maven.compiler.release>
|
||||||
|
<!-- The TeamSpeak 3 client whose icon packs ship (-Dts3.client.dir=…); without one, none do. -->
|
||||||
|
<ts3.client.dir>${project.basedir}/../../TeamSpeak3-Client-linux_amd64</ts3.client.dir>
|
||||||
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.manevolent</groupId>
|
<groupId>com.github.manevolent</groupId>
|
||||||
@@ -26,4 +33,23 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
</resource>
|
||||||
|
<!-- TeamSpeak's own icon packs and country flags, proprietary and so taken from an install, not the repository. -->
|
||||||
|
<resource>
|
||||||
|
<directory>${ts3.client.dir}/gfx</directory>
|
||||||
|
<targetPath>gfx/teamspeak</targetPath>
|
||||||
|
<includes>
|
||||||
|
<include>default.zip</include>
|
||||||
|
<include>default_colored_2014.zip</include>
|
||||||
|
<include>default_mono_2014.zip</include>
|
||||||
|
<include>countries.zip</include>
|
||||||
|
</includes>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
import com.ts3client.config.Settings;
|
|
||||||
import com.ts3client.sound.SoundPlayer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Factory for a platform's voice capture and playback. Injected into the
|
|
||||||
* connection layer so the core stays independent of any concrete audio stack.
|
|
||||||
*/
|
|
||||||
public interface AudioBackend {
|
|
||||||
|
|
||||||
VoiceInput createInput(Settings settings);
|
|
||||||
|
|
||||||
VoiceOutput createOutput(Settings settings);
|
|
||||||
|
|
||||||
/** Player for notification sounds (sound packs); shared by all connections. */
|
|
||||||
SoundPlayer createSoundPlayer(Settings settings);
|
|
||||||
|
|
||||||
/** Human-readable codec/backend description, e.g. for an "about" line. */
|
|
||||||
String description();
|
|
||||||
}
|
|
||||||
@@ -1,238 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Microphone pre-processing chain applied before voice activation and Opus encoding,
|
|
||||||
* mirroring the capture-side denoise/typing filters of the TeamSpeak 3 client.
|
|
||||||
*
|
|
||||||
* <p>The stages run in the same order as the TeamSpeak client's WebRTC capture chain:
|
|
||||||
* a {@link HighPassFilter} (always-on rumble/DC removal), then a streaming short-time
|
|
||||||
* Fourier transform (square-root Hann window, 50% overlap-add) carrying a
|
|
||||||
* {@link NoiseSuppressor} ("Remove background noise") and a {@link TypingAttenuator}
|
|
||||||
* ("Typing attenuation") — sharing one FFT/IFFT per hop — and finally an
|
|
||||||
* {@link AutomaticGainControl} ("AGC"). Echo cancellation (WebRTC AEC3) is omitted as
|
|
||||||
* it requires the loudspeaker reference signal.
|
|
||||||
*
|
|
||||||
* <p>Input frames of any length are decoupled from the STFT hop by internal ring
|
|
||||||
* buffers; when noise/typing suppression is active the output is delayed by one hop
|
|
||||||
* (~5 ms). The high-pass filter and AGC are zero-latency. When every stage is
|
|
||||||
* disabled the chain is fully bypassed and audio passes through untouched.
|
|
||||||
*
|
|
||||||
* <p>Pure DSP with no platform dependencies, so any frontend/backend can reuse it.
|
|
||||||
* Not thread-safe: drive it from a single capture thread; the enable/level setters
|
|
||||||
* are cheap volatiles safe to call from the UI thread.
|
|
||||||
*/
|
|
||||||
public final class AudioEnhancer {
|
|
||||||
|
|
||||||
private static final int FFT_SIZE = 512; // power of two -> 10.7 ms @ 48 kHz
|
|
||||||
private static final int HOP = FFT_SIZE / 2; // 50% overlap
|
|
||||||
private static final int BINS = FFT_SIZE / 2 + 1;
|
|
||||||
|
|
||||||
private final double[] window = new double[FFT_SIZE];
|
|
||||||
private final double[] re = new double[FFT_SIZE];
|
|
||||||
private final double[] im = new double[FFT_SIZE];
|
|
||||||
private final double[] power = new double[BINS];
|
|
||||||
private final double[] gain = new double[BINS];
|
|
||||||
|
|
||||||
private final double[] frame = new double[FFT_SIZE]; // sliding analysis frame
|
|
||||||
private final double[] ola = new double[FFT_SIZE]; // overlap-add accumulator
|
|
||||||
|
|
||||||
private final FloatRing input = new FloatRing(FFT_SIZE * 4);
|
|
||||||
private final FloatRing output = new FloatRing(FFT_SIZE * 4);
|
|
||||||
private final float[] hopIn = new float[HOP];
|
|
||||||
|
|
||||||
private final NoiseSuppressor noiseSuppressor = new NoiseSuppressor(BINS);
|
|
||||||
private final TypingAttenuator typingAttenuator;
|
|
||||||
private final HighPassFilter highPass;
|
|
||||||
private final AutomaticGainControl agc;
|
|
||||||
|
|
||||||
private volatile boolean noiseEnabled;
|
|
||||||
private volatile boolean typingEnabled;
|
|
||||||
private volatile boolean agcEnabled;
|
|
||||||
private boolean active; // any stage on: HPF + AGC state is live
|
|
||||||
private boolean stftRunning; // noise/typing on: STFT rings are live
|
|
||||||
|
|
||||||
public AudioEnhancer(int sampleRate) {
|
|
||||||
for (int i = 0; i < FFT_SIZE; i++) {
|
|
||||||
// sqrt(Hann): analysis*synthesis = Hann, which is COLA at 50% overlap.
|
|
||||||
window[i] = Math.sqrt(0.5 * (1 - Math.cos(2 * Math.PI * i / FFT_SIZE)));
|
|
||||||
}
|
|
||||||
this.typingAttenuator = new TypingAttenuator(BINS, sampleRate, FFT_SIZE);
|
|
||||||
this.highPass = new HighPassFilter(sampleRate);
|
|
||||||
this.agc = new AutomaticGainControl(sampleRate);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setNoiseSuppression(boolean enabled) {
|
|
||||||
this.noiseEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDenoiserLevel(double level) {
|
|
||||||
noiseSuppressor.setLevel(level);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTypingAttenuation(boolean enabled) {
|
|
||||||
this.typingEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAgc(boolean enabled) {
|
|
||||||
this.agcEnabled = enabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Clears all filter state; call when (re)starting capture. */
|
|
||||||
public void reset() {
|
|
||||||
resetStft();
|
|
||||||
highPass.reset();
|
|
||||||
agc.reset();
|
|
||||||
active = false;
|
|
||||||
stftRunning = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void resetStft() {
|
|
||||||
input.clear();
|
|
||||||
output.clear();
|
|
||||||
Arrays.fill(frame, 0);
|
|
||||||
Arrays.fill(ola, 0);
|
|
||||||
noiseSuppressor.reset();
|
|
||||||
typingAttenuator.reset();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enhances one frame of mono PCM in place. {@code buf[0..len)} is overwritten with
|
|
||||||
* the processed (one-hop-delayed when noise/typing suppression is on) signal.
|
|
||||||
* Returns immediately if every stage is disabled.
|
|
||||||
*/
|
|
||||||
public void process(float[] buf, int len) {
|
|
||||||
boolean stft = noiseEnabled || typingEnabled;
|
|
||||||
boolean anyStage = stft || agcEnabled;
|
|
||||||
if (!anyStage) {
|
|
||||||
if (active) reset(); // drop stale filter/delay state on full disable
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!active) {
|
|
||||||
reset();
|
|
||||||
active = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1) High-pass filter (always-on part of the active chain).
|
|
||||||
highPass.process(buf, len);
|
|
||||||
|
|
||||||
// 2) STFT noise + typing suppression (only when either is enabled).
|
|
||||||
if (stft) {
|
|
||||||
if (!stftRunning) {
|
|
||||||
resetStft();
|
|
||||||
stftRunning = true;
|
|
||||||
}
|
|
||||||
runStft(buf, len);
|
|
||||||
} else if (stftRunning) {
|
|
||||||
stftRunning = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3) Automatic gain control (last, on the cleaned signal).
|
|
||||||
if (agcEnabled) {
|
|
||||||
agc.process(buf, len);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void runStft(float[] buf, int len) {
|
|
||||||
input.write(buf, len);
|
|
||||||
while (input.available() >= HOP) {
|
|
||||||
System.arraycopy(frame, HOP, frame, 0, FFT_SIZE - HOP);
|
|
||||||
input.read(hopIn, HOP);
|
|
||||||
for (int i = 0; i < HOP; i++) {
|
|
||||||
frame[FFT_SIZE - HOP + i] = hopIn[i];
|
|
||||||
}
|
|
||||||
processBlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
// During the initial one-hop priming the output ring is short; pad with zeros.
|
|
||||||
int ready = output.available();
|
|
||||||
if (ready < len) {
|
|
||||||
for (int i = 0; i < len - ready; i++) buf[i] = 0f;
|
|
||||||
output.read(buf, len - ready, ready);
|
|
||||||
} else {
|
|
||||||
output.read(buf, 0, len);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processBlock() {
|
|
||||||
for (int i = 0; i < FFT_SIZE; i++) {
|
|
||||||
re[i] = frame[i] * window[i];
|
|
||||||
im[i] = 0;
|
|
||||||
}
|
|
||||||
Fft.forward(re, im);
|
|
||||||
|
|
||||||
for (int k = 0; k < BINS; k++) {
|
|
||||||
power[k] = re[k] * re[k] + im[k] * im[k];
|
|
||||||
gain[k] = 1.0;
|
|
||||||
}
|
|
||||||
if (noiseEnabled) noiseSuppressor.apply(power, gain);
|
|
||||||
if (typingEnabled) typingAttenuator.apply(power, gain);
|
|
||||||
|
|
||||||
// Apply the real-valued gain to each bin and its conjugate mirror.
|
|
||||||
for (int k = 0; k < BINS; k++) {
|
|
||||||
double g = gain[k];
|
|
||||||
re[k] *= g;
|
|
||||||
im[k] *= g;
|
|
||||||
if (k > 0 && k < FFT_SIZE - k) {
|
|
||||||
int m = FFT_SIZE - k;
|
|
||||||
re[m] *= g;
|
|
||||||
im[m] *= g;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Fft.inverse(re, im);
|
|
||||||
|
|
||||||
for (int i = 0; i < FFT_SIZE; i++) {
|
|
||||||
ola[i] += re[i] * window[i];
|
|
||||||
}
|
|
||||||
output.write(ola, HOP);
|
|
||||||
System.arraycopy(ola, HOP, ola, 0, FFT_SIZE - HOP);
|
|
||||||
Arrays.fill(ola, FFT_SIZE - HOP, FFT_SIZE, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Minimal single-producer/single-consumer float ring buffer. */
|
|
||||||
private static final class FloatRing {
|
|
||||||
private final float[] buf;
|
|
||||||
private int head, tail, size;
|
|
||||||
|
|
||||||
FloatRing(int capacity) {
|
|
||||||
this.buf = new float[capacity];
|
|
||||||
}
|
|
||||||
|
|
||||||
int available() {
|
|
||||||
return size;
|
|
||||||
}
|
|
||||||
|
|
||||||
void clear() {
|
|
||||||
head = tail = size = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void write(float[] src, int len) {
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
buf[tail] = src[i];
|
|
||||||
tail = (tail + 1) % buf.length;
|
|
||||||
}
|
|
||||||
size += len;
|
|
||||||
}
|
|
||||||
|
|
||||||
void write(double[] src, int len) {
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
buf[tail] = (float) src[i];
|
|
||||||
tail = (tail + 1) % buf.length;
|
|
||||||
}
|
|
||||||
size += len;
|
|
||||||
}
|
|
||||||
|
|
||||||
void read(float[] dst, int len) {
|
|
||||||
read(dst, 0, len);
|
|
||||||
}
|
|
||||||
|
|
||||||
void read(float[] dst, int offset, int len) {
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
dst[offset + i] = buf[head];
|
|
||||||
head = (head + 1) % buf.length;
|
|
||||||
}
|
|
||||||
size -= len;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Automatic gain control — WebRTC APM's {@code gain_controller} (AGC2 adaptive
|
|
||||||
* digital) / Speex {@code AGC} stage. It normalises voice loudness toward a target
|
|
||||||
* level so quiet microphones are boosted and loud ones tamed, keeping perceived volume
|
|
||||||
* consistent across speakers.
|
|
||||||
*
|
|
||||||
* <p>Placed last in the capture chain (after noise suppression), it tracks the frame
|
|
||||||
* level and moves an applied gain toward {@code target / level}: it attenuates quickly
|
|
||||||
* to head off clipping and boosts slowly to avoid pumping. A noise gate freezes the
|
|
||||||
* gain while the input is near silence, so background noise between words is never
|
|
||||||
* amplified; the per-sample gain ramp avoids zipper artefacts and a final clamp guards
|
|
||||||
* against overshoot.
|
|
||||||
*/
|
|
||||||
final class AutomaticGainControl {
|
|
||||||
|
|
||||||
private static final double TARGET_RMS = 0.12; // ~ -18.4 dBFS
|
|
||||||
private static final double MAX_GAIN = dbToGain(30); // up to +30 dB boost
|
|
||||||
private static final double MIN_GAIN = dbToGain(-20); // down to -20 dB
|
|
||||||
private static final double NOISE_GATE_RMS = dbToGain(-55); // freeze below this level
|
|
||||||
|
|
||||||
private final double attackCoeff; // gain decreasing (signal too loud): fast
|
|
||||||
private final double releaseCoeff; // gain increasing (too quiet): slow
|
|
||||||
|
|
||||||
private double gain = 1.0;
|
|
||||||
|
|
||||||
AutomaticGainControl(int sampleRate) {
|
|
||||||
this.attackCoeff = 1 - Math.exp(-1.0 / (0.005 * sampleRate)); // ~5 ms
|
|
||||||
this.releaseCoeff = 1 - Math.exp(-1.0 / (0.300 * sampleRate)); // ~300 ms
|
|
||||||
}
|
|
||||||
|
|
||||||
void reset() {
|
|
||||||
gain = 1.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Applies gain normalisation to one mono frame in place. */
|
|
||||||
void process(float[] buf, int len) {
|
|
||||||
double sumSq = 0;
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
sumSq += (double) buf[i] * buf[i];
|
|
||||||
}
|
|
||||||
double rms = Math.sqrt(sumSq / len);
|
|
||||||
|
|
||||||
double desired = gain;
|
|
||||||
if (rms >= NOISE_GATE_RMS) {
|
|
||||||
desired = TARGET_RMS / rms;
|
|
||||||
if (desired > MAX_GAIN) desired = MAX_GAIN;
|
|
||||||
else if (desired < MIN_GAIN) desired = MIN_GAIN;
|
|
||||||
}
|
|
||||||
// Boost slowly, attenuate quickly.
|
|
||||||
double coeff = desired < gain ? attackCoeff : releaseCoeff;
|
|
||||||
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
gain += (desired - gain) * coeff;
|
|
||||||
double y = buf[i] * gain;
|
|
||||||
if (y > 1.0) y = 1.0;
|
|
||||||
else if (y < -1.0) y = -1.0;
|
|
||||||
buf[i] = (float) y;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static double dbToGain(double db) {
|
|
||||||
return Math.pow(10.0, db / 20.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Second-order Butterworth high-pass filter (RBJ biquad, transposed direct form II).
|
|
||||||
* Mirrors WebRTC APM's {@code high_pass_filter} stage — an always-on part of the
|
|
||||||
* capture chain that removes DC offset, mains hum and low-frequency rumble below the
|
|
||||||
* speech band before noise suppression sees the signal.
|
|
||||||
*/
|
|
||||||
final class HighPassFilter {
|
|
||||||
|
|
||||||
private static final double CUTOFF_HZ = 80.0; // WebRTC APM high-pass cutoff
|
|
||||||
|
|
||||||
private final double b0, b1, b2, a1, a2;
|
|
||||||
private double z1, z2;
|
|
||||||
|
|
||||||
HighPassFilter(int sampleRate) {
|
|
||||||
double w0 = 2 * Math.PI * CUTOFF_HZ / sampleRate;
|
|
||||||
double cos = Math.cos(w0);
|
|
||||||
double alpha = Math.sin(w0) / Math.sqrt(2.0); // Q = 1/sqrt(2) (Butterworth)
|
|
||||||
double a0 = 1 + alpha;
|
|
||||||
this.b0 = (1 + cos) / 2 / a0;
|
|
||||||
this.b1 = -(1 + cos) / a0;
|
|
||||||
this.b2 = (1 + cos) / 2 / a0;
|
|
||||||
this.a1 = -2 * cos / a0;
|
|
||||||
this.a2 = (1 - alpha) / a0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void reset() {
|
|
||||||
z1 = 0;
|
|
||||||
z2 = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Filters one mono frame in place. */
|
|
||||||
void process(float[] buf, int len) {
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
double x = buf[i];
|
|
||||||
double y = b0 * x + z1;
|
|
||||||
z1 = b1 * x - a1 * y + z2;
|
|
||||||
z2 = b2 * x - a2 * y;
|
|
||||||
buf[i] = (float) y;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Single-channel spectral noise suppressor — the "Remove background noise"
|
|
||||||
* (denoise) stage. The TeamSpeak 3 client filters steady background noise with
|
|
||||||
* WebRTC's {@code noise_suppression} module (and a Speex denoiser fallback); this is
|
|
||||||
* a self-contained equivalent that operates on the STFT bins produced by
|
|
||||||
* {@link AudioEnhancer}.
|
|
||||||
*
|
|
||||||
* <p>The noise floor is tracked per bin by continuous minimum statistics (Doblinger's
|
|
||||||
* recursive minimum tracker): the estimate follows the valleys of the smoothed power
|
|
||||||
* spectrum, so modulated speech — which dips between syllables — is
|
|
||||||
* preserved while only near-stationary background energy is learned as noise. From
|
|
||||||
* that floor a Wiener gain is formed with a decision-directed a priori SNR
|
|
||||||
* (Ephraim–Malah smoothing, which keeps musical noise low). A configurable
|
|
||||||
* aggressiveness ({@code denoiser_level}, 0–1) sets both the over-subtraction
|
|
||||||
* factor and the gain floor, i.e. how deeply steady noise is cut.
|
|
||||||
*/
|
|
||||||
final class NoiseSuppressor {
|
|
||||||
|
|
||||||
/** Power-spectrum smoothing feeding the minimum tracker. */
|
|
||||||
private static final double POWER_SMOOTH = 0.7;
|
|
||||||
/** Doblinger minimum-tracker constants. */
|
|
||||||
private static final double MIN_GAMMA = 0.998;
|
|
||||||
private static final double MIN_BETA = 0.96;
|
|
||||||
/** Over-estimation applied to the tracked minimum to get the noise power. */
|
|
||||||
private static final double NOISE_OVEREST = 1.5;
|
|
||||||
/** Decision-directed smoothing of the a priori SNR (higher = less musical noise). */
|
|
||||||
private static final double DD_ALPHA = 0.98;
|
|
||||||
/** Floor on the a priori SNR (~ -25 dB) to bound the deepest Wiener gain. */
|
|
||||||
private static final double XI_MIN = 0.003;
|
|
||||||
|
|
||||||
private final int bins;
|
|
||||||
private final double[] smoothed;
|
|
||||||
private final double[] prevSmoothed;
|
|
||||||
private final double[] minTrack;
|
|
||||||
private final double[] priorClean; // previous enhanced power, for the DD estimate
|
|
||||||
|
|
||||||
private double overSubtraction = 1.5;
|
|
||||||
private double gainFloor = dbToGain(-18);
|
|
||||||
private boolean initialised;
|
|
||||||
|
|
||||||
NoiseSuppressor(int bins) {
|
|
||||||
this.bins = bins;
|
|
||||||
this.smoothed = new double[bins];
|
|
||||||
this.prevSmoothed = new double[bins];
|
|
||||||
this.minTrack = new double[bins];
|
|
||||||
this.priorClean = new double[bins];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets aggressiveness in [0,1]. 0 is a light touch (~6 dB max cut), 1 is
|
|
||||||
* heavy (~30 dB) with stronger over-subtraction.
|
|
||||||
*/
|
|
||||||
void setLevel(double level) {
|
|
||||||
double l = Math.max(0, Math.min(1, level));
|
|
||||||
this.gainFloor = dbToGain(-(6 + 24 * l));
|
|
||||||
this.overSubtraction = 1.0 + 1.5 * l;
|
|
||||||
}
|
|
||||||
|
|
||||||
void reset() {
|
|
||||||
initialised = false;
|
|
||||||
Arrays.fill(smoothed, 0);
|
|
||||||
Arrays.fill(prevSmoothed, 0);
|
|
||||||
Arrays.fill(minTrack, 0);
|
|
||||||
Arrays.fill(priorClean, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Multiplies the running per-bin gain by this stage's Wiener gain. */
|
|
||||||
void apply(double[] power, double[] gain) {
|
|
||||||
if (!initialised) {
|
|
||||||
for (int k = 0; k < bins; k++) {
|
|
||||||
smoothed[k] = prevSmoothed[k] = minTrack[k] = power[k];
|
|
||||||
priorClean[k] = power[k];
|
|
||||||
}
|
|
||||||
initialised = true;
|
|
||||||
}
|
|
||||||
for (int k = 0; k < bins; k++) {
|
|
||||||
double p = power[k] + 1e-12;
|
|
||||||
|
|
||||||
double s = POWER_SMOOTH * smoothed[k] + (1 - POWER_SMOOTH) * p;
|
|
||||||
// Doblinger continuous minimum tracking of the smoothed power.
|
|
||||||
double mt;
|
|
||||||
if (minTrack[k] < s) {
|
|
||||||
mt = MIN_GAMMA * minTrack[k]
|
|
||||||
+ ((1 - MIN_GAMMA) / (1 - MIN_BETA)) * (s - MIN_BETA * smoothed[k]);
|
|
||||||
} else {
|
|
||||||
mt = s;
|
|
||||||
}
|
|
||||||
minTrack[k] = mt;
|
|
||||||
smoothed[k] = s;
|
|
||||||
double noiseK = NOISE_OVEREST * mt + 1e-12;
|
|
||||||
|
|
||||||
double gamma = p / (noiseK * overSubtraction); // a posteriori SNR
|
|
||||||
double xi = DD_ALPHA * (priorClean[k] / noiseK)
|
|
||||||
+ (1 - DD_ALPHA) * Math.max(gamma - 1, 0); // a priori SNR
|
|
||||||
if (xi < XI_MIN) xi = XI_MIN;
|
|
||||||
|
|
||||||
double g = xi / (1 + xi); // Wiener gain
|
|
||||||
if (g < gainFloor) g = gainFloor;
|
|
||||||
|
|
||||||
priorClean[k] = g * g * p;
|
|
||||||
gain[k] *= g;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static double dbToGain(double db) {
|
|
||||||
return Math.pow(10.0, db / 20.0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lightweight speech-presence detector used by the "Automatic" and "Hybrid" voice
|
|
||||||
* activation modes (the TeamSpeak 3 client uses a WebRTC GMM detector for the same
|
|
||||||
* purpose). It classifies each 20 ms frame from three features — short-term
|
|
||||||
* energy, spectral flatness and dominant frequency — against an adaptive noise
|
|
||||||
* floor, following Moattar & Homayounpour's real-time VAD.
|
|
||||||
*
|
|
||||||
* <p>Pure DSP with no platform dependencies, so any frontend/backend can reuse it.
|
|
||||||
* A frame votes for speech when at least two of the three features exceed the
|
|
||||||
* baseline; the smoothed vote fraction is exposed as a [0,1] probability.
|
|
||||||
*/
|
|
||||||
public final class SpeechDetector {
|
|
||||||
|
|
||||||
private static final int FFT_SIZE = 1024;
|
|
||||||
|
|
||||||
// Primary thresholds from the reference algorithm (16-bit sample scale).
|
|
||||||
private static final double ENERGY_PRIM = 40.0;
|
|
||||||
private static final double DOMINANT_FREQ_PRIM = 185.0;
|
|
||||||
private static final double FLATNESS_PRIM = 5.0;
|
|
||||||
|
|
||||||
private final int sampleRate;
|
|
||||||
private final double[] re = new double[FFT_SIZE];
|
|
||||||
private final double[] im = new double[FFT_SIZE];
|
|
||||||
|
|
||||||
private double minEnergy;
|
|
||||||
private double minDominantFreq;
|
|
||||||
private double minFlatness;
|
|
||||||
private long silenceFrames;
|
|
||||||
private long frameCount;
|
|
||||||
private double probability;
|
|
||||||
|
|
||||||
public SpeechDetector(int sampleRate) {
|
|
||||||
this.sampleRate = sampleRate;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void reset() {
|
|
||||||
frameCount = 0;
|
|
||||||
silenceFrames = 0;
|
|
||||||
probability = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getProbability() {
|
|
||||||
return probability;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Processes one frame of mono PCM in [-1,1] and returns the smoothed speech
|
|
||||||
* probability in [0,1].
|
|
||||||
*/
|
|
||||||
public double process(float[] frame) {
|
|
||||||
double energy = 0;
|
|
||||||
int n = Math.min(frame.length, FFT_SIZE);
|
|
||||||
for (int i = 0; i < n; i++) {
|
|
||||||
double s = frame[i] * 32768.0; // emulate 16-bit scale
|
|
||||||
energy += s * s;
|
|
||||||
re[i] = frame[i];
|
|
||||||
im[i] = 0;
|
|
||||||
}
|
|
||||||
for (int i = n; i < FFT_SIZE; i++) {
|
|
||||||
re[i] = 0;
|
|
||||||
im[i] = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Fft.forward(re, im);
|
|
||||||
|
|
||||||
int half = FFT_SIZE / 2;
|
|
||||||
double geoLogSum = 0;
|
|
||||||
double arithSum = 0;
|
|
||||||
double maxMag = 0;
|
|
||||||
int maxBin = 0;
|
|
||||||
for (int k = 1; k < half; k++) {
|
|
||||||
double mag = Math.sqrt(re[k] * re[k] + im[k] * im[k]) + 1e-12;
|
|
||||||
geoLogSum += Math.log(mag);
|
|
||||||
arithSum += mag;
|
|
||||||
if (mag > maxMag) {
|
|
||||||
maxMag = mag;
|
|
||||||
maxBin = k;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
int bins = half - 1;
|
|
||||||
double geoMean = Math.exp(geoLogSum / bins);
|
|
||||||
double arithMean = arithSum / bins;
|
|
||||||
double flatness = -10.0 * Math.log10(geoMean / arithMean); // high = tonal (speech)
|
|
||||||
double dominantFreq = (double) maxBin * sampleRate / FFT_SIZE;
|
|
||||||
|
|
||||||
if (frameCount == 0) {
|
|
||||||
minEnergy = Math.max(energy, 1.0);
|
|
||||||
minDominantFreq = dominantFreq;
|
|
||||||
minFlatness = flatness;
|
|
||||||
}
|
|
||||||
|
|
||||||
double energyThresh = ENERGY_PRIM * Math.log10(Math.max(minEnergy, 1.0));
|
|
||||||
int votes = 0;
|
|
||||||
if (energy - minEnergy >= energyThresh) votes++;
|
|
||||||
if (dominantFreq - minDominantFreq >= DOMINANT_FREQ_PRIM) votes++;
|
|
||||||
if (flatness - minFlatness >= FLATNESS_PRIM) votes++;
|
|
||||||
|
|
||||||
boolean speech = votes >= 2;
|
|
||||||
if (!speech) {
|
|
||||||
// Adapt the noise floor towards the current (silent) energy.
|
|
||||||
silenceFrames++;
|
|
||||||
minEnergy = ((silenceFrames * minEnergy) + energy) / (silenceFrames + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
double instant = votes / 3.0;
|
|
||||||
probability = 0.6 * probability + 0.4 * instant;
|
|
||||||
frameCount++;
|
|
||||||
return probability;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Transient (keystroke) suppressor — the "Typing attenuation" stage, which per
|
|
||||||
* the TeamSpeak 3 client "tries to detect and reduce the sounds made by typing"
|
|
||||||
* (WebRTC's {@code transient_suppression} module). Key clicks are short, impulsive,
|
|
||||||
* broadband bursts with a strong high-frequency component, unlike voiced speech which
|
|
||||||
* is sustained and low-frequency dominant.
|
|
||||||
*
|
|
||||||
* <p>Each STFT block is scored for a keystroke signature: a sudden jump in total
|
|
||||||
* power (both against the previous block and a slow running floor) together with an
|
|
||||||
* elevated high-frequency energy ratio. Matching blocks are ducked broadband with an
|
|
||||||
* immediate attack and a short release. A hold cap ensures only genuinely brief
|
|
||||||
* events are cut — a sustained sound such as a fricative outlasts the cap and is
|
|
||||||
* released, so speech is preserved.
|
|
||||||
*/
|
|
||||||
final class TypingAttenuator {
|
|
||||||
|
|
||||||
private static final double HF_HZ = 4000.0; // high-frequency band start
|
|
||||||
private static final double ONSET_FACTOR = 2.5; // total power vs slow floor
|
|
||||||
private static final double FLUX_FACTOR = 3.0; // total power vs previous block
|
|
||||||
private static final double HF_RATIO = 0.30; // fraction of energy above HF_HZ
|
|
||||||
private static final double SUPPRESS = 0.12; // ducking gain on a detected click (~ -18 dB)
|
|
||||||
private static final double RELEASE = 0.25; // recovery fraction per block after a click
|
|
||||||
private static final double FLOOR_SMOOTH = 0.98; // slow power-floor tracking
|
|
||||||
private static final int MAX_HOLD = 4; // max consecutive ducked blocks (~clicks only)
|
|
||||||
|
|
||||||
private final int bins;
|
|
||||||
private final int hfBin;
|
|
||||||
|
|
||||||
private double slowPower;
|
|
||||||
private double prevPower;
|
|
||||||
private double envGain = 1.0;
|
|
||||||
private int heldBlocks;
|
|
||||||
|
|
||||||
TypingAttenuator(int bins, int sampleRate, int fftSize) {
|
|
||||||
this.bins = bins;
|
|
||||||
this.hfBin = (int) Math.round(HF_HZ * fftSize / sampleRate);
|
|
||||||
}
|
|
||||||
|
|
||||||
void reset() {
|
|
||||||
slowPower = 0;
|
|
||||||
prevPower = 0;
|
|
||||||
envGain = 1.0;
|
|
||||||
heldBlocks = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Multiplies the running per-bin gain by the current broadband ducking gain. */
|
|
||||||
void apply(double[] power, double[] gain) {
|
|
||||||
double total = 0, high = 0;
|
|
||||||
for (int k = 0; k < bins; k++) {
|
|
||||||
total += power[k];
|
|
||||||
if (k >= hfBin) high += power[k];
|
|
||||||
}
|
|
||||||
double hfRatio = high / (total + 1e-12);
|
|
||||||
|
|
||||||
boolean signature = total > slowPower * ONSET_FACTOR
|
|
||||||
&& total > prevPower * FLUX_FACTOR
|
|
||||||
&& hfRatio > HF_RATIO;
|
|
||||||
|
|
||||||
if (signature && heldBlocks < MAX_HOLD) {
|
|
||||||
envGain = SUPPRESS; // fast attack: duck immediately
|
|
||||||
heldBlocks++;
|
|
||||||
} else {
|
|
||||||
envGain += (1 - envGain) * RELEASE;
|
|
||||||
if (!signature) {
|
|
||||||
heldBlocks = 0;
|
|
||||||
// Only let the floor track when we're not inside a transient.
|
|
||||||
slowPower = slowPower == 0 ? total : FLOOR_SMOOTH * slowPower + (1 - FLOOR_SMOOTH) * total;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
prevPower = total;
|
|
||||||
|
|
||||||
for (int k = 0; k < bins; k++) {
|
|
||||||
gain[k] *= envGain;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
package com.ts3client.audio;
|
|
||||||
|
|
||||||
import com.github.manevolent.ts3j.audio.Microphone;
|
|
||||||
import com.ts3client.config.Settings;
|
|
||||||
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Voice capture source feeding the TS3 socket. Extends ts3j's {@link Microphone}
|
|
||||||
* (the encoded-packet supplier) with capture lifecycle and voice-gating controls
|
|
||||||
* so the connection layer can drive it without knowing the platform backend.
|
|
||||||
*/
|
|
||||||
public interface VoiceInput extends Microphone {
|
|
||||||
|
|
||||||
void start();
|
|
||||||
|
|
||||||
void stop();
|
|
||||||
|
|
||||||
void setMuted(boolean muted);
|
|
||||||
|
|
||||||
void setMode(Settings.InputMode mode);
|
|
||||||
|
|
||||||
void setVadMode(Settings.VadMode mode);
|
|
||||||
|
|
||||||
/** Voice-activation volume-gate threshold in dBFS. */
|
|
||||||
void setThresholdDb(double db);
|
|
||||||
|
|
||||||
/** Speech-probability threshold (0..1) for Automatic/Hybrid modes. */
|
|
||||||
void setSpeechThreshold(double threshold);
|
|
||||||
|
|
||||||
/** Keep voice activation active while in push-to-talk mode. */
|
|
||||||
void setVadOverPtt(boolean enabled);
|
|
||||||
|
|
||||||
void setInputGain(double gain);
|
|
||||||
|
|
||||||
/** Enables removal of steady background noise (spectral denoise). */
|
|
||||||
void setNoiseSuppression(boolean enabled);
|
|
||||||
|
|
||||||
/** Background-noise removal aggressiveness, 0 (light) .. 1 (heavy). */
|
|
||||||
void setDenoiserLevel(double level);
|
|
||||||
|
|
||||||
/** Enables detection and attenuation of keyboard typing sounds. */
|
|
||||||
void setTypingAttenuation(boolean enabled);
|
|
||||||
|
|
||||||
/** Enables automatic gain control (normalise microphone loudness). */
|
|
||||||
void setAgc(boolean enabled);
|
|
||||||
|
|
||||||
/** Applies Opus encoder parameters, taking effect immediately if capturing. */
|
|
||||||
void setOpusParameters(OpusParameters parameters);
|
|
||||||
|
|
||||||
void setPushToTalk(boolean pressed);
|
|
||||||
|
|
||||||
/** Receives the live input level in dBFS, once per captured frame. */
|
|
||||||
void setLevelListener(Consumer<Double> listener);
|
|
||||||
|
|
||||||
/** Receives local transmit-state transitions (talking / silent). */
|
|
||||||
void setTalkListener(Consumer<Boolean> listener);
|
|
||||||
|
|
||||||
/** Called when speech is detected while the microphone is muted. */
|
|
||||||
void setMutedTalkListener(Runnable listener);
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
package com.ts3client.config;
|
|
||||||
|
|
||||||
/** A saved server for quick connect. */
|
|
||||||
public final class Bookmark {
|
|
||||||
public String label;
|
|
||||||
public String address;
|
|
||||||
public int port = 9987;
|
|
||||||
public String nickname;
|
|
||||||
public String password = "";
|
|
||||||
/** Identity to connect with; empty means "use the default identity". */
|
|
||||||
public String identityId = "";
|
|
||||||
/**
|
|
||||||
* Channel to join on connect, as a "/"-separated path ("Lobby/Games") or
|
|
||||||
* "/<channelId>". Empty means the server's default channel.
|
|
||||||
*/
|
|
||||||
public String channel = "";
|
|
||||||
/** Password for {@link #channel}, if it is protected. */
|
|
||||||
public String channelPassword = "";
|
|
||||||
/** Connect to this server automatically when the client starts. */
|
|
||||||
public boolean connectOnStartup = false;
|
|
||||||
|
|
||||||
public Bookmark() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public Bookmark(String label, String address, int port, String nickname, String password) {
|
|
||||||
this.label = label;
|
|
||||||
this.address = address;
|
|
||||||
this.port = port;
|
|
||||||
this.nickname = nickname;
|
|
||||||
this.password = password == null ? "" : password;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Display name, falling back to "address:port" when no label is set. */
|
|
||||||
public String displayName() {
|
|
||||||
if (label != null && !label.isBlank()) return label;
|
|
||||||
return address + ":" + port;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return displayName();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,256 +0,0 @@
|
|||||||
package com.ts3client.config;
|
|
||||||
|
|
||||||
import com.ts3client.sound.NotificationSettings;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simple persistent settings backed by a properties file in the user's home
|
|
||||||
* directory (~/.ts3jclient/settings.properties).
|
|
||||||
*
|
|
||||||
* <p>Holds connection defaults, audio device selection and voice-activation
|
|
||||||
* parameters. Loaded once at startup and saved whenever the user changes
|
|
||||||
* something in the options dialog.
|
|
||||||
*/
|
|
||||||
public final class Settings {
|
|
||||||
|
|
||||||
/** How the microphone decides when to transmit. */
|
|
||||||
public enum InputMode {
|
|
||||||
/** Transmit whenever voice activation detects speech. */
|
|
||||||
VOICE_ACTIVATION,
|
|
||||||
/** Transmit only while the push-to-talk key is held. */
|
|
||||||
PUSH_TO_TALK,
|
|
||||||
/** Always transmit (continuous). */
|
|
||||||
CONTINUOUS
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Voice-activation strategy, mirroring the TS3 client's VAD modes. */
|
|
||||||
public enum VadMode {
|
|
||||||
/** Speech-probability detector only. */
|
|
||||||
AUTOMATIC,
|
|
||||||
/** Volume gate (RMS threshold) only. */
|
|
||||||
VOLUME_GATE,
|
|
||||||
/** Volume gate combined with speech probability. */
|
|
||||||
HYBRID
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final File DIR = new File(System.getProperty("user.home"), ".ts3jclient");
|
|
||||||
private static final File FILE = new File(DIR, "settings.properties");
|
|
||||||
|
|
||||||
private final Properties props = new Properties();
|
|
||||||
|
|
||||||
// ---- connection ----
|
|
||||||
public String lastAddress = "localhost";
|
|
||||||
public String nickname = System.getProperty("user.name", "TS3J User");
|
|
||||||
public String serverPassword = "";
|
|
||||||
/** Legacy single-identity file; only used to migrate into the identity store. */
|
|
||||||
public String identityFile = new File(DIR, "identity.ini").getAbsolutePath();
|
|
||||||
/** Id of the identity used when a server doesn't select one of its own. */
|
|
||||||
public String defaultIdentityId = "";
|
|
||||||
|
|
||||||
// ---- audio devices (mixer names; empty = system default) ----
|
|
||||||
public String inputDevice = "";
|
|
||||||
public String outputDevice = "";
|
|
||||||
|
|
||||||
// ---- voice ----
|
|
||||||
public InputMode inputMode = InputMode.VOICE_ACTIVATION;
|
|
||||||
/** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */
|
|
||||||
public VadMode vadMode = VadMode.HYBRID;
|
|
||||||
/** VAD threshold in dBFS (RMS). Typical range -60 (sensitive) .. -10 (loud). */
|
|
||||||
public double vadThresholdDb = -45.0;
|
|
||||||
/** Speech-probability threshold (0..1) for Automatic/Hybrid modes. */
|
|
||||||
public double speechThreshold = 0.5;
|
|
||||||
/** Keep voice activation running while in push-to-talk mode. */
|
|
||||||
public boolean vadOverPtt = false;
|
|
||||||
/** Push-to-talk key as an AWT virtual-key code; the frontend interprets it. Default: Ctrl (VK_CONTROL). */
|
|
||||||
public int pushToTalkKey = 17;
|
|
||||||
/** Opus target bitrate in bits/sec. */
|
|
||||||
public int bitrate = 48000;
|
|
||||||
/** Opus complexity 0..10. */
|
|
||||||
public int complexity = 10;
|
|
||||||
/** Opus variable bitrate. */
|
|
||||||
public boolean vbr = true;
|
|
||||||
/** Opus in-band forward error correction. */
|
|
||||||
public boolean fec = true;
|
|
||||||
/** Expected packet loss percent (drives FEC). */
|
|
||||||
public int packetLoss = 5;
|
|
||||||
/** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */
|
|
||||||
public boolean music = false;
|
|
||||||
/** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */
|
|
||||||
public double outputVolume = 1.0;
|
|
||||||
/** Microphone input gain multiplier applied before VAD/encode. */
|
|
||||||
public double inputVolume = 1.0;
|
|
||||||
/** Remove steady background noise from the microphone (spectral denoise). */
|
|
||||||
public boolean denoise = true;
|
|
||||||
/** Background-noise removal aggressiveness, 0 (light) .. 1 (heavy). */
|
|
||||||
public double denoiserLevel = 0.5;
|
|
||||||
/** Detect and attenuate keyboard typing sounds in the microphone. */
|
|
||||||
public boolean typingAttenuation = true;
|
|
||||||
/** Automatic gain control: normalise microphone loudness to a target level. */
|
|
||||||
public boolean agc = true;
|
|
||||||
|
|
||||||
// ---- notification sounds ----
|
|
||||||
/** Directory name of the active sound pack; empty picks the first one found. */
|
|
||||||
public String soundPack = "default";
|
|
||||||
/** Notification sound volume, 0..1. */
|
|
||||||
public double soundVolume = 1.0;
|
|
||||||
/** Extra folder to look for sound packs in, on top of the well-known locations. */
|
|
||||||
public String soundPackDir = "";
|
|
||||||
// ---- icons ----
|
|
||||||
/** File name of the active icon pack; empty uses the built-in icons. */
|
|
||||||
public String iconPack = "default_colored_2014.zip";
|
|
||||||
/** Extra folder to look for icon packs in, on top of the well-known locations. */
|
|
||||||
public String iconPackDir = "";
|
|
||||||
|
|
||||||
/** Which actions make a sound, and which ones are important enough to survive muting. */
|
|
||||||
public final NotificationSettings notifications = new NotificationSettings();
|
|
||||||
|
|
||||||
public static Settings load() {
|
|
||||||
Settings s = new Settings();
|
|
||||||
try {
|
|
||||||
if (FILE.isFile()) {
|
|
||||||
try (FileInputStream in = new FileInputStream(FILE)) {
|
|
||||||
s.props.load(in);
|
|
||||||
}
|
|
||||||
s.applyFromProps();
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
// Corrupt/unreadable settings -> fall back to defaults.
|
|
||||||
}
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void save() {
|
|
||||||
try {
|
|
||||||
if (!DIR.isDirectory()) {
|
|
||||||
//noinspection ResultOfMethodCallIgnored
|
|
||||||
DIR.mkdirs();
|
|
||||||
}
|
|
||||||
writeToProps();
|
|
||||||
try (FileOutputStream out = new FileOutputStream(FILE)) {
|
|
||||||
props.store(out, "TS3J Swing Client settings");
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public File identityFile() {
|
|
||||||
return new File(identityFile);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The directory holding all persistent client state (settings, identities, caches). */
|
|
||||||
public static File configDir() {
|
|
||||||
return DIR;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void applyFromProps() {
|
|
||||||
lastAddress = props.getProperty("lastAddress", lastAddress);
|
|
||||||
nickname = props.getProperty("nickname", nickname);
|
|
||||||
serverPassword = props.getProperty("serverPassword", serverPassword);
|
|
||||||
identityFile = props.getProperty("identityFile", identityFile);
|
|
||||||
defaultIdentityId = props.getProperty("defaultIdentityId", defaultIdentityId);
|
|
||||||
inputDevice = props.getProperty("inputDevice", inputDevice);
|
|
||||||
outputDevice = props.getProperty("outputDevice", outputDevice);
|
|
||||||
inputMode = parseMode(props.getProperty("inputMode"), inputMode);
|
|
||||||
vadMode = parseVadMode(props.getProperty("vadMode"), vadMode);
|
|
||||||
vadThresholdDb = parseD(props.getProperty("vadThresholdDb"), vadThresholdDb);
|
|
||||||
speechThreshold = parseD(props.getProperty("speechThreshold"), speechThreshold);
|
|
||||||
vadOverPtt = parseB(props.getProperty("vadOverPtt"), vadOverPtt);
|
|
||||||
pushToTalkKey = parseI(props.getProperty("pushToTalkKey"), pushToTalkKey);
|
|
||||||
bitrate = parseI(props.getProperty("bitrate"), bitrate);
|
|
||||||
complexity = parseI(props.getProperty("complexity"), complexity);
|
|
||||||
vbr = parseB(props.getProperty("vbr"), vbr);
|
|
||||||
fec = parseB(props.getProperty("fec"), fec);
|
|
||||||
packetLoss = parseI(props.getProperty("packetLoss"), packetLoss);
|
|
||||||
music = parseB(props.getProperty("music"), music);
|
|
||||||
outputVolume = parseD(props.getProperty("outputVolume"), outputVolume);
|
|
||||||
inputVolume = parseD(props.getProperty("inputVolume"), inputVolume);
|
|
||||||
denoise = parseB(props.getProperty("denoise"), denoise);
|
|
||||||
denoiserLevel = parseD(props.getProperty("denoiserLevel"), denoiserLevel);
|
|
||||||
typingAttenuation = parseB(props.getProperty("typingAttenuation"), typingAttenuation);
|
|
||||||
agc = parseB(props.getProperty("agc"), agc);
|
|
||||||
soundPack = props.getProperty("soundPack", soundPack);
|
|
||||||
soundVolume = parseD(props.getProperty("soundVolume"), soundVolume);
|
|
||||||
soundPackDir = props.getProperty("soundPackDir", soundPackDir);
|
|
||||||
iconPack = props.getProperty("iconPack", iconPack);
|
|
||||||
iconPackDir = props.getProperty("iconPackDir", iconPackDir);
|
|
||||||
notifications.load(props);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void writeToProps() {
|
|
||||||
props.setProperty("lastAddress", lastAddress);
|
|
||||||
props.setProperty("nickname", nickname);
|
|
||||||
props.setProperty("serverPassword", serverPassword);
|
|
||||||
props.setProperty("identityFile", identityFile);
|
|
||||||
props.setProperty("defaultIdentityId", defaultIdentityId);
|
|
||||||
props.setProperty("inputDevice", inputDevice);
|
|
||||||
props.setProperty("outputDevice", outputDevice);
|
|
||||||
props.setProperty("inputMode", inputMode.name());
|
|
||||||
props.setProperty("vadMode", vadMode.name());
|
|
||||||
props.setProperty("vadThresholdDb", Double.toString(vadThresholdDb));
|
|
||||||
props.setProperty("speechThreshold", Double.toString(speechThreshold));
|
|
||||||
props.setProperty("vadOverPtt", Boolean.toString(vadOverPtt));
|
|
||||||
props.setProperty("pushToTalkKey", Integer.toString(pushToTalkKey));
|
|
||||||
props.setProperty("bitrate", Integer.toString(bitrate));
|
|
||||||
props.setProperty("complexity", Integer.toString(complexity));
|
|
||||||
props.setProperty("vbr", Boolean.toString(vbr));
|
|
||||||
props.setProperty("fec", Boolean.toString(fec));
|
|
||||||
props.setProperty("packetLoss", Integer.toString(packetLoss));
|
|
||||||
props.setProperty("music", Boolean.toString(music));
|
|
||||||
props.setProperty("outputVolume", Double.toString(outputVolume));
|
|
||||||
props.setProperty("inputVolume", Double.toString(inputVolume));
|
|
||||||
props.setProperty("denoise", Boolean.toString(denoise));
|
|
||||||
props.setProperty("denoiserLevel", Double.toString(denoiserLevel));
|
|
||||||
props.setProperty("typingAttenuation", Boolean.toString(typingAttenuation));
|
|
||||||
props.setProperty("agc", Boolean.toString(agc));
|
|
||||||
props.setProperty("soundPack", soundPack);
|
|
||||||
props.setProperty("soundVolume", Double.toString(soundVolume));
|
|
||||||
props.setProperty("soundPackDir", soundPackDir);
|
|
||||||
props.setProperty("iconPack", iconPack);
|
|
||||||
props.setProperty("iconPackDir", iconPackDir);
|
|
||||||
notifications.store(props);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static InputMode parseMode(String v, InputMode def) {
|
|
||||||
if (v == null) return def;
|
|
||||||
try {
|
|
||||||
return InputMode.valueOf(v);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return def;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static VadMode parseVadMode(String v, VadMode def) {
|
|
||||||
if (v == null) return def;
|
|
||||||
try {
|
|
||||||
return VadMode.valueOf(v);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return def;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static double parseD(String v, double def) {
|
|
||||||
if (v == null) return def;
|
|
||||||
try {
|
|
||||||
return Double.parseDouble(v);
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
return def;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int parseI(String v, int def) {
|
|
||||||
if (v == null) return def;
|
|
||||||
try {
|
|
||||||
return Integer.parseInt(v);
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
return def;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean parseB(String v, boolean def) {
|
|
||||||
return v == null ? def : Boolean.parseBoolean(v);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
package com.ts3client.gfx;
|
|
||||||
|
|
||||||
import com.ts3client.config.InstallDirs;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Finds the icon packs installed on this machine: the client's own {@code gfx/}
|
|
||||||
* folder, an extra folder the user configured, and the {@code gfx/} folder of an
|
|
||||||
* installed TeamSpeak 3 client (whose packs are usable as they are, see
|
|
||||||
* {@link IconPack}).
|
|
||||||
*/
|
|
||||||
public final class IconPacks {
|
|
||||||
|
|
||||||
/** The pack every other one falls back to, as TeamSpeak does. */
|
|
||||||
public static final String DEFAULT_ID = "default.zip";
|
|
||||||
|
|
||||||
private IconPacks() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Loads every pack found under {@code extraDirectory} and the well-known
|
|
||||||
* locations, the first search root winning on a name clash.
|
|
||||||
*
|
|
||||||
* @param userDirectory the client's own pack folder (may not exist yet)
|
|
||||||
* @param extraDirectory an additional folder chosen by the user, or {@code null}
|
|
||||||
* @return the packs, ordered by display name
|
|
||||||
*/
|
|
||||||
public static List<IconPack> findAll(File userDirectory, String extraDirectory) {
|
|
||||||
Map<String, IconPack> byId = new LinkedHashMap<>();
|
|
||||||
for (File root : InstallDirs.searchRoots("gfx", userDirectory, extraDirectory)) {
|
|
||||||
File[] children = root.listFiles();
|
|
||||||
if (children == null) continue;
|
|
||||||
for (File child : children) {
|
|
||||||
if (child.isFile() && !child.getName().toLowerCase(Locale.ROOT).endsWith(".zip")) continue;
|
|
||||||
if (byId.containsKey(child.getName())) continue;
|
|
||||||
IconPack pack = IconPack.load(child);
|
|
||||||
if (pack != null) byId.put(pack.id(), pack);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
List<IconPack> packs = new ArrayList<>(byId.values());
|
|
||||||
packs.sort(Comparator.comparing(p -> p.name().toLowerCase(Locale.ROOT)));
|
|
||||||
return packs;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return the pack with this id, or {@code null} when it is not installed */
|
|
||||||
public static IconPack select(List<IconPack> packs, String id) {
|
|
||||||
for (IconPack p : packs) {
|
|
||||||
if (p.id().equals(id)) return p;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return the pack unresolved icons are taken from, or {@code null} */
|
|
||||||
public static IconPack fallback(List<IconPack> packs) {
|
|
||||||
return select(packs, DEFAULT_ID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
package com.ts3client.net;
|
|
||||||
|
|
||||||
/** Mutable view-model of a connected client. */
|
|
||||||
public final class ClientEntry {
|
|
||||||
public final int id;
|
|
||||||
public int channelId;
|
|
||||||
public String nickname;
|
|
||||||
public String uniqueId = "";
|
|
||||||
public int type; // 0 = normal voice client, 1 = server-query
|
|
||||||
public int talkPower;
|
|
||||||
|
|
||||||
public int[] serverGroupIds = new int[0];
|
|
||||||
public int channelGroupId;
|
|
||||||
|
|
||||||
// Filled on demand from clientinfo.
|
|
||||||
public String platform = "";
|
|
||||||
public String version = "";
|
|
||||||
public long idleTimeMs;
|
|
||||||
public String description = "";
|
|
||||||
|
|
||||||
public boolean talking;
|
|
||||||
public boolean inputMuted; // microphone muted (client_input_muted)
|
|
||||||
public boolean outputMuted; // speakers muted / deafened (client_output_muted)
|
|
||||||
public boolean away;
|
|
||||||
/** The message published with the away state, empty when there is none. */
|
|
||||||
public String awayMessage = "";
|
|
||||||
public boolean channelCommander;
|
|
||||||
public boolean self;
|
|
||||||
|
|
||||||
public ClientEntry(int id, String nickname) {
|
|
||||||
this.id = id;
|
|
||||||
this.nickname = nickname;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isQuery() {
|
|
||||||
return type == 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package com.ts3client.net;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* UI-facing callbacks fired by {@link TeamspeakConnection}. Implementations are
|
|
||||||
* responsible for marshalling to the Swing EDT.
|
|
||||||
*/
|
|
||||||
public interface ConnectionListener {
|
|
||||||
|
|
||||||
/** Message scope for chat display. */
|
|
||||||
enum ChatScope {SERVER, CHANNEL, PRIVATE}
|
|
||||||
|
|
||||||
void onStatus(String status);
|
|
||||||
|
|
||||||
void onConnected();
|
|
||||||
|
|
||||||
void onDisconnected(String reason);
|
|
||||||
|
|
||||||
/** The channel/client model changed and any tree view should be rebuilt. */
|
|
||||||
void onModelChanged();
|
|
||||||
|
|
||||||
/** On-demand channel/client details finished loading; refresh any info view. */
|
|
||||||
void onInfoUpdated();
|
|
||||||
|
|
||||||
/** A group icon finished downloading; repaint anything showing icons. */
|
|
||||||
void onIconsUpdated();
|
|
||||||
|
|
||||||
void onChat(ChatScope scope, int fromClientId, String fromName, String message);
|
|
||||||
|
|
||||||
/** A client (possibly the local one) started or stopped talking. */
|
|
||||||
void onTalkStateChanged(int clientId, boolean talking);
|
|
||||||
|
|
||||||
void onError(String message);
|
|
||||||
|
|
||||||
/** Someone poked the local client. */
|
|
||||||
void onPoke(String fromName, String message);
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
package com.ts3client.net;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A snapshot of a client's connection statistics, as shown in the Connection
|
|
||||||
* Info window. Values default to {@code -1} meaning "unknown / not reported",
|
|
||||||
* which callers should render as a dash.
|
|
||||||
*
|
|
||||||
* <p>For the local client the figures are read live from the socket's own
|
|
||||||
* packet counters and are fully populated, including the per-{@link Kind}
|
|
||||||
* breakdown. For a remote client the figures come from the server's
|
|
||||||
* {@code notifyconnectioninfo} report and only the aggregate totals are
|
|
||||||
* available; {@link #perKind} is then empty.
|
|
||||||
*/
|
|
||||||
public final class ConnectionStats {
|
|
||||||
|
|
||||||
/** The three traffic categories TeamSpeak accounts separately. */
|
|
||||||
public enum Kind {KEEPALIVE, CONTROL, SPEECH}
|
|
||||||
|
|
||||||
public int clientId;
|
|
||||||
public String nickname = "";
|
|
||||||
public boolean self;
|
|
||||||
|
|
||||||
/** True when derived from local live counters (self); false for a server snapshot. */
|
|
||||||
public boolean live;
|
|
||||||
|
|
||||||
public String ip = "";
|
|
||||||
public String version = "";
|
|
||||||
public String platform = "";
|
|
||||||
|
|
||||||
public double pingMs = -1;
|
|
||||||
public double pingDeviationMs = -1;
|
|
||||||
/** Total packet loss as a fraction 0..1, or -1 if unknown. */
|
|
||||||
public double packetLoss = -1;
|
|
||||||
public long connectedTimeMs = -1;
|
|
||||||
public long idleTimeMs = -1;
|
|
||||||
|
|
||||||
public long filetransferBandwidthSent = -1;
|
|
||||||
public long filetransferBandwidthReceived = -1;
|
|
||||||
|
|
||||||
// Aggregate totals across all traffic kinds.
|
|
||||||
public long packetsSentTotal = -1;
|
|
||||||
public long packetsReceivedTotal = -1;
|
|
||||||
public long bytesSentTotal = -1;
|
|
||||||
public long bytesReceivedTotal = -1;
|
|
||||||
public long bandwidthSentLastSecond = -1;
|
|
||||||
public long bandwidthReceivedLastSecond = -1;
|
|
||||||
public long bandwidthSentLastMinute = -1;
|
|
||||||
public long bandwidthReceivedLastMinute = -1;
|
|
||||||
|
|
||||||
/** Per-category breakdown (one row per {@link Kind}); empty when unavailable. */
|
|
||||||
public final List<KindStats> perKind = new ArrayList<>();
|
|
||||||
|
|
||||||
public boolean hasBreakdown() {
|
|
||||||
return !perKind.isEmpty();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Returns the stats for {@code kind}, or {@code null} if not present. */
|
|
||||||
public KindStats kind(Kind kind) {
|
|
||||||
for (KindStats k : perKind) {
|
|
||||||
if (k.kind == kind) return k;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Returns the stats for {@code kind}, creating and registering the row if needed. */
|
|
||||||
public KindStats getOrCreateKind(Kind kind) {
|
|
||||||
KindStats existing = kind(kind);
|
|
||||||
if (existing != null) return existing;
|
|
||||||
KindStats created = new KindStats(kind);
|
|
||||||
perKind.add(created);
|
|
||||||
return created;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One category's counters. Values default to {@code -1} meaning "unknown". */
|
|
||||||
public static final class KindStats {
|
|
||||||
public final Kind kind;
|
|
||||||
public double packetLoss = -1; // fraction 0..1
|
|
||||||
public long packetsSent = -1;
|
|
||||||
public long packetsReceived = -1;
|
|
||||||
public long bytesSent = -1;
|
|
||||||
public long bytesReceived = -1;
|
|
||||||
public long bandwidthSentLastSecond = -1;
|
|
||||||
public long bandwidthReceivedLastSecond = -1;
|
|
||||||
public long bandwidthSentLastMinute = -1;
|
|
||||||
public long bandwidthReceivedLastMinute = -1;
|
|
||||||
|
|
||||||
public KindStats(Kind kind) {
|
|
||||||
this.kind = kind;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user