Compare commits
273
Commits
v1.0.0
...
380ea5acd6
@@ -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,153 @@
|
|||||||
|
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"
|
||||||
|
ndk {
|
||||||
|
abiFilters += listOf("arm64-v8a", "x86_64")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
|
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
+14
@@ -0,0 +1,14 @@
|
|||||||
|
# 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.** { *; }
|
||||||
|
|
||||||
|
# ini4j (identity .ini files) instantiates its parsers, builders, formatters
|
||||||
|
# and escape tools through ServiceFinder, by reflection.
|
||||||
|
-keepclassmembers class org.ini4j.spi.** { <init>(); }
|
||||||
@@ -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,36 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import eu.lixko.ts3j.client.config.BanReasonPresets
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmarks
|
||||||
|
import eu.lixko.ts3j.client.config.IdentityStore
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactStore
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
|
||||||
|
|
||||||
|
/** What lives as long as the process, wired together once; each screen is handed only the parts it uses. */
|
||||||
|
class AppParts(context: Context) {
|
||||||
|
val settings: Settings = Settings.load()
|
||||||
|
val icons = IconTheme(context, settings)
|
||||||
|
val pictures = WebPictures(context.cacheDir, settings)
|
||||||
|
val swipe = SwipePrefs(context)
|
||||||
|
/** The reasons offered when adding a ban; shared by every server. */
|
||||||
|
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
|
||||||
|
|
||||||
|
private val bookmarkStore = Bookmarks.load()
|
||||||
|
private val identityStore = IdentityStore.load(settings)
|
||||||
|
private val contactStore = ContactStore.load()
|
||||||
|
|
||||||
|
val identities: IdentityManager = IdentityManager(context, identityStore, settings, bookmarkStore) { bookmarks.refresh() }
|
||||||
|
val bookmarks: BookmarkManager = BookmarkManager(context, icons, bookmarkStore, identities) { sessions.bookmarkEdited(it) }
|
||||||
|
val contacts: ContactManager = ContactManager(context, contactStore, settings)
|
||||||
|
val whisperLists: WhisperListManager = WhisperListManager()
|
||||||
|
val audio: AudioSetup = AudioSetup(context, settings)
|
||||||
|
val myTeamSpeak: MyTeamSpeakAccount = MyTeamSpeakAccount(context, pictures,
|
||||||
|
TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore), bookmarks, identities,
|
||||||
|
identityStore, bookmarkStore, settings) { sessions.myTeamSpeakChanged() }
|
||||||
|
|
||||||
|
private val serverParts = ServerParts(context, settings, identityStore, audio, contactStore, myTeamSpeak)
|
||||||
|
val sessions: SessionController = SessionController(context, settings, identities, bookmarks, serverParts,
|
||||||
|
LevelMonitor(settings, audio.audio))
|
||||||
|
}
|
||||||
@@ -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,76 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
|
||||||
|
import eu.lixko.ts3j.client.android.audio.AudioRoute
|
||||||
|
import eu.lixko.ts3j.client.audio.AudioDevice
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.sound.SoundNotifier
|
||||||
|
import eu.lixko.ts3j.client.sound.SoundPack
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/** The devices and routing audio goes through, the sound packs, and the floating push-to-talk button. */
|
||||||
|
class AudioSetup internal constructor(private val context: Context, private val settings: Settings) {
|
||||||
|
internal val audio = AndroidAudioBackend(context)
|
||||||
|
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
|
||||||
|
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
|
||||||
|
|
||||||
|
private val routePrefs = AudioRoutePrefs(context)
|
||||||
|
private val _route = MutableStateFlow(routePrefs.load())
|
||||||
|
val route: StateFlow<AudioRoute> = _route
|
||||||
|
|
||||||
|
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
|
||||||
|
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
|
||||||
|
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
|
||||||
|
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
|
||||||
|
|
||||||
|
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
|
||||||
|
|
||||||
|
init {
|
||||||
|
audio.setRoute(_route.value)
|
||||||
|
audio.addDeviceListener {
|
||||||
|
_inputDevices.value = audio.io().inputDevices()
|
||||||
|
_outputDevices.value = audio.io().outputDevices()
|
||||||
|
}
|
||||||
|
settings.outputDevice.addListener { soundPlayer.setOutputDevice(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Microphone preset and playback usage; the open lines move over at once. */
|
||||||
|
fun setRoute(route: AudioRoute) {
|
||||||
|
routePrefs.save(route)
|
||||||
|
_route.value = route
|
||||||
|
audio.setRoute(route)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
|
||||||
|
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
|
||||||
|
|
||||||
|
val soundPack: SoundPack? get() = sounds.pack()
|
||||||
|
|
||||||
|
fun setSoundPack(pack: SoundPack) {
|
||||||
|
sounds.setPack(pack)
|
||||||
|
settings.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unpacks the packs the app ships with, when this version has not yet. */
|
||||||
|
fun installSoundPacks() {
|
||||||
|
if (!SoundPackInstaller(context).install()) return
|
||||||
|
sounds.reload()
|
||||||
|
_soundPacks.value = sounds.availablePacks()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
|
||||||
|
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
|
||||||
|
/** Whether push to talk floats a button over other apps while this one is off screen. */
|
||||||
|
val pttOverlay: StateFlow<Boolean> = _pttOverlay
|
||||||
|
|
||||||
|
fun setPttOverlay(enabled: Boolean) {
|
||||||
|
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
|
||||||
|
_pttOverlay.value = enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val OVERLAY_ENABLED = "enabled"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmarks
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/** The bookmarks, as the connect page lists them and home-screen shortcuts lead to them. */
|
||||||
|
class BookmarkManager internal constructor(
|
||||||
|
context: Context,
|
||||||
|
icons: IconTheme,
|
||||||
|
private val store: Bookmarks,
|
||||||
|
private val identities: IdentityManager,
|
||||||
|
/** A saved bookmark changed, for the servers connected with it. */
|
||||||
|
private val onEdited: (Bookmark) -> Unit,
|
||||||
|
) {
|
||||||
|
private val shortcuts = BookmarkShortcuts(context, icons)
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
private val _all = MutableStateFlow(store.all().toList())
|
||||||
|
val all: StateFlow<List<Bookmark>> = _all
|
||||||
|
|
||||||
|
/** Picks up bookmarks added or changed elsewhere, such as by an import. */
|
||||||
|
fun refresh() {
|
||||||
|
_all.value = store.all().toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun find(id: String): Bookmark? = store.find(id)
|
||||||
|
|
||||||
|
internal fun startupBookmarks(): List<Bookmark> = store.startupBookmarks()
|
||||||
|
|
||||||
|
internal fun add(bookmark: Bookmark) {
|
||||||
|
store.add(bookmark)
|
||||||
|
save()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bookmark to [address] as typed into the connect form, not yet saved. */
|
||||||
|
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark {
|
||||||
|
val (host, port) = SessionController.parseAddress(address)
|
||||||
|
// Only a nickname other than the identity's is the server's own.
|
||||||
|
val own = nickname.takeIf { it != identities.nicknameFor(identityId) }.orEmpty()
|
||||||
|
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */
|
||||||
|
fun save(index: Int, edited: Bookmark) {
|
||||||
|
val all = store.all()
|
||||||
|
if (index !in all.indices) {
|
||||||
|
store.add(edited)
|
||||||
|
} else {
|
||||||
|
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
|
||||||
|
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
|
||||||
|
all[index] = edited
|
||||||
|
}
|
||||||
|
save()
|
||||||
|
onEdited(edited)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remove(bookmark: Bookmark) {
|
||||||
|
val index = store.all().indexOf(bookmark)
|
||||||
|
if (index < 0) return
|
||||||
|
store.remove(index)
|
||||||
|
save()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
|
||||||
|
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
|
||||||
|
main.post {
|
||||||
|
val all = store.all()
|
||||||
|
var changed = false
|
||||||
|
for (i in all.indices) {
|
||||||
|
val b = all[i]
|
||||||
|
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
|
||||||
|
// A new entry, so the list the UI holds changes along with it.
|
||||||
|
all[i] = b.copy().also { it.iconId = iconId }
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if (changed) save()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun save() {
|
||||||
|
store.save()
|
||||||
|
refresh()
|
||||||
|
shortcuts.sync(_all.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
val canPinShortcuts: Boolean get() = shortcuts.supported
|
||||||
|
|
||||||
|
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
|
||||||
|
fun pinShortcut(bookmark: Bookmark) {
|
||||||
|
// A bookmark not saved since ids came in has a new one on every load until it is.
|
||||||
|
store.save()
|
||||||
|
shortcuts.pin(bookmark)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,83 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Immutable
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatScope
|
||||||
|
import eu.lixko.ts3j.client.text.HtmlText
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
|
||||||
|
/** 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.scope()) {
|
||||||
|
ChatScope.SERVER -> server
|
||||||
|
ChatScope.CHANNEL -> channel
|
||||||
|
ChatScope.PRIVATE -> private.firstOrNull { it.key == key }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies [change] to a conversation, opening a private one titled [title] if needed. */
|
||||||
|
fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key.scope()) {
|
||||||
|
ChatScope.SERVER -> copy(server = change(server))
|
||||||
|
ChatScope.CHANNEL -> copy(channel = change(channel))
|
||||||
|
ChatScope.PRIVATE -> {
|
||||||
|
val existing = private.indexOfFirst { it.key == key }
|
||||||
|
if (existing < 0) {
|
||||||
|
copy(private = private + change(Conversation(key, title)))
|
||||||
|
} else {
|
||||||
|
copy(private = private.toMutableList().also { it[existing] = change(it[existing]) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close(key: ChatKey): Chats = copy(private = private.filter { it.key != key })
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/** As many lines as a log history loads; older ones leave the conversation. */
|
||||||
|
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,243 @@
|
|||||||
|
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 icons: IconTheme
|
||||||
|
private lateinit var audio: AudioSetup
|
||||||
|
private lateinit var wifiLock: WifiManager.WifiLock
|
||||||
|
private lateinit var wifiBackgroundLock: WifiManager.WifiLock
|
||||||
|
private lateinit var wakeLock: PowerManager.WakeLock
|
||||||
|
private lateinit var overlay: PttOverlay
|
||||||
|
private var foregroundTypes = 0
|
||||||
|
private var shown: ServerController? = null
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
val parts = (application as Ts3Application).parts
|
||||||
|
sessions = parts.sessions
|
||||||
|
icons = parts.icons
|
||||||
|
audio = parts.audio
|
||||||
|
getSystemService(NotificationManager::class.java).createNotificationChannel(
|
||||||
|
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
|
||||||
|
)
|
||||||
|
// 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 {
|
||||||
|
icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
overlay = PttOverlay(this, icons, sessions::setPushToTalk)
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val owner = sessions.micOwner.flatMapLatest { server ->
|
||||||
|
server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null)
|
||||||
|
}
|
||||||
|
combine(owner, sessions.onScreen, audio.pttOverlay) { held, onScreen, enabled ->
|
||||||
|
val (state, tree) = held ?: return@combine null
|
||||||
|
val wanted = enabled && !onScreen && state.connected && state.micActive &&
|
||||||
|
state.inputMode == Settings.InputMode.PUSH_TO_TALK
|
||||||
|
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 = 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 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,53 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.contacts.Contact
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactDefaults
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactStore
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
/** The contacts: friends, blocked clients and how each is treated. */
|
||||||
|
class ContactManager internal constructor(
|
||||||
|
private val context: Context,
|
||||||
|
internal val store: ContactStore,
|
||||||
|
private val settings: Settings,
|
||||||
|
) {
|
||||||
|
/** Copies of the contacts, as the store's own entries change in place. */
|
||||||
|
private val _all = MutableStateFlow(copies())
|
||||||
|
val all: StateFlow<List<Contact>> = _all
|
||||||
|
|
||||||
|
init {
|
||||||
|
// Mutations report on whichever thread made them, a connection thread included.
|
||||||
|
store.addListener { _all.value = copies() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copies(): List<Contact> = store.all().map { it.copy() }
|
||||||
|
|
||||||
|
/** A copy of the contact to edit and hand back to [save]. */
|
||||||
|
fun find(uniqueId: String): Contact? = store.find(uniqueId)?.copy()
|
||||||
|
|
||||||
|
fun save(contact: Contact) = store.put(contact)
|
||||||
|
|
||||||
|
fun remove(uniqueId: String) = store.remove(uniqueId)
|
||||||
|
|
||||||
|
/** What a new contact starts with; changed in place, then [saveDefaults]. */
|
||||||
|
val defaults: ContactDefaults get() = settings.contactDefaults
|
||||||
|
|
||||||
|
fun saveDefaults() = settings.save()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
|
||||||
|
*
|
||||||
|
* @return how many contacts the file held and how many of them were new
|
||||||
|
*/
|
||||||
|
suspend fun import(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
|
||||||
|
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
|
||||||
|
found.size to if (found.isEmpty()) 0 else store.merge(found)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.ChannelFiles
|
||||||
|
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 files: ChannelFiles) {
|
||||||
|
|
||||||
|
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 -> files.download(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 ->
|
||||||
|
files.upload(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.set(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.get()) ?: 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,173 @@
|
|||||||
|
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.get(),
|
||||||
|
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.get()) != null) return
|
||||||
|
val fallback = entry ?: store.all().firstOrNull() ?: return
|
||||||
|
settings.defaultIdentityId.set(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.get()))?.nickname.orEmpty()
|
||||||
|
|
||||||
|
/** The nickname a connect with [id] goes by: the identity's own, else the global one. */
|
||||||
|
fun nicknameFor(id: String): String = nicknameOf(id).ifBlank { settings.nickname.get() }
|
||||||
|
|
||||||
|
fun setDefault(id: String) {
|
||||||
|
settings.defaultIdentityId.set(id)
|
||||||
|
settings.save()
|
||||||
|
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,97 @@
|
|||||||
|
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(): Settings.InputMode {
|
||||||
|
val mode = settings.inputMode.get()
|
||||||
|
return if (mode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else mode
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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((application as Ts3Application).parts) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,143 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachment
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachments
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTeamSpeak
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
|
||||||
|
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.teamspeak.SyncItem
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
/** A file to share in chat, open for reading. */
|
||||||
|
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The myTeamSpeak account the app stays signed in to: what it syncs, and the files shared
|
||||||
|
* in chat, which are kept in its cloud storage. Its reads block, so they run on [Dispatchers.IO].
|
||||||
|
*/
|
||||||
|
class MyTeamSpeakAccount internal constructor(
|
||||||
|
private val context: Context,
|
||||||
|
private val pictures: WebPictures,
|
||||||
|
private val importer: TeamSpeakImporter,
|
||||||
|
private val bookmarks: BookmarkManager,
|
||||||
|
private val identities: IdentityManager,
|
||||||
|
identityStore: IdentityStore,
|
||||||
|
bookmarkStore: Bookmarks,
|
||||||
|
settings: Settings,
|
||||||
|
/** Signed in or out, for the servers to pass on. */
|
||||||
|
private val onSignInChanged: () -> Unit,
|
||||||
|
) {
|
||||||
|
val login: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
|
||||||
|
|
||||||
|
private val _signedIn = MutableStateFlow(login.isSignedIn)
|
||||||
|
val signedIn: StateFlow<Boolean> = _signedIn
|
||||||
|
|
||||||
|
private val sync = MyTeamSpeakSync(login, identityStore, bookmarkStore, settings)
|
||||||
|
|
||||||
|
/** Files shared in chat. */
|
||||||
|
internal val attachments = ChatAttachments(login).also {
|
||||||
|
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun signIn(email: String, password: String): MyTeamSpeak.Account =
|
||||||
|
withContext(Dispatchers.IO) { login.signIn(email, password) }
|
||||||
|
.also {
|
||||||
|
_signedIn.value = true
|
||||||
|
onSignInChanged()
|
||||||
|
// Shared pictures that could not be had signed out.
|
||||||
|
pictures.retryFailed()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun fetch(): MyTeamSpeak.Account =
|
||||||
|
try {
|
||||||
|
withContext(Dispatchers.IO) { login.fetch() }
|
||||||
|
} finally {
|
||||||
|
// A sign-in the server no longer takes has signed out.
|
||||||
|
_signedIn.value = login.isSignedIn
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun signOut() {
|
||||||
|
login.signOut()
|
||||||
|
_signedIn.value = false
|
||||||
|
onSignInChanged()
|
||||||
|
withContext(Dispatchers.IO) { attachments.close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
|
||||||
|
|
||||||
|
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use; contacts announce themselves. */
|
||||||
|
suspend fun import(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
|
||||||
|
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
|
||||||
|
.also {
|
||||||
|
bookmarks.refresh()
|
||||||
|
identities.refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads what changed in the account and works out what goes which way. Call on the main
|
||||||
|
* thread, which owns the bookmarks and identities; the network part runs on [Dispatchers.IO].
|
||||||
|
*/
|
||||||
|
suspend fun planSync(): MyTeamSpeakSync.Plan =
|
||||||
|
try {
|
||||||
|
sync.plan(withContext(Dispatchers.IO) { sync.fetch() })
|
||||||
|
} finally {
|
||||||
|
_signedIn.value = login.isSignedIn
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sends this side's changes, then brings the account's here; [plan]'s conflicts settled. Main thread. */
|
||||||
|
suspend fun finishSync(plan: MyTeamSpeakSync.Plan): MyTeamSpeakSync.Result {
|
||||||
|
try {
|
||||||
|
withContext(Dispatchers.IO) { sync.upload(plan) }
|
||||||
|
} finally {
|
||||||
|
_signedIn.value = login.isSignedIn
|
||||||
|
}
|
||||||
|
return sync.apply(plan).also {
|
||||||
|
bookmarks.refresh()
|
||||||
|
identities.refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches a file shared in chat whole. */
|
||||||
|
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
|
||||||
|
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
|
||||||
|
|
||||||
|
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
|
||||||
|
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
|
||||||
|
val data = downloadAttachment(ref)
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
|
||||||
|
out.use { it.write(data) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A file picked to share in chat, or why it cannot be. */
|
||||||
|
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
|
||||||
|
runCatching {
|
||||||
|
val resolver = context.contentResolver
|
||||||
|
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
|
||||||
|
null, null, null)?.use { c ->
|
||||||
|
if (!c.moveToFirst()) null
|
||||||
|
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
|
||||||
|
} ?: ("" to -1L)
|
||||||
|
when {
|
||||||
|
size < 0 -> throw IOException("Could not read the file's size")
|
||||||
|
size > ChatAttachments.MAX_UPLOAD_BYTES ->
|
||||||
|
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
|
||||||
|
}
|
||||||
|
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
|
||||||
|
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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…")
|
||||||
|
session.disconnectNow("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.connectErrorId() == ERROR_BANNED) break
|
||||||
|
show("Reconnecting, retrying soon…")
|
||||||
|
delay(retry)
|
||||||
|
retry = (retry * 2).coerceAtMost(MAX_RETRY_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (session.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,19 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.net.RequestException
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.future.await
|
||||||
|
import java.util.concurrent.CompletableFuture
|
||||||
|
|
||||||
|
/** A server request's outcome, failing with its [RequestException]. */
|
||||||
|
internal suspend fun <T> CompletableFuture<T>.result(): Result<T> =
|
||||||
|
try {
|
||||||
|
Result.success(await())
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(RequestException.of(e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same for a request with no result. */
|
||||||
|
internal suspend fun CompletableFuture<Void>.done(): Result<Unit> = result().map { }
|
||||||
@@ -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,556 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatScope
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactType
|
||||||
|
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.Permissions
|
||||||
|
import eu.lixko.ts3j.client.net.RequestException
|
||||||
|
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.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 parts: ServerParts,
|
||||||
|
/** The owner, told of what happens to this server. */
|
||||||
|
private val app: SessionController,
|
||||||
|
) {
|
||||||
|
internal val session = parts.session(Listener())
|
||||||
|
private val network = parts.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 != null && value.isPrivate) parts.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(session.icons(), session.avatars())
|
||||||
|
|
||||||
|
/** A private chat a notification asked to show, until the UI took it up. */
|
||||||
|
private val _chatRequest = MutableStateFlow<ChatKey?>(null)
|
||||||
|
val chatRequest: StateFlow<ChatKey?> = _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) session.microphone() else null
|
||||||
|
internal val playback get() = if (session.isConnected) session.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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The bookmark this server was connected from, if any. */
|
||||||
|
@Volatile
|
||||||
|
private var bookmarkId: String? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var whisperControls = false
|
||||||
|
|
||||||
|
internal fun applyBookmark(bookmark: Bookmark) {
|
||||||
|
bookmarkId = bookmark.id
|
||||||
|
whisperControls = bookmark.showWhisperControls
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes on an edit of the bookmark we connected from, without reconnecting. */
|
||||||
|
internal fun bookmarkEdited(bookmark: Bookmark) {
|
||||||
|
if (bookmark.id == bookmarkId) applyBookmark(bookmark)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bookmark leading back to this server, joining [channelId]; not yet saved. */
|
||||||
|
fun bookmark(channelId: Int): Bookmark? = session.toBookmark(session.model().channelPath(channelId))
|
||||||
|
?.also { it.showWhisperControls = whisperControls }
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
/** Asks for talk power giving [reason], or withdraws the request with null. */
|
||||||
|
fun setTalkRequest(reason: String?) =
|
||||||
|
if (reason == null) session.cancelTalkRequest() else session.requestTalkPower(reason)
|
||||||
|
|
||||||
|
// ---- channels and clients ----
|
||||||
|
|
||||||
|
fun joinChannel(channelId: Int, password: String? = null) {
|
||||||
|
if (session.isConnected) session.channels().join(channelId, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSubscribed(channelId: Int, subscribed: Boolean) {
|
||||||
|
if (session.isConnected) session.channels().setSubscribed(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() }
|
||||||
|
|
||||||
|
/** What we may do on this server; nothing while not connected. */
|
||||||
|
val permissions: Permissions get() = session.permissions()
|
||||||
|
|
||||||
|
/** The channel kicked clients go back to; 0 until the server named it. */
|
||||||
|
val defaultChannelId: Int get() = session.model().defaultChannelId()
|
||||||
|
|
||||||
|
fun moveClients(clientIds: Collection<Int>, channelId: Int) {
|
||||||
|
if (session.isConnected) session.clients().move(clientIds, channelId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun poke(clientId: Int, message: String) {
|
||||||
|
if (session.isConnected) session.clients().poke(clientId, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The client's playback volume change in dB; 0 when unchanged. */
|
||||||
|
fun clientVolume(clientId: Int): Double =
|
||||||
|
session.model().getClient(clientId)?.let { session.contacts().volumeModifier(it) } ?: 0.0
|
||||||
|
|
||||||
|
fun setClientVolume(clientId: Int, decibels: Double) {
|
||||||
|
session.model().getClient(clientId)?.let { session.contacts().setVolumeModifier(it, decibels) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- whisper ----
|
||||||
|
|
||||||
|
fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper)
|
||||||
|
|
||||||
|
fun whisperToChannel(channelId: Int) = session.model().getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) }
|
||||||
|
|
||||||
|
fun whisperToClient(clientId: Int) = session.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? = session.model().getChannel(channelId)?.let { session.model().channelPath(it.id) }
|
||||||
|
|
||||||
|
fun clientRef(clientId: Int): WhisperList.Client? =
|
||||||
|
session.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 session.model().allClients().filter { it.id != session.selfClientId() && !it.uniqueId.isNullOrEmpty() }
|
||||||
|
.sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) }
|
||||||
|
|
||||||
|
fun channelPaths(): List<String> = session.channelPaths()
|
||||||
|
|
||||||
|
// ---- channel administration ----
|
||||||
|
|
||||||
|
/** 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) session.model().siblingsOf(channelId) else session.model().childrenOf(parentId)
|
||||||
|
|
||||||
|
/** A channel's editable properties as the server has them. */
|
||||||
|
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = session.channels().settings(channelId).result()
|
||||||
|
|
||||||
|
suspend fun editChannel(channelId: Int, changes: Map<String, String>): Result<Unit> =
|
||||||
|
if (changes.isEmpty()) Result.success(Unit)
|
||||||
|
else session.channels().edit(channelId, changes, emptyMap(), emptyList()).done()
|
||||||
|
|
||||||
|
suspend fun createChannel(parentId: Int, settings: ChannelSettings): Result<Unit> =
|
||||||
|
session.channels().create(parentId, settings.creationParameters(), emptyMap()).result().map { }
|
||||||
|
|
||||||
|
/** Deletes a channel, with its sub-channels and the clients in it moved out. */
|
||||||
|
suspend fun deleteChannel(channelId: Int): Result<Unit> = session.channels().delete(channelId, true).done()
|
||||||
|
|
||||||
|
// ---- files ----
|
||||||
|
|
||||||
|
val files = parts.fileTransfers(session.files())
|
||||||
|
|
||||||
|
/** 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 { session.files().list(channelId, password, path) } }
|
||||||
|
|
||||||
|
suspend fun createDirectory(channelId: Int, password: String, path: String): Result<Unit> =
|
||||||
|
fileCall { session.files().createDirectory(channelId, password, path) }
|
||||||
|
|
||||||
|
suspend fun deleteFile(channelId: Int, password: String, path: String): Result<Unit> =
|
||||||
|
fileCall { session.files().delete(channelId, password, path) }
|
||||||
|
|
||||||
|
suspend fun renameFile(channelId: Int, password: String, from: String, to: String): Result<Unit> =
|
||||||
|
fileCall { session.files().rename(channelId, password, from, to) }
|
||||||
|
|
||||||
|
private suspend fun fileCall(call: () -> Unit): Result<Unit> = withContext(Dispatchers.IO) { runCatching(call) }
|
||||||
|
|
||||||
|
// ---- moderation ----
|
||||||
|
|
||||||
|
val canRequestTalkPower: Boolean get() = session.canRequestTalkPower()
|
||||||
|
|
||||||
|
fun kickFromChannel(clientIds: Collection<Int>, reason: String) {
|
||||||
|
if (session.isConnected) session.clients().kickFromChannel(clientIds, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun kickFromServer(clientIds: Collection<Int>, reason: String) {
|
||||||
|
if (session.isConnected) session.clients().kickFromServer(clientIds, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setTalker(clientIds: Collection<Int>, talker: Boolean) {
|
||||||
|
if (session.isConnected) session.clients().setTalker(clientIds, talker)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bans a client for [seconds], or for good with 0. */
|
||||||
|
fun ban(clientId: Int, seconds: Long, reason: String) {
|
||||||
|
if (session.isConnected) session.clients().ban(clientId, seconds, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun serverGroupChoices(clientId: Int): List<GroupChoice> =
|
||||||
|
session.model().getClient(clientId)?.let(session.model()::serverGroupChoices).orEmpty()
|
||||||
|
|
||||||
|
fun channelGroupChoices(clientId: Int): List<GroupChoice> =
|
||||||
|
session.model().getClient(clientId)?.let(session.model()::channelGroupChoices).orEmpty()
|
||||||
|
|
||||||
|
fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) {
|
||||||
|
val client = session.model().getClient(clientId) ?: return
|
||||||
|
if (session.isConnected) session.clients().setServerGroup(client.databaseId, groupId, assign)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gives a client [groupId] in the channel they are in. */
|
||||||
|
fun setChannelGroup(clientId: Int, groupId: Int) {
|
||||||
|
val client = session.model().getClient(clientId) ?: return
|
||||||
|
if (session.isConnected) session.clients().setChannelGroup(client.databaseId, client.channelId, groupId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- ban list ----
|
||||||
|
|
||||||
|
/** 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 -> session.requestConnectionInfo(clientId) { done.resume(it) } }
|
||||||
|
|
||||||
|
/** The server's bans, or why they could not be read. */
|
||||||
|
suspend fun banList(): Result<List<BanEntry>> = session.bans().list().result()
|
||||||
|
|
||||||
|
suspend fun addBan(rule: BanRule): Result<Unit> = session.bans().add(rule).done()
|
||||||
|
|
||||||
|
suspend fun replaceBan(banId: Int, rule: BanRule): Result<Unit> = session.bans().replace(banId, rule).done()
|
||||||
|
|
||||||
|
suspend fun deleteBans(banIds: Collection<Int>): Result<Unit> = session.bans().delete(banIds).done()
|
||||||
|
|
||||||
|
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = permissions.canDeleteBans(bans, session.selfUniqueId())
|
||||||
|
|
||||||
|
fun canEditBan(ban: BanEntry): Boolean = permissions.canEditBan(ban, session.selfUniqueId())
|
||||||
|
|
||||||
|
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(session.selfUniqueId())
|
||||||
|
|
||||||
|
/** Uploads [data] as our avatar. */
|
||||||
|
suspend fun setAvatar(data: ByteArray): Result<Unit> {
|
||||||
|
if (!session.isConnected) return Result.failure(RequestException.notConnected())
|
||||||
|
val file = withContext(Dispatchers.IO) {
|
||||||
|
File.createTempFile("avatar", null, parts.cacheDir).apply { writeBytes(data) }
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
session.avatarAdmin().set(file).done()
|
||||||
|
} finally {
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- details ----
|
||||||
|
|
||||||
|
fun serverDetails(): Details? =
|
||||||
|
if (session.isConnected) Details.server(session.model(), "${session.address()}:${session.port()}") else null
|
||||||
|
|
||||||
|
fun channelDetails(channelId: Int): Details? = session.model().getChannel(channelId)?.let(Details::channel)
|
||||||
|
|
||||||
|
fun clientDetails(clientId: Int): Details? = session.model().getClient(clientId)?.let {
|
||||||
|
Details.client(it, session.model(), parts.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 = session.model().getChannel(channelId) ?: return
|
||||||
|
if (session.isConnected && !channel.descriptionLoaded) session.channels().requestInfo(channelId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestClientDetails(clientId: Int) {
|
||||||
|
if (session.isConnected) session.clients().requestInfo(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 = session.model().getClient(clientId) ?: return
|
||||||
|
parts.contactStore.add(client.uniqueId, client.nickname, type, parts.settings.contactDefaults)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun contactsChanged() {
|
||||||
|
treeScope.launch { session.contacts().applyAll() }
|
||||||
|
scheduleTree(structure = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- chat ----
|
||||||
|
|
||||||
|
/** Opens the private chat with a client, loading what was said before. */
|
||||||
|
fun openPrivateChat(clientId: Int): ChatKey {
|
||||||
|
val key = ChatKey.privateWith(clientId)
|
||||||
|
val client = session.model().getClient(clientId)
|
||||||
|
if (client != null) {
|
||||||
|
_chats.update { chats ->
|
||||||
|
chats.update(key, session.contacts().displayName(client)) { it.copy(uniqueId = client.uniqueId) }
|
||||||
|
}
|
||||||
|
session.loadPrivateChatHistory(clientId, client.uniqueId)
|
||||||
|
}
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
|
||||||
|
fun closePrivateChat(key: ChatKey) = _chats.update { it.close(key) }
|
||||||
|
|
||||||
|
fun send(key: ChatKey, text: String) = session.sendChat(key, text)
|
||||||
|
|
||||||
|
/** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */
|
||||||
|
suspend fun sendFile(key: ChatKey, uri: Uri) {
|
||||||
|
parts.openShared(uri)
|
||||||
|
.onSuccess { session.sendAttachment(key, parts.attachments, it.data, it.size, it.name) }
|
||||||
|
.onFailure { app.error(it.message ?: "Could not read the file") }
|
||||||
|
}
|
||||||
|
|
||||||
|
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.privateWith(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.privateWith(clientId), text) else parts.notifier.clear(id, clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun addLine(key: ChatKey, title: String, html: String) {
|
||||||
|
val line = ChatLine(lineIds.incrementAndGet(), html)
|
||||||
|
_chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun replaceLines(key: ChatKey, title: String, html: List<String>) {
|
||||||
|
val lines = html.map { ChatLine(lineIds.incrementAndGet(), it) }
|
||||||
|
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One of this app's own notices, in the server chat. */
|
||||||
|
private fun system(text: String) = addLine(ChatKey.SERVER, "", ChatHtml.system(text))
|
||||||
|
|
||||||
|
// ---- snapshots ----
|
||||||
|
|
||||||
|
private fun snapshotState(): SessionState {
|
||||||
|
val self = session.model().getClient(session.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) session.selfClientId() else 0,
|
||||||
|
channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
|
||||||
|
inputMode = parts.settings.inputMode.get(),
|
||||||
|
hostButton = if (session.isConnected) session.model().hostButton() else null,
|
||||||
|
self = session.selfState(),
|
||||||
|
whisper = session.whisper()?.label,
|
||||||
|
whisperNobody = session.isWhisperingToNobody,
|
||||||
|
whisperControls = whisperControls,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = session.model().buildTree()
|
||||||
|
_tree.value = ServerTree.of(roots, session.model(), session.contacts().store(),
|
||||||
|
parts.settings.colorContacts.get(), parts.settings.countryFlags.get(), parts.settings.clientRowColors)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inner class Listener : ServerSession.Listener {
|
||||||
|
override fun onSessionChanged() = refresh()
|
||||||
|
|
||||||
|
override fun append(key: ChatKey, title: String, html: String) = addLine(key, title, html)
|
||||||
|
|
||||||
|
override fun setHistory(key: ChatKey, title: String, html: List<String>) = replaceLines(key, title, html)
|
||||||
|
|
||||||
|
override fun rename(key: ChatKey, name: String) = _chats.update {
|
||||||
|
when (key.scope()) {
|
||||||
|
ChatScope.SERVER -> it.copy(server = it.server.copy(title = name.ifBlank { "Server" }))
|
||||||
|
ChatScope.CHANNEL -> it.copy(channel = it.channel.copy(title = name.ifBlank { "Channel" }))
|
||||||
|
else -> it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun closePrivateChats() = _chats.update { it.copy(private = emptyList()) }
|
||||||
|
|
||||||
|
override fun onPrivateMessage(fromClientId: Int, fromName: String, message: String) {
|
||||||
|
if (!app.foreground) parts.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPrivateMessageSent(toClientId: Int, message: String) =
|
||||||
|
parts.notifier.sent(id, toClientId, ChatHtml.plainMessage(message))
|
||||||
|
|
||||||
|
override fun onConnected() {
|
||||||
|
network.onConnected()
|
||||||
|
app.connected(this@ServerController)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDisconnected(reason: String?) {
|
||||||
|
network.onDisconnected()
|
||||||
|
parts.notifier.clearServer(id)
|
||||||
|
app.disconnected(this@ServerController)
|
||||||
|
scheduleTree(structure = true)
|
||||||
|
refresh()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onModelChanged() {
|
||||||
|
scheduleTree(structure = true)
|
||||||
|
// A server edit may have changed it.
|
||||||
|
if (session.isConnected && session.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 onTalkStateChanged(clientId: Int, talking: Boolean) {
|
||||||
|
if (clientId == session.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)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TREE_FRAME_MS = 30L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
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.IconRepository
|
||||||
|
import eu.lixko.ts3j.client.net.avatar.AvatarRepository
|
||||||
|
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 iconStore: IconRepository,
|
||||||
|
private val avatarStore: AvatarRepository,
|
||||||
|
) {
|
||||||
|
|
||||||
|
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 = iconStore.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 = avatarStore.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 avatarStore.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,34 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import eu.lixko.ts3j.client.config.IdentityStore
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactStore
|
||||||
|
import eu.lixko.ts3j.client.net.ChannelFiles
|
||||||
|
import eu.lixko.ts3j.client.session.ServerSession
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** What every server the app is on runs on and reports to, shared by all of them. */
|
||||||
|
class ServerParts internal constructor(
|
||||||
|
private val context: Context,
|
||||||
|
internal val settings: Settings,
|
||||||
|
private val identityStore: IdentityStore,
|
||||||
|
private val audio: AudioSetup,
|
||||||
|
internal val contactStore: ContactStore,
|
||||||
|
private val myTeamSpeak: MyTeamSpeakAccount,
|
||||||
|
) {
|
||||||
|
internal val notifier = MessageNotifier(context)
|
||||||
|
internal val network = NetworkFollower(context)
|
||||||
|
internal val cacheDir: File get() = context.cacheDir
|
||||||
|
internal val attachments get() = myTeamSpeak.attachments
|
||||||
|
|
||||||
|
internal fun session(listener: ServerSession.Listener) =
|
||||||
|
ServerSession(settings, identityStore, audio.audio, audio.sounds, contactStore, listener).also {
|
||||||
|
it.setMyTeamSpeakLogin(myTeamSpeak.login)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun fileTransfers(files: ChannelFiles) = FileTransfers(context, files)
|
||||||
|
|
||||||
|
internal suspend fun openShared(uri: Uri) = myTeamSpeak.openShared(uri)
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
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,
|
||||||
|
talker = c.talker,
|
||||||
|
lacksTalkPower = model.lacksTalkPower(c),
|
||||||
|
talkRequest = c.talkRequest,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
/** Granted talk power. */
|
||||||
|
val talker: Boolean,
|
||||||
|
/** Short of the channel's needed talk power, so kept from talking. */
|
||||||
|
val lacksTalkPower: Boolean,
|
||||||
|
/** Waiting for talk power. */
|
||||||
|
val talkRequest: Boolean,
|
||||||
|
)
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.config.Setting
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import eu.lixko.ts3j.client.net.HostButton
|
||||||
|
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.text.BBCode
|
||||||
|
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 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,
|
||||||
|
/** Whether the menus offer whispering, as the bookmark connected with says. */
|
||||||
|
val whisperControls: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 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 internal constructor(
|
||||||
|
private val context: Context,
|
||||||
|
private val settings: Settings,
|
||||||
|
private val identities: IdentityManager,
|
||||||
|
private val bookmarks: BookmarkManager,
|
||||||
|
private val parts: ServerParts,
|
||||||
|
private val levels: LevelMonitor,
|
||||||
|
) {
|
||||||
|
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
|
||||||
|
|
||||||
|
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) parts.notifier.clearPokes()
|
||||||
|
// The process may be let go of any time once out of sight.
|
||||||
|
else parts.contactStore.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
val micLevel: StateFlow<MicLevel> = levels.level
|
||||||
|
@Volatile
|
||||||
|
private var watchingLevel = false
|
||||||
|
|
||||||
|
init {
|
||||||
|
// Mutations report on whichever thread made them, a connection thread included.
|
||||||
|
parts.contactStore.addListener { _servers.value.forEach(ServerController::contactsChanged) }
|
||||||
|
Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer)
|
||||||
|
settings.countryFlags.addListener { servers.value.forEach { it.scheduleTree(structure = false) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
val lastAddress: String get() = settings.lastAddress.get()
|
||||||
|
|
||||||
|
// ---- 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.set(address)
|
||||||
|
if (identities.nicknameOf(identityId).isBlank()) settings.nickname.set(nickname)
|
||||||
|
settings.save()
|
||||||
|
start(host, port, nickname, password, identityId, "", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connect(bookmark: Bookmark) {
|
||||||
|
start {
|
||||||
|
it.session.setMyTeamSpeakFeatures(bookmark.myTeamSpeakFeatures)
|
||||||
|
it.applyBookmark(bookmark)
|
||||||
|
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(), parts, 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()) {
|
||||||
|
bookmarks.add(link.toBookmark())
|
||||||
|
}
|
||||||
|
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 = bookmarks.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 bookmarks.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 })
|
||||||
|
parts.contactStore.flush()
|
||||||
|
parts.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) parts.notifier.poke(from, BBCode.toPlain(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
|
||||||
|
|
||||||
|
// ---- what the servers share ----
|
||||||
|
|
||||||
|
/** A saved bookmark changed; the servers connected with it take on what applies at once. */
|
||||||
|
internal fun bookmarkEdited(bookmark: Bookmark) = _servers.value.forEach { it.bookmarkEdited(bookmark) }
|
||||||
|
|
||||||
|
internal fun serverIconChanged(address: String, port: Int, iconId: Long) = bookmarks.serverIconChanged(address, port, iconId)
|
||||||
|
|
||||||
|
/** The channels of a server we are on at [host]:[port], to pick one to join. */
|
||||||
|
fun channelPathsAt(host: String, port: Int): List<String> = sessions.connectedTo(host, port)?.channelPaths().orEmpty()
|
||||||
|
|
||||||
|
/** The channel we are in on the server at [host]:[port]; null when we are not on it. */
|
||||||
|
fun currentChannelAt(host: String, port: Int): String? = sessions.connectedTo(host, port)?.currentChannelPath()
|
||||||
|
|
||||||
|
/** Signed in or out of myTeamSpeak. */
|
||||||
|
internal fun myTeamSpeakChanged() = _servers.value.forEach { it.session.updateMyTeamSpeak() }
|
||||||
|
|
||||||
|
/** Puts new client row colours, already set in [settings], into effect. */
|
||||||
|
fun clientRowColorsChanged() {
|
||||||
|
settings.save()
|
||||||
|
servers.value.forEach { it.scheduleTree(structure = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Switches between push to talk and voice activation; returns the new mode. */
|
||||||
|
fun toggleInputMode(): Settings.InputMode {
|
||||||
|
settings.inputMode.set(if (settings.inputMode.get() == Settings.InputMode.PUSH_TO_TALK)
|
||||||
|
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK)
|
||||||
|
applySettings()
|
||||||
|
return settings.inputMode.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saves the settings and puts the voice ones into effect at once. */
|
||||||
|
fun applySettings() {
|
||||||
|
settings.save()
|
||||||
|
try {
|
||||||
|
for (server in _servers.value) {
|
||||||
|
server.microphone?.apply(settings)
|
||||||
|
server.refresh()
|
||||||
|
server.scheduleTree(structure = false)
|
||||||
|
}
|
||||||
|
levels.apply()
|
||||||
|
} catch (e: RuntimeException) {
|
||||||
|
error(e.message ?: "Microphone unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Output device, volume and receive buffer are global, so they go to every connection. */
|
||||||
|
private fun applyOutputSettings() {
|
||||||
|
for (server in _servers.value) {
|
||||||
|
server.playback?.setMasterVolume(settings.outputVolume.get())
|
||||||
|
server.playback?.setOutputDevice(settings.outputDevice.get())
|
||||||
|
server.playback?.setReceiveBuffer(settings.receiveBuffer.get())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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) ?: parts.notifier.clear(serverId, clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val DEFAULT_PORT = 9987
|
||||||
|
|
||||||
|
/** `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,37 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/** What a sideways swipe over the channel tree does. */
|
||||||
|
enum class TreeSwipe { OFF, CHAT, SERVERS }
|
||||||
|
|
||||||
|
/** The swipe gestures, an Android-only choice kept apart from the shared settings. */
|
||||||
|
class SwipePrefs(context: Context) {
|
||||||
|
|
||||||
|
private val prefs = context.getSharedPreferences("swipe", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
private val _tree = MutableStateFlow(
|
||||||
|
TreeSwipe.entries.firstOrNull { it.name == prefs.getString(TREE, null) } ?: TreeSwipe.CHAT)
|
||||||
|
val tree: StateFlow<TreeSwipe> = _tree
|
||||||
|
|
||||||
|
private val _chatTabs = MutableStateFlow(prefs.getBoolean(CHAT_TABS, true))
|
||||||
|
/** Whether a sideways swipe over the chat goes to the neighbouring conversation. */
|
||||||
|
val chatTabs: StateFlow<Boolean> = _chatTabs
|
||||||
|
|
||||||
|
fun setTree(swipe: TreeSwipe) {
|
||||||
|
prefs.edit().putString(TREE, swipe.name).apply()
|
||||||
|
_tree.value = swipe
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setChatTabs(enabled: Boolean) {
|
||||||
|
prefs.edit().putBoolean(CHAT_TABS, enabled).apply()
|
||||||
|
_chatTabs.value = enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val TREE = "tree"
|
||||||
|
const val CHAT_TABS = "chatTabs"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import eu.lixko.ts3j.client.config.AppDirs
|
||||||
|
|
||||||
|
class Ts3Application : Application() {
|
||||||
|
|
||||||
|
lateinit var parts: AppParts
|
||||||
|
private set
|
||||||
|
|
||||||
|
val sessions: SessionController get() = parts.sessions
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
// Before any store loads: there is no home directory to find them in.
|
||||||
|
AppDirs.init(filesDir, filesDir.toPath().resolve("chats"))
|
||||||
|
parts = AppParts(this)
|
||||||
|
Thread(parts.audio::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.get()
|
||||||
|
|
||||||
|
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,41 @@
|
|||||||
|
package eu.lixko.ts3j.client.android
|
||||||
|
|
||||||
|
import eu.lixko.ts3j.client.config.WhisperList
|
||||||
|
import eu.lixko.ts3j.client.config.WhisperLists
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/** The saved whisper lists, shared by every server. */
|
||||||
|
class WhisperListManager internal constructor() {
|
||||||
|
private val store = WhisperLists.load()
|
||||||
|
private val _all = MutableStateFlow(copies())
|
||||||
|
val all: StateFlow<List<WhisperList>> = _all
|
||||||
|
|
||||||
|
private fun copies() = store.all().map { it.copy() }
|
||||||
|
|
||||||
|
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
|
||||||
|
fun save(index: Int, list: WhisperList) {
|
||||||
|
val all = store.all()
|
||||||
|
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
|
||||||
|
saved()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
|
||||||
|
fun addTo(index: Int, newName: String, add: (WhisperList) -> Unit) {
|
||||||
|
val list = store.all().getOrNull(index)?.copy() ?: WhisperList(newName)
|
||||||
|
add(list)
|
||||||
|
save(index, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remove(index: Int) {
|
||||||
|
val all = store.all()
|
||||||
|
if (index !in all.indices) return
|
||||||
|
all.removeAt(index)
|
||||||
|
saved()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saved() {
|
||||||
|
store.save()
|
||||||
|
_all.value = copies()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
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.foundation.layout.fillMaxSize
|
||||||
|
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.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.AppParts
|
||||||
|
import eu.lixko.ts3j.client.android.SessionEvent
|
||||||
|
import eu.lixko.ts3j.client.android.TreeSwipe
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun App(parts: AppParts) {
|
||||||
|
val sessions = parts.sessions
|
||||||
|
val current by sessions.current.collectAsStateWithLifecycle()
|
||||||
|
// Each server keeps its own screen state (chat open, conversation) while another is shown.
|
||||||
|
val serverStates = rememberSaveableStateHolder()
|
||||||
|
var connectOpen by rememberSaveable { mutableStateOf(false) }
|
||||||
|
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(sessions) {
|
||||||
|
sessions.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) sessions.current.value?.let(sessions::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()) sessions.current.value?.let(sessions::giveMicrophoneTo)
|
||||||
|
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
|
||||||
|
}
|
||||||
|
|
||||||
|
val openContacts: (String?) -> Unit = { uniqueId ->
|
||||||
|
contactsOpen = true
|
||||||
|
editingContact = uniqueId
|
||||||
|
contactDirect = uniqueId != null
|
||||||
|
}
|
||||||
|
|
||||||
|
CompositionLocalProvider(LocalIconTheme provides parts.icons, LocalWebPictures provides parts.pictures) {
|
||||||
|
val server = current
|
||||||
|
val bookmark = editingBookmark
|
||||||
|
when {
|
||||||
|
bookmark != null -> BookmarkScreen(sessions, parts.bookmarks, parts.identities, bookmark, onDone = { editingBookmark = null })
|
||||||
|
contactsOpen -> ContactsScreen(parts.contacts, editingContact, onEdit = { uniqueId ->
|
||||||
|
if (uniqueId == null && contactDirect) contactsOpen = false
|
||||||
|
contactDirect = false
|
||||||
|
editingContact = uniqueId
|
||||||
|
}, onBack = { contactsOpen = false })
|
||||||
|
myTeamSpeakOpen -> MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { myTeamSpeakOpen = false })
|
||||||
|
settingsOpen -> SettingsScreen(parts, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
|
||||||
|
server != null && !connectOpen -> {
|
||||||
|
val servers by sessions.servers.collectAsStateWithLifecycle()
|
||||||
|
val treeSwipe by parts.swipe.tree.collectAsStateWithLifecycle()
|
||||||
|
val serverSwipe = rememberSwipeState()
|
||||||
|
SwipeHost(
|
||||||
|
serverSwipe, server,
|
||||||
|
neighbour = { at, dir ->
|
||||||
|
if (treeSwipe != TreeSwipe.SERVERS) null
|
||||||
|
else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) }
|
||||||
|
},
|
||||||
|
onSwipe = sessions::select,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
) { shown ->
|
||||||
|
serverStates.SaveableStateProvider(shown.id) {
|
||||||
|
CompositionLocalProvider(LocalServerImages provides shown.images) {
|
||||||
|
PictureViewerHost(shown) {
|
||||||
|
ServerScreen(sessions, parts.whisperLists, parts.myTeamSpeak, parts.swipe, parts.banReasons, shown, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
|
||||||
|
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it },
|
||||||
|
serverSwipe = serverSwipe, active = shown == server)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> ConnectScreen(sessions, parts.bookmarks, parts.identities, parts.myTeamSpeak, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking,
|
||||||
|
onEditBookmark = { editingBookmark = it },
|
||||||
|
onBack = if (current != null) ({ connectOpen = false }) else null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,103 @@
|
|||||||
|
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.MyTeamSpeakAccount
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachment
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTsException
|
||||||
|
import java.io.IOException
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */
|
||||||
|
class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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(
|
||||||
|
account: MyTeamSpeakAccount,
|
||||||
|
server: ServerController,
|
||||||
|
snackbar: SnackbarHostState,
|
||||||
|
shown: ChatKey,
|
||||||
|
): AttachmentActions {
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val signedIn by account.signedIn.collectAsStateWithLifecycle()
|
||||||
|
val key by rememberUpdatedState(shown)
|
||||||
|
val viewer = LocalPictureViewer.current
|
||||||
|
val pictures = LocalWebPictures.current
|
||||||
|
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
|
||||||
|
|
||||||
|
var saving by rememberSaveable { mutableStateOf<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 {
|
||||||
|
account.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('.')) {
|
||||||
|
pictures?.data(href) ?: runCatching { account.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,312 @@
|
|||||||
|
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 () -> Result<Unit>, failure: String ->
|
||||||
|
scope.launch {
|
||||||
|
action().onFailure { snackbar.showSnackbar("$failure: ${it.message}") }
|
||||||
|
generation++
|
||||||
|
}
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
edit?.let { e ->
|
||||||
|
val existing = (e as? BanEdit.Existing)?.ban
|
||||||
|
BanEditor(existing, presets, server.permissions.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.permissions.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,185 @@
|
|||||||
|
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.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.IconButton
|
||||||
|
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.BookmarkManager
|
||||||
|
import eu.lixko.ts3j.client.android.IdentityManager
|
||||||
|
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,
|
||||||
|
b.myTeamSpeakFeatures, b.showWhisperControls)
|
||||||
|
},
|
||||||
|
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
|
||||||
|
myTeamSpeakFeatures = saved[12] as Boolean
|
||||||
|
showWhisperControls = saved[13] as Boolean
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Every setting of one bookmark, saved only on Save. */
|
||||||
|
@Composable
|
||||||
|
fun BookmarkScreen(sessions: SessionController, bookmarks: BookmarkManager, identityManager: IdentityManager, edit: BookmarkEdit, onDone: () -> Unit) {
|
||||||
|
val b = edit.bookmark
|
||||||
|
val identities by identityManager.all.collectAsStateWithLifecycle()
|
||||||
|
var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) }
|
||||||
|
var address by rememberSaveable {
|
||||||
|
mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}")
|
||||||
|
}
|
||||||
|
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) }
|
||||||
|
var myTeamSpeakFeatures by rememberSaveable { mutableStateOf(b.myTeamSpeakFeatures) }
|
||||||
|
var showWhisperControls by rememberSaveable { mutableStateOf(b.showWhisperControls) }
|
||||||
|
|
||||||
|
val save = {
|
||||||
|
val (host, port) = SessionController.parseAddress(address)
|
||||||
|
bookmarks.save(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
|
||||||
|
it.myTeamSpeakFeatures = myTeamSpeakFeatures
|
||||||
|
it.showWhisperControls = showWhisperControls
|
||||||
|
})
|
||||||
|
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(identityManager.nicknameFor(identityId)) }, singleLine = true)
|
||||||
|
val paths = remember(address) {
|
||||||
|
SessionController.parseAddress(address).let { (host, port) -> sessions.channelPathsAt(host, port) }
|
||||||
|
}
|
||||||
|
val current = remember(address) {
|
||||||
|
SessionController.parseAddress(address).let { (host, port) -> sessions.currentChannelAt(host, port) }
|
||||||
|
}
|
||||||
|
ChannelField(channel, paths, current) { 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 })
|
||||||
|
}
|
||||||
|
Row(Modifier.fillMaxWidth().clickable { myTeamSpeakFeatures = !myTeamSpeakFeatures },
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Enable myTeamSpeak features", Modifier.weight(1f))
|
||||||
|
Switch(myTeamSpeakFeatures, { myTeamSpeakFeatures = it })
|
||||||
|
}
|
||||||
|
Row(Modifier.fillMaxWidth().clickable { showWhisperControls = !showWhisperControls },
|
||||||
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Show whisper controls", Modifier.weight(1f))
|
||||||
|
Switch(showWhisperControls, { showWhisperControls = it })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The channel to join, typed or picked among [paths] of the server when we are on it,
|
||||||
|
* or taken from [current], the one we are in there.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
private fun ChannelField(channel: String, paths: List<String>, current: 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 = {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
IconButton(onClick = { current?.let(onChange) }, enabled = current != null) {
|
||||||
|
PackIcon(listOf("MAKE_CURRENT_CHANNEL_DEFAULT", "CHANNEL_SWITCH"), "This channel")
|
||||||
|
}
|
||||||
|
if (paths.isNotEmpty()) 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,212 @@
|
|||||||
|
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 saved = if (creating) server.createChannel(edit.parentId, trimmed)
|
||||||
|
else server.editChannel(edit.channelId, trimmed.changesFrom(o))
|
||||||
|
saving = false
|
||||||
|
saved.onSuccess { onDone() }.onFailure {
|
||||||
|
snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + it.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,366 @@
|
|||||||
|
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 = {},
|
||||||
|
/** Clients picked to be moved or kicked together. */
|
||||||
|
selected: Set<Int> = emptySet(),
|
||||||
|
/** Picks a client into [selected]; null when there is nothing to do with several. */
|
||||||
|
onClientLongPress: ((ClientItem) -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
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
|
||||||
|
!row.ref.channel && row.ref.id in selected -> MaterialTheme.colorScheme.secondaryContainer
|
||||||
|
row.ref == foundCurrent -> findCurrentColor()
|
||||||
|
row.ref 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, onClientLongPress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
onLongClick: (() -> Unit)? = null,
|
||||||
|
content: @Composable RowScope.() -> Unit,
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.background(tint)
|
||||||
|
.background(background)
|
||||||
|
.height(ROW)
|
||||||
|
.then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onLongClick = onLongClick, 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,
|
||||||
|
onLongPress: ((ClientItem) -> Unit)?,
|
||||||
|
) {
|
||||||
|
val client = row.client
|
||||||
|
RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background),
|
||||||
|
onLongClick = onLongPress?.let { { it(client) } }) {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// TeamSpeak's order: talk power ahead of the groups, a talk request after them.
|
||||||
|
if (client.talker) PackIcon("IS_TALKER", "Talk power granted", size = ICON)
|
||||||
|
else if (client.lacksTalkPower) PackIcon("INPUT_MUTED", "Insufficient talk power", size = ICON)
|
||||||
|
for (id in client.groupIconIds) ServerIcon(id, size = ICON)
|
||||||
|
if (client.talkRequest) PackIcon("TALK_POWER_REQUEST", "Talk power requested", 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,221 @@
|
|||||||
|
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.fillMaxSize
|
||||||
|
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.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.ChatLine
|
||||||
|
import eu.lixko.ts3j.client.android.ChatMatch
|
||||||
|
import eu.lixko.ts3j.client.android.Chats
|
||||||
|
import eu.lixko.ts3j.client.android.Conversation
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.text.TextQuery
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.flow.filter
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ChatPane(
|
||||||
|
chats: Chats,
|
||||||
|
selected: Conversation,
|
||||||
|
canSend: Boolean,
|
||||||
|
onSelect: (ChatKey) -> Unit,
|
||||||
|
onClose: (ChatKey) -> 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 = {},
|
||||||
|
/** Whether a swipe over the lines goes to the neighbouring conversation. */
|
||||||
|
swipeTabs: Boolean = false,
|
||||||
|
/** For the lines, such as a swipe out of the chat. */
|
||||||
|
linesModifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
Column(modifier) {
|
||||||
|
val tabs = rememberLazyListState()
|
||||||
|
// A conversation picked by other means than its chip, such as a swipe, comes into view.
|
||||||
|
LaunchedEffect(selected.key) {
|
||||||
|
val index = chats.all.indexOfFirst { it.key == selected.key }
|
||||||
|
val info = tabs.layoutInfo
|
||||||
|
if (index >= 0 && info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
|
||||||
|
tabs.animateScrollToItem(index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LazyRow(
|
||||||
|
state = tabs,
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val swipe = rememberSwipeState()
|
||||||
|
SwipeHost(
|
||||||
|
swipe, selected.key,
|
||||||
|
neighbour = { key, dir ->
|
||||||
|
if (!swipeTabs) null
|
||||||
|
else chats.all.indexOfFirst { it.key == key }.takeIf { it >= 0 }?.let { chats.all.getOrNull(it + dir)?.key }
|
||||||
|
},
|
||||||
|
onSwipe = onSelect,
|
||||||
|
modifier = Modifier.weight(1f).then(linesModifier).swipeSource(swipe),
|
||||||
|
) { key ->
|
||||||
|
// Each conversation opens at its newest line; the one beside it while swiping shows all of its own.
|
||||||
|
if (key == selected.key) Lines(lines, onLink, Modifier.fillMaxSize(), find, current, reveal, onRevealed)
|
||||||
|
else chats[key]?.let { Lines(it.lines, onLink, Modifier.fillMaxSize(), TextQuery.EMPTY, null, null) {} }
|
||||||
|
}
|
||||||
|
// 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) -> 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.isPrivate) ({
|
||||||
|
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,246 @@
|
|||||||
|
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.Box
|
||||||
|
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.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
|
import androidx.compose.material.icons.filled.MoreVert
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuAnchorType
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||||
|
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
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.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.text.withStyle
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.BookmarkManager
|
||||||
|
import eu.lixko.ts3j.client.android.IdentityInfo
|
||||||
|
import eu.lixko.ts3j.client.android.IdentityManager
|
||||||
|
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.net.IconRepository
|
||||||
|
|
||||||
|
/** Where to connect to: an address typed in, or a bookmark. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ConnectScreen(
|
||||||
|
sessions: SessionController,
|
||||||
|
bookmarkManager: BookmarkManager,
|
||||||
|
identityManager: IdentityManager,
|
||||||
|
account: MyTeamSpeakAccount,
|
||||||
|
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 sessions.lastEnd.collectAsStateWithLifecycle()
|
||||||
|
val bookmarks by bookmarkManager.all.collectAsStateWithLifecycle()
|
||||||
|
val identities by identityManager.all.collectAsStateWithLifecycle()
|
||||||
|
val myTeamSpeakSignedIn by account.signedIn.collectAsStateWithLifecycle()
|
||||||
|
var address by rememberSaveable { mutableStateOf(sessions.lastAddress) }
|
||||||
|
var identityId by rememberSaveable { mutableStateOf("") }
|
||||||
|
var nickname by rememberSaveable { mutableStateOf(identityManager.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 = identityManager.nicknameFor(it)
|
||||||
|
}
|
||||||
|
lastEnd?.let {
|
||||||
|
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Button(
|
||||||
|
onClick = { onConnect { sessions.connect(address.trim(), nickname.trim(), password, identityId) } },
|
||||||
|
enabled = address.isNotBlank() && nickname.isNotBlank(),
|
||||||
|
) { Text("Connect") }
|
||||||
|
TextButton(onClick = {
|
||||||
|
onEditBookmark(BookmarkEdit(-1, bookmarkManager.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 { sessions.connect(bookmark) } },
|
||||||
|
onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) },
|
||||||
|
onPin = if (bookmarkManager.canPinShortcuts) ({ bookmarkManager.pinShortcut(bookmark) }) else null,
|
||||||
|
onRemove = { bookmarkManager.remove(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,274 @@
|
|||||||
|
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.ContactManager
|
||||||
|
import eu.lixko.ts3j.client.contacts.Contact
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactDefaults
|
||||||
|
import eu.lixko.ts3j.client.contacts.ContactType
|
||||||
|
import eu.lixko.ts3j.client.contacts.NicknameDisplay
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
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(contacts: ContactManager, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) {
|
||||||
|
var defaults by rememberSaveable { mutableStateOf(false) }
|
||||||
|
when {
|
||||||
|
editing != null -> return ContactScreen(contacts, editing, onBack = { onEdit(null) })
|
||||||
|
defaults -> return ContactDefaultsScreen(contacts, onBack = { defaults = false })
|
||||||
|
}
|
||||||
|
|
||||||
|
val all by contacts.all.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 { contacts.import(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 (all.isEmpty()) {
|
||||||
|
item {
|
||||||
|
Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " +
|
||||||
|
"or import the contacts of TeamSpeak 3 from its settings.db.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ((type, title) in GROUPS) {
|
||||||
|
val group = all.filter { it.type == type }.sortedBy { label(it).lowercase() }
|
||||||
|
if (group.isEmpty()) continue
|
||||||
|
item(key = type) { Section(title) }
|
||||||
|
items(group, key = { it.key() }) { contact ->
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
|
||||||
|
supportingContent = { Text(lastSeen(contact)) },
|
||||||
|
modifier = Modifier.clickable { onEdit(contact.key()) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One contact's settings; each is stored as it is changed, the names once the page is left. */
|
||||||
|
@Composable
|
||||||
|
private fun ContactScreen(contacts: ContactManager, uniqueId: String, onBack: () -> Unit) {
|
||||||
|
val all by contacts.all.collectAsStateWithLifecycle()
|
||||||
|
// A client's unique id may stand for a contact filed under its myTeamSpeak ID.
|
||||||
|
val key = remember(uniqueId) { contacts.find(uniqueId)?.key() ?: uniqueId }
|
||||||
|
val contact = all.firstOrNull { it.key() == key }
|
||||||
|
if (contact == null) {
|
||||||
|
LaunchedEffect(Unit) { onBack() }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Starts from the stored entry, which may have been seen again since this page opened.
|
||||||
|
fun edit(change: Contact.() -> Unit) {
|
||||||
|
contacts.find(key)?.let { contacts.save(it.apply(change)) }
|
||||||
|
}
|
||||||
|
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
|
||||||
|
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
|
||||||
|
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
|
||||||
|
val idLabel = if (contact.uniqueId.isEmpty()) "myTeamSpeak ID" else "Unique ID"
|
||||||
|
LinkRow(idLabel, contact.shownId()) {
|
||||||
|
// The system confirms the copy itself.
|
||||||
|
context.getSystemService(ClipboardManager::class.java)
|
||||||
|
.setPrimaryClip(ClipData.newPlainText(idLabel, contact.shownId()))
|
||||||
|
}
|
||||||
|
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
|
||||||
|
contacts.remove(key)
|
||||||
|
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(contacts: ContactManager, onBack: () -> Unit) {
|
||||||
|
val defaults = contacts.defaults
|
||||||
|
var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) }
|
||||||
|
var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) }
|
||||||
|
fun edit(change: ContactDefaults.Entry.() -> Unit) {
|
||||||
|
val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() }
|
||||||
|
defaults.of(tab).copyFrom(changed)
|
||||||
|
contacts.saveDefaults()
|
||||||
|
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.label()
|
||||||
|
|
||||||
|
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,238 @@
|
|||||||
|
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 () -> Result<Unit> ->
|
||||||
|
scope.launch {
|
||||||
|
call().onSuccess { reloads++ }.onFailure { snackbar.showSnackbar(it.message ?: it.javaClass.simpleName) }
|
||||||
|
}
|
||||||
|
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,261 @@
|
|||||||
|
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.ClientAdmin
|
||||||
|
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", ClientAdmin.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") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Talk power, the kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out.
|
||||||
|
* Null when there is none of them.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun clientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit): (@Composable () -> Unit)? {
|
||||||
|
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
|
||||||
|
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
|
||||||
|
val kickChannel = !client.self && server.permissions.canKickFromChannel()
|
||||||
|
val kickServer = !client.self && server.permissions.canKickFromServer()
|
||||||
|
val ban = !client.self && server.permissions.canBanClients()
|
||||||
|
val talker = server.permissions.canGrantTalkPower() && (client.talker || client.lacksTalkPower)
|
||||||
|
val showServerGroups = serverGroups.any { it.allowed() }
|
||||||
|
val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() }
|
||||||
|
if (!(talker || kickChannel || kickServer || ban || showServerGroups || showChannelGroups)) return null
|
||||||
|
return {
|
||||||
|
ClientModeration(server, client, serverGroups, channelGroups, talker, kickChannel, kickServer, ban,
|
||||||
|
showServerGroups, showChannelGroups, onDone)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ClientModeration(
|
||||||
|
server: ServerController,
|
||||||
|
client: ClientItem,
|
||||||
|
serverGroups: List<GroupChoice>,
|
||||||
|
channelGroups: List<GroupChoice>,
|
||||||
|
talker: Boolean,
|
||||||
|
kickChannel: Boolean,
|
||||||
|
kickServer: Boolean,
|
||||||
|
ban: Boolean,
|
||||||
|
showServerGroups: Boolean,
|
||||||
|
showChannelGroups: Boolean,
|
||||||
|
onDone: () -> Unit,
|
||||||
|
) {
|
||||||
|
var kick by remember { mutableStateOf<Boolean?>(null) }
|
||||||
|
var banning by remember { mutableStateOf(false) }
|
||||||
|
var groups by remember { mutableStateOf<Boolean?>(null) }
|
||||||
|
|
||||||
|
if (talker) {
|
||||||
|
if (client.talker) Action("TALK_POWER_REVOKE", "Revoke talk power") { server.setTalker(listOf(client.id), false); onDone() }
|
||||||
|
else Action("TALK_POWER_GRANT", "Grant talk power") { server.setTalker(listOf(client.id), true); onDone() }
|
||||||
|
}
|
||||||
|
if (kickChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false }
|
||||||
|
if (kickServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true }
|
||||||
|
if (ban) Action("BAN_CLIENT", "Ban") { banning = true }
|
||||||
|
if (showServerGroups) Action("PERMISSIONS_SERVER_GROUPS", "Server groups") { groups = true }
|
||||||
|
if (showChannelGroups) Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group") { 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(listOf(client.id), reason) else server.kickFromChannel(listOf(client.id), reason)
|
||||||
|
onDone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (banning) {
|
||||||
|
BanPrompt(client.name, server.permissions.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,297 @@
|
|||||||
|
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.MyTeamSpeakAccount
|
||||||
|
import eu.lixko.ts3j.client.config.Bookmark
|
||||||
|
import eu.lixko.ts3j.client.myts.AccountInfo
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTeamSpeak
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTsException
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.SyncItem
|
||||||
|
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
|
||||||
|
import java.io.IOException
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The myTeamSpeak account: sign in and out, pick what the account synchronises to import,
|
||||||
|
* or synchronise both ways. Signing in lasts until signing out; the password itself is not kept.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
|
||||||
|
val login = account.login
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var signedIn by remember { mutableStateOf(login.isSignedIn) }
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
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>()) }
|
||||||
|
var conflicted by remember { mutableStateOf<MyTeamSpeakSync.Plan?>(null) }
|
||||||
|
|
||||||
|
fun show(fetched: MyTeamSpeak.Account) {
|
||||||
|
info = fetched.info()
|
||||||
|
all = fetched.items()
|
||||||
|
rows = all.filter { it !is SyncItem.Folder && (it !is SyncItem.Contact || TeamSpeakImporter.isImportable(it)) }.map {
|
||||||
|
val imported = account.isImported(it)
|
||||||
|
ItemRow(it, imported, !imported)
|
||||||
|
}
|
||||||
|
message = if (rows.isEmpty()) "The account holds no bookmarks, identities or contacts." 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun finishSync(plan: MyTeamSpeakSync.Plan) {
|
||||||
|
val r = account.finishSync(plan)
|
||||||
|
rows = rows.map { it.copy(imported = account.isImported(it.item)) }
|
||||||
|
message = if (r.sent() == 0 && r.received() == 0) "In sync."
|
||||||
|
else "Synchronized: ${r.sent()} sent, ${r.received()} received."
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
if (signedIn) work { show(account.fetch()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
conflicted?.let { plan ->
|
||||||
|
SyncConflictsScreen(plan.conflicts()) { accepted ->
|
||||||
|
conflicted = null
|
||||||
|
if (accepted) work { finishSync(plan) } else message = "Synchronization cancelled."
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
BackHandler(onBack = onBack)
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text("myTeamSpeak") },
|
||||||
|
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
|
||||||
|
actions = {
|
||||||
|
if (signedIn) {
|
||||||
|
IconButton(onClick = { work { show(account.fetch()) } }, 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, identities and contacts 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(account.signIn(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 { account.signOut() }
|
||||||
|
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 },
|
||||||
|
"Contacts" to rows.filter { it.item is SyncItem.Contact },
|
||||||
|
)) {
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
if (rows.isNotEmpty()) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
work {
|
||||||
|
val r = account.import(all, rows.filter { it.selected }.map { it.item })
|
||||||
|
rows = rows.map { it.copy(imported = account.isImported(it.item), selected = false) }
|
||||||
|
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " +
|
||||||
|
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " +
|
||||||
|
"${count(r.contactsAdded(), "contact", "contacts")}."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = !busy && rows.any { it.selected },
|
||||||
|
) { Text("Import selected") }
|
||||||
|
}
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = {
|
||||||
|
work {
|
||||||
|
val plan = account.planSync()
|
||||||
|
if (plan.conflicts().isEmpty()) finishSync(plan) else conflicted = plan
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = !busy,
|
||||||
|
) { Text("Synchronize") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
is SyncItem.Contact -> item.customName().ifBlank { item.myTeamSpeakId() }
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun details(item: SyncItem) = when (item) {
|
||||||
|
is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port())
|
||||||
|
is SyncItem.Identity -> item.nickname()
|
||||||
|
is SyncItem.Contact -> item.myTeamSpeakId()
|
||||||
|
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.Setting
|
||||||
|
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(settings: Settings, sessions: SessionController, onBack: () -> Unit) {
|
||||||
|
fun <T> change(setting: Setting<T>, value: T) {
|
||||||
|
setting.set(value)
|
||||||
|
sessions.applySettings()
|
||||||
|
}
|
||||||
|
var vbr by remember { mutableStateOf(settings.vbr.get()) }
|
||||||
|
var fec by remember { mutableStateOf(settings.fec.get()) }
|
||||||
|
var music by remember { mutableStateOf(settings.music.get()) }
|
||||||
|
var redundancy by remember { mutableStateOf(settings.redundancyDelay.get()) }
|
||||||
|
var copies by remember { mutableStateOf(settings.redundancyCopies.get()) }
|
||||||
|
var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer.get()) }
|
||||||
|
|
||||||
|
SubScreen("Network", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
|
||||||
|
Section("Encoder")
|
||||||
|
Level("Bitrate", settings.bitrate.get() / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) {
|
||||||
|
change(settings.bitrate, it.roundToInt() * 1000)
|
||||||
|
}
|
||||||
|
Toggle("Variable bitrate (VBR)", vbr) {
|
||||||
|
vbr = it
|
||||||
|
change(settings.vbr, it)
|
||||||
|
}
|
||||||
|
Toggle("Forward error correction (FEC)", fec) {
|
||||||
|
fec = it
|
||||||
|
change(settings.fec, it)
|
||||||
|
}
|
||||||
|
Level("Complexity", settings.complexity.get().toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) {
|
||||||
|
change(settings.complexity, it.roundToInt())
|
||||||
|
}
|
||||||
|
Toggle("Music codec (stereo, higher fidelity)", music) {
|
||||||
|
music = it
|
||||||
|
change(settings.music, it)
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Redundancy")
|
||||||
|
ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) {
|
||||||
|
redundancy = it
|
||||||
|
change(settings.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(settings.redundancyCopies, copies)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Receive")
|
||||||
|
ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) {
|
||||||
|
receiveBuffer = it
|
||||||
|
change(settings.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 message = server.setAvatar(data).fold({ "Avatar set." }, { it.message })
|
||||||
|
Toast.makeText(context, message, 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(sessions: SessionController): PttTarget {
|
||||||
|
val owner by sessions.micOwner.collectAsStateWithLifecycle()
|
||||||
|
val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle()
|
||||||
|
val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle()
|
||||||
|
val self = tree.client(state.selfClientId)
|
||||||
|
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(sessions: SessionController, onBack: () -> Unit) {
|
||||||
|
val target = rememberPttTarget(sessions)
|
||||||
|
SubScreen("Giant PTT", onBack) { padding ->
|
||||||
|
val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp)
|
||||||
|
if (target.owner != null && target.state.connected) {
|
||||||
|
PushToTalk(target.talking, sessions::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,126 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.State
|
||||||
|
import androidx.compose.runtime.derivedStateOf
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import eu.lixko.ts3j.client.android.ChatMatch
|
||||||
|
import eu.lixko.ts3j.client.android.Conversation
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.ServerTree
|
||||||
|
import eu.lixko.ts3j.client.android.TreeFind
|
||||||
|
import eu.lixko.ts3j.client.android.findIn
|
||||||
|
|
||||||
|
/** The channel tree as it shows under the find bar: what of it, which rows are folded, and the match it is on. */
|
||||||
|
@Stable
|
||||||
|
internal class TreeView(
|
||||||
|
private val server: ServerController,
|
||||||
|
private val source: State<ServerTree>,
|
||||||
|
private val collapsedSource: State<Set<Int>>,
|
||||||
|
private val find: FindState,
|
||||||
|
) {
|
||||||
|
val treeFind by derivedStateOf { TreeFind(find.usable, find.channels) }
|
||||||
|
val filtering by derivedStateOf { find.filter && !treeFind.query.isEmpty }
|
||||||
|
val tree by derivedStateOf { if (filtering) source.value.only(treeFind) else source.value }
|
||||||
|
val hits by derivedStateOf { source.value.hits(treeFind) }
|
||||||
|
val found by derivedStateOf { hits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }
|
||||||
|
|
||||||
|
/** The match the tree is on. */
|
||||||
|
private var at by mutableStateOf<Int?>(null)
|
||||||
|
val current: TreeRef? get() = at?.takeIf { it in hits }?.let { TreeRef(treeFind.channels, it) }
|
||||||
|
val position: Int get() = hits.indexOf(at) + 1
|
||||||
|
|
||||||
|
/** A row to bring into view. */
|
||||||
|
var reveal by mutableStateOf<TreeRef?>(null)
|
||||||
|
|
||||||
|
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
|
||||||
|
private var folded by mutableStateOf(Folded(null, emptySet()))
|
||||||
|
private val filterFolded: Set<Int> get() = folded.ids.takeIf { folded.find == treeFind }.orEmpty()
|
||||||
|
val collapsed: Set<Int> get() = if (filtering) filterFolded else collapsedSource.value
|
||||||
|
|
||||||
|
private data class Folded(val find: TreeFind?, val ids: Set<Int>)
|
||||||
|
|
||||||
|
fun toggle(channelId: Int) {
|
||||||
|
if (!filtering) server.toggleCollapsed(channelId)
|
||||||
|
else if (channelId in filterFolded) folded = Folded(treeFind, filterFolded - channelId)
|
||||||
|
else folded = Folded(treeFind, filterFolded + channelId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens the channels down to [ref] and brings it into view. */
|
||||||
|
fun show(ref: TreeRef) {
|
||||||
|
val tree = source.value
|
||||||
|
val path = (if (ref.channel) tree.parentsOf(ref.id) else tree.pathTo(ref.id)).orEmpty()
|
||||||
|
if (filtering) folded = Folded(treeFind, filterFolded - path.toSet()) else server.expand(path)
|
||||||
|
reveal = ref
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showHit(id: Int) {
|
||||||
|
at = id
|
||||||
|
show(TreeRef(treeFind.channels, id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For a new search: on the first match while the tree is on screen, else on none. */
|
||||||
|
fun restart(onScreen: Boolean) {
|
||||||
|
at = null
|
||||||
|
if (onScreen) hits.firstOrNull()?.let(::showHit)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun step(delta: Int) {
|
||||||
|
if (hits.isNotEmpty()) showHit(hits[next(hits.indexOf(at), delta, hits.size)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberTreeView(
|
||||||
|
server: ServerController,
|
||||||
|
tree: State<ServerTree>,
|
||||||
|
collapsed: State<Set<Int>>,
|
||||||
|
find: FindState,
|
||||||
|
): TreeView = remember(server, tree, collapsed, find) { TreeView(server, tree, collapsed, find) }
|
||||||
|
|
||||||
|
/** A conversation as it shows under the find bar: its lines, and the match it is on. */
|
||||||
|
@Stable
|
||||||
|
internal class ChatSearch(private val conversation: State<Conversation>, private val find: FindState) {
|
||||||
|
val query get() = find.usable
|
||||||
|
val lines by derivedStateOf {
|
||||||
|
val all = conversation.value.lines
|
||||||
|
if (find.filter && !query.isEmpty) all.filter { query.matches(it.plain) } else all
|
||||||
|
}
|
||||||
|
val hits by derivedStateOf { findIn(lines, query, MAX_CHAT_MATCHES) }
|
||||||
|
val capped: Boolean get() = hits.size == MAX_CHAT_MATCHES
|
||||||
|
|
||||||
|
/** The match the chat is on. */
|
||||||
|
var at by mutableStateOf<ChatMatch?>(null)
|
||||||
|
private set
|
||||||
|
val position: Int get() = hits.indexOf(at) + 1
|
||||||
|
|
||||||
|
/** A line to bring into view. */
|
||||||
|
var reveal by mutableStateOf<Long?>(null)
|
||||||
|
|
||||||
|
/** For a new search: on the newest match while the chat is on screen, else on none. */
|
||||||
|
fun restart(onScreen: Boolean) {
|
||||||
|
at = if (onScreen) hits.lastOrNull() else null
|
||||||
|
reveal = at?.line
|
||||||
|
}
|
||||||
|
|
||||||
|
fun step(delta: Int) {
|
||||||
|
if (hits.isEmpty()) return
|
||||||
|
at = hits[next(hits.indexOf(at), delta, hits.size)]
|
||||||
|
reveal = at?.line
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberChatSearch(conversation: State<Conversation>, find: FindState): ChatSearch =
|
||||||
|
remember(conversation, find) { ChatSearch(conversation, find) }
|
||||||
|
|
||||||
|
/** More matches than this nobody steps through one by one. */
|
||||||
|
private const val MAX_CHAT_MATCHES = 5000
|
||||||
|
|
||||||
|
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
|
||||||
|
private fun next(at: Int, delta: Int, size: Int): Int =
|
||||||
|
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
|
||||||
@@ -0,0 +1,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,105 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.saveable.listSaver
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatScope
|
||||||
|
import eu.lixko.ts3j.client.config.WhisperList
|
||||||
|
|
||||||
|
/** What fills a server's screen: its tree and chat, or a page of its own. */
|
||||||
|
internal sealed interface ServerPage {
|
||||||
|
data object Main : ServerPage
|
||||||
|
data object BanList : ServerPage
|
||||||
|
data object WhisperLists : ServerPage
|
||||||
|
data class EditChannel(val edit: ChannelEdit) : ServerPage
|
||||||
|
/** A channel's files, with the password the channel takes. */
|
||||||
|
data class Files(val channelId: Int, val name: String, val password: String) : ServerPage
|
||||||
|
data class ConnectionInfo(val clientId: Int) : ServerPage
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A sheet or dialog over the tree and chat; one at a time. */
|
||||||
|
internal sealed interface Overlay {
|
||||||
|
data object None : Overlay
|
||||||
|
data object Server : Overlay
|
||||||
|
/** [fromTree] when it was opened from the tree rather than a link. */
|
||||||
|
data class Client(val id: Int, val fromTree: Boolean) : Overlay
|
||||||
|
data class Channel(val id: Int) : Overlay
|
||||||
|
/** A locked channel being joined, while its password is asked for. */
|
||||||
|
data class JoinLocked(val channelId: Int) : Overlay
|
||||||
|
/** A locked channel whose files are wanted, while its password is asked for. */
|
||||||
|
data class FilesLocked(val channelId: Int) : Overlay
|
||||||
|
data class DeleteChannel(val id: Int) : Overlay
|
||||||
|
/** Kicking the clients picked in the tree: from the server, or from their channels. */
|
||||||
|
data class Kick(val fromServer: Boolean) : Overlay
|
||||||
|
/** Something being added to a whisper list, while the list is picked: its name and how to add it. */
|
||||||
|
class AddToWhisperList(val name: String, val add: (WhisperList) -> Unit) : Overlay
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a server's screen is: on which page, the tree or the chat, and what is over it. */
|
||||||
|
@Stable
|
||||||
|
internal class ServerNav(page: ServerPage = ServerPage.Main, showChat: Boolean = false, chatKey: ChatKey = ChatKey.CHANNEL) {
|
||||||
|
var page by mutableStateOf(page)
|
||||||
|
var showChat by mutableStateOf(showChat)
|
||||||
|
/** The conversation the chat shows. */
|
||||||
|
var chatKey by mutableStateOf(chatKey)
|
||||||
|
var overlay by mutableStateOf<Overlay>(Overlay.None)
|
||||||
|
|
||||||
|
fun openChat(key: ChatKey) {
|
||||||
|
chatKey = key
|
||||||
|
showChat = true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun back() {
|
||||||
|
page = ServerPage.Main
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismiss() {
|
||||||
|
overlay = Overlay.None
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
// Sheets and dialogs are not kept: they would come back over a tree that has moved on.
|
||||||
|
val Saver = listSaver<ServerNav, Any>(
|
||||||
|
save = { listOf(it.showChat, saveKey(it.chatKey)) + savePage(it.page) },
|
||||||
|
restore = { ServerNav(restorePage(it.drop(2)), it[0] as Boolean, restoreKey(it[1] as String)) },
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun saveKey(key: ChatKey) = when (key.scope()) {
|
||||||
|
ChatScope.SERVER -> "server"
|
||||||
|
ChatScope.CHANNEL -> "channel"
|
||||||
|
ChatScope.PRIVATE -> "private:${key.clientId()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun restoreKey(saved: String) = when {
|
||||||
|
saved == "server" -> ChatKey.SERVER
|
||||||
|
saved.startsWith("private:") -> ChatKey.privateWith(saved.substringAfter(':').toInt())
|
||||||
|
else -> ChatKey.CHANNEL
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun savePage(page: ServerPage): List<Any> = when (page) {
|
||||||
|
ServerPage.Main -> listOf("main")
|
||||||
|
ServerPage.BanList -> listOf("bans")
|
||||||
|
ServerPage.WhisperLists -> listOf("whisper")
|
||||||
|
is ServerPage.EditChannel -> listOf("edit", page.edit.channelId, page.edit.parentId)
|
||||||
|
is ServerPage.Files -> listOf("files", page.channelId, page.name, page.password)
|
||||||
|
is ServerPage.ConnectionInfo -> listOf("info", page.clientId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun restorePage(saved: List<Any>): ServerPage = when (saved[0]) {
|
||||||
|
"bans" -> ServerPage.BanList
|
||||||
|
"whisper" -> ServerPage.WhisperLists
|
||||||
|
"edit" -> ServerPage.EditChannel(ChannelEdit(saved[1] as Int, saved[2] as Int))
|
||||||
|
"files" -> ServerPage.Files(saved[1] as Int, saved[2] as String, saved[3] as String)
|
||||||
|
"info" -> ServerPage.ConnectionInfo(saved[1] as Int)
|
||||||
|
else -> ServerPage.Main
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberServerNav(): ServerNav = rememberSaveable(saver = ServerNav.Saver) { ServerNav() }
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.ChannelItem
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.ServerTree
|
||||||
|
import eu.lixko.ts3j.client.android.SessionState
|
||||||
|
import eu.lixko.ts3j.client.android.WhisperListManager
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/** Joins [channel], asking for its password first when it is locked. */
|
||||||
|
internal fun ServerNav.join(server: ServerController, channel: ChannelItem) {
|
||||||
|
if (channel.locked) overlay = Overlay.JoinLocked(channel.id) else server.joinChannel(channel.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The sheet or dialog [ServerNav.overlay] names; a sheet goes with its client or channel when that leaves the tree. */
|
||||||
|
@Composable
|
||||||
|
internal fun ServerOverlay(
|
||||||
|
nav: ServerNav,
|
||||||
|
whisperLists: WhisperListManager,
|
||||||
|
server: ServerController,
|
||||||
|
state: SessionState,
|
||||||
|
tree: ServerTree,
|
||||||
|
treeView: TreeView,
|
||||||
|
picking: TreePicking,
|
||||||
|
snackbar: SnackbarHostState,
|
||||||
|
onLink: (String) -> Unit,
|
||||||
|
onEditContact: (String) -> Unit,
|
||||||
|
onEditBookmark: (BookmarkEdit) -> Unit,
|
||||||
|
) {
|
||||||
|
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
|
||||||
|
val can = server.permissions
|
||||||
|
// Out here: the dialog leaves the composition, and would take its scope along, before the deletion fails.
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val dismiss = nav::dismiss
|
||||||
|
/** Closes the overlay, then does [action]. */
|
||||||
|
fun then(action: () -> Unit): () -> Unit = { dismiss(); action() }
|
||||||
|
|
||||||
|
when (val o = nav.overlay) {
|
||||||
|
Overlay.None -> {}
|
||||||
|
Overlay.Server -> remember(tree, infoUpdates) { server.serverDetails() }?.let {
|
||||||
|
ServerSheet(it, onLink, onDismiss = dismiss,
|
||||||
|
onBookmark = then { server.bookmark(state.channelId)?.let { b -> onEditBookmark(BookmarkEdit(-1, b)) } },
|
||||||
|
onBanList = if (can.canViewBanList()) then { nav.page = ServerPage.BanList } else null,
|
||||||
|
onCreateChannel = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, 0)) } else null)
|
||||||
|
}
|
||||||
|
is Overlay.Client -> {
|
||||||
|
val id = o.id
|
||||||
|
LaunchedEffect(id) { server.requestClientDetails(id) }
|
||||||
|
tree.client(id)?.let { client ->
|
||||||
|
ClientSheet(
|
||||||
|
client = client,
|
||||||
|
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
|
||||||
|
onLink = onLink,
|
||||||
|
away = state.away,
|
||||||
|
initialVolume = remember(id) { server.clientVolume(id) },
|
||||||
|
onDismiss = dismiss,
|
||||||
|
onMessage = then { nav.openChat(server.openPrivateChat(id)) },
|
||||||
|
onPoke = { server.poke(id, it); dismiss() },
|
||||||
|
onVolume = { server.setClientVolume(id, it) },
|
||||||
|
onAway = { server.setAway(it); dismiss() },
|
||||||
|
onTalkRequest = if (client.self && (client.talkRequest || server.canRequestTalkPower)) {
|
||||||
|
{ server.setTalkRequest(it); dismiss() }
|
||||||
|
} else null,
|
||||||
|
onAddContact = { server.addContact(id, it) },
|
||||||
|
onEditContact = then { onEditContact(client.uniqueId) },
|
||||||
|
onConnectionInfo = then { nav.page = ServerPage.ConnectionInfo(id) },
|
||||||
|
onWhisper = if (state.whisperControls) then { server.whisperToClient(id) } else null,
|
||||||
|
onAddToWhisperList = if (state.whisperControls) then {
|
||||||
|
server.clientRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(client.name) { it.clients.add(ref) } }
|
||||||
|
} else null,
|
||||||
|
onMove = if (can.canMoveClients()) then { picking.moving = setOf(id) } else null,
|
||||||
|
onMoveToOwnChannel = if (can.canMoveClients() && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
|
||||||
|
then { server.moveClients(listOf(id), state.channelId) }
|
||||||
|
} else null,
|
||||||
|
onFindInTree = if (o.fromTree) null else then {
|
||||||
|
nav.showChat = false
|
||||||
|
treeView.show(TreeRef(false, id))
|
||||||
|
},
|
||||||
|
moderation = clientModeration(server, client, dismiss),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is Overlay.Channel -> {
|
||||||
|
val id = o.id
|
||||||
|
LaunchedEffect(id) { server.requestChannelDetails(id) }
|
||||||
|
tree.channel(id)?.let { channel ->
|
||||||
|
ChannelSheet(
|
||||||
|
channel = channel,
|
||||||
|
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
|
||||||
|
onLink = onLink,
|
||||||
|
current = id == state.channelId,
|
||||||
|
onDismiss = dismiss,
|
||||||
|
onJoin = then { nav.join(server, channel) },
|
||||||
|
onSubscribe = { server.setSubscribed(id, it); dismiss() },
|
||||||
|
onWhisper = if (state.whisperControls) then { server.whisperToChannel(id) } else null,
|
||||||
|
onAddToWhisperList = if (state.whisperControls) then {
|
||||||
|
server.channelRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(channel.name) { it.channels.add(ref) } }
|
||||||
|
} else null,
|
||||||
|
onFiles = if (can.canBrowseFiles()) then {
|
||||||
|
if (channel.locked) nav.overlay = Overlay.FilesLocked(id)
|
||||||
|
else nav.page = ServerPage.Files(id, channel.name, "")
|
||||||
|
} else null,
|
||||||
|
onCreateSub = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, id)) } else null,
|
||||||
|
onEdit = if (can.canEditChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(id)) } else null,
|
||||||
|
onDelete = if (can.canDeleteChannels()) then { nav.overlay = Overlay.DeleteChannel(id) } else null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is Overlay.Kick -> {
|
||||||
|
val others = picking.kickable(o.fromServer)
|
||||||
|
val whom = others.singleOrNull()?.let { tree.client(it)?.name } ?: "${others.size} clients"
|
||||||
|
KickPrompt(
|
||||||
|
if (o.fromServer) "Kick $whom from the server?" else "Kick $whom from the channel?",
|
||||||
|
onDismiss = dismiss,
|
||||||
|
) { reason ->
|
||||||
|
dismiss()
|
||||||
|
picking.kick(o.fromServer, reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is Overlay.JoinLocked -> TextPrompt(
|
||||||
|
title = "Join ${tree.channel(o.channelId)?.name.orEmpty()}",
|
||||||
|
label = "Channel password",
|
||||||
|
confirm = "Join",
|
||||||
|
password = true,
|
||||||
|
onDismiss = dismiss,
|
||||||
|
onConfirm = { dismiss(); server.joinChannel(o.channelId, it) },
|
||||||
|
)
|
||||||
|
is Overlay.FilesLocked -> TextPrompt(
|
||||||
|
title = "Files of ${tree.channel(o.channelId)?.name.orEmpty()}",
|
||||||
|
label = "Channel password",
|
||||||
|
confirm = "Open",
|
||||||
|
password = true,
|
||||||
|
onDismiss = dismiss,
|
||||||
|
onConfirm = { dismiss(); nav.page = ServerPage.Files(o.channelId, tree.channel(o.channelId)?.name.orEmpty(), it) },
|
||||||
|
)
|
||||||
|
is Overlay.DeleteChannel -> {
|
||||||
|
val channel = tree.channel(o.id)
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = dismiss,
|
||||||
|
title = { Text("Delete ${channel?.name.orEmpty()}?") },
|
||||||
|
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
|
||||||
|
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
|
||||||
|
} else null,
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = then {
|
||||||
|
scope.launch { server.deleteChannel(o.id).onFailure { snackbar.showSnackbar("Could not delete the channel: ${it.message}") } }
|
||||||
|
}) { Text("Delete") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
is Overlay.AddToWhisperList -> AddToWhisperListDialog(whisperLists, o.name, onDismiss = dismiss) { index, newName ->
|
||||||
|
dismiss()
|
||||||
|
whisperLists.addTo(index, newName, o.add)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.consumeWindowInsets
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.derivedStateOf
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
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.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.LocalUriHandler
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.SwipePrefs
|
||||||
|
import eu.lixko.ts3j.client.android.TreeSwipe
|
||||||
|
import eu.lixko.ts3j.client.android.WhisperListManager
|
||||||
|
import eu.lixko.ts3j.client.chat.ChatKey
|
||||||
|
import eu.lixko.ts3j.client.config.BanReasonPresets
|
||||||
|
import eu.lixko.ts3j.client.myts.ChatAttachment
|
||||||
|
import eu.lixko.ts3j.client.session.ServerLink
|
||||||
|
import eu.lixko.ts3j.client.text.TsLink
|
||||||
|
|
||||||
|
/** A connection: the channel tree and the chat, with the voice controls underneath. */
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ServerScreen(
|
||||||
|
sessions: SessionController,
|
||||||
|
whisperLists: WhisperListManager,
|
||||||
|
account: MyTeamSpeakAccount,
|
||||||
|
swipe: SwipePrefs,
|
||||||
|
banReasons: BanReasonPresets,
|
||||||
|
server: ServerController,
|
||||||
|
snackbar: SnackbarHostState,
|
||||||
|
onSettings: () -> Unit,
|
||||||
|
/** Opens the given client's contact page. */
|
||||||
|
onEditContact: (String) -> Unit,
|
||||||
|
onEnableMicrophone: () -> Unit,
|
||||||
|
onConnectOther: () -> Unit,
|
||||||
|
onEditBookmark: (BookmarkEdit) -> Unit,
|
||||||
|
/** Turns to another server, for a swipe over the tree. */
|
||||||
|
serverSwipe: SwipeState? = null,
|
||||||
|
/** False for a server beside the one on show while swiping to it. */
|
||||||
|
active: Boolean = true,
|
||||||
|
) {
|
||||||
|
val sessionState = server.state.collectAsStateWithLifecycle()
|
||||||
|
val state by sessionState
|
||||||
|
val treeState = server.tree.collectAsStateWithLifecycle()
|
||||||
|
val tree by treeState
|
||||||
|
val chatsState = server.chats.collectAsStateWithLifecycle()
|
||||||
|
val chats by chatsState
|
||||||
|
|
||||||
|
val nav = rememberServerNav()
|
||||||
|
// Out here, so the tree keeps its place while the chat or another page replaces it.
|
||||||
|
val treeList = rememberLazyListState()
|
||||||
|
val conversationState = remember(chatsState, nav) { derivedStateOf { chatsState.value[nav.chatKey] ?: chatsState.value.channel } }
|
||||||
|
val conversation by conversationState
|
||||||
|
val picking = rememberTreePicking(server, treeState, sessionState)
|
||||||
|
|
||||||
|
val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
|
||||||
|
val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
|
||||||
|
// The chat lies to the right of the tree.
|
||||||
|
val chatBesideTree = treeSwipe == TreeSwipe.CHAT
|
||||||
|
val pageSwipe = rememberSwipeState()
|
||||||
|
|
||||||
|
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
|
||||||
|
LaunchedEffect(chatRequest) {
|
||||||
|
val key = chatRequest ?: return@LaunchedEffect
|
||||||
|
nav.openChat(if (chats[key] != null) key else server.openPrivateChat(key.clientId))
|
||||||
|
server.chatRequestHandled()
|
||||||
|
}
|
||||||
|
|
||||||
|
val viewing = if (nav.showChat) conversation.key else null
|
||||||
|
LifecycleResumeEffect(viewing, active) {
|
||||||
|
if (active) server.viewing = viewing
|
||||||
|
onPauseOrDispose { server.viewing = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
val uriHandler = LocalUriHandler.current
|
||||||
|
val attachments = rememberAttachmentActions(account, server, snackbar, conversation.key)
|
||||||
|
val onLink: (String) -> Unit = { href ->
|
||||||
|
val ref = TsLink.parse(href)
|
||||||
|
when {
|
||||||
|
ChatAttachment.isHref(href) -> attachments.open(href)
|
||||||
|
ServerLink.isLink(href) -> ServerLink.parse(href)?.let { sessions.open(it) }
|
||||||
|
ref == null -> runCatching { uriHandler.openUri(href) }
|
||||||
|
ref.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false)
|
||||||
|
else -> nav.overlay = Overlay.Channel(ref.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find: in the tree, clients or channels; in the chat, the conversation on screen.
|
||||||
|
val find = rememberSaveable(saver = FindState.Saver) { FindState() }
|
||||||
|
val treeView = rememberTreeView(server, treeState, server.collapsed.collectAsStateWithLifecycle(), find)
|
||||||
|
val chatSearch = rememberChatSearch(conversationState, find)
|
||||||
|
LaunchedEffect(treeView.treeFind, nav.showChat) { treeView.restart(onScreen = !nav.showChat) }
|
||||||
|
LaunchedEffect(chatSearch.query, conversation.key, find.filter, nav.showChat) { chatSearch.restart(onScreen = nav.showChat) }
|
||||||
|
|
||||||
|
when (val page = nav.page) {
|
||||||
|
ServerPage.Main -> {}
|
||||||
|
ServerPage.BanList -> return BanListScreen(server, banReasons, onBack = nav::back)
|
||||||
|
ServerPage.WhisperLists -> return WhisperListsScreen(whisperLists, server, onBack = nav::back)
|
||||||
|
is ServerPage.EditChannel -> return ChannelEditScreen(server, page.edit, onDone = nav::back)
|
||||||
|
is ServerPage.Files -> return FilesScreen(server, page.channelId, page.name, page.password, onBack = nav::back)
|
||||||
|
is ServerPage.ConnectionInfo -> return ConnectionInfoScreen(server, page.clientId, tree.client(page.clientId), onBack = nav::back)
|
||||||
|
}
|
||||||
|
|
||||||
|
val onTree = !nav.showChat
|
||||||
|
BackHandler(active && nav.showChat) { nav.showChat = false }
|
||||||
|
BackHandler(active && onTree && picking.moving != null) { picking.moving = null }
|
||||||
|
BackHandler(active && onTree && picking.moving == null && picking.selection.isNotEmpty()) { picking.clear() }
|
||||||
|
BackHandler(active && 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 (nav.showChat) {
|
||||||
|
FindBar(find, inTree = false, chatSearch.position, chatSearch.hits.size, chatSearch.capped, chatSearch::step)
|
||||||
|
} else {
|
||||||
|
FindBar(find, inTree = true, treeView.position, treeView.hits.size, false, treeView::step)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
TopAppBar(
|
||||||
|
title = { ServerSwitcher(sessions, server, state, onConnectOther) },
|
||||||
|
expandedHeight = 48.dp,
|
||||||
|
actions = {
|
||||||
|
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
|
||||||
|
if (state.connected && state.whisperControls) WhisperMenu(whisperLists, server, state) { nav.page = ServerPage.WhisperLists }
|
||||||
|
IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
|
||||||
|
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
bottomBar = {
|
||||||
|
Column {
|
||||||
|
val ptt = rememberPttTarget(sessions)
|
||||||
|
WhisperBanner(state) { server.setWhisper(null) }
|
||||||
|
VoiceBar(state, ptt.owner != null, ptt.talking, sessions, server, onEnableMicrophone, nav.showChat, chats.anyUnread) {
|
||||||
|
nav.showChat = !nav.showChat
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
snackbarHost = { SnackbarHost(snackbar) },
|
||||||
|
) { padding ->
|
||||||
|
SwipeHost(
|
||||||
|
pageSwipe, nav.showChat,
|
||||||
|
neighbour = { chat, dir -> if (chatBesideTree && (dir > 0) != chat) !chat else null },
|
||||||
|
onSwipe = { nav.showChat = it },
|
||||||
|
modifier = Modifier.padding(padding).consumeWindowInsets(padding).imePadding(),
|
||||||
|
) { chat ->
|
||||||
|
if (!chat) Column(Modifier.fillMaxSize()) {
|
||||||
|
PickingBar(picking, server, tree, state.channelId) { nav.overlay = Overlay.Kick(it) }
|
||||||
|
ChannelTree(
|
||||||
|
serverName = state.title,
|
||||||
|
tree = treeView.tree,
|
||||||
|
collapsed = treeView.collapsed,
|
||||||
|
currentChannel = state.channelId,
|
||||||
|
onToggle = { treeView.toggle(it.id) },
|
||||||
|
onChannel = { channel ->
|
||||||
|
val clients = picking.moving
|
||||||
|
when {
|
||||||
|
channel.spacer != null -> {}
|
||||||
|
clients != null -> picking.moveTo(channel.id, clients)
|
||||||
|
else -> nav.overlay = Overlay.Channel(channel.id)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onChannelDoubleTap = { channel ->
|
||||||
|
val clients = picking.moving
|
||||||
|
when {
|
||||||
|
clients != null -> picking.moveTo(channel.id, clients)
|
||||||
|
channel.id == state.channelId -> {}
|
||||||
|
else -> nav.join(server, channel)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onClient = {
|
||||||
|
if (picking.selection.isEmpty()) nav.overlay = Overlay.Client(it.id, fromTree = true)
|
||||||
|
else picking.toggle(it.id)
|
||||||
|
},
|
||||||
|
onServer = { nav.overlay = Overlay.Server },
|
||||||
|
modifier = Modifier.weight(1f).swipeSource(when (treeSwipe) {
|
||||||
|
TreeSwipe.CHAT -> pageSwipe
|
||||||
|
TreeSwipe.SERVERS -> serverSwipe
|
||||||
|
TreeSwipe.OFF -> null
|
||||||
|
}),
|
||||||
|
reveal = treeView.reveal,
|
||||||
|
onRevealed = { treeView.reveal = null },
|
||||||
|
found = treeView.found,
|
||||||
|
foundCurrent = treeView.current,
|
||||||
|
listState = treeList,
|
||||||
|
selected = picking.selection,
|
||||||
|
onClientLongPress = if (picking.canPick) ({ picking.pick(it.id) }) else null,
|
||||||
|
onShowSelf = { treeView.show(TreeRef(false, state.selfClientId)) },
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
ChatPane(
|
||||||
|
chats = chats,
|
||||||
|
selected = conversation,
|
||||||
|
canSend = state.connected,
|
||||||
|
onSelect = { nav.chatKey = it },
|
||||||
|
onClose = { key ->
|
||||||
|
if (nav.chatKey == key) nav.chatKey = ChatKey.CHANNEL
|
||||||
|
server.closePrivateChat(key)
|
||||||
|
},
|
||||||
|
onSend = { server.send(conversation.key, it) },
|
||||||
|
onAttach = attachments.share,
|
||||||
|
onLink = onLink,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
lines = chatSearch.lines,
|
||||||
|
find = chatSearch.query,
|
||||||
|
current = chatSearch.at,
|
||||||
|
reveal = chatSearch.reveal,
|
||||||
|
onRevealed = { chatSearch.reveal = null },
|
||||||
|
swipeTabs = chatTabSwipe,
|
||||||
|
linesModifier = Modifier.swipeSource(if (chatBesideTree) pageSwipe else null),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ServerOverlay(nav, whisperLists, server, state, tree, treeView, picking, snackbar, onLink, onEditContact, onEditBookmark)
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.MenuDefaults
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionState
|
||||||
|
|
||||||
|
/** The server's own icon, else the pack's server icon. */
|
||||||
|
@Composable
|
||||||
|
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
|
||||||
|
val tree by server.tree.collectAsStateWithLifecycle()
|
||||||
|
val version by server.images.version.collectAsStateWithLifecycle()
|
||||||
|
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
|
||||||
|
if (icon != null) Image(icon, null, modifier.size(24.dp))
|
||||||
|
else PackIcon("SERVER_GREEN", null, modifier)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The server on screen, opening onto the others and connecting to another. */
|
||||||
|
@Composable
|
||||||
|
internal fun ServerSwitcher(sessions: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
|
||||||
|
val servers by sessions.servers.collectAsStateWithLifecycle()
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
Box(Modifier.fillMaxWidth()) {
|
||||||
|
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
|
||||||
|
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; sessions.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,141 @@
|
|||||||
|
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.AppParts
|
||||||
|
import eu.lixko.ts3j.client.android.IconTheme
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.SwipePrefs
|
||||||
|
import eu.lixko.ts3j.client.android.TreeSwipe
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
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(parts: AppParts, onContacts: () -> Unit, onBack: () -> Unit) {
|
||||||
|
var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
|
||||||
|
when (page) {
|
||||||
|
SettingsPage.SOUND -> return SoundSettingsScreen(parts.settings, parts.sessions, parts.audio, onBack = { page = null })
|
||||||
|
SettingsPage.NETWORK -> return NetworkSettingsScreen(parts.settings, parts.sessions, onBack = { page = null })
|
||||||
|
SettingsPage.GIANT_PTT -> return GiantPttScreen(parts.sessions, onBack = { page = null })
|
||||||
|
SettingsPage.DESIGN -> return DesignScreen(parts.settings, parts.icons, parts.swipe, parts.sessions, onBack = { page = null })
|
||||||
|
SettingsPage.IDENTITIES -> return IdentitiesScreen(parts.identities, onBack = { page = null })
|
||||||
|
SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { page = null })
|
||||||
|
null -> {}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (parts.myTeamSpeak.login.isSignedIn) "Signed in as ${parts.myTeamSpeak.login.username()}"
|
||||||
|
else "Sign in to bring over your synchronised bookmarks, identities and contacts",
|
||||||
|
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DesignScreen(settings: Settings, icons: IconTheme, swipe: SwipePrefs, sessions: SessionController, onBack: () -> Unit) {
|
||||||
|
SubScreen("Design", onBack) { padding ->
|
||||||
|
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
|
||||||
|
IconPackPicker(icons)
|
||||||
|
var pictures by remember { mutableStateOf(settings.descriptionPictures.get()) }
|
||||||
|
Toggle("Show pictures in descriptions", pictures) {
|
||||||
|
pictures = it
|
||||||
|
settings.descriptionPictures.set(it)
|
||||||
|
settings.save()
|
||||||
|
}
|
||||||
|
Section("Channel tree")
|
||||||
|
var flags by remember { mutableStateOf(settings.countryFlags.get()) }
|
||||||
|
Toggle("Show country flags in the channel tree", flags) {
|
||||||
|
flags = it
|
||||||
|
settings.countryFlags.set(it)
|
||||||
|
settings.save()
|
||||||
|
}
|
||||||
|
val colors = settings.clientRowColors
|
||||||
|
var any by remember { mutableIntStateOf(colors.any) }
|
||||||
|
var talking by remember { mutableIntStateOf(colors.talking) }
|
||||||
|
var mutedAway by remember { mutableIntStateOf(colors.mutedAway) }
|
||||||
|
RowColorPicker("Client background", any) {
|
||||||
|
any = it
|
||||||
|
colors.any = it
|
||||||
|
sessions.clientRowColorsChanged()
|
||||||
|
}
|
||||||
|
RowColorPicker("While talking", talking) {
|
||||||
|
talking = it
|
||||||
|
colors.talking = it
|
||||||
|
sessions.clientRowColorsChanged()
|
||||||
|
}
|
||||||
|
RowColorPicker("Muted / away", mutedAway) {
|
||||||
|
mutedAway = it
|
||||||
|
colors.mutedAway = it
|
||||||
|
sessions.clientRowColorsChanged()
|
||||||
|
}
|
||||||
|
val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
|
||||||
|
Picker("Swipe sideways", listOf(
|
||||||
|
TreeSwipe.OFF to "Off",
|
||||||
|
TreeSwipe.CHAT to "Channel tree and chat",
|
||||||
|
TreeSwipe.SERVERS to "Connected servers",
|
||||||
|
), treeSwipe, swipe::setTree)
|
||||||
|
Section("Chat")
|
||||||
|
val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
|
||||||
|
Toggle("Swipe between chat tabs", chatTabSwipe, swipe::setChatTabs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,309 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.expandVertically
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.ColumnScope
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.foundation.relocation.BringIntoViewRequester
|
||||||
|
import androidx.compose.foundation.relocation.bringIntoViewRequester
|
||||||
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
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,
|
||||||
|
/** Asks for talk power with a reason, or withdraws the request with null; null when we may not ask. */
|
||||||
|
onTalkRequest: ((String?) -> Unit)?,
|
||||||
|
onAddContact: (ContactType) -> Unit,
|
||||||
|
onEditContact: () -> Unit,
|
||||||
|
onConnectionInfo: () -> Unit,
|
||||||
|
/** Both null when whisper controls are hidden. */
|
||||||
|
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; null when there are none. */
|
||||||
|
moderation: (@Composable () -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
var poking by remember { mutableStateOf(false) }
|
||||||
|
var requesting by remember { mutableStateOf(false) }
|
||||||
|
val sheetState = rememberModalBottomSheetState()
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
// A half-open sheet would fold the admin actions out below the screen's edge.
|
||||||
|
val adminActions = @Composable { content: @Composable ColumnScope.() -> Unit ->
|
||||||
|
ExpandableAction("PERMISSIONS_CLIENTS", "Admin actions…", onExpand = { scope.launch { sheetState.expand() } }, content)
|
||||||
|
}
|
||||||
|
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
|
||||||
|
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) }
|
||||||
|
if (client.self) {
|
||||||
|
Action("AWAY", if (away) "Back" else "Away") { onAway(!away) }
|
||||||
|
onTalkRequest?.let { request ->
|
||||||
|
if (client.talkRequest) Action("TALK_POWER_CANCEL_REQUEST", "Cancel talk power request") { request(null) }
|
||||||
|
else Action("TALK_POWER_REQUEST", "Request talk power") { requesting = true }
|
||||||
|
}
|
||||||
|
moderation?.let { adminActions { it() } }
|
||||||
|
} else {
|
||||||
|
Action("PLAYER_CHAT", "Send message", onClick = onMessage)
|
||||||
|
Action("POKE", "Poke") { poking = true }
|
||||||
|
onWhisper?.let { Action("PLAYER_WHISPER", "Whisper", onClick = it) }
|
||||||
|
// "Add to whisper list…" (onAddToWhisperList) is left out for now.
|
||||||
|
onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) }
|
||||||
|
if (onMove != null || moderation != null) {
|
||||||
|
adminActions {
|
||||||
|
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
|
||||||
|
moderation?.invoke()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action("INFO", "Connection info", onClick = onConnectionInfo)
|
||||||
|
if (!client.self) {
|
||||||
|
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) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (requesting) {
|
||||||
|
TextPrompt(
|
||||||
|
title = "Request talk power",
|
||||||
|
label = "Reason",
|
||||||
|
confirm = "Request",
|
||||||
|
onDismiss = { requesting = false },
|
||||||
|
onConfirm = { requesting = false; onTalkRequest?.invoke(it.trim()) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
/** Both null when whisper controls are hidden. */
|
||||||
|
onWhisper: (() -> Unit)?,
|
||||||
|
onAddToWhisperList: (() -> Unit)?,
|
||||||
|
/** Each null when we may not. */
|
||||||
|
onFiles: (() -> Unit)?,
|
||||||
|
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) }
|
||||||
|
}
|
||||||
|
onWhisper?.let { Action("WHISPER", "Whisper", onClick = it) }
|
||||||
|
onAddToWhisperList?.let { Action("ON_WHISPERLIST", "Add to whisper list…", onClick = it) }
|
||||||
|
onFiles?.let { Action("FILETRANSFER", "Browse files", onClick = it) }
|
||||||
|
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),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A row that, once tapped, gives its place to the [content] it stands for, scrolled into view. */
|
||||||
|
@Composable
|
||||||
|
internal fun ExpandableAction(
|
||||||
|
iconKey: String,
|
||||||
|
label: String,
|
||||||
|
onExpand: () -> Unit = {},
|
||||||
|
content: @Composable ColumnScope.() -> Unit,
|
||||||
|
) {
|
||||||
|
var expanded by remember { mutableStateOf(false) }
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val inView = remember { BringIntoViewRequester() }
|
||||||
|
if (!expanded) {
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(label) },
|
||||||
|
leadingContent = { PackIcon(iconKey, null) },
|
||||||
|
trailingContent = { Icon(Icons.Filled.KeyboardArrowDown, null) },
|
||||||
|
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
|
||||||
|
modifier = Modifier.fillMaxWidth().clickable { expanded = true; onExpand() }.padding(horizontal = 8.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
AnimatedVisibility(expanded, enter = expandVertically() + fadeIn()) {
|
||||||
|
Column(
|
||||||
|
Modifier.bringIntoViewRequester(inView)
|
||||||
|
// Follows the items as they unfold.
|
||||||
|
.onSizeChanged { scope.launch { inView.bringIntoView() } },
|
||||||
|
content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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.AudioSetup
|
||||||
|
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.Setting
|
||||||
|
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(settings: Settings, sessions: SessionController, audio: AudioSetup, onBack: () -> Unit) {
|
||||||
|
fun <T> change(setting: Setting<T>, value: T) {
|
||||||
|
setting.set(value)
|
||||||
|
sessions.applySettings()
|
||||||
|
}
|
||||||
|
var inputMode by remember { mutableStateOf(settings.inputMode.get()) }
|
||||||
|
var vadMode by remember { mutableStateOf(settings.vadMode.get()) }
|
||||||
|
var agc by remember { mutableStateOf(settings.agc.get()) }
|
||||||
|
var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning.get()) }
|
||||||
|
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) }
|
||||||
|
var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) }
|
||||||
|
var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) }
|
||||||
|
val inputs by audio.inputDevices.collectAsStateWithLifecycle()
|
||||||
|
val outputs by audio.outputDevices.collectAsStateWithLifecycle()
|
||||||
|
val route by audio.route.collectAsStateWithLifecycle()
|
||||||
|
val level by sessions.micLevel.collectAsStateWithLifecycle()
|
||||||
|
val packs by audio.soundPacks.collectAsStateWithLifecycle()
|
||||||
|
var pack by remember { mutableStateOf(audio.soundPack?.id()) }
|
||||||
|
LifecycleStartEffect(Unit) {
|
||||||
|
sessions.watchLevel(true)
|
||||||
|
onStopOrDispose { sessions.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(settings.inputDevice, it)
|
||||||
|
}
|
||||||
|
DevicePicker("Speaker", outputs, outputDevice) {
|
||||||
|
outputDevice = it
|
||||||
|
change(settings.outputDevice, it)
|
||||||
|
}
|
||||||
|
Picker(
|
||||||
|
"Microphone preset",
|
||||||
|
INPUT_PRESETS.map { (preset, label) ->
|
||||||
|
val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !audio.unprocessedSupported
|
||||||
|
preset to if (unsupported) "$label (not supported here)" else label
|
||||||
|
},
|
||||||
|
route.inputPreset(),
|
||||||
|
) { audio.setRoute(AudioRoute(it, route.usage())) }
|
||||||
|
Hint(PRESET_HINTS.getValue(route.inputPreset()))
|
||||||
|
Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp))
|
||||||
|
for ((usage, label) in USAGES) {
|
||||||
|
Choice(label, route.usage() == usage) { audio.setRoute(AudioRoute(route.inputPreset(), usage)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Transmission")
|
||||||
|
for ((mode, label) in INPUT_MODES) {
|
||||||
|
Choice(label, inputMode == mode) {
|
||||||
|
inputMode = mode
|
||||||
|
change(settings.inputMode, mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(audio)
|
||||||
|
val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC
|
||||||
|
LevelMeter(level, threshold.takeIf { gated })
|
||||||
|
if (!level.live) {
|
||||||
|
Hint(if (sessions.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(settings.vadMode, mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (vadMode != Settings.VadMode.AUTOMATIC) {
|
||||||
|
Level("Volume threshold", settings.vadThresholdDb.get().toFloat(), -50f..50f, { "${it.roundToInt()}" },
|
||||||
|
onChange = { threshold = it }) {
|
||||||
|
change(settings.vadThresholdDb, it.roundToInt().toDouble())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (vadMode != Settings.VadMode.VOLUME_GATE) {
|
||||||
|
Level("Speech likelihood", settings.speechThreshold.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
|
||||||
|
change(settings.speechThreshold, it.toDouble())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Processing")
|
||||||
|
val suppression = if (settings.denoise.get()) settings.denoiserLevel.get() + 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()
|
||||||
|
settings.denoise.set(step > 0)
|
||||||
|
if (step > 0) settings.denoiserLevel.set(step - 1)
|
||||||
|
sessions.applySettings()
|
||||||
|
}
|
||||||
|
Toggle("Automatic gain control", agc) {
|
||||||
|
agc = it
|
||||||
|
change(settings.agc, it)
|
||||||
|
}
|
||||||
|
if (agc) {
|
||||||
|
Level("Boost quiet speech", settings.agcBoostDb.get().toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(),
|
||||||
|
{ "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) {
|
||||||
|
change(settings.agcBoostDb, it.roundToInt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Playback")
|
||||||
|
Level("Volume", settings.outputVolume.get().toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) {
|
||||||
|
change(settings.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(audio::setSoundPack)
|
||||||
|
pack = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Level("Volume", settings.soundVolume.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
|
||||||
|
change(settings.soundVolume, it.toDouble())
|
||||||
|
}
|
||||||
|
Toggle("Beep when talking while muted", mutedTalkWarning) {
|
||||||
|
mutedTalkWarning = it
|
||||||
|
change(settings.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(audio: AudioSetup) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val enabled by audio.pttOverlay.collectAsStateWithLifecycle()
|
||||||
|
val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||||
|
if (canDrawOverlays(context)) audio.setPttOverlay(true)
|
||||||
|
}
|
||||||
|
Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on ->
|
||||||
|
if (!on || canDrawOverlays(context)) audio.setPttOverlay(on)
|
||||||
|
else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")))
|
||||||
|
}
|
||||||
|
Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,152 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.animation.core.animate
|
||||||
|
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||||
|
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||||
|
import androidx.compose.foundation.gestures.awaitHorizontalTouchSlopOrCancellation
|
||||||
|
import androidx.compose.foundation.gestures.horizontalDrag
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableFloatStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.rememberUpdatedState
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clipToBounds
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||||
|
import androidx.compose.ui.input.pointer.PointerId
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.input.pointer.positionChange
|
||||||
|
import androidx.compose.ui.input.pointer.positionChangeIgnoreConsumed
|
||||||
|
import androidx.compose.ui.input.pointer.util.VelocityTracker
|
||||||
|
import androidx.compose.ui.input.pointer.util.addPointerInputChange
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.sign
|
||||||
|
|
||||||
|
/** How fast a short swipe must be to turn the page. */
|
||||||
|
private val FLING_VELOCITY = 600.dp
|
||||||
|
|
||||||
|
/** Where a sideways swipe between a [SwipeHost]'s pages is at. */
|
||||||
|
@Stable
|
||||||
|
class SwipeState {
|
||||||
|
/** How far the page on show has moved, in pixels; negative to the left. */
|
||||||
|
internal var shift by mutableFloatStateOf(0f)
|
||||||
|
/** Whether a swipe is under way, so the pages either side are on show too. */
|
||||||
|
internal var active by mutableStateOf(false)
|
||||||
|
/** The pointer that went down over one of the [swipeSource]s. */
|
||||||
|
internal var armed: PointerId? = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberSwipeState() = remember { SwipeState() }
|
||||||
|
|
||||||
|
/** Lets a swipe that starts over this element turn [state]'s pages. */
|
||||||
|
internal fun Modifier.swipeSource(state: SwipeState?): Modifier =
|
||||||
|
if (state == null) this else pointerInput(state) {
|
||||||
|
awaitEachGesture {
|
||||||
|
// Seen before the host looks at the same press.
|
||||||
|
state.armed = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial).id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pages side by side, [current] on show and those either side ([neighbour] gives them, -1 to the left,
|
||||||
|
* 1 to the right) following the finger. A swipe has to start over a [swipeSource] of [state];
|
||||||
|
* one that has no page to go to is left to a host further out. [onSwipe] is told of the page swiped to.
|
||||||
|
* Pages are told apart by equality, so [T] should be a key rather than a snapshot of what it shows.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun <T : Any> SwipeHost(
|
||||||
|
state: SwipeState,
|
||||||
|
current: T,
|
||||||
|
neighbour: (T, Int) -> T?,
|
||||||
|
onSwipe: (T) -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
page: @Composable (T) -> Unit,
|
||||||
|
) {
|
||||||
|
var shown by remember { mutableStateOf(current) }
|
||||||
|
/** A page swiped to that [current] has not caught up with yet. */
|
||||||
|
var awaited by remember { mutableStateOf<T?>(null) }
|
||||||
|
val latest by rememberUpdatedState(current)
|
||||||
|
val pageNear by rememberUpdatedState(neighbour)
|
||||||
|
val swiped by rememberUpdatedState(onSwipe)
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var settling by remember { mutableStateOf<Job?>(null) }
|
||||||
|
LaunchedEffect(current) {
|
||||||
|
awaited = null
|
||||||
|
if (!state.active) shown = current
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(modifier.clipToBounds().pointerInput(state) {
|
||||||
|
awaitEachGesture {
|
||||||
|
val down = awaitFirstDown(requireUnconsumed = false)
|
||||||
|
if (state.armed != down.id) return@awaitEachGesture
|
||||||
|
val start = awaitHorizontalTouchSlopOrCancellation(down.id) { change, over ->
|
||||||
|
if (pageNear(shown, direction(over)) != null) change.consume()
|
||||||
|
} ?: return@awaitEachGesture
|
||||||
|
settling?.cancel()
|
||||||
|
state.active = true
|
||||||
|
val width = size.width.toFloat()
|
||||||
|
val left = pageNear(shown, -1)
|
||||||
|
val right = pageNear(shown, 1)
|
||||||
|
val drag = { dx: Float ->
|
||||||
|
state.shift = (state.shift + dx).coerceIn(if (right != null) -width else 0f, if (left != null) width else 0f)
|
||||||
|
}
|
||||||
|
val velocity = VelocityTracker()
|
||||||
|
velocity.addPointerInputChange(start)
|
||||||
|
drag(start.positionChangeIgnoreConsumed().x)
|
||||||
|
val lifted = horizontalDrag(start.id) { change ->
|
||||||
|
drag(change.positionChange().x)
|
||||||
|
change.consume()
|
||||||
|
velocity.addPointerInputChange(change)
|
||||||
|
}
|
||||||
|
val fling = if (lifted) velocity.calculateVelocity().x else 0f
|
||||||
|
val from = state.shift
|
||||||
|
val dir = when {
|
||||||
|
abs(fling) > FLING_VELOCITY.toPx() -> direction(fling)
|
||||||
|
abs(from) > width / 3 -> direction(from)
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
// A fling back against the swipe turns no page.
|
||||||
|
val target = if (dir != 0 && dir == direction(from)) pageNear(shown, dir) else null
|
||||||
|
settling = scope.launch {
|
||||||
|
animate(from, if (target != null) -dir * width else 0f, fling) { value, _ -> state.shift = value }
|
||||||
|
if (target != null) {
|
||||||
|
shown = target
|
||||||
|
awaited = target
|
||||||
|
swiped(target)
|
||||||
|
} else if (awaited == null) {
|
||||||
|
shown = latest
|
||||||
|
}
|
||||||
|
state.shift = 0f
|
||||||
|
state.active = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
val at = shown
|
||||||
|
val pages = if (!state.active) listOf(at to 0)
|
||||||
|
else listOfNotNull(neighbour(at, -1)?.to(-1), at to 0, neighbour(at, 1)?.to(1))
|
||||||
|
for ((item, slot) in pages) {
|
||||||
|
// Keyed, so the page swiped to keeps its state when it becomes the one on show.
|
||||||
|
key(item) {
|
||||||
|
Box(Modifier.fillMaxSize().graphicsLayer { translationX = state.shift + slot * size.width }) {
|
||||||
|
page(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A drag or fling to the left heads for what lies to the right. */
|
||||||
|
private fun direction(dx: Float): Int = -sign(dx).toInt()
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
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.navigationBarsPadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.itemsIndexed
|
||||||
|
import androidx.compose.foundation.selection.selectable
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.RadioButton
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.mutableStateMapOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync.Conflict
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which copy to keep of each item changed both here and in myTeamSpeak since the last
|
||||||
|
* synchronisation: the item's fields side by side, the ones that differ in bold.
|
||||||
|
* [onDone] gets whether the user went on; the choices are recorded on the conflicts.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun SyncConflictsScreen(conflicts: List<Conflict>, onDone: (Boolean) -> Unit) {
|
||||||
|
// Mirrors the choices recorded on the conflicts, for recomposition.
|
||||||
|
val choices = remember(conflicts) {
|
||||||
|
mutableStateMapOf<Int, Conflict.Choice>().apply {
|
||||||
|
conflicts.forEachIndexed { i, c -> c.choice()?.let { put(i, it) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun choose(index: Int, choice: Conflict.Choice) {
|
||||||
|
conflicts[index].choose(choice)
|
||||||
|
choices[index] = choice
|
||||||
|
}
|
||||||
|
BackHandler { onDone(false) }
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text("Synchronization conflicts") },
|
||||||
|
navigationIcon = { IconButton(onClick = { onDone(false) }) { Icon(Icons.Filled.Close, "Cancel") } },
|
||||||
|
)
|
||||||
|
},
|
||||||
|
bottomBar = {
|
||||||
|
Surface(tonalElevation = 3.dp) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.HERE) } }) {
|
||||||
|
Text("Keep all of this device's")
|
||||||
|
}
|
||||||
|
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.CLOUD) } }) {
|
||||||
|
Text("Keep all of myTeamSpeak's")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Button(onClick = { onDone(true) }, enabled = choices.size == conflicts.size) { Text("Synchronize") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { padding ->
|
||||||
|
LazyColumn(
|
||||||
|
Modifier.padding(padding),
|
||||||
|
contentPadding = PaddingValues(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
item { Text("Changed here and in myTeamSpeak since the last synchronization:") }
|
||||||
|
itemsIndexed(conflicts) { index, conflict ->
|
||||||
|
ConflictCard(conflict, choices[index]) { choose(index, it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ConflictCard(conflict: Conflict, choice: Conflict.Choice?, onChoose: (Conflict.Choice) -> Unit) {
|
||||||
|
Card(Modifier.fillMaxWidth()) {
|
||||||
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Text((if (conflict.isIdentity) "Identity: " else "Bookmark: ") + conflict.title(),
|
||||||
|
style = MaterialTheme.typography.titleMedium)
|
||||||
|
Row {
|
||||||
|
Spacer(0.3f)
|
||||||
|
Header(if (conflict.deletedHere()) "This device (deleted)" else "This device")
|
||||||
|
Header(if (conflict.deletedInCloud()) "myTeamSpeak (deleted)" else "myTeamSpeak")
|
||||||
|
}
|
||||||
|
for (d in conflict.differences()) {
|
||||||
|
Row {
|
||||||
|
Text(d.label(), Modifier.weight(0.3f), style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Value(if (conflict.deletedHere()) "—" else d.here(), d.differs())
|
||||||
|
Value(if (conflict.deletedInCloud()) "—" else d.cloud(), d.differs())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Option(if (conflict.deletedHere()) "Delete" else "Keep this device's", choice == Conflict.Choice.HERE) {
|
||||||
|
onChoose(Conflict.Choice.HERE)
|
||||||
|
}
|
||||||
|
Option(if (conflict.deletedInCloud()) "Delete" else "Keep myTeamSpeak's", choice == Conflict.Choice.CLOUD) {
|
||||||
|
onChoose(Conflict.Choice.CLOUD)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun androidx.compose.foundation.layout.RowScope.Spacer(weight: Float) {
|
||||||
|
androidx.compose.foundation.layout.Spacer(Modifier.weight(weight))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun androidx.compose.foundation.layout.RowScope.Header(text: String) {
|
||||||
|
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.labelMedium)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun androidx.compose.foundation.layout.RowScope.Value(text: String, differs: Boolean) {
|
||||||
|
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.bodySmall,
|
||||||
|
fontWeight = if (differs) FontWeight.Bold else FontWeight.Normal)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Option(text: String, selected: Boolean, onClick: () -> Unit) {
|
||||||
|
Row(
|
||||||
|
Modifier.fillMaxWidth().selectable(selected, onClick = onClick, role = Role.RadioButton),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
RadioButton(selected, onClick = null)
|
||||||
|
Text(text, Modifier.padding(start = 8.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,145 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.Stable
|
||||||
|
import androidx.compose.runtime.State
|
||||||
|
import androidx.compose.runtime.derivedStateOf
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.ServerTree
|
||||||
|
import eu.lixko.ts3j.client.android.SessionState
|
||||||
|
|
||||||
|
/** Clients picked in the tree by a long press, to act on together, and clients being moved while a channel is picked. */
|
||||||
|
@Stable
|
||||||
|
internal class TreePicking(
|
||||||
|
private val server: ServerController,
|
||||||
|
private val tree: State<ServerTree>,
|
||||||
|
private val state: State<SessionState>,
|
||||||
|
) {
|
||||||
|
/** The clients to move, while a channel for them is being picked. */
|
||||||
|
var moving by mutableStateOf<Set<Int>?>(null)
|
||||||
|
|
||||||
|
private var picked by mutableStateOf(emptySet<Int>())
|
||||||
|
/** The picked clients still on the server. */
|
||||||
|
val selection by derivedStateOf { picked.filterTo(LinkedHashSet()) { tree.value.client(it) != null } }
|
||||||
|
|
||||||
|
val canPick: Boolean get() = with(server.permissions) { canMoveClients() || canKickFromChannel() || canKickFromServer() }
|
||||||
|
|
||||||
|
fun pick(clientId: Int) {
|
||||||
|
picked = selection + clientId
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toggle(clientId: Int) {
|
||||||
|
picked = if (clientId in selection) selection - clientId else selection + clientId
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
picked = emptySet()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Those of the selection not in our channel. */
|
||||||
|
val outsideOwnChannel: Set<Int>
|
||||||
|
get() = selection - tree.value.channel(state.value.channelId)?.clients.orEmpty().map { it.id }.toSet()
|
||||||
|
|
||||||
|
/** Whom of the selection a kick goes to: never us, and from a channel, nobody already in the default one. */
|
||||||
|
fun kickable(fromServer: Boolean): Set<Int> {
|
||||||
|
val inDefault = if (fromServer) emptySet() else tree.value.channel(server.defaultChannelId)?.clients.orEmpty().map { it.id }.toSet()
|
||||||
|
return selection - state.value.selfClientId - inDefault
|
||||||
|
}
|
||||||
|
|
||||||
|
fun kick(fromServer: Boolean, reason: String) {
|
||||||
|
val whom = kickable(fromServer)
|
||||||
|
if (fromServer) server.kickFromServer(whom, reason) else server.kickFromChannel(whom, reason)
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun moveTo(channelId: Int, clients: Set<Int>) {
|
||||||
|
server.moveClients(clients, channelId)
|
||||||
|
moving = null
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun rememberTreePicking(server: ServerController, tree: State<ServerTree>, state: State<SessionState>): TreePicking =
|
||||||
|
remember(server, tree, state) { TreePicking(server, tree, state) }
|
||||||
|
|
||||||
|
/** Above the tree: the clients being moved, or what may be done with those picked. */
|
||||||
|
@Composable
|
||||||
|
internal fun PickingBar(picking: TreePicking, server: ServerController, tree: ServerTree, ownChannel: Int, onKick: (fromServer: Boolean) -> Unit) {
|
||||||
|
val moving = picking.moving
|
||||||
|
val selection = picking.selection
|
||||||
|
if (moving != null) {
|
||||||
|
val clients = moving.mapNotNull { tree.client(it) }
|
||||||
|
if (clients.isEmpty()) {
|
||||||
|
LaunchedEffect(moving) { picking.moving = null }
|
||||||
|
} else {
|
||||||
|
MovePrompt(clients.singleOrNull()?.name ?: "${clients.size} clients") { picking.moving = null }
|
||||||
|
}
|
||||||
|
} else if (selection.isNotEmpty()) {
|
||||||
|
val can = server.permissions
|
||||||
|
val outside = picking.outsideOwnChannel
|
||||||
|
SelectionBar(
|
||||||
|
count = selection.size,
|
||||||
|
onMove = if (can.canMoveClients()) ({ picking.moving = selection }) else null,
|
||||||
|
onMoveHere = if (can.canMoveClients() && outside.isNotEmpty()) ({ picking.moveTo(ownChannel, outside) }) else null,
|
||||||
|
onKickChannel = if (can.canKickFromChannel() && picking.kickable(false).isNotEmpty()) ({ onKick(false) }) else null,
|
||||||
|
onKickServer = if (can.canKickFromServer() && picking.kickable(true).isNotEmpty()) ({ onKick(true) }) else null,
|
||||||
|
onClear = picking::clear,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How many clients are picked in the tree, and what may be done with them at once. */
|
||||||
|
@Composable
|
||||||
|
private fun SelectionBar(
|
||||||
|
count: Int,
|
||||||
|
onMove: (() -> Unit)?,
|
||||||
|
onMoveHere: (() -> Unit)?,
|
||||||
|
onKickChannel: (() -> Unit)?,
|
||||||
|
onKickServer: (() -> Unit)?,
|
||||||
|
onClear: () -> Unit,
|
||||||
|
) {
|
||||||
|
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Clear selection") }
|
||||||
|
Text("$count selected", Modifier.weight(1f), maxLines = 1, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
onMove?.let { IconButton(onClick = it) { PackIcon("CHANNEL_SWITCH", "Move to…") } }
|
||||||
|
onMoveHere?.let { IconButton(onClick = it) { PackIcon("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to my channel") } }
|
||||||
|
onKickChannel?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_CHANNEL", "Kick from channel") } }
|
||||||
|
onKickServer?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_SERVER", "Kick from server") } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
|
||||||
|
@Composable
|
||||||
|
private fun MovePrompt(name: String, onCancel: () -> Unit) {
|
||||||
|
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
PackIcon("CHANNEL_SWITCH", null)
|
||||||
|
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
TextButton(onClick = onCancel) { Text("Cancel") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package eu.lixko.ts3j.client.android.ui
|
||||||
|
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.combinedClickable
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.material3.Badge
|
||||||
|
import androidx.compose.material3.BadgedBox
|
||||||
|
import androidx.compose.material3.FilledTonalButton
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.IconToggleButton
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.minimumInteractiveComponentSize
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.alpha
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import eu.lixko.ts3j.client.android.ServerController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionController
|
||||||
|
import eu.lixko.ts3j.client.android.SessionState
|
||||||
|
import eu.lixko.ts3j.client.config.Settings
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
|
||||||
|
* microphone is used. Holding the mute button switches between push to talk and voice activation.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
internal fun VoiceBar(
|
||||||
|
state: SessionState,
|
||||||
|
/** Whether some server holds the microphone, for push-to-talk to talk on. */
|
||||||
|
captured: Boolean,
|
||||||
|
talking: Boolean,
|
||||||
|
sessions: 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 = sessions.toggleInputMode()
|
||||||
|
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
|
||||||
|
else "Switched to voice activation mode."
|
||||||
|
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
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, sessions::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
|
||||||
|
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
|
||||||
|
PackIcon("CAPTURE", null)
|
||||||
|
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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() }
|
||||||
|
}
|
||||||
@@ -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.SessionState
|
||||||
|
import eu.lixko.ts3j.client.android.WhisperListManager
|
||||||
|
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(whisperLists: WhisperListManager, server: ServerController, state: SessionState, onManage: () -> Unit) {
|
||||||
|
val lists by whisperLists.all.collectAsStateWithLifecycle()
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") }
|
||||||
|
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(whisperLists: WhisperListManager, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) {
|
||||||
|
val lists by whisperLists.all.collectAsStateWithLifecycle()
|
||||||
|
var naming by remember { mutableStateOf(false) }
|
||||||
|
if (naming) {
|
||||||
|
TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = {
|
||||||
|
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(whisperLists: WhisperListManager, server: ServerController, onBack: () -> Unit) {
|
||||||
|
val lists by whisperLists.all.collectAsStateWithLifecycle()
|
||||||
|
/** The list being edited: its index, -1 for a new one; null on the overview. */
|
||||||
|
var editing by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||||
|
editing?.let { index ->
|
||||||
|
WhisperListScreen(whisperLists, 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; whisperLists.remove(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(whisperLists: WhisperListManager, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) {
|
||||||
|
var name by rememberSaveable { mutableStateOf(saved.name) }
|
||||||
|
var list by remember { mutableStateOf(saved.copy()) }
|
||||||
|
val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) }
|
||||||
|
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 = {
|
||||||
|
whisperLists.save(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.AbstractCtlOpusEncoder;
|
||||||
|
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 AbstractCtlOpusEncoder {
|
||||||
|
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)
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user