Compare commits

..
46 Commits
Author SHA1 Message Date
erikbrockoandClaude Opus 5.5 f78e4fcd66 Android: tidier client group dialogs
test / test (push) Has been cancelled
The group dialogs list a group we may not assign only when the client is
in it, and the rows drop the 48dp minimum touch target for a 6dp padding.
The Server groups and Channel group actions share one row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:33:54 +00:00
erikbrockoandClaude Opus 5.5 b586a80a14 Hide the default port in bookmark lists
Bookmark.hostPort gives the address alone for port 9987 and address:port
otherwise. The Android connect screen, the myTeamSpeak item lists on
desktop and Android, and the display name of an unnamed bookmark use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:29:42 +00:00
erikbrockoandClaude Opus 5.5 455fc514f5 myTeamSpeak: account items under Identities and Bookmarks
The items the account synchronises are listed in an Identities and a
Bookmarks section, each with a Select all / Deselect all button on its
heading line, on desktop and Android. The desktop tables drop the Type
column and name the details column Nickname or Address.

FormPanel.sectionHeader and addSection take an optional trailing component.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:26:10 +00:00
erikbrockoandClaude Opus 5.5 00d9d85e54 Android: myTeamSpeak button on the connect screen without bookmarks
With no bookmarks, the connect screen shows "Sign in to myTeamSpeak"
("Import from myTeamSpeak" when signed in), which opens the same
myTeamSpeak screen as Settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:26:10 +00:00
erikbrockoandClaude Opus 5.5 cdd41e7527 Android: launcher label "TS3J"
"TeamSpook TS3j" does not fit under a home-screen icon, so the launcher
activity is labelled "TS3J". The application label, shown in App info and
notifications, stays "TeamSpook TS3j".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:10:29 +00:00
erikbrockoandClaude Opus 5.5 aee0e55df5 Android: product name on the connect screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:55:17 +00:00
erikbrockoandClaude Opus 5.5 a713b1e818 Android: keep chats scrolled to the newest line
A chat follows its end until the user scrolls away from it: a restored log,
new lines and content that grows later all keep the newest line fully in
view, a tall last message included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:55:17 +00:00
erikbrockoandClaude Opus 5.5 78fc45f9b2 Rename to TeamSpook TS3j, package eu.lixko.ts3j.client
Java/Kotlin sources move from com.ts3client to eu.lixko.ts3j.client, and
the Android application id becomes eu.lixko.ts3j.client. The product name
shows as "TeamSpook TS3j" in window titles, the tray, the launcher entries,
notifications and PipeWire streams.

The desktop profile directory, WM_CLASS and ts3j.* system properties keep
their names so existing settings and launchers carry on working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 14:43:34 +00:00
erikbrockoandClaude Opus 5.5 1a762c2689 Import bookmarks in TeamSpeak's order
TeamSpeak stores sync items in creation order; each names the item above
it in its folder, and a reorder only rewrites those links. The decoder
now keeps that link and SyncOrder follows the chains, so items read from
settings.db or myTeamSpeak come out as the official client lists them,
a folder's contents in its place. Broken links and loops go last in
stored order. Bookmarks imported earlier keep their place.

The reordered.db fixture was written by the official client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 13:15:28 +00:00
erikbrockoandClaude Opus 5.5 8d04cc5ba4 Android: connect bookmarks on startup
The bookmark page has a "Connect on startup" switch, the same flag the
desktop client and the TeamSpeak import use. A fresh launch connects
every such bookmark once per process, skipping the server a link or
home-screen shortcut opened the app to. The bookmarks list marks them
with a green "AC".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 13:15:28 +00:00
erikbrockoandClaude Opus 5.5 55e8b7bccb Android: signed, smaller release APKs
Release builds now come out one APK per ABI, signed from a gitignored
keystore.properties. Oboe is built from source with libopus and a static
libc++ into the one native library, which exports only its JNI entry
points; dex and native code are compressed in the APK and library
translations dropped. The arm64 APK went from 11.6 MB to 5.5 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 12:23:09 +00:00
erikbrockoandClaude Opus 5.5 44ecc15bd8 New application icon on both apps
Rubin's vase with a headset: the vase's outline is two faces looking at
each other, one talking into the microphone. Blue on transparent; the
Android launcher puts it on white, as no launcher shows a transparent
adaptive icon. Desktop windows, tray, the .desktop entry and the macOS
dock all use it, with a bolder variant below 32 px.

ts3-client/tools/AppIcon.java generates the SVGs and the launcher
foreground.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 23:06:46 +00:00
erikbrockoandClaude Opus 5.5 a334173fcc Android: whisper to channels, clients and whisper lists
The channel and client sheets whisper to them or add them to a whisper
list. The top bar's whisper menu picks a list, replies to the last
whisper, stops whispering and edits the lists; a banner over the voice
bar says who the microphone whispers to.

Core keeps the whisper on the session, finding its channels by path and
its clients by unique id again as the server changes, and the saved lists
in whisperlists.properties. ts3j now sends whisper packets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:19:52 +00:00
erikbrockoandClaude Opus 5.5 eed8049100 Android: browse a channel's files
Browse files on the channel sheet walks the channel's folders: download
to where the user picks, upload a document, new folder, rename, delete.
Transfers go through cache files and outlive the page, with progress and
cancel; a locked channel asks for its password first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:19:52 +00:00
erikbrockoandClaude Opus 5.5 7938b49b07 Android: create, edit and delete channels
A one-page channel editor with what the desktop dialog has but the
permissions and the icon: name, password, topic, description, type,
sorting, talk power, codec preset or codec and quality, and the limits.
Create channel is on the server sheet; create sub-channel, edit and
delete on the channel sheet, each only with the permission for it.

The codec list, presets and bandwidth move to core for both editors.
Core gains channel delete, and the desktop channel menu a Delete Channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:19:52 +00:00
erikbrockoandClaude Opus 5.5 60ef727f22 Android: home-screen shortcuts to bookmarks
"Add to home screen" in a bookmark's menu pins a shortcut that connects
to the bookmark, or goes to its channel when already on that server. The
shortcut names the bookmark by a new stable id, so it follows edits and
stops working once the bookmark is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:19:52 +00:00
erikbrockoandClaude Opus 5.5 e76804fb2d Open ts3server:// links on both apps
A link connects with its nickname, passwords, channel (path or cid) and
privilege key, the key used once on; addbookmark saves it as a bookmark.
A link to a server we are on already goes to its channel instead.

Android takes the links from browsers and other apps through an intent
filter, and from chat. The desktop opens them from chat and descriptions,
and its launcher entry claims the scheme when run from the jar; a second
launch hands its link to the running instance over a Unix socket in the
user's runtime directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:19:52 +00:00
erikbrockoandClaude Opus 5.5 45d6fcda3d Ignore the bundled TeamSpeak 6 server
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:40:10 +00:00
erikbrockoandClaude Opus 5.5 33066f454a Android: bookmark edit page, and bookmarks that join a channel
Edit from a bookmark's menu or create from the connect form: name,
address, passwords, identity, nickname, and the channel to join, picked
from the server's channels while connected there. The channel and server
sheets add the server as a bookmark joining that channel.

Bookmarking the current server takes the connect's own nickname and
password (core ServerSession.toBookmark), on desktop too, rather than the
global ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:26:18 +00:00
erikbrockoandClaude Opus 5.5 ad7bb4fc6e Fold the noise removal toggle into one Off/6/12/18/21 dB slider
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:16:06 +00:00
erikbrockoandClaude Opus 5.5 cbe92e84ff Fix myTeamSpeak sign-in for accounts with add-on items
The server returns every item class the account holds, not only the
requested ones, and add-on items come unencrypted. Decrypting them failed
the integrity check and aborted the whole import. Only decrypt the
classes that were asked for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:14:43 +00:00
erikbrockoandClaude Opus 5.5 ad9dfa5be0 Share pictures and files in chat, the way TeamSpeak 6 does
A shared file goes to the sender's myTeamSpeak cloud storage, and an
ordinary text message carries TeamSpeak 6's ts.file.myts pointer to it, so
TeamSpeak 6 users see the file and we see theirs. Pictures show inline
through the description picture cache, other files as a link to save;
logged history shows them too. Sharing and fetching need a myTeamSpeak
sign-in.

Desktop: share button, drop or paste files and pictures, a picture viewer.
Android: attach from the system picker, tap to view or save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:23:25 +00:00
erikbrockoandClaude Opus 5.5 1bb788b501 Show the myTeamSpeak ID, UUID and creation date in the account tab
The ID is the account's base32 myTeamSpeak ID: the localpart of its chat
ID and the user the myTeamSpeak file API addresses. All three come from
the sign-in reply already fetched, on desktop and Android.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 08:03:59 +00:00
erikbrockoandClaude Opus 5.5 023b449fba Add offline messages: inbox, compose and reply, unread notice
Tools > Offline Messages (Ctrl+O) lists the server inbox, shows a message and
marks it read; compose and reply follow the official windows. The unread count
comes from client_unread_messages: new mail is logged with a link to the inbox
and shown as an envelope in the status bar. Recipients can be given by unique
id, which needs no search permission.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:58:44 +00:00
erikbrockoandClaude Opus 5.5 e54623bc47 Keep outgoing voice smooth over long sessions
Drain live mic frames each tick, raise capture priority, and hold a
high-performance Wi-Fi lock on Android so power saving stays off in the
background.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:14:42 +00:00
erikbrockoandClaude Opus 5.5 59176ea017 Colour client rows in the channel tree: for everyone, while talking, while muted or away
Design settings on desktop and Android offer a few see-through presets
that suit light and dark themes alike, or a custom colour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:47:51 +00:00
erikbrockoandClaude Opus 5.5 4cdbdea9a2 Join a channel by double-tapping it in the tree
The channel sheet's Join and the double-tap share one password prompt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:32:41 +00:00
erikbrockoandClaude Opus 5.5 ec3a43a689 Float a "Me" indicator over the channel tree while our own row is off screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:26:20 +00:00
erikbrockoandClaude Opus 5.5 ac01d3eacd Keep push-to-talk held when the finger slides off the button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:19:06 +00:00
erikbrockoandClaude Opus 5.5 652027c1c1 Keep the channel tree's scroll position while the chat replaces it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:19:05 +00:00
erikbrockoandClaude Opus 5.5 f00490a663 Add Giant PTT: a full-screen talk button on Android and a resizable window on desktop
Holding it forces transmission in any input mode, past the voice-activation gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:14:43 +00:00
erikbrockoandClaude Opus 5.5 a2bfcf9f28 Move the remaining encoder settings to Network; use sliders for redundancy and buffering
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:03:00 +00:00
erikbrockoandClaude Opus 5.5 33317df2eb Rebuild Connection Info after the official dialog
Lay the window out as TeamSpeak 3's: name, times, ping and address
(with a copy button) beside the avatar, then Total / Speech / Keep Alive
/ Control tabs holding a Total / In / Out table, and a Quota tab. Android
gets the same tabs and table.

Wait for both notifyconnectioninfo reports for another client (the
server's cached copy, then the client's fresh counters) instead of
taking the first, often all zeros. Ask the server about ourselves too,
for our address and outgoing loss. Month transfer totals come from
clientgetvariables, our quota from the needed permissions, and file
transfers now count their bytes for our own transfer rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:59:44 +00:00
erikbrockoandClaude Opus 5.5 70aac6f5ce Add extra receive buffering and decode Opus FEC on loss
A new Extra buffering setting (Network page) holds more playback delay
than the jitter buffer measures it needs, so late packets still make
it in time on a bad connection. A lost frame is now rebuilt from the
FEC copy in the next packet when that one is already held, and the
Connection Info shows how many were recovered.

Held packets' arrival marks now move with the timeline when the delay
changes; libspeex leaves them, which made a multi-frame jump count
twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:38:20 +00:00
erikbrockoandClaude Opus 5.5 5ec4204d1d Move bitrate, FEC and redundancy to a Network settings page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:29:16 +00:00
erikbrockoandClaude Opus 5.5 9458ff3400 Add Connection Info on Android and count received voice
Connection Info gains a "Voice received" section on both frontends,
counting what our own playback made of a speaker's voice (everyone's,
for ourselves): packets received, frames played and missed, packets
out of order, dropped as too late, and discarded as copies. Android
gets the window itself as a page from the client sheet.

The rows and their formatting live in core, shared by both frontends;
the Swing dialog keeps its tabs on one row. A minute's bandwidth now
shows as the average rate it is labelled as, not the minute's bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:26:59 +00:00
erikbrockoandClaude Opus 5.5 c8c54bd381 Add voice redundancy and the encoder settings on Android
Redundancy sends every voice packet again, one to four times, 20 to
200 ms apart. Listeners' jitter buffers grow to wait for the copies,
native clients' included, so a lost packet costs nothing while a copy
arrives. With a native client listening over a bursty lossy uplink,
the frames lost to concealment fell from 10% to under 1%.

Android gets the desktop's encoder settings: bitrate, complexity, VBR,
FEC, music codec, and the new redundancy delay and copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:17:13 +00:00
erikbrockoandClaude Opus 5.5 6cd75eb1cd Let late voice packets teach the jitter buffer
A packet arriving after playback passed its slot was dropped before the
buffer saw it, so the buffer never learned how late packets ran and did
not grow to cover them. The official client puts every packet, however
late; such packets now reach the buffer too, without starting a new
talk burst.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:17:13 +00:00
erikbrockoandClaude Opus 5.5 853681fcaa Save server log settings without Stream.toList
Stream.toList() is API 34; on Android 13 every settings save crashed
with NoSuchMethodError once the server log settings were stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:17:13 +00:00
erikbrockoandClaude Opus 5.5 dc413f4975 Add voice recording
Tools > Start Recording / Start Multitrack Recording / Stop Recording
record what is heard on the server, our own voice included, into Ogg
Opus, and publish client_is_recording. A plain recording mixes everyone
down to mono; a multitrack one gives each speaker (by unique id) an
uncoupled mono stream of their own under channel mapping family 255,
named in the tags after their nickname when the recording started,
silent until they first speak, and continuing into name-2.ogg past 255
speakers. Tracks are spooled beside the output and muxed on stop, since
the header carries the channel count.

The status bar shows a label that stops the recording; the existing
recording hotkeys start one straight into the last-used folder.
OggOpusFile now shares the new Ogg page writer and Opus header code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 14:57:51 +00:00
erikbrockoandClaude Opus 5.5 93e0b36083 Drop the line count from the Server Log window
The label under the log now only appears while loading, on a failure or
for an empty log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:23:31 +00:00
erikbrockoandClaude Opus 5.5 8255d986ac Add the Server Log window
Tools > Server Log (Ctrl+Shift+L), offered with b_virtualserver_log_view,
reads the virtual server's log with logview, a hundred lines at a time,
with Show Older going further back. As in TS3, lines can be narrowed by
level, left out by exclude terms, coloured by keyword, and shown in UTC
or local time; the choices are kept in the settings. The find bar, with
its show-only-matches toggle, takes the place of TS3's separate search
and filter fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:19:52 +00:00
erikbrockoandClaude Opus 5.5 fb1de8ac5b Add the Complaints List and Make a Complaint
Tools > Complaints List (Ctrl+Shift+C) shows the server's complaints
grouped by target, with Remove, Reload and Ban Client, as TS3 does. The
client menu gains Make a Complaint below Poke. The complaint delete
permissions are missing from the needed-permissions subset, so they are
asked for alongside the move/kick/ban powers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:03:57 +00:00
erikbrockoandClaude Opus 5.5 ee1a83e981 Add shortcuts for Disconnect, Ban List and Options
Ctrl+D disconnects from the current server, Ctrl+Shift+B opens the ban
list (only where it may be viewed) and Alt+P the options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 00:11:15 +00:00
erikbrockoandClaude Opus 5.5 06180b4273 Add Request Talk Power and Set Phonetic Nickname to the Self menu
A request asks for a reason, as TS3 does, and turns the item into Cancel
Talk Power Request until it is granted or withdrawn. The phonetic nickname
applies to the current server. client_talk_request carries the request's
timestamp, so any non-zero value now counts as a pending request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 00:04:46 +00:00
erikbrockoandClaude Opus 5.5 7c2d4c7c42 Match TS3's menu layout: Self's away submenu and mic items, bookmarks first, more shortcuts
Self now opens with a Set Away submenu mirroring the toolbar button, then
Activate Microphone and Mute/Unmute items that follow the current state.
The bookmark actions come before the bookmarks. Shortcuts: Ctrl+Q quits,
Ctrl+B manages bookmarks, Ctrl+I opens Identities, Ctrl+Shift+O Contacts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 00:04:37 +00:00
860 changed files with 70081 additions and 58520 deletions
+5
View File
@@ -7,6 +7,7 @@ out/
# Bundled proprietary TeamSpeak clients (reference binaries, not our source) # Bundled proprietary TeamSpeak clients (reference binaries, not our source)
/TeamSpeak3-Client-linux_amd64/ /TeamSpeak3-Client-linux_amd64/
/ts6/ /ts6/
/ts6-server/
/re-android/ /re-android/
# Packages # Packages
@@ -43,3 +44,7 @@ android/.gradle/
android/.kotlin/ android/.kotlin/
android/**/.cxx/ android/**/.cxx/
android/local.properties android/local.properties
# Release signing (keystore.properties points at the key)
android/keystore.properties
*.jks
+42 -5
View File
@@ -1,3 +1,5 @@
import java.util.Properties
plugins { plugins {
alias(libs.plugins.android.application) alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose) alias(libs.plugins.kotlin.compose)
@@ -35,7 +37,7 @@ abstract class BundleSoundPacks : DefaultTask() {
} }
exec.javaexec { exec.javaexec {
classpath = encoder classpath = encoder
mainClass.set("com.ts3client.audio.desktop.EncodeSoundPacks") mainClass.set("eu.lixko.ts3j.client.audio.desktop.EncodeSoundPacks")
jvmArgs("--enable-native-access=ALL-UNNAMED") jvmArgs("--enable-native-access=ALL-UNNAMED")
args(source.path, File(out, "sound").path) args(source.path, File(out, "sound").path)
} }
@@ -66,30 +68,62 @@ androidComponents {
} }
} }
/**
* 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 { android {
namespace = "com.ts3client.android" namespace = "eu.lixko.ts3j.client.android"
compileSdk = 37 compileSdk = 37
ndkVersion = "30.0.16248370" ndkVersion = "30.0.16248370"
defaultConfig { defaultConfig {
applicationId = "com.ts3client.android" applicationId = "eu.lixko.ts3j.client"
minSdk = 33 minSdk = 33
targetSdk = 36 targetSdk = 36
versionCode = 1 versionCode = 1
versionName = "0.1.0" 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.
splits {
abi {
isEnable = gradle.startParameter.taskNames.any { it.contains("Release") }
reset()
include("arm64-v8a", "x86_64")
isUniversalApk = false
} }
} }
buildTypes { buildTypes {
release { release {
signingConfig = signingConfigs.findByName("release")
isMinifyEnabled = true isMinifyEnabled = true
isShrinkResources = true isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
} }
} }
androidResources {
// The app is English only; drops the libraries' translations.
localeFilters += "en"
}
buildFeatures { buildFeatures {
compose = true compose = true
} }
@@ -100,6 +134,9 @@ android {
} }
packaging { packaging {
// Compressed in the APK, which then is smaller to send; extracted on install.
dex.useLegacyPackaging = true
jniLibs.useLegacyPackaging = true
resources { resources {
// BouncyCastle ships Java 9+ module metadata Android has no use for. // BouncyCastle ships Java 9+ module metadata Android has no use for.
excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF" excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
+1 -1
View File
@@ -2,7 +2,7 @@
-dontwarn javax.naming.** -dontwarn javax.naming.**
# Reached from native code by name. # Reached from native code by name.
-keepclasseswithmembernames class com.ts3client.android.audio.** { -keepclasseswithmembernames class eu.lixko.ts3j.client.android.audio.** {
native <methods>; native <methods>;
} }
+9
View File
@@ -21,11 +21,13 @@
<application <application
android:name=".Ts3Application" android:name=".Ts3Application"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:theme="@android:style/Theme.Material.NoActionBar"> android:theme="@android:style/Theme.Material.NoActionBar">
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:label="@string/launcher_name"
android:exported="true" android:exported="true"
android:launchMode="singleTop" android:launchMode="singleTop"
android:windowSoftInputMode="adjustResize"> android:windowSoftInputMode="adjustResize">
@@ -33,6 +35,13 @@
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </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> </activity>
<service <service
@@ -1,30 +0,0 @@
package com.ts3client.android
import android.content.Context
import com.ts3client.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"
}
}
@@ -1,88 +0,0 @@
package com.ts3client.android
import androidx.compose.runtime.Immutable
import com.ts3client.text.HtmlText
import com.ts3client.text.TextQuery
/** Which conversation a chat line belongs to. */
sealed interface ChatKey {
data object Server : ChatKey
data object Channel : ChatKey
data class Private(val clientId: Int) : ChatKey
}
/** One entry of a chat, as HTML in the form [com.ts3client.text.ChatHtml] writes. */
@Immutable
data class ChatLine(val id: Long, val html: String) {
/** The text to find in. */
val plain: String by lazy { HtmlText.plain(html) }
}
@Immutable
data class Conversation(
val key: ChatKey,
val title: String,
/** The peer's unique id in a private chat, once known. */
val uniqueId: String = "",
val lines: List<ChatLine> = emptyList(),
val unread: Boolean = false,
)
/** Every conversation of the session: the server's, the channel's, then the private ones. */
@Immutable
data class Chats(
val server: Conversation = Conversation(ChatKey.Server, "Server"),
val channel: Conversation = Conversation(ChatKey.Channel, "Channel"),
val private: List<Conversation> = emptyList(),
) {
val all: List<Conversation> get() = listOf(server, channel) + private
val anyUnread: Boolean get() = all.any { it.unread }
operator fun get(key: ChatKey): Conversation? = when (key) {
ChatKey.Server -> server
ChatKey.Channel -> channel
is ChatKey.Private -> private.firstOrNull { it.key == key }
}
/** Applies [change] to a conversation, opening a private one titled [title] if needed. */
fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) {
ChatKey.Server -> copy(server = change(server))
ChatKey.Channel -> copy(channel = change(channel))
is ChatKey.Private -> {
val existing = private.indexOfFirst { it.key == key }
if (existing < 0) {
copy(private = private + change(Conversation(key, title)))
} else {
copy(private = private.toMutableList().also { it[existing] = change(it[existing]) })
}
}
}
fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key })
companion object {
/** As many lines as a log history loads; older ones leave the conversation. */
const val MAX_LINES = 1000
}
}
fun Conversation.append(line: ChatLine, read: Boolean): Conversation =
copy(lines = (lines + line).takeLast(Chats.MAX_LINES), unread = unread || !read)
/** The [nth] match of the find bar's query in the line [line]. */
data class ChatMatch(val line: Long, val nth: Int)
/** Every match of [query] in [lines], oldest first; past [limit], only the newest. */
fun findIn(lines: List<ChatLine>, query: TextQuery, limit: Int): List<ChatMatch> {
if (query.isEmpty) return emptyList()
val out = ArrayList<ChatMatch>()
for (line in lines) {
val m = query.matcher(line.plain) ?: return emptyList()
var n = 0
while (m.find()) {
if (m.end() > m.start()) out += ChatMatch(line.id, n++)
}
}
return if (out.size > limit) out.subList(out.size - limit, out.size) else out
}
@@ -1,231 +0,0 @@
package com.ts3client.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 com.ts3client.config.Settings
import com.ts3client.net.ClientStatus
import com.ts3client.session.SelfState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/**
* Keeps the process in the foreground while connected, so the connection and its audio
* survive the app leaving the screen, and offers the essentials in its notification.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ConnectionService : LifecycleService() {
private lateinit var sessions: SessionController
private lateinit var wifiLock: WifiManager.WifiLock
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var overlay: PttOverlay
private var foregroundTypes = 0
private var shown: ServerController? = null
override fun onCreate() {
super.onCreate()
sessions = (application as Ts3Application).sessions
getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
)
// Voice goes out every 20 ms; Wi-Fi power saving and a sleeping CPU would stretch that.
wifiLock = getSystemService(WifiManager::class.java)
.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "ts3j:voice")
.apply { setReferenceCounted(false); acquire() }
wakeLock = getSystemService(PowerManager::class.java)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ts3j:connection")
.apply { setReferenceCounted(false); acquire() }
show(sessions.current.value?.state?.value ?: SessionState(), capturing = false)
lifecycleScope.launch {
// The server count shows in the notification too.
combine(shownServer(), sessions.micOwner, sessions.servers) { shown, owner, _ -> shown to (owner != null) }
.conflate()
.collect { (shown, capturing) ->
if (shown != null) {
this@ConnectionService.shown = shown.first
show(shown.second, capturing)
// Talking flips the icon often, and Android drops updates that come too fast.
delay(MIN_UPDATE_MS)
}
}
}
lifecycleScope.launch {
sessions.current.flatMapLatest { it?.state ?: flowOf(null) }.collectLatest { state ->
if (state == null) {
// A reconnect leaves the server briefly; only stop once it stays gone.
delay(STOP_DELAY_MS)
stopSelf()
}
}
}
lifecycleScope.launch {
sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
}
overlay = PttOverlay(this, sessions.icons, sessions::setPushToTalk)
lifecycleScope.launch {
val owner = sessions.micOwner.flatMapLatest { server ->
server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null)
}
combine(owner, sessions.onScreen, sessions.pttOverlay) { held, onScreen, enabled ->
val (state, tree) = held ?: return@combine null
val wanted = enabled && !onScreen && state.connected && state.micActive &&
state.inputMode == Settings.InputMode.PUSH_TO_TALK
val status = tree.client(state.selfClientId)?.status
when {
!wanted -> null
state.micMuted -> PttOverlay.Look.MUTED
status == ClientStatus.TALKING || status == ClientStatus.COMMANDER_TALKING -> PttOverlay.Look.TALKING
else -> PttOverlay.Look.IDLE
}
}.distinctUntilChanged().collect { look ->
if (look == null) overlay.hide() else overlay.show(look)
}
}
}
/**
* The server the notification speaks for, as the desktop tray icon does: the one
* holding the microphone, or the visible one when nobody is capturing.
*/
private fun shownServer(): Flow<Pair<ServerController, SessionState>?> =
combine(sessions.current, sessions.micOwner) { current, owner -> current to owner }
.flatMapLatest { (current, owner) ->
combine(current?.state ?: flowOf(null), owner?.state ?: flowOf(null)) { currentState, ownerState ->
when {
owner != null && ownerState?.connected == true -> owner to ownerState
current != null && currentState != null -> current to currentState
else -> null
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val server = shown ?: sessions.current.value ?: return START_NOT_STICKY
val state = server.state.value
when (intent?.action) {
ACTION_TOGGLE_MUTE -> server.setMicMuted(!state.micMuted)
ACTION_TOGGLE_DEAFEN -> server.setDeafened(!state.deafened)
ACTION_DISCONNECT -> server.disconnect()
}
return START_NOT_STICKY
}
/**
* The user swiped the app away: they are done with it, connection included. Leaving
* properly spares the server a ghost that would hold our identity until it times out.
*/
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
lifecycleScope.launch(Dispatchers.IO) {
sessions.leave()
stopSelf()
}
}
override fun onDestroy() {
overlay.hide()
wifiLock.release()
wakeLock.release()
super.onDestroy()
}
/** Posts the notification, re-declaring what the service uses when that changed. */
private fun show(state: SessionState, capturing: Boolean) {
val types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or
if (capturing && hasMicPermission()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0
val notification = notification(state)
if (types != foregroundTypes) {
startForeground(NOTIFICATION_ID, notification, types)
foregroundTypes = types
} else {
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification)
}
}
private fun hasMicPermission() =
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
private fun notification(state: SessionState): Notification {
val open = PendingIntent.getActivity(
this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE
)
val others = sessions.servers.value.size - 1
return Notification.Builder(this, CHANNEL)
.setSmallIcon(statusIcon(state.self))
.setLargeIcon(largeIcon(state.self))
.setContentTitle(if (others > 0) "${state.title} +$others" else state.title)
.setContentText(state.status)
.setContentIntent(open)
.setOngoing(true)
.addAction(action(ACTION_TOGGLE_MUTE, if (state.micMuted) "Unmute" else "Mute"))
.addAction(action(ACTION_TOGGLE_DEAFEN, if (state.deafened) "Undeafen" else "Deafen"))
.addAction(action(ACTION_DISCONNECT, "Disconnect"))
.build()
}
/**
* The status bar shows only the shape of an icon, which pack art loses, so it is
* drawn from the Material pack whatever pack is chosen.
*/
private fun statusIcon(self: SelfState): Icon {
val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt()
val bitmap = sessions.icons.renderMaterial(key, size, Color.WHITE)
?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
return Icon.createWithBitmap(bitmap)
}
/** The expanded notification has room for the chosen pack's own art, as the tree draws it. */
private fun largeIcon(self: SelfState): Icon? {
val key = self.iconKey() ?: return null
val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt()
return sessions.icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500))
?.let(Icon::createWithBitmap)
}
private fun action(action: String, label: String): Notification.Action {
val intent = PendingIntent.getService(
this, action.hashCode(), Intent(this, ConnectionService::class.java).setAction(action),
PendingIntent.FLAG_IMMUTABLE
)
return Notification.Action.Builder(null, label, intent).build()
}
private companion object {
const val CHANNEL = "connection"
const val NOTIFICATION_ID = 1
const val STOP_DELAY_MS = 3_000L
const val MIN_UPDATE_MS = 250L
const val STATUS_ICON_DP = 24
const val LARGE_ICON_DP = 48
const val ACTION_TOGGLE_MUTE = "com.ts3client.android.TOGGLE_MUTE"
const val ACTION_TOGGLE_DEAFEN = "com.ts3client.android.TOGGLE_DEAFEN"
const val ACTION_DISCONNECT = "com.ts3client.android.DISCONNECT"
}
}
@@ -1,143 +0,0 @@
package com.ts3client.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 com.ts3client.config.AppDirs
import com.ts3client.config.Settings
import com.ts3client.gfx.IconPack
import com.ts3client.gfx.IconPacks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File
/**
* The icon packs the app draws with: the Material pack it ships, and TeamSpeak packs
* imported into its `gfx` folder, which are the very zips a TeamSpeak 3 install keeps in
* its own. Whatever the chosen pack lacks comes from the Material one.
*/
class IconTheme(private val context: Context, private val settings: Settings) {
private val folder = File(AppDirs.profile(), "gfx")
private val material: IconPack = IconPacks.material()
@Volatile
private var lookupOrder = listOf(material)
private val cache = LruCache<String, Bitmap>(256)
private val _packs = MutableStateFlow(emptyList<IconPack>())
val packs: StateFlow<List<IconPack>> = _packs
private val _active = MutableStateFlow(material)
val active: StateFlow<IconPack> = _active
init {
reload()
}
fun select(pack: IconPack) {
settings.iconPack = pack.id()
settings.save()
reload()
}
/**
* Copies a pack's zip into the app and switches to it.
*
* @return the pack, or `null` when the file is no icon pack
*/
fun import(uri: Uri): IconPack? {
folder.mkdirs()
val target = File(folder, displayName(uri).substringAfterLast('/').let {
if (it.endsWith(".zip", ignoreCase = true)) it else "$it.zip"
})
val staged = File(folder, target.name + ".part")
context.contentResolver.openInputStream(uri)?.use { input ->
staged.outputStream().use { input.copyTo(it) }
} ?: return null
target.delete()
staged.renameTo(target)
val pack = IconPack.load(target)
if (pack == null) {
target.delete()
return null
}
select(pack)
return _active.value
}
/**
* Draws the first of [keys] the packs have.
*
* @param rgb the colour for art that paints in the text colour
*/
fun render(keys: List<String>, size: Int, rgb: Int): Bitmap? = render(lookupOrder, keys, size, rgb)
/** Draws from the Material pack whatever pack is chosen, for chrome that must stay legible on its own colours. */
fun renderMaterial(key: String, size: Int, rgb: Int): Bitmap? = render(listOf(material), listOf(key), size, rgb)
private fun render(order: List<IconPack>, keys: List<String>, size: Int, rgb: Int): Bitmap? {
val cacheKey = "${order.first().id()}/${keys.joinToString(",")}@$size#$rgb"
cache.get(cacheKey)?.let { return it }
for (key in keys) {
for (pack in order) {
val data = pack.icon(key, size) ?: continue
val bitmap = (if (pack.isVector(key, size)) rasterize(IconPack.withCurrentColor(data, rgb), size)
else decode(data, size)) ?: continue
cache.put(cacheKey, bitmap)
return bitmap
}
}
return null
}
private fun reload() {
val packs = IconPacks.findAll(folder, null)
val active = IconPacks.select(packs, settings.iconPack) ?: material
lookupOrder = IconPacks.lookupOrder(active, packs, material)
cache.evictAll()
_packs.value = packs
_active.value = active
}
private fun displayName(uri: Uri): String =
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
if (it.moveToFirst()) it.getString(0) else null
} ?: uri.lastPathSegment ?: "iconpack.zip"
private fun rasterize(svg: ByteArray, size: Int): Bitmap? = try {
val document = SVG.getFromString(String(svg, Charsets.UTF_8))
if (document.documentViewBox == null && document.documentWidth > 0 && document.documentHeight > 0) {
document.setDocumentViewBox(0f, 0f, document.documentWidth, document.documentHeight)
}
// Otherwise the art keeps the size it was authored at inside the viewport.
document.setDocumentWidth("100%")
document.setDocumentHeight("100%")
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
document.renderToCanvas(Canvas(it), RenderOptions().viewPort(0f, 0f, size.toFloat(), size.toFloat()))
}
} catch (e: Exception) {
null
}
/** Scales a bitmap icon into the square, keeping the aspect ratio of art that is not. */
private fun decode(data: ByteArray, size: Int): Bitmap? {
val source = BitmapFactory.decodeByteArray(data, 0, data.size) ?: return null
if (source.width == size && source.height == size) return source
val factor = minOf(size.toFloat() / source.width, size.toFloat() / source.height)
val w = source.width * factor
val h = source.height * factor
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
val left = (size - w) / 2
val top = (size - h) / 2
Canvas(it).drawBitmap(source, null, RectF(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG))
}
}
}
@@ -1,170 +0,0 @@
package com.ts3client.android
import android.content.Context
import android.net.Uri
import com.ts3client.config.Bookmarks
import com.ts3client.config.IdentityEntry
import com.ts3client.config.IdentityStore
import com.ts3client.config.Settings
import com.ts3client.teamspeak.TeamSpeakImporter
import com.ts3client.teamspeak.TeamSpeakSettingsDb
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
/** What the identity manager shows of one identity. */
data class IdentityInfo(
val id: String,
val name: String,
val uniqueId: String,
val securityLevel: Int,
val isDefault: Boolean,
val nickname: String,
val phoneticNickname: String,
)
/** A search for a better key offset under way. */
data class Improvement(val id: String, val target: Int, val reached: Int)
/**
* The identities, as TeamSpeak's Tools → Identities manages them: create, import, export,
* rename, remove, pick the default and raise the security level. Raising the level runs
* on until it is reached or stopped, whichever page is on screen.
*/
class IdentityManager(
private val context: Context,
private val store: IdentityStore,
private val settings: Settings,
private val bookmarks: Bookmarks,
private val onBookmarksChanged: () -> Unit,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val _all = MutableStateFlow(snapshot())
val all: StateFlow<List<IdentityInfo>> = _all
private val _improving = MutableStateFlow<Improvement?>(null)
val improving: StateFlow<Improvement?> = _improving
private var improvement: Job? = null
/** Picks up identities added elsewhere, such as by an import or a first connect. */
fun refresh() {
_all.value = snapshot()
}
private fun snapshot(): List<IdentityInfo> = store.all().map {
IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId,
it.nickname, it.phoneticNickname)
}
/** Generates an identity at TeamSpeak's default security level; the first one becomes the default. */
suspend fun generate(name: String): IdentityInfo = added {
store.generate(name, IdentityStore.DEFAULT_SECURITY_LEVEL)
}
/** Imports a TeamSpeak identity file, under the name it carries. */
suspend fun importFile(uri: Uri): IdentityInfo = added {
context.contentResolver.openInputStream(uri)?.use { store.importStream(it, null) }
?: throw IOException("Cannot open the file")
}
/** Imports the identities of a TeamSpeak 3 `settings.db`. */
suspend fun importFromTeamSpeak(uri: Uri): TeamSpeakImporter.Result = withContext(Dispatchers.IO) {
withLocalCopy(context, uri) { TeamSpeakImporter(store, bookmarks, settings).importIdentities(it) }
}.also {
adoptDefault(null)
refresh()
}
private suspend fun added(create: () -> IdentityEntry): IdentityInfo {
val entry = withContext(Dispatchers.IO) { create() }
adoptDefault(entry)
refresh()
return _all.value.first { it.id == entry.id }
}
/** Makes [entry], or else the first identity, the default while there is none. */
private fun adoptDefault(entry: IdentityEntry?) {
if (store.byId(settings.defaultIdentityId) != null) return
val fallback = entry ?: store.all().firstOrNull() ?: return
settings.defaultIdentityId = fallback.id
settings.save()
}
/** Writes the identity out in TeamSpeak's format, for the official client or another device. */
suspend fun export(id: String, uri: Uri) = withContext(Dispatchers.IO) {
val entry = store.byId(id) ?: return@withContext
val out = context.contentResolver.openOutputStream(uri, "wt") ?: throw IOException("Cannot write the file")
store.exportTo(entry, out)
}
fun rename(id: String, name: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
store.rename(entry, name)
refresh()
}
}
fun setNicknames(id: String, nickname: String, phoneticNickname: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
store.setNicknames(entry, nickname, phoneticNickname)
refresh()
}
}
/** The nickname of the identity a connect with [id] uses; empty when it has none. */
fun nicknameOf(id: String): String =
(store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty()
fun setDefault(id: String) {
settings.defaultIdentityId = id
settings.save()
refresh()
}
/** Deletes the identity; bookmarks that connected with it fall back to the default. */
fun remove(id: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
// Else the search would write the file back once it ends.
if (_improving.value?.id == id) improvement?.cancelAndJoin()
store.remove(entry, settings, bookmarks)
onBookmarksChanged()
refresh()
}
}
/** Searches for a key offset reaching [target], keeping the best found when stopped. */
fun improve(id: String, target: Int) {
if (improvement?.isActive == true) return
val entry = store.byId(id) ?: return
_improving.value = Improvement(id, target, entry.securityLevel)
improvement = scope.launch {
try {
store.improveSecurity(entry, target) { reached, _ ->
_improving.value = Improvement(id, target, reached)
isActive
}
} catch (e: IOException) {
// The level reached stays in memory for this run.
} finally {
_improving.value = null
refresh()
}
}
}
fun stopImproving() {
improvement?.cancel()
}
}
@@ -1,95 +0,0 @@
package com.ts3client.android
import com.ts3client.audio.AudioBackend
import com.ts3client.audio.InputLevel
import com.ts3client.audio.VoiceInput
import com.ts3client.config.Settings
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The microphone's level on [InputLevel]'s scale, and whether that would be sent. */
data class MicLevel(
val db: Double = InputLevel.SILENCE_DB,
val transmitting: Boolean = false,
/** Whether a microphone is being listened to at all. */
val live: Boolean = false,
)
/**
* The level meter behind the voice-activation settings. While connected it listens to the
* connection's own microphone, so it shows exactly what gets sent; otherwise it runs a test
* microphone of its own for as long as someone watches.
*/
class LevelMonitor(private val settings: Settings, private val audio: AudioBackend) {
private val _level = MutableStateFlow(MicLevel())
val level: StateFlow<MicLevel> = _level
/** The connection's microphone, when that is the one listened to. */
private var borrowed: VoiceInput? = null
private var test: VoiceInput? = null
/**
* Starts or stops listening.
*
* @param source the connection's microphone while it captures, else null
* @param busy whether a connection is under way, which will bring its own microphone
*/
@Synchronized
fun update(watching: Boolean, source: VoiceInput?, busy: Boolean, mayCapture: Boolean) {
when {
!watching -> release()
source != null -> if (borrowed !== source) {
release()
source.setLevelListener(::onLevel)
borrowed = source
}
busy || !mayCapture -> release()
test == null -> startTest()
}
}
/** The own microphone's transmit state, which the connection reports. */
fun talking(transmitting: Boolean) {
if (borrowed != null) _level.value = _level.value.copy(transmitting = transmitting)
}
/** Puts changed voice settings into effect on the test microphone. */
@Synchronized
fun apply() {
test?.let {
it.apply(settings)
it.setMode(testMode())
}
}
private fun startTest() {
release()
val input = audio.createInput(settings)
input.setMode(testMode())
input.setLevelListener(::onLevel)
input.setTalkListener { _level.value = _level.value.copy(transmitting = it) }
try {
input.start()
} catch (e: RuntimeException) {
return // no microphone to be had; the meter stays idle
}
test = input
}
private fun release() {
borrowed?.setLevelListener(null)
borrowed = null
test?.stop()
test = null
_level.value = MicLevel()
}
private fun onLevel(db: Double) {
_level.value = _level.value.copy(db = db, live = true)
}
/** Push-to-talk would never open without the button, and the test is there to tune the gate. */
private fun testMode() =
if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode
}
@@ -1,21 +0,0 @@
package com.ts3client.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()
}
}
@@ -1,45 +0,0 @@
package com.ts3client.android
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import com.ts3client.android.ui.App
import com.ts3client.android.ui.Ts3Theme
class MainActivity : ComponentActivity() {
private val sessions get() = (application as Ts3Application).sessions
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (savedInstanceState == null) openRequestedChat(intent)
setContent {
Ts3Theme { App(sessions) }
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
openRequestedChat(intent)
}
override fun onStart() {
super.onStart()
sessions.foreground = true
}
override fun onStop() {
sessions.foreground = false
super.onStop()
}
/** A private message notification opens its conversation. */
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)
}
}
@@ -1,141 +0,0 @@
package com.ts3client.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 = "com.ts3client.android.SERVER"
const val EXTRA_CHAT = "com.ts3client.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
}
}
@@ -1,220 +0,0 @@
package com.ts3client.android
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import com.ts3client.session.ServerSession
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.CopyOnWriteArrayList
/**
* Keeps the connections on the network Android routes over.
*
* A TS3 server knows its clients by address, so once the phone moves from Wi-Fi to mobile
* data (or back) an old connection is dead weight: it can only time out. This notices the
* move, says goodbye over the old network while that still works, and connects again over
* the new one, back into the channel we were in. A server that still holds our old
* connection may refuse the new one for a while as a clone, so a failed attempt is retried.
*
* The process's sockets are bound to the network a connection was made over. Otherwise the
* old connection would silently follow the new default network, and its goodbye would come
* from an address the server does not know. A socket keeps the network it was made on, so
* each connection remembers its own.
*/
class NetworkFollower(context: Context) {
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val follows = CopyOnWriteArrayList<Follow>()
/** The system's default network; null while there is none. */
@Volatile
private var network: Network? = null
init {
connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(available: Network) {
network = available
follows.forEach(Follow::reconsider)
}
override fun onLost(lost: Network) {
if (network == lost) network = null
follows.forEach(Follow::reconsider)
}
})
}
/** Follows [session] until [Follow.forget]. */
fun follow(session: ServerSession, onChange: () -> Unit, system: (String) -> Unit): Follow =
Follow(session, onChange, system).also(follows::add)
/** Binds new sockets to [to], or lets them go by the default network once no connection wants one. */
private fun bind(to: Network?) {
connectivity.bindProcessToNetwork(to ?: follows.firstNotNullOfOrNull { f -> f.bound.takeIf { f.wanted } })
}
inner class Follow internal constructor(
private val session: ServerSession,
private val onChange: () -> Unit,
private val system: (String) -> Unit,
) {
/** The network the connection was made over. */
@Volatile
internal var bound: Network? = null
/** The user wants to be on the server: from their connect until they, or the server, end it. */
@Volatile
internal var wanted = false
private var settle: Job? = null
@Volatile
private var recovery: Job? = null
@Volatile
private var attempt: CompletableDeferred<Boolean>? = null
/** What to show in place of the session's status while getting back on the server. */
@Volatile
var status: String? = null
private set
val isRecovering: Boolean get() = recovery?.isActive == true
/** Before a connect the user asked for, which goes over the network there is now. */
fun connecting() {
recovery?.cancel()
wanted = true
bindHere(connectivity.activeNetwork)
}
/** The user leaves the server. */
fun leaving() {
wanted = false
recovery?.cancel()
unbind()
}
/** The session is thrown away. */
fun forget() {
leaving()
follows.remove(this)
}
fun onConnected() {
attempt?.complete(true)
}
fun onDisconnected() {
val pending = attempt
when {
pending != null -> pending.complete(false)
isRecovering -> {}
// A socket on a network that went away fails at once, before we hear of the change.
wanted && networkGone() -> synchronized(this) {
if (!isRecovering) recovery = recover()
}
// The server let us go (a kick, a shutdown, a failed first connect): leave it at that.
else -> {
wanted = false
unbind()
}
}
}
/** Waits for the network to settle: a handover often shows several changes in a row. */
internal fun reconsider() {
synchronized(this) {
settle?.cancel()
settle = scope.launch {
delay(SETTLE_MS)
synchronized(this@Follow) {
if (wanted && bound != network && !isRecovering) recovery = recover()
}
}
}
}
private fun recover() = scope.launch {
try {
val back = withTimeoutOrNull(GIVE_UP_MS) {
system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…")
if (session.isBusy) session.connection().disconnectBlocking("Network changed")
var retry = RETRY_MS
while (true) {
val current = awaitNetwork()
bindHere(current)
show("Reconnecting…")
val done = CompletableDeferred<Boolean>()
attempt = done
session.reconnect()
val connected = done.await()
attempt = null
if (connected) break
if (session.connection().connectErrorId == ERROR_BANNED) break
show("Reconnecting, retrying soon…")
delay(retry)
retry = (retry * 2).coerceAtMost(MAX_RETRY_MS)
}
}
if (session.connection().connectErrorId == ERROR_BANNED) {
wanted = false
unbind()
} else if (back == null) {
system("Could not get back on the server.")
wanted = false
unbind()
}
} finally {
attempt = null
status = null
onChange()
// The network may have moved again while we were busy.
reconsider()
}
}
private fun networkGone(): Boolean {
val on = bound ?: return false
return connectivity.getNetworkCapabilities(on) == null || connectivity.activeNetwork != on
}
private suspend fun awaitNetwork(): Network {
while (true) {
connectivity.activeNetwork?.let { return it }
show("Waiting for network…")
delay(POLL_MS)
}
}
private fun show(text: String) {
status = text
onChange()
}
private fun bindHere(to: Network?) {
bound = to
bind(to)
}
private fun unbind() {
bound = null
bind(null)
}
}
private companion object {
const val SETTLE_MS = 1_500L
/** The server's refusal for a banned client; asking again will not help. */
const val ERROR_BANNED = 3329
const val RETRY_MS = 5_000L
const val MAX_RETRY_MS = 30_000L
const val POLL_MS = 500L
const val GIVE_UP_MS = 5 * 60_000L
}
}
@@ -1,42 +0,0 @@
package com.ts3client.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
}
@@ -1,176 +0,0 @@
package com.ts3client.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)
}
}
@@ -1,17 +0,0 @@
package com.ts3client.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)
}
}
@@ -1,39 +0,0 @@
package com.ts3client.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
}
}
}
@@ -1,469 +0,0 @@
package com.ts3client.android
import com.ts3client.contacts.ContactType
import com.ts3client.net.ChannelNode
import com.ts3client.net.Details
import com.ts3client.net.GroupChoice
import com.ts3client.net.ban.BanEntry
import com.ts3client.net.ban.BanRule
import com.ts3client.net.ConnectionListener.ChatScope
import com.ts3client.session.ServerSession
import com.ts3client.text.BBCode
import com.ts3client.text.ChatHtml
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* One server the app is on: its [ServerSession], and the snapshots the UI shows of it. Session
* callbacks arrive on connection threads and are turned into immutable snapshots.
*/
class ServerController internal constructor(
/** Unique among the servers of this process run. */
val id: Int,
private val app: SessionController,
) {
internal val session = ServerSession(
app.settings, app.identityStore, app.audio, app.sounds, app.contactStore, Listener()
)
internal val conn get() = session.connection()
private val network = app.network.follow(session, ::refresh, ::system)
/** Whether this server holds the microphone; set by [SessionController] as it moves. */
@Volatile
internal var micOwner = false
/** Set once connecting began, so a session that never started is not taken for one that ended. */
@Volatile
private var started = false
/** Set when the user left, so the end needs no telling. */
@Volatile
internal var left = false
private val _state = MutableStateFlow(SessionState())
val state: StateFlow<SessionState> = _state
private val _tree = MutableStateFlow(ServerTree())
val tree: StateFlow<ServerTree> = _tree
private val _chats = MutableStateFlow(Chats())
val chats: StateFlow<Chats> = _chats
/** Channels the user folded away in the tree. */
private val _collapsed = MutableStateFlow(emptySet<Int>())
val collapsed: StateFlow<Set<Int>> = _collapsed
/** The conversation on screen, whose new lines are read as they come. */
@Volatile
var viewing: ChatKey? = null
set(value) {
field = value
if (value != null) markRead(value)
if (value is ChatKey.Private) app.notifier.clear(id, value.clientId)
}
/** Counts the answers to info requests, for the details on screen to be read again. */
private val _infoUpdates = MutableStateFlow(0)
val infoUpdates: StateFlow<Int> = _infoUpdates
val images = ServerImages(conn)
/** A private chat a notification asked to show, until the UI took it up. */
private val _chatRequest = MutableStateFlow<ChatKey.Private?>(null)
val chatRequest: StateFlow<ChatKey.Private?> = _chatRequest
private val lineIds = AtomicLong()
/** Tree snapshots are taken one at a time, at most once per [TREE_FRAME_MS]. */
private val treeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default.limitedParallelism(1))
private val treePending = AtomicBoolean()
private val structureChanged = AtomicBoolean(true)
private var roots: List<ChannelNode> = emptyList()
val isConnected: Boolean get() = session.isConnected
internal val isBusy: Boolean get() = session.isBusy || network.isRecovering
internal val microphone get() = if (session.isConnected) conn.microphone else null
internal val playback get() = if (session.isConnected) conn.playback else null
/** Not on the server and not trying to get back on it: done with. */
internal val ended: Boolean get() = started && !isBusy
// ---- connection ----
internal fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
channel: String, channelPassword: String) {
network.connecting()
started = true
session.connect(host, port, nickname, password, identityId, channel, channelPassword)
refresh()
}
fun disconnect() {
left = true
network.leaving()
session.disconnect()
}
/** Before the app goes away with the connection, which [SessionController.leave] then ends. */
internal fun leaving() {
left = true
network.leaving()
}
internal fun dispose() {
network.forget()
treeScope.cancel()
session.dispose()
}
// ---- the local client ----
fun setMicMuted(muted: Boolean) = session.setMicMuted(muted)
fun setDeafened(deafened: Boolean) = session.setDeafened(deafened)
fun setAway(away: Boolean) = session.setAway(away, null)
// ---- channels and clients ----
fun joinChannel(channelId: Int, password: String? = null) {
if (session.isConnected) conn.joinChannel(channelId, password)
}
fun setSubscribed(channelId: Int, subscribed: Boolean) {
if (session.isConnected) conn.setChannelsSubscribed(listOf(channelId), subscribed)
}
fun toggleCollapsed(channelId: Int) =
_collapsed.update { if (channelId in it) it - channelId else it + channelId }
fun expand(channelIds: Collection<Int>) = _collapsed.update { it - channelIds.toSet() }
val canMoveClients: Boolean get() = session.canMoveClients()
fun moveClient(clientId: Int, channelId: Int) {
if (session.isConnected) conn.moveClient(clientId, channelId, null)
}
fun poke(clientId: Int, message: String) {
if (session.isConnected) conn.poke(clientId, message)
}
/** The client's playback volume change in dB; 0 when unchanged. */
fun clientVolume(clientId: Int): Double =
conn.model.getClient(clientId)?.let { conn.getClientVolumeModifier(it) } ?: 0.0
fun setClientVolume(clientId: Int, decibels: Double) {
conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) }
}
// ---- moderation ----
val canKickFromChannel: Boolean get() = session.canKickFromChannel()
val canKickFromServer: Boolean get() = session.canKickFromServer()
val canBanClients: Boolean get() = session.canBanClients()
val canViewBanList: Boolean get() = session.canViewBanList()
val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create")
/** The longest ban we may hand out in seconds; 0 or -1 for no limit. */
val maxBanSeconds: Long get() = conn.model.maxBanSeconds()
fun kickFromChannel(clientId: Int, reason: String) {
if (session.isConnected) conn.kickFromChannel(clientId, reason)
}
fun kickFromServer(clientId: Int, reason: String) {
if (session.isConnected) conn.kickFromServer(clientId, reason)
}
/** Bans a client for [seconds], or for good with 0. */
fun ban(clientId: Int, seconds: Long, reason: String) {
if (session.isConnected) conn.banClient(clientId, seconds, reason)
}
fun serverGroupChoices(clientId: Int): List<GroupChoice> =
conn.model.getClient(clientId)?.let(conn.model::serverGroupChoices).orEmpty()
fun channelGroupChoices(clientId: Int): List<GroupChoice> =
conn.model.getClient(clientId)?.let(conn.model::channelGroupChoices).orEmpty()
fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) {
val client = conn.model.getClient(clientId) ?: return
if (session.isConnected) conn.setClientServerGroup(client.databaseId, groupId, assign)
}
/** Gives a client [groupId] in the channel they are in. */
fun setChannelGroup(clientId: Int, groupId: Int) {
val client = conn.model.getClient(clientId) ?: return
if (session.isConnected) conn.setClientChannelGroup(client.databaseId, client.channelId, groupId)
}
// ---- ban list ----
/** The server's bans, or why they could not be read. */
suspend fun banList(): Result<List<BanEntry>> = suspendCoroutine { done ->
conn.requestBanList { bans, error ->
done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */
suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } }
suspend fun replaceBan(banId: Int, rule: BanRule): String? =
suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } }
suspend fun deleteBans(banIds: Collection<Int>): String? =
suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } }
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId)
fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId)
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId)
/** Uploads [data] as our avatar; null once it is set, else why not. */
suspend fun setAvatar(data: ByteArray): String? {
if (!session.isConnected) return "Not connected"
val file = withContext(Dispatchers.IO) {
File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) }
}
return try {
suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } }
} finally {
file.delete()
}
}
// ---- details ----
fun serverDetails(): Details? =
if (session.isConnected) Details.server(conn.model, "${conn.serverHost}:${conn.serverPort}") else null
fun channelDetails(channelId: Int): Details? = conn.model.getChannel(channelId)?.let(Details::channel)
fun clientDetails(clientId: Int): Details? = conn.model.getClient(clientId)?.let {
Details.client(it, conn.model, app.contactStore.find(it.uniqueId))
}
/** Asks the server for what the channel's details lack; they change once it answers. */
fun requestChannelDetails(channelId: Int) {
val channel = conn.model.getChannel(channelId) ?: return
if (session.isConnected && !channel.descriptionLoaded) conn.requestChannelInfo(channelId)
}
fun requestClientDetails(clientId: Int) {
if (session.isConnected) conn.requestClientInfo(clientId)
}
/** Files a client on the server as a contact; a new entry takes the type's defaults. */
fun addContact(clientId: Int, type: ContactType) {
val client = conn.model.getClient(clientId) ?: return
app.contactStore.add(client.uniqueId, client.nickname, type, app.settings.contactDefaults)
}
internal fun contactsChanged() {
treeScope.launch { conn.applyContacts() }
scheduleTree(structure = false)
}
// ---- chat ----
/** Opens the private chat with a client, loading what was said before. */
fun openPrivateChat(clientId: Int): ChatKey.Private {
val key = ChatKey.Private(clientId)
val client = conn.model.getClient(clientId)
if (client != null) {
_chats.update { chats ->
chats.update(key, conn.displayName(client)) { it.copy(uniqueId = client.uniqueId) }
}
conn.loadPrivateChatHistory(clientId, client.uniqueId)
}
return key
}
fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) }
fun send(key: ChatKey, text: String) {
when (key) {
ChatKey.Server -> session.sendChat(ChatScope.SERVER, 0, text)
ChatKey.Channel -> session.sendChat(ChatScope.CHANNEL, 0, text)
is ChatKey.Private -> session.sendChat(ChatScope.PRIVATE, key.clientId, text)
}
}
fun markRead(key: ChatKey) {
if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } }
}
internal fun requestChat(clientId: Int) {
_chatRequest.value = ChatKey.Private(clientId)
}
fun chatRequestHandled() {
_chatRequest.value = null
}
/** Answers a private message from its notification. */
internal fun reply(clientId: Int, text: String) {
if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId)
}
private fun append(key: ChatKey, title: String, html: String) {
if (html.isEmpty()) return
val line = ChatLine(lineIds.incrementAndGet(), html)
_chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } }
}
private fun setHistory(key: ChatKey, title: String, entries: List<String>) {
val lines = entries.map(ChatHtml::logEntry).filter { it.isNotEmpty() }
.map { ChatLine(lineIds.incrementAndGet(), it) }
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
}
private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text))
// ---- snapshots ----
private fun snapshotState(): SessionState {
val self = conn.model.getClient(conn.selfClientId)
return SessionState(
title = session.title(),
status = network.status ?: session.status(),
connected = session.isConnected,
busy = isBusy,
micActive = micOwner && app.hasMicPermission(),
micPermission = app.hasMicPermission(),
micMuted = session.isMicMuted,
deafened = session.isDeafened,
away = session.isAway,
selfClientId = if (session.isConnected) conn.selfClientId else 0,
channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
inputMode = app.settings.inputMode,
hostButton = if (session.isConnected) conn.model.hostButton() else null,
self = session.selfState(),
)
}
internal fun refresh() {
_state.value = snapshotState()
app.serverChanged(this)
}
/** Takes a new tree snapshot soon; [structure] when channels or clients came, went or moved. */
internal fun scheduleTree(structure: Boolean) {
if (structure) structureChanged.set(true)
if (!treePending.compareAndSet(false, true)) return
treeScope.launch {
delay(TREE_FRAME_MS)
treePending.set(false)
if (structureChanged.getAndSet(false)) roots = conn.model.buildTree()
_tree.value = ServerTree.of(roots, conn.model, conn.contacts, app.settings.colorContacts,
app.settings.countryFlags)
val serverName = if (session.isConnected) conn.model.serverName.orEmpty() else ""
val channelName = session.currentChannel()?.name.orEmpty()
_chats.update {
it.copy(
server = it.server.copy(title = serverName.ifBlank { "Server" }),
channel = it.channel.copy(title = channelName.ifBlank { "Channel" }),
)
}
refresh()
}
}
private inner class Listener : ServerSession.Listener {
override fun onSessionChanged() = refresh()
override fun onSystemMessage(text: String) = system(text)
override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) {
val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname
val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text)
append(key(scope, peerClientId), peerName, html)
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, BBCode.toPlain(text))
}
override fun onStatus(status: String) {}
override fun onConnected() {
network.onConnected()
app.connected(this@ServerController)
refresh()
}
override fun onDisconnected(reason: String?) {
network.onDisconnected()
app.notifier.clearServer(id)
_chats.update { it.copy(private = emptyList()) }
app.disconnected(this@ServerController)
scheduleTree(structure = true)
refresh()
}
override fun onModelChanged() {
scheduleTree(structure = true)
// A server edit may have changed it.
if (session.isConnected && conn.model.hostButton() != _state.value.hostButton) refresh()
}
override fun onServerIconChanged(iconId: Long) =
app.serverIconChanged(session.address(), session.port(), iconId)
override fun onInfoUpdated() {
_infoUpdates.update { it + 1 }
// Avatars announce their arrival as info updates.
images.loaded()
}
override fun onIconsUpdated() = images.loaded()
override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) {
append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message))
if (scope == ChatScope.PRIVATE && !app.foreground) {
app.notifier.received(id, fromClientId, fromName, BBCode.toPlain(message))
}
}
override fun onChatHistory(scope: ChatScope, htmlEntries: List<String>) {
if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries)
}
override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List<String>) =
setHistory(ChatKey.Private(clientId), nickname, htmlEntries)
override fun onTalkStateChanged(clientId: Int, talking: Boolean) {
if (clientId == conn.selfClientId && micOwner) app.talking(talking)
scheduleTree(structure = false)
}
override fun onError(message: String) = app.error(message)
override fun onPoke(fromName: String, message: String) = app.poked(fromName, message)
override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message))
override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html))
}
private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) {
ChatScope.SERVER -> ChatKey.Server
ChatScope.CHANNEL -> ChatKey.Channel
ChatScope.PRIVATE -> ChatKey.Private(peerClientId)
}
private companion object {
const val TREE_FRAME_MS = 30L
}
}
@@ -1,61 +0,0 @@
package com.ts3client.android
import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import com.ts3client.net.TeamspeakConnection
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.util.concurrent.ConcurrentHashMap
/**
* One server's icons and its clients' avatars, decoded once. What is still
* downloading reads as null until [version] moves on.
*/
class ServerImages internal constructor(private val conn: TeamspeakConnection) {
private val icons = ConcurrentHashMap<Long, ImageBitmap>()
private val avatars = ConcurrentHashMap<String, Picture>()
private val _version = MutableStateFlow(0)
val version: StateFlow<Int> = _version
internal fun loaded() = _version.update { it + 1 }
fun icon(id: Long): ImageBitmap? {
if (id == 0L) return null
icons[id]?.let { return it }
val bitmap = conn.icons.get(id)?.let { decode(it, ICON_PX) } ?: return null
icons[id] = bitmap
return bitmap
}
fun avatar(uniqueId: String, flag: String): Picture? {
if (flag.isEmpty()) return null
avatars[flag]?.let { return it }
val picture = conn.avatars.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null
avatars[flag] = picture
return picture
}
/** The avatar's file as the server keeps it; null while it has none or it is still downloading. */
fun avatarData(uniqueId: String, flag: String): ByteArray? =
if (flag.isEmpty()) null else conn.avatars.get(uniqueId, flag)?.data()
/** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */
private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2
val options = BitmapFactory.Options().apply { inSampleSize = sample }
return BitmapFactory.decodeByteArray(data, 0, data.size, options)?.asImageBitmap()
}
private companion object {
const val ICON_PX = 64
const val AVATAR_PX = 512
}
}
@@ -1,185 +0,0 @@
package com.ts3client.android
import androidx.compose.runtime.Immutable
import com.ts3client.contacts.ContactStore
import com.ts3client.contacts.ContactType
import com.ts3client.net.ChannelNode
import com.ts3client.net.ClientEntry
import com.ts3client.net.ClientStatus
import com.ts3client.net.ServerModel
import com.ts3client.net.Spacers
import com.ts3client.net.TreeMatch
import com.ts3client.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): ServerTree =
ServerTree(
roots.map { channel(it, model, contacts, colorContacts) },
model.serverIconId(),
countryFlags,
)
private fun channel(c: ChannelNode, model: ServerModel, contacts: ContactStore, colorContacts: Boolean): 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) },
children = c.children.map { channel(it, model, contacts, colorContacts) },
)
}
private fun client(c: ClientEntry, model: ServerModel, contacts: ContactStore, colorContacts: Boolean): ClientItem {
val contact = contacts.find(c.uniqueId)
val away = c.away && c.awayMessage.isNotEmpty() && contact?.ignoreAwayMessage != true
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 = ClientStatus.of(c),
self = c.self,
contactType = contact?.type,
highlight = if (colorContacts) contact?.type ?: ContactType.NEUTRAL else ContactType.NEUTRAL,
groupIconIds = (model.serverGroupsOf(c.serverGroupIds) + listOfNotNull(model.channelGroup(c.channelGroupId)))
.map { it.iconId }.filter { it != 0L },
avatarFlag = c.avatarFlag.orEmpty(),
country = c.country.orEmpty(),
serverGroupIds = c.serverGroupIds.toList(),
channelGroupId = c.channelGroupId,
)
}
}
}
/** What the find bar looks for in the tree: clients, or with [channels] channels. */
@Immutable
data class TreeFind(val query: TextQuery, val channels: Boolean) {
fun matches(c: ChannelItem) = channels && TreeMatch.channel(query, c.name)
fun matches(c: ClientItem) = !channels && TreeMatch.client(query, c.nickname, c.name)
}
@Immutable
data class ChannelItem(
val id: Int,
val name: String,
/** Set for a spacer: a cosmetic separator rather than a channel to join. */
val spacer: Spacers.Spacer?,
val locked: Boolean,
val full: Boolean,
val subscribed: Boolean,
/** 0 for none. */
val iconId: Long,
val clients: List<ClientItem>,
val children: List<ChannelItem>,
)
@Immutable
data class ClientItem(
val id: Int,
val uniqueId: String,
val nickname: String,
/** The name shown: the contact's own name for them where there is one. */
val name: String,
val awayMessage: String,
val status: ClientStatus,
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,
)
@@ -1,475 +0,0 @@
package com.ts3client.android
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.Looper
import com.ts3client.android.audio.AndroidAudioBackend
import com.ts3client.android.audio.AudioRoute
import com.ts3client.audio.AudioDevice
import com.ts3client.config.BanReasonPresets
import com.ts3client.config.Bookmark
import com.ts3client.config.Bookmarks
import com.ts3client.config.IdentityStore
import com.ts3client.config.Settings
import com.ts3client.contacts.Contact
import com.ts3client.contacts.ContactStore
import com.ts3client.myts.MyTeamSpeak
import com.ts3client.net.HostButton
import com.ts3client.myts.MyTeamSpeakLogin
import com.ts3client.session.SelfState
import com.ts3client.session.ServerSession
import com.ts3client.session.Sessions
import com.ts3client.sound.SoundNotifier
import com.ts3client.sound.SoundPack
import com.ts3client.teamspeak.SyncItem
import com.ts3client.teamspeak.TeamSpeakImporter
import com.ts3client.teamspeak.TeamSpeakSettingsDb
import com.ts3client.text.BBCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.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,
)
/** 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
}
/**
* The servers the app is on and what they share, outliving any activity: [ConnectionService]
* keeps the process in the foreground while any is connected. Only one server captures with
* the microphone at a time; [Sessions] hands it over.
*/
class SessionController(private val context: Context) {
val settings: Settings = Settings.load()
val icons = IconTheme(context, settings)
val pictures = WebPictures(context.cacheDir, settings)
internal val cacheDir: File get() = context.cacheDir
private val bookmarkStore = Bookmarks.load()
internal val identityStore = IdentityStore.load(settings)
val identities = IdentityManager(context, identityStore, settings, bookmarkStore) {
_bookmarks.value = bookmarkStore.all().toList()
}
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
internal val notifier = MessageNotifier(context)
internal val contactStore = ContactStore.load()
/** The reasons offered when adding a ban; shared by every server. */
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
internal val network = NetworkFollower(context)
private val main = Handler(Looper.getMainLooper())
private val nextId = AtomicInteger()
/** Touched on the main thread only, as [Sessions] wants. */
private val sessions = Sessions { main.post(::microphoneMoved) }
private val _servers = MutableStateFlow(emptyList<ServerController>())
/** Every server the app is on or getting on, in the order they were connected. */
val servers: StateFlow<List<ServerController>> = _servers
private val _current = MutableStateFlow<ServerController?>(null)
/** The server on screen; null when there is none. */
val current: StateFlow<ServerController?> = _current
private val _micOwner = MutableStateFlow<ServerController?>(null)
/** The server capturing with the microphone; null when none is. */
val micOwner: StateFlow<ServerController?> = _micOwner
/** Why the last connection that ended did, for the connect form to show; null when it was left. */
private val _lastEnd = MutableStateFlow<String?>(null)
val lastEnd: StateFlow<String?> = _lastEnd
/** Copies of the contacts, as the store's own entries change in place. */
private val _contacts = MutableStateFlow(contactCopies())
val contacts: StateFlow<List<Contact>> = _contacts
private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList())
val bookmarks: StateFlow<List<Bookmark>> = _bookmarks
private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16)
val events: SharedFlow<SessionEvent> = _events
private val _onScreen = MutableStateFlow(false)
val onScreen: StateFlow<Boolean> = _onScreen
/** Whether the app is on screen; pokes and private messages are notified of while it is not. */
var foreground: Boolean
get() = _onScreen.value
set(value) {
_onScreen.value = value
if (value) notifier.clearPokes()
// The process may be let go of any time once out of sight.
else contactStore.flush()
}
private val levels = LevelMonitor(settings, audio)
val micLevel: StateFlow<MicLevel> = levels.level
@Volatile
private var watchingLevel = false
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
// Mutations report on whichever thread made them, a connection thread included.
contactStore.addListener {
_contacts.value = contactCopies()
_servers.value.forEach(ServerController::contactsChanged)
}
}
/** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */
fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname }
val lastAddress: String get() = settings.lastAddress
// ---- connection ----
/** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */
fun connect(address: String, nickname: String, password: String = "", identityId: String = "") {
val (host, port) = parseAddress(address)
settings.lastAddress = address
if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname
settings.save()
start(host, port, nickname, password, identityId, "", "")
}
fun connect(bookmark: Bookmark) {
start(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) {
val server = ServerController(nextId.incrementAndGet(), this)
sessions.add(server.session)
_servers.update { it + server }
_current.value = server
_lastEnd.value = null
context.startForegroundService(Intent(context, ConnectionService::class.java))
server.start(host, port, nickname, password, identityId, channel, channelPassword)
}
fun select(server: ServerController) {
if (server in _servers.value) _current.value = server
}
/** Leaves every server before returning, for when the app goes away with the connections. */
fun leave() {
val servers = _servers.value
servers.forEach(ServerController::leaving)
ServerSession.shutdownAll(servers.map { it.session })
contactStore.flush()
}
fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id }
/** A server's state changed; one that is done with goes from the list. */
internal fun serverChanged(server: ServerController) {
if (server.micOwner) updateLevels()
if (server.ended) main.post { remove(server) }
}
private fun remove(server: ServerController) {
if (server !in _servers.value || !server.ended) return
sessions.remove(server.session)
val rest = _servers.value - server
_servers.value = rest
if (_current.value == server) _current.value = rest.lastOrNull()
server.dispose()
val reason = server.state.value.status
_lastEnd.value = if (server.left) null else reason
if (!server.left && rest.isNotEmpty()) error("${server.state.value.title}: $reason")
}
internal fun connected(server: ServerController) {
// The first connect generates an identity when there was none.
identities.refresh()
main.post {
// Without the permission yet, the UI hands the microphone over once it is granted.
if (hasMicPermission()) sessions.connected(server.session)
}
}
internal fun disconnected(server: ServerController) {
main.post { sessions.disconnected(server.session) }
}
internal fun error(message: String) {
_events.tryEmit(SessionEvent.Error(message))
}
internal fun poked(from: String, message: String) {
_events.tryEmit(SessionEvent.Poke(from, message))
if (!foreground) notifier.poke(from, BBCode.toPlain(message))
}
internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
// ---- bookmarks ----
fun addBookmark(label: String, address: String, nickname: String, password: String, identityId: String) {
val (host, port) = parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != nicknameFor(identityId) }.orEmpty()
bookmarkStore.add(Bookmark(label.ifBlank { address }, host, port, own, password).also {
it.identityId = identityId
})
saveBookmarks()
}
/** Connects the bookmark with another identity; empty for the default one. */
fun setBookmarkIdentity(bookmark: Bookmark, identityId: String) {
val index = bookmarkStore.all().indexOf(bookmark)
if (index < 0) return
// A new entry, so the list the UI holds changes along with it.
bookmarkStore.all()[index] = bookmark.copy().also { it.identityId = identityId }
saveBookmarks()
}
fun removeBookmark(bookmark: Bookmark) {
val index = bookmarkStore.all().indexOf(bookmark)
if (index < 0) return
bookmarkStore.remove(index)
saveBookmarks()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
main.post {
val all = bookmarkStore.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) saveBookmarks()
}
}
private fun saveBookmarks() {
bookmarkStore.save()
_bookmarks.value = bookmarkStore.all().toList()
}
// ---- contacts ----
private fun contactCopies(): List<Contact> = contactStore.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [saveContact]. */
fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy()
fun saveContact(contact: Contact) = contactStore.put(contact)
fun removeContact(uniqueId: String) = contactStore.remove(uniqueId)
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun importContacts(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else contactStore.merge(found)
}
// ---- myTeamSpeak ----
/** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings)
suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) }
suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account = withContext(Dispatchers.IO) { myTeamSpeak.fetch() }
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */
suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
_bookmarks.value = bookmarkStore.all().toList()
identities.refresh()
}
// ---- sound packs ----
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setCountryFlags(shown: Boolean) {
settings.countryFlags = shown
settings.save()
servers.value.forEach { it.scheduleTree(structure = false) }
}
fun setDescriptionPictures(shown: Boolean) {
settings.descriptionPictures = shown
settings.save()
}
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
// ---- the local client ----
fun hasMicPermission() =
context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
/** Moves the microphone to [server]; needs RECORD_AUDIO granted. */
fun giveMicrophoneTo(server: ServerController) {
if (server.isConnected) sessions.giveMicrophoneTo(server.session)
}
/** Opens the microphone of the server holding it while push-to-talk is held. */
fun setPushToTalk(pressed: Boolean) = sessions.setPushToTalk(pressed)
private fun microphoneMoved() {
val owner = sessions.microphoneOwner()
for (server in _servers.value) {
server.micOwner = server.session == owner
server.refresh()
}
_micOwner.value = _servers.value.firstOrNull { it.micOwner }
updateLevels()
}
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
/** Switches between push to talk and voice activation; returns the new mode. */
fun toggleInputMode(): Settings.InputMode {
settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK)
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK
applySettings()
return settings.inputMode
}
/** Saves the settings and puts the voice and device ones into effect at once. */
fun applySettings() {
settings.save()
soundPlayer.setOutputDevice(settings.outputDevice)
try {
for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume)
server.playback?.setOutputDevice(settings.outputDevice)
server.microphone?.apply(settings)
server.refresh()
server.scheduleTree(structure = false)
}
levels.apply()
} catch (e: RuntimeException) {
error(e.message ?: "Microphone unavailable")
}
}
/** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) {
routePrefs.save(route)
_route.value = route
audio.setRoute(route)
}
/** Listens to the microphone for the level meter while [on]. */
fun watchLevel(on: Boolean) {
watchingLevel = on
updateLevels()
}
private fun updateLevels() {
val owner = _micOwner.value
levels.update(watchingLevel, owner?.microphone, owner?.isBusy == true, hasMicPermission())
}
// ---- notifications ----
/** Shows a private chat a notification was tapped for. */
fun requestChat(serverId: Int, clientId: Int) {
val server = server(serverId) ?: return
_current.value = server
server.requestChat(clientId)
}
/** Answers a private message from its notification. */
fun reply(serverId: Int, clientId: Int, text: String) {
server(serverId)?.reply(clientId, text) ?: notifier.clear(serverId, clientId)
}
private companion object {
const val DEFAULT_PORT = 9987
const val OVERLAY_ENABLED = "enabled"
fun parseAddress(address: String): Pair<String, Int> {
val host = address.substringBefore(':').trim()
val port = address.substringAfter(':', "").trim().toIntOrNull() ?: DEFAULT_PORT
return host to port
}
}
}
@@ -1,53 +0,0 @@
package com.ts3client.android
import android.content.Context
import android.content.res.AssetManager
import com.ts3client.config.AppDirs
import java.io.File
/**
* Unpacks the sound packs bundled in the APK into the profile's `sound` folder, where
* [com.ts3client.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"
}
}
@@ -1,31 +0,0 @@
package com.ts3client.android
import android.content.Context
import android.os.Bundle
import android.speech.tts.TextToSpeech
import com.ts3client.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()
}
}
@@ -1,18 +0,0 @@
package com.ts3client.android
import android.app.Application
import com.ts3client.config.AppDirs
class Ts3Application : Application() {
lateinit var sessions: SessionController
private set
override fun onCreate() {
super.onCreate()
// Before any store loads: there is no home directory to find them in.
AppDirs.init(filesDir, filesDir.toPath().resolve("chats"))
sessions = SessionController(this)
Thread(sessions::installSoundPacks, "sound-packs").start()
}
}
@@ -1,58 +0,0 @@
package com.ts3client.android
import android.util.LruCache
import com.ts3client.config.Settings
import com.ts3client.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 } }
}
/** Whether pictures are shown at all, rather than links to them. */
val enabled: Boolean get() = settings.descriptionPictures
suspend fun state(url: String): State {
decoded.get(url)?.let { return State.Shown(it) }
if (url in undecodable) return State.Broken
val file = downloads.get(url) ?: return if (downloads.failed(url)) State.Broken else State.Loading
val picture = withContext(Dispatchers.IO) { decodePicture(file.readBytes(), MAX_PX) }
if (picture == null) {
undecodable += url
return State.Broken
}
decoded.put(url, picture)
return State.Shown(picture)
}
/** The picture's file as downloaded; null while it is not there. */
suspend fun data(url: String): ByteArray? = withContext(Dispatchers.IO) { downloads.get(url)?.readBytes() }
private companion object {
const val CACHED = 32
const val MAX_PX = 1024
}
}
@@ -1,105 +0,0 @@
package com.ts3client.android.ui
import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ts3client.android.SessionController
import com.ts3client.android.SessionEvent
@Composable
fun App(vm: SessionController) {
val current by vm.current.collectAsStateWithLifecycle()
// Each server keeps its own screen state (chat open, conversation) while another is shown.
val serverStates = rememberSaveableStateHolder()
var connectOpen by rememberSaveable { mutableStateOf(false) }
val snackbar = remember { SnackbarHostState() }
var settingsOpen by rememberSaveable { mutableStateOf(false) }
var contactsOpen by rememberSaveable { mutableStateOf(false) }
var 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 poke by remember { mutableStateOf<SessionEvent.Poke?>(null) }
LaunchedEffect(vm) {
vm.events.collect { event ->
when (event) {
is SessionEvent.Poke -> poke = event
is SessionEvent.Error -> snackbar.showSnackbar(event.message)
}
}
}
val context = LocalContext.current
val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo)
}
fun missing(vararg names: String) =
names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
// The connection runs without either permission, just silent or without its notification.
val connectAsking: (() -> Unit) -> Unit = { connect ->
connect()
connectOpen = false
val ask = missing(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS)
if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray())
}
val enableMicrophone: () -> Unit = {
if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo)
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
}
val openContacts: (String?) -> Unit = { uniqueId ->
contactsOpen = true
editingContact = uniqueId
contactDirect = uniqueId != null
}
CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) {
val server = current
when {
contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId ->
if (uniqueId == null && contactDirect) contactsOpen = false
contactDirect = false
editingContact = uniqueId
}, onBack = { contactsOpen = false })
settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
server != null && !connectOpen -> {
serverStates.SaveableStateProvider(server.id) {
CompositionLocalProvider(LocalServerImages provides server.images) {
PictureViewerHost(server) {
ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
onConnectOther = { connectOpen = true })
}
}
}
}
else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, connectAsking,
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") } },
)
}
}
@@ -1,313 +0,0 @@
package com.ts3client.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 com.ts3client.android.ServerController
import com.ts3client.config.BanReasonPresets
import com.ts3client.net.ban.BanEntry
import com.ts3client.net.ban.BanPattern
import com.ts3client.net.ban.BanRule
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
/** What the ban list shows instead of itself: a ban's editor, a new or an existing ban's. */
private sealed interface BanEdit {
data object New : BanEdit
data class Existing(val ban: BanEntry) : BanEdit
}
/** The server's ban list, as TeamSpeak's Ban List window: searchable, own bans apart, add, edit and remove. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: () -> Unit) {
val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
var bans by remember { mutableStateOf<List<BanEntry>?>(null) }
var status by remember { mutableStateOf("Loading…") }
/** Bumped to read the list again. */
var generation by remember { mutableIntStateOf(0) }
var query by rememberSaveable { mutableStateOf("") }
var onlyOwn by rememberSaveable { mutableStateOf(false) }
var shown by remember { mutableStateOf<BanEntry?>(null) }
var edit by remember { mutableStateOf<BanEdit?>(null) }
LaunchedEffect(generation) {
status = "Loading…"
server.banList()
.onSuccess {
bans = it
status = if (it.size == 1) "1 ban" else "${it.size} bans"
}
.onFailure {
bans = emptyList()
status = "Failed to request ban list: ${it.message}"
}
}
/** Reports a failed change, or re-reads the list to show what the server now holds. */
val change = { action: suspend () -> String?, failure: String ->
scope.launch {
val error = action()
if (error != null) snackbar.showSnackbar("$failure: $error")
generation++
}
Unit
}
edit?.let { e ->
val existing = (e as? BanEdit.Existing)?.ban
BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule ->
edit = null
if (existing == null) change({ server.addBan(rule) }, "Error adding ban")
else change({ server.replaceBan(existing.id, rule) }, "Error editing ban")
}
return
}
SubScreen(
"Ban list", onBack,
actions = {
if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") }
IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") }
},
snackbar = snackbar,
) { padding ->
val needle = query.trim().lowercase(Locale.ROOT)
val filtered = remember(bans, needle, onlyOwn) {
bans.orEmpty().filter { ban ->
(!onlyOwn || server.isOwnBan(ban)) && (needle.isEmpty() || searchText(ban).contains(needle))
}
}
Column(Modifier.padding(padding).imePadding().fillMaxSize()) {
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(query, { query = it }, Modifier.weight(1f), placeholder = { Text("Search") },
singleLine = true, leadingIcon = { PackIcon("SEARCH", null) })
FilterChip(onlyOwn, { onlyOwn = !onlyOwn }, label = { Text("Own") })
}
Text(status, Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
LazyColumn(Modifier.weight(1f)) {
items(filtered, key = { it.id }) { ban ->
ListItem(
headlineContent = { Text(ban.targets(), maxLines = 2, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Column {
if (ban.reason.isNotEmpty()) Text(ban.reason, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text("${ban.invokerName} · ${expiry(ban)}", style = MaterialTheme.typography.bodySmall)
}
},
modifier = Modifier.clickable { shown = ban },
)
HorizontalDivider()
}
}
}
}
shown?.let { ban ->
BanSheet(
ban,
onDismiss = { shown = null },
onEdit = if (server.canEditBan(ban)) ({ shown = null; edit = BanEdit.Existing(ban) }) else null,
onDelete = if (server.canDeleteBans(listOf(ban))) ({
shown = null
change({ server.deleteBans(listOf(ban.id)) }, "Error deleting ban")
}) else null,
)
}
}
private fun searchText(ban: BanEntry): String =
listOf(ban.targets(), ban.reason, ban.invokerName, date(ban.createdEpochSeconds), expiry(ban))
.joinToString("\n").lowercase(Locale.ROOT)
private val DATE: DateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
private fun date(epochSeconds: Long): String =
if (epochSeconds <= 0) "" else DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault()))
private fun expiry(ban: BanEntry): String = if (ban.isPermanent) "Never expires" else "Expires ${date(ban.expiresEpochSeconds())}"
/** Everything about one ban, and what may be done with it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun BanSheet(ban: BanEntry, onDismiss: () -> Unit, onEdit: (() -> Unit)?, onDelete: (() -> Unit)?) {
var confirmDelete by remember { mutableStateOf(false) }
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Fact("Name", ban.name)
Fact("IP", ban.ip)
Fact("Unique ID", ban.uid)
Fact("Last nickname", ban.lastNickname)
Fact("myTeamSpeak ID", ban.mytsid)
Fact("Reason", ban.reason)
Fact("Creator", ban.invokerName)
Fact("Created", date(ban.createdEpochSeconds))
Fact("Expires", if (ban.isPermanent) "Never" else date(ban.expiresEpochSeconds()))
Fact("Enforced", ban.enforcements.toString())
}
onEdit?.let { Action("EDIT", "Edit", onClick = it) }
onDelete?.let { Action("DELETE", "Delete") { confirmDelete = true } }
}
}
if (confirmDelete && onDelete != null) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete ban?") },
text = { Text(ban.targets()) },
confirmButton = { TextButton(onClick = { confirmDelete = false; onDelete() }) { Text("Delete") } },
dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } },
)
}
}
@Composable
private fun Fact(label: String, value: String) {
if (value.isEmpty()) return
Column {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, style = MaterialTheme.typography.bodyMedium)
}
}
/** Adds a ban, or rewrites [existing]: what it matches, why, and for how long. */
@Composable
private fun BanEditor(
existing: BanEntry?,
presets: BanReasonPresets,
maxSeconds: Long,
onBack: () -> Unit,
onSave: (BanRule) -> Unit,
) {
val decoded = remember { BanPattern.decode(existing?.ip, existing?.name) }
var ip by remember { mutableStateOf(decoded.ip) }
var name by remember { mutableStateOf(decoded.name) }
var pattern by remember { mutableStateOf(if (existing == null) BanPattern.WILDCARD_IPV4 else decoded.pattern) }
var uid by remember { mutableStateOf(existing?.uid.orEmpty()) }
var mytsid by remember { mutableStateOf(existing?.mytsid.orEmpty()) }
var reason by remember { mutableStateOf(existing?.reason.orEmpty()) }
val duration = remember { BanDurationState(existing?.durationSeconds ?: DEFAULT_BAN_SECONDS) }
val rule = BanRule(pattern.ipToRegex(ip), pattern.nameToRegex(name), uid, mytsid, duration.seconds, reason)
val ipValid = BanPattern.isValidRegex(rule.ipRegex)
val nameValid = BanPattern.isValidRegex(rule.nameRegex)
val valid = rule.hasTarget() && ipValid && nameValid && duration.valid
SubScreen(
if (existing == null) "Add ban" else "Edit ban", onBack,
actions = { TextButton(onClick = { onSave(rule) }, enabled = valid) { Text("Save") } },
) { padding ->
Column(
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(ip, { ip = it }, Modifier.fillMaxWidth(), label = { Text("IP") }, singleLine = true,
isError = !ipValid)
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true,
isError = !nameValid)
PatternField(pattern) { pattern = it }
OutlinedTextField(uid, { uid = it }, Modifier.fillMaxWidth(), label = { Text("Unique ID") }, singleLine = true)
OutlinedTextField(mytsid, { mytsid = it }, Modifier.fillMaxWidth(), label = { Text("myTeamSpeak ID") },
singleLine = true)
ReasonField(reason, { reason = it }, presets)
BanDurationField(duration, maxSeconds)
}
}
}
/** How the IP and name are written: wildcards, fixed strings or regular expressions. */
@Composable
private fun PatternField(pattern: BanPattern, onSelect: (BanPattern) -> Unit) {
var open by remember { mutableStateOf(false) }
Row(verticalAlignment = Alignment.CenterVertically) {
Text("Interpret as", Modifier.weight(1f))
Box {
OutlinedButton(onClick = { open = true }) { Text(pattern.label()) }
DropdownMenu(open, { open = false }) {
for (p in BanPattern.entries) DropdownMenuItem({ Text(p.label()) }, onClick = { open = false; onSelect(p) })
}
}
}
}
/** The reason, with the saved presets to pick from and the reason typed to save as one. */
@Composable
private fun ReasonField(reason: String, onChange: (String) -> Unit, presets: BanReasonPresets) {
var open by remember { mutableStateOf(false) }
var saved by remember { mutableStateOf(presets.all().toList()) }
Box {
Row(verticalAlignment = Alignment.Top) {
LimitedField(reason, onChange, "Reason", BanRule.REASON_LIMIT, Modifier.weight(1f))
IconButton(onClick = { open = true }, Modifier.padding(top = 8.dp)) { Icon(Icons.Filled.ArrowDropDown, "Presets") }
}
DropdownMenu(open, { open = false }, Modifier.align(Alignment.TopEnd)) {
for (preset in saved) {
DropdownMenuItem({ Text(preset, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; onChange(preset.take(BanRule.REASON_LIMIT)) },
trailingIcon = {
IconButton(onClick = {
presets.remove(preset)
presets.save()
saved = presets.all().toList()
}) { PackIcon("DELETE", "Remove preset") }
})
}
if (saved.isNotEmpty()) HorizontalDivider()
DropdownMenuItem({ Text("Save as preset") }, enabled = reason.isNotBlank(), onClick = {
open = false
presets.add(reason)
presets.save()
saved = presets.all().toList()
})
}
}
}
@@ -1,266 +0,0 @@
package com.ts3client.android.ui
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
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.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.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 com.ts3client.android.ChannelItem
import com.ts3client.android.ClientItem
import com.ts3client.android.ServerTree
import com.ts3client.contacts.ContactType
import com.ts3client.gfx.IconKeys
import com.ts3client.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
}
@Composable
fun ChannelTree(
serverName: String,
tree: ServerTree,
collapsed: Set<Int>,
currentChannel: Int,
onToggle: (ChannelItem) -> Unit,
onChannel: (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,
) {
val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) }
val listState = rememberLazyListState()
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
}
}
LazyColumn(modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 4.dp)) {
item(key = "server") {
RowLayout(depth = 0, onClick = onServer) {
PackIcon("SERVER_GREEN", null, size = ICON)
Text(serverName, Modifier.weight(1f), fontWeight = FontWeight.Bold, maxLines = 1,
overflow = TextOverflow.Ellipsis)
ServerIcon(tree.serverIconId, size = ICON)
}
}
items(rows, key = { it.key }) { row ->
val background = rowBackground(
when (row.ref) {
flashing -> FLASH
foundCurrent -> findCurrentColor()
in found -> findMatchColor()
else -> Color.Transparent
},
)
when (row) {
is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel)
is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient)
}
}
}
}
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,
content: @Composable RowScope.() -> Unit,
) {
Row(
Modifier
.fillMaxWidth()
.background(background)
.height(ROW)
.then(if (onClick != null) Modifier.clickable(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) {
val channel = row.channel
val spacer = channel.spacer
RowLayout(row.depth, onClick = { onChannel(channel) }, background = background) {
Box(
Modifier.fillMaxHeight().width(ICON + 4.dp)
.then(if (row.expandable) Modifier.clickable { onToggle(channel) } else Modifier),
contentAlignment = Alignment.Center,
) {
if (row.expandable) {
Icon(Icons.Filled.KeyboardArrowDown, if (row.expanded) "Collapse" else "Expand",
Modifier.size(ICON + 2.dp).rotate(if (row.expanded) 0f else -90f))
}
}
if (spacer != null) {
SpacerLabel(spacer.align(), spacer.caption().orEmpty(), Modifier.weight(1f))
} else {
PackIcon(IconKeys.channel(channel.locked, channel.full, channel.subscribed).asList(), null, size = ICON)
Text(
channel.name,
Modifier.weight(1f),
color = if (row.current) MaterialTheme.colorScheme.primary else Color.Unspecified,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
ServerIcon(channel.iconId, size = ICON)
}
}
}
/** A spacer's caption, placed as its tag asks; a repeated one of dashes or the like becomes a rule. */
@Composable
private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) {
if (align == '*') {
if (caption.isNotEmpty() && caption.all { it in "-_=.~" }) {
HorizontalDivider(modifier)
} else {
Text(caption.repeat(200 / caption.length.coerceAtLeast(1)), modifier, maxLines = 1, overflow = TextOverflow.Clip)
}
return
}
val textAlign = when (align) {
'c' -> TextAlign.Center
'r' -> TextAlign.End
else -> TextAlign.Start
}
Text(caption, modifier, textAlign = textAlign, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) {
val client = row.client
RowLayout(row.depth, onClick = { onClient(client) }, background = background) {
Spacer(Modifier.width(ICON + 4.dp))
StatusIcon(client.status)
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
client.name,
fontWeight = if (client.self) FontWeight.Bold else FontWeight.Normal,
color = when (client.highlight) {
ContactType.FRIEND -> StatusColors.friend
ContactType.BLOCKED -> StatusColors.blocked
else -> Color.Unspecified
},
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (client.awayMessage.isNotEmpty()) {
Text("[${client.awayMessage}]", Modifier.weight(1f, fill = false),
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
for (id in client.groupIconIds) ServerIcon(id, size = ICON)
// The country's flag comes last, at the row's edge.
if (countryFlags) CountryFlag(client.country)
}
}
@Composable
fun StatusIcon(status: ClientStatus, modifier: Modifier = Modifier) {
PackIcon(IconKeys.client(status), status.name, modifier, size = ICON)
}
@@ -1,179 +0,0 @@
package com.ts3client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.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.key
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.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 com.ts3client.android.ChatKey
import com.ts3client.android.ChatLine
import com.ts3client.android.ChatMatch
import com.ts3client.android.Chats
import com.ts3client.android.Conversation
import com.ts3client.text.TextQuery
import kotlinx.coroutines.flow.first
@Composable
fun ChatPane(
chats: Chats,
selected: Conversation,
canSend: Boolean,
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit,
onSend: (String) -> Unit,
onLink: (String) -> Unit,
modifier: Modifier = Modifier,
/** The lines to show, when not all of [selected]'s. */
lines: List<ChatLine> = selected.lines,
find: TextQuery = TextQuery.EMPTY,
/** The match the find bar is on. */
current: ChatMatch? = null,
/** A line to scroll to. */
reveal: Long? = null,
onRevealed: () -> Unit = {},
) {
Column(modifier) {
LazyRow(
contentPadding = PaddingValues(horizontal = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(chats.all, key = { it.key.toString() }) { conversation ->
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
}
}
// Each conversation opens at its newest line.
key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) }
// One unsent message per conversation, kept while another one is on screen.
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
val draftKey = selected.key.toString()
val draft = drafts[draftKey].orEmpty()
val send = {
if (draft.isNotBlank()) {
onSend(draft.trim())
drafts.remove(draftKey)
}
}
Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
draft, { drafts[draftKey] = it },
Modifier.weight(1f).onPreviewKeyEvent { e ->
// A hardware keyboard's Enter sends, as on the desktop; Shift+Enter starts a new line.
val enter = e.key == Key.Enter && !e.isShiftPressed
if (enter && e.type == KeyEventType.KeyDown) send()
enter
},
placeholder = { Text("Message ${selected.title}", maxLines = 1, overflow = TextOverflow.Ellipsis) },
enabled = canSend,
maxLines = 4,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
)
IconButton(onClick = send, enabled = canSend && draft.isNotBlank()) {
Icon(Icons.AutoMirrored.Filled.Send, "Send")
}
}
}
}
private val DraftsSaver = Saver<SnapshotStateMap<String, String>, HashMap<String, String>>(
save = { HashMap(it) },
restore = { mutableStateMapOf<String, String>().apply { putAll(it) } },
)
@Composable
private fun ConversationChip(
conversation: Conversation,
selected: Boolean,
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit,
) {
val key = conversation.key
FilterChip(
selected = selected,
onClick = { onSelect(key) },
label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingIcon = if (conversation.unread) ({ Badge() }) else null,
trailingIcon = if (key is ChatKey.Private) ({
Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) })
}) else null,
)
}
/** The conversation's lines, following new ones while the newest is in view. */
@Composable
private fun Lines(
lines: List<ChatLine>,
onLink: (String) -> Unit,
modifier: Modifier,
find: TextQuery,
current: ChatMatch?,
reveal: Long?,
onRevealed: () -> Unit,
) {
val listState = rememberLazyListState(initialFirstVisibleItemIndex = (lines.size - 1).coerceAtLeast(0))
val link by rememberUpdatedState(onLink)
LaunchedEffect(lines.lastOrNull()?.id) {
val info = listState.layoutInfo
val atEnd = info.visibleItemsInfo.lastOrNull()?.index?.let { it >= info.totalItemsCount - 2 } ?: true
if (atEnd && lines.isNotEmpty()) listState.scrollToItem(lines.size - 1)
}
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)
}
}
}
@@ -1,307 +0,0 @@
package com.ts3client.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 com.ts3client.android.WebPictures
import com.ts3client.text.BBCode
import com.ts3client.text.ChatHtml
import com.ts3client.text.TextQuery
/**
* HTML as [BBCode][com.ts3client.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("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&amp;", "&")
/**
* 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 {
val openLink = image.href?.let { href -> { onLink(href) } }
viewer(ViewedPicture(pictureName(image.url), image.url, openLink) { pictures.data(image.url) })
} else if (image.href != null) Modifier.clickable { onLink(image.href) } else Modifier),
)
}
}
}
}
/** 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(BBCode.shortAddress(it))}</a>" }, color, onLink)
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
PackIcon(iconKey, "Picture", size = 16.dp)
Text(text, style = style)
}
}
/**
* 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",
)
@@ -1,248 +0,0 @@
package com.ts3client.android.ui
import android.graphics.BitmapFactory
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
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.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.Icon
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.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.asImageBitmap
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 com.ts3client.android.IdentityInfo
import com.ts3client.android.SessionController
import com.ts3client.config.Bookmark
import com.ts3client.net.IconRepository
/** Where to connect to: an address typed in, or a bookmark. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConnectScreen(
vm: SessionController,
snackbar: SnackbarHostState,
onSettings: () -> Unit,
onConnect: (() -> Unit) -> Unit,
/** Back to the servers already connected; null when there are none. */
onBack: (() -> Unit)?,
) {
val lastEnd by vm.lastEnd.collectAsStateWithLifecycle()
val bookmarks by vm.bookmarks.collectAsStateWithLifecycle()
val identities by vm.identities.all.collectAsStateWithLifecycle()
var address by rememberSaveable { mutableStateOf(vm.lastAddress) }
var identityId by rememberSaveable { mutableStateOf("") }
var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) }
var password by rememberSaveable { mutableStateOf("") }
var naming by rememberSaveable { mutableStateOf(false) }
var choosingFor by remember { mutableStateOf<Bookmark?>(null) }
if (onBack != null) BackHandler(onBack = onBack)
Scaffold(
topBar = {
TopAppBar(
title = { Text("TeamSpeak") },
navigationIcon = {
if (onBack != null) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
},
actions = {
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
},
)
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
LazyColumn(
Modifier.padding(padding).imePadding(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
item {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
singleLine = true)
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
label = { Text("Server password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) {
identityId = it
nickname = vm.nicknameFor(it)
}
lastEnd?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(
onClick = { onConnect { vm.connect(address.trim(), nickname.trim(), password, identityId) } },
enabled = address.isNotBlank() && nickname.isNotBlank(),
) { Text("Connect") }
TextButton(onClick = { naming = true }, 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)
}
}
items(bookmarks) { bookmark ->
BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } },
onChooseIdentity = { choosingFor = bookmark }, onRemove = { vm.removeBookmark(bookmark) })
}
}
}
if (naming) {
TextPrompt(
title = "Add bookmark",
label = "Name",
confirm = "Add",
initial = address,
onDismiss = { naming = false },
onConfirm = {
naming = false
vm.addBookmark(it, address.trim(), nickname.trim(), password, identityId)
},
)
}
choosingFor?.let { bookmark ->
IdentityDialog(identities, bookmark.identityId, onDismiss = { choosingFor = null }) {
choosingFor = null
vm.setBookmarkIdentity(bookmark, it)
}
}
}
/** 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
private 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)
})
}
}
}
}
@Composable
private fun IdentityDialog(identities: List<IdentityInfo>, selected: String, onDismiss: () -> Unit, onSelect: (String) -> Unit) {
val shown = shownId(identities, selected)
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Connect with") },
text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
for ((id, name) in identityChoices(identities)) Choice(name, id == shown) { onSelect(id) }
}
},
confirmButton = {},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** 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)
}
@Composable
private fun BookmarkRow(
bookmark: Bookmark,
identities: List<IdentityInfo>,
onConnect: () -> Unit,
onChooseIdentity: () -> Unit,
onRemove: () -> Unit,
) {
val identity = identities.firstOrNull { it.id == bookmark.identityId }
var menu by remember { mutableStateOf(false) }
ListItem(
headlineContent = { Text(bookmark.displayName()) },
supportingContent = {
Text("${bookmark.address}:${bookmark.port}" + (identity?.let { " · ${it.name}" } ?: ""))
},
leadingContent = { BookmarkIcon(bookmark.iconId) },
trailingContent = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Bookmark options") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Identity") }, onClick = { menu = false; onChooseIdentity() })
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; onRemove() })
}
}
},
modifier = Modifier.clickable(onClick = onConnect),
)
}
@@ -1,271 +0,0 @@
package com.ts3client.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 com.ts3client.android.SessionController
import com.ts3client.contacts.Contact
import com.ts3client.contacts.ContactDefaults
import com.ts3client.contacts.ContactType
import com.ts3client.contacts.NicknameDisplay
import kotlinx.coroutines.launch
import java.time.format.DateTimeFormatter
import kotlin.math.roundToInt
private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
private val DISPLAYS = listOf(
NicknameDisplay.ONLY_NICKNAME to "Nickname",
NicknameDisplay.ONLY_CUSTOM to "Custom name",
NicknameDisplay.BOTH to "Both",
)
private val GROUPS = listOf(
ContactType.FRIEND to "Friends",
ContactType.BLOCKED to "Blocked",
ContactType.NEUTRAL to "Neutral",
)
/**
* The contact list, grouped as TeamSpeak's Contacts window groups it, with each
* contact's own page and the defaults new contacts start out with.
*
* @param editing the unique id of the contact whose page is open, if any
*/
@Composable
fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) {
var defaults by rememberSaveable { mutableStateOf(false) }
when {
editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) })
defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false })
}
val contacts by vm.contacts.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
var imported by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
imported = runCatching { vm.importContacts(uri) }.fold(
{ (found, added) ->
if (found == 0) "That file holds no contacts."
else "Imported $found contacts, $added of them new."
},
{ "That file is not a TeamSpeak 3 settings.db." },
)
}
}
SubScreen("Contacts", onBack, actions = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Defaults for new contacts") }, onClick = { menu = false; defaults = true })
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
menu = false
importer.launch(arrayOf("*/*"))
})
}
}
}) { padding ->
LazyColumn(Modifier.padding(padding)) {
imported?.let { item { Hint(it) } }
if (contacts.isEmpty()) {
item {
Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " +
"or import the contacts of TeamSpeak 3 from its settings.db.")
}
}
for ((type, title) in GROUPS) {
val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() }
if (group.isEmpty()) continue
item(key = type) { Section(title) }
items(group, key = { it.uniqueId }) { contact ->
ListItem(
headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
supportingContent = { Text(lastSeen(contact)) },
modifier = Modifier.clickable { onEdit(contact.uniqueId) },
)
}
}
}
}
}
/** One contact's settings; each is stored as it is changed, the names once the page is left. */
@Composable
private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) {
val contacts by vm.contacts.collectAsStateWithLifecycle()
val contact = contacts.firstOrNull { it.uniqueId == uniqueId }
if (contact == null) {
LaunchedEffect(Unit) { onBack() }
return
}
// Starts from the stored entry, which may have been seen again since this page opened.
fun edit(change: Contact.() -> Unit) {
vm.contact(uniqueId)?.let { vm.saveContact(it.apply(change)) }
}
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
var removing by remember { mutableStateOf(false) }
val leave = {
if (customName.trim() != contact.nickname || phoneticName.trim() != contact.phoneticNickname) {
edit {
nickname = customName.trim()
phoneticNickname = phoneticName.trim()
}
}
onBack()
}
SubScreen(label(contact), leave, actions = {
IconButton(onClick = { removing = true }) { PackIcon(if (contact.type == ContactType.BLOCKED) "REMOVE_FOE" else "REMOVE_FRIEND", "Remove from contacts") }
}) { padding ->
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
OutlinedTextField(customName, { customName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
label = { Text("Custom nickname") }, singleLine = true)
OutlinedTextField(phoneticName, { phoneticName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
label = { Text("Phonetic nickname") }, singleLine = true)
Section("Contact")
Segments(GROUPS.map { (type, _) -> type to type.label() }, contact.type) { edit { type = it } }
Section("Show as")
Segments(DISPLAYS, contact.nicknameDisplay) { edit { nicknameDisplay = it } }
Section("Ignore")
Toggle("Mute", contact.automute) { edit { automute = it } }
Toggle("Ignore server and channel chat", contact.ignorePublicMessages) { edit { ignorePublicMessages = it } }
Toggle("Ignore private chat", contact.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
Toggle("Ignore pokes", contact.ignorePokes) { edit { ignorePokes = it } }
Toggle("Hide avatar", contact.ignoreAvatar) { edit { ignoreAvatar = it } }
Toggle("Hide away message", contact.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
Toggle("Deny whisper", !contact.whisperAllowed) { edit { whisperAllowed = !it } }
Section("Playback")
val volume = if (contact.hasVolumeModifier) contact.volumeModifier.toFloat() else 0f
Level("Volume", volume, -30f..20f, ::formatVolume) { db ->
val rounded = db.roundToInt().toDouble()
edit {
hasVolumeModifier = rounded != 0.0
volumeModifier = rounded
}
}
Section("Details")
val context = LocalContext.current
LinkRow("Unique ID", contact.uniqueId) {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId))
}
ListItem(headlineContent = { Text(lastSeen(contact)) })
}
}
if (removing) {
AlertDialog(
onDismissRequest = { removing = false },
title = { Text("Remove ${label(contact)}?") },
text = { Text("Their settings here are forgotten; they show as anyone else again.") },
confirmButton = {
TextButton(onClick = {
removing = false
vm.removeContact(uniqueId)
onBack()
}) { Text("Remove") }
},
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
)
}
}
/** What a client starts out with when added as a friend, blocked or neutral. */
@Composable
private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) {
val defaults = vm.settings.contactDefaults
var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) }
var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) }
fun edit(change: ContactDefaults.Entry.() -> Unit) {
val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() }
defaults.of(tab).copyFrom(changed)
vm.settings.save()
entry = changed
}
SubScreen("Defaults for new contacts", onBack) { padding ->
Column(Modifier.padding(padding)) {
PrimaryTabRow(selectedTabIndex = GROUPS.indexOfFirst { it.first == tab }) {
for ((type, title) in GROUPS) Tab(tab == type, onClick = { tab = type }, text = { Text(title) })
}
Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Show as")
Segments(DISPLAYS, entry.nicknameDisplay) { edit { nicknameDisplay = it } }
Section("Ignore")
Toggle("Mute", entry.automute) { edit { automute = it } }
Toggle("Ignore server and channel chat", entry.ignorePublicMessages) { edit { ignorePublicMessages = it } }
Toggle("Ignore private chat", entry.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
Toggle("Ignore pokes", entry.ignorePokes) { edit { ignorePokes = it } }
Toggle("Hide avatar", entry.ignoreAvatar) { edit { ignoreAvatar = it } }
Toggle("Hide away message", entry.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
Toggle("Deny whisper", entry.ignoreWhisper) { edit { ignoreWhisper = it } }
}
}
}
}
private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId }
private fun lastSeen(contact: Contact): String {
val seen = contact.lastSeen ?: return "Never seen"
val where = contact.lastSeenServerName.ifBlank { contact.lastSeenServerAddress }
return "Last seen ${SEEN.format(seen)}" + if (where.isNotBlank()) " on $where" else ""
}
private fun formatVolume(db: Float): String {
val rounded = db.roundToInt()
return if (rounded == 0) "Unchanged" else "${if (rounded > 0) "+" else ""}$rounded dB"
}
private fun typeColor(type: ContactType): Color = when (type) {
ContactType.FRIEND -> StatusColors.friend
ContactType.BLOCKED -> StatusColors.blocked
ContactType.NEUTRAL -> Color.Unspecified
}
@@ -1,137 +0,0 @@
package com.ts3client.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 com.ts3client.net.Details
import com.ts3client.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
@@ -1,190 +0,0 @@
package com.ts3client.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 com.ts3client.gfx.IconKeys
import com.ts3client.net.ClientStatus
import com.ts3client.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 }
}
}
@@ -1,64 +0,0 @@
package com.ts3client.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 com.ts3client.android.Picture
import com.ts3client.android.WebPictures
import com.ts3client.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
@@ -1,282 +0,0 @@
package com.ts3client.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 com.ts3client.android.IdentityInfo
import com.ts3client.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"
@@ -1,225 +0,0 @@
package com.ts3client.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.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.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 com.ts3client.android.ClientItem
import com.ts3client.android.ServerController
import com.ts3client.net.GroupChoice
import com.ts3client.net.TeamspeakConnection
import com.ts3client.net.ban.BanRule
import com.ts3client.net.ban.BanUnit
/** Asks to confirm a kick, with an optional reason. */
@Composable
fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) {
var reason by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = { LimitedField(reason, { reason = it }, "Reason", TeamspeakConnection.KICK_REASON_LIMIT) },
confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** Asks for a ban's reason and length. */
@Composable
fun BanPrompt(name: String, maxSeconds: Long, onDismiss: () -> Unit, onBan: (seconds: Long, reason: String) -> Unit) {
var reason by remember { mutableStateOf("") }
val duration = remember { BanDurationState(DEFAULT_BAN_SECONDS) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Ban $name") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
LimitedField(reason, { reason = it }, "Reason", BanRule.REASON_LIMIT)
BanDurationField(duration, maxSeconds)
}
},
confirmButton = {
TextButton(onClick = { onBan(duration.seconds, reason.trim()) }, enabled = duration.valid) { Text("Ban") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** Thirty minutes, as the official client starts its ban dialog. */
internal const val DEFAULT_BAN_SECONDS = 30 * 60L
/** A one-line field that takes no more than [limit] characters, counting them as they come. */
@Composable
internal fun LimitedField(value: String, onChange: (String) -> Unit, label: String, limit: Int, modifier: Modifier = Modifier) {
OutlinedTextField(
value, { onChange(it.take(limit)) },
modifier.fillMaxWidth(),
label = { Text(label) },
singleLine = true,
supportingText = { Text("${value.length}/$limit", Modifier.fillMaxWidth(), textAlign = TextAlign.End) },
)
}
/** A ban's length as typed: an amount of a [BanUnit]. */
internal class BanDurationState(seconds: Long) {
var unit by mutableStateOf(BanUnit.largestFor(seconds))
var amount by mutableStateOf(BanUnit.largestFor(seconds).amountOf(seconds).takeIf { it > 0 }?.toString() ?: "30")
val valid: Boolean get() = unit == BanUnit.PERMANENT || (amount.toLongOrNull() ?: 0) > 0
/** The length in seconds; 0 for permanent. */
val seconds: Long get() = unit.toSeconds(amount.toLongOrNull() ?: 0)
fun set(seconds: Long) {
unit = BanUnit.largestFor(seconds)
if (unit != BanUnit.PERMANENT) amount = unit.amountOf(seconds).toString()
}
}
/** The amount, its unit, and a jump to the longest ban the server lets us hand out. */
@Composable
internal fun BanDurationField(state: BanDurationState, maxSeconds: Long, modifier: Modifier = Modifier) {
var units by remember { mutableStateOf(false) }
Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
if (state.unit == BanUnit.PERMANENT) "" else state.amount,
{ text -> state.amount = text.filter(Char::isDigit).take(9) },
Modifier.width(120.dp),
enabled = state.unit != BanUnit.PERMANENT,
label = { Text("Duration") },
singleLine = true,
isError = !state.valid,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
Box(Modifier.weight(1f)) {
OutlinedButton(onClick = { units = true }, Modifier.fillMaxWidth()) { Text(state.unit.label()) }
DropdownMenu(units, { units = false }) {
for (unit in BanUnit.entries) {
DropdownMenuItem({ Text(unit.label()) }, onClick = { units = false; state.unit = unit })
}
}
}
if (maxSeconds != 0L) TextButton(onClick = { state.set(maxSeconds) }) { Text("Max") }
}
}
/**
* A client's groups to tick: several server groups, or with [single] the one channel group.
* Groups we have no power over show 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 = {
LazyColumn {
items(choices, 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 = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (single) {
RadioButton(choice.assigned(), onClick = toggle, enabled = choice.allowed())
} else {
Checkbox(choice.assigned(), onCheckedChange = { toggle() }, enabled = choice.allowed())
}
Box(Modifier.width(24.dp), contentAlignment = Alignment.Center) {
if (group.iconId != 0L) ServerIcon(group.iconId)
}
Text(group.name, Modifier.padding(start = 8.dp))
}
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } },
)
}
/** The kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out. */
@Composable
fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit) {
var kick by remember { mutableStateOf<Boolean?>(null) }
var banning by remember { mutableStateOf(false) }
var groups by remember { mutableStateOf<Boolean?>(null) }
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
if (!client.self) {
if (server.canKickFromChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false }
if (server.canKickFromServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true }
if (server.canBanClients) Action("BAN_CLIENT", "Ban") { banning = true }
}
if (serverGroups.any { it.allowed() }) Action("PERMISSIONS_SERVER_GROUPS", "Server groups") { groups = true }
if (channelGroups.any { it.allowed() && !it.assigned() }) {
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(client.id, reason) else server.kickFromChannel(client.id, reason)
onDone()
}
}
if (banning) {
BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason ->
banning = false
server.ban(client.id, seconds, reason)
onDone()
}
}
groups?.let { ofServer ->
GroupsDialog(
if (ofServer) "Server groups" else "Channel group",
if (ofServer) serverGroups else channelGroups,
single = !ofServer,
onDismiss = { groups = null },
) { groupId, assign ->
if (ofServer) server.setServerGroup(client.id, groupId, assign) else server.setChannelGroup(client.id, groupId)
}
}
}
@@ -1,219 +0,0 @@
package com.ts3client.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.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.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 com.ts3client.android.SessionController
import com.ts3client.myts.MyTeamSpeak
import com.ts3client.myts.MyTsException
import com.ts3client.teamspeak.SyncItem
import kotlinx.coroutines.launch
import java.io.IOException
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
/**
* The myTeamSpeak account: sign in and out, and pick what the account synchronises to
* import. Signing in lasts until signing out; the password itself is not kept.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
val login = vm.myTeamSpeak
val scope = rememberCoroutineScope()
var signedIn by remember { mutableStateOf(login.isSignedIn) }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf(false) }
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var all by remember { mutableStateOf(emptyList<SyncItem>()) }
var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
BackHandler(onBack = onBack)
fun show(account: MyTeamSpeak.Account) {
all = account.items()
rows = all.filter { it !is SyncItem.Folder }.map {
val imported = vm.isImported(it)
ItemRow(it, imported, !imported)
}
message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null
error = false
}
fun work(block: suspend () -> Unit) {
busy = true
message = null
scope.launch {
try {
block()
} catch (e: MyTsException) {
message = e.message
error = true
} catch (e: IOException) {
message = "Could not reach myTeamSpeak: ${e.message}"
error = true
}
// A sign-in the server no longer takes has signed out.
signedIn = login.isSignedIn
busy = false
}
}
LaunchedEffect(Unit) {
if (signedIn) work { show(vm.fetchMyTeamSpeak()) }
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("myTeamSpeak") },
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = {
if (signedIn) {
IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) {
PackIcon("REFRESH", "Refresh")
}
}
},
)
},
) { padding ->
LazyColumn(
Modifier.padding(padding).imePadding(),
contentPadding = PaddingValues(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
if (!signedIn) {
item {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Sign in to bring over the bookmarks and identities your account synchronises. " +
"The app stays signed in; your password itself is not kept.")
OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") },
singleLine = true, enabled = !busy,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email))
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), label = { Text("Password") },
singleLine = true, enabled = !busy, visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
Button(
onClick = {
work {
show(vm.signInMyTeamSpeak(email.trim(), password))
password = ""
}
},
enabled = !busy && email.isNotBlank() && password.isNotEmpty(),
) { Text("Sign in") }
}
}
} else {
item {
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Signed in as ${login.username()}", style = MaterialTheme.typography.titleMedium)
Text(login.email(), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
OutlinedButton(onClick = {
login.signOut()
signedIn = false
rows = emptyList()
all = emptyList()
message = null
}) { Text("Sign out") }
}
}
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)
}
}
items(rows, key = { it.item.uuid() }) { row ->
val toggle = { rows = rows.map { if (it === row) it.copy(selected = !it.selected) else it } }
ListItem(
headlineContent = { Text(name(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = { Text(details(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingContent = { Checkbox(row.selected, { toggle() }) },
trailingContent = if (row.imported) ({ Text("Imported", style = MaterialTheme.typography.labelMedium) }) else null,
modifier = Modifier.clickable(onClick = toggle),
)
}
if (rows.isNotEmpty()) {
item {
Button(
onClick = {
work {
val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item })
rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) }
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " +
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")}."
}
},
enabled = !busy && rows.any { it.selected },
modifier = Modifier.padding(horizontal = 16.dp),
) { Text("Import selected") }
}
}
}
message?.let { text ->
item {
Text(text, Modifier.padding(horizontal = 16.dp),
color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface)
}
}
}
}
}
private fun name(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> item.name().ifBlank { item.address() }
is SyncItem.Identity -> "Identity: ${item.name()}"
else -> ""
}
private fun details(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> "${item.address()}:${item.port()}"
is SyncItem.Identity -> item.nickname()
else -> ""
}
private fun count(n: Int, one: String, many: String) = "$n ${if (n == 1) one else many}"
@@ -1,42 +0,0 @@
package com.ts3client.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 com.ts3client.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)
}
}
@@ -1,220 +0,0 @@
package com.ts3client.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 com.ts3client.android.Picture
import com.ts3client.android.SavedPictures
import com.ts3client.android.ServerController
import com.ts3client.android.decodePicture
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** A picture to open full size. */
class ViewedPicture(
/** What to call it when saved, without an extension. */
val name: String,
/** Where it is on the web; null for an avatar. */
val url: String? = null,
/** Follows the link it sits in; null when it sits in none. */
val openLink: (() -> Unit)? = null,
/** Our own avatar, which there is no taking. */
val ownAvatar: Boolean = false,
/** Its file; null when it is not there. */
val read: suspend () -> ByteArray?,
)
/** Opens a picture full size; null where nothing can. */
val LocalPictureViewer = staticCompositionLocalOf<((ViewedPicture) -> Unit)?> { null }
/** Lets [content] open pictures full size, over everything, with [server] to take one as our avatar on. */
@Composable
fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) {
var viewed by remember { mutableStateOf<ViewedPicture?>(null) }
CompositionLocalProvider(LocalPictureViewer provides { viewed = it }, content = content)
val context = LocalContext.current
viewed?.let { picture ->
PictureViewer(
picture,
onSteal = if (picture.ownAvatar) null else { data ->
val error = server.setAvatar(data)
Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show()
},
onDismiss = { viewed = null },
)
}
}
/** A name to save the picture at [url] under: its file's, or "picture" when it has none. */
fun pictureName(url: String): String =
url.substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/')
.substringBeforeLast('.').ifBlank { "picture" }
/** The picture on black, filling the screen; pinch or double-tap to zoom, tap to hide the bar. */
@Composable
private fun PictureViewer(
picture: ViewedPicture,
/** Takes the picture as our avatar; null when it cannot be. */
onSteal: (suspend (ByteArray) -> Unit)?,
onDismiss: () -> Unit,
) {
val state by produceState<Shown?>(null, picture) {
val data = picture.read()
value = Shown(data, data?.let { withContext(Dispatchers.Default) { decodePicture(it, MAX_PX) } })
}
val data = state?.data
var bar by remember { mutableStateOf(true) }
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
var size by remember { mutableStateOf(IntSize.Zero) }
fun panTo(target: Offset) {
val maxX = size.width * (scale - 1) / 2
val maxY = size.height * (scale - 1) / 2
offset = Offset(target.x.coerceIn(-maxX, maxX), target.y.coerceIn(-maxY, maxY))
}
Dialog(onDismiss, DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
Box(
Modifier.fillMaxSize().background(Color.Black).onSizeChanged { size = it }
.pointerInput(Unit) {
detectTapGestures(
onTap = { bar = !bar },
onDoubleTap = { scale = if (scale > 1f) 1f else DOUBLE_TAP_SCALE; panTo(Offset.Zero) },
)
}
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(1f, MAX_SCALE)
panTo(offset + pan)
}
},
contentAlignment = Alignment.Center,
) {
val shown = state?.picture
when {
state == null -> PackIcon("LOADING_IMAGE", "Loading picture")
shown == null -> PackIcon("BROKEN_IMAGE", "Broken picture")
else -> Image(
rememberPicturePainter(shown), null,
Modifier.fillMaxSize().graphicsLayer {
scaleX = scale
scaleY = scale
translationX = offset.x
translationY = offset.y
},
contentScale = ContentScale.Fit,
)
}
if (bar) {
CompositionLocalProvider(LocalContentColor provides Color.White) {
Bar(picture, data, onSteal, onDismiss, Modifier.align(Alignment.TopCenter))
}
}
}
}
}
@Composable
private fun Bar(
picture: ViewedPicture,
data: ByteArray?,
onSteal: (suspend (ByteArray) -> Unit)?,
onDismiss: () -> Unit,
modifier: Modifier,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
Row(
modifier.fillMaxWidth()
.background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.6f), Color.Transparent)))
.statusBarsPadding(),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
Box(Modifier.weight(1f))
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Picture options") }
DropdownMenu(menu, onDismissRequest = { menu = false }) {
DropdownMenuItem({ Text("Save") }, enabled = data != null, onClick = {
menu = false
val bytes = data ?: return@DropdownMenuItem
scope.launch {
val saved = SavedPictures.save(context, picture.name, bytes)
Toast.makeText(context, if (saved) "Saved." else "Could not save.", Toast.LENGTH_SHORT).show()
}
})
if (onSteal != null) {
DropdownMenuItem({ Text("Steal for avatar") }, enabled = data != null, onClick = {
menu = false
val bytes = data ?: return@DropdownMenuItem
scope.launch { onSteal(bytes) }
})
}
picture.url?.let { url ->
DropdownMenuItem({ Text("Copy URL") }, onClick = {
menu = false
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("URL", url))
})
}
picture.openLink?.let { open ->
DropdownMenuItem({ Text("Open link") }, onClick = {
menu = false
onDismiss()
open()
})
}
}
}
}
}
/** The picture's file, and the picture when the file is one; both null when it is not there. */
private class Shown(val data: ByteArray?, val picture: Picture?)
private const val MAX_PX = 4096
private const val MAX_SCALE = 8f
private const val DOUBLE_TAP_SCALE = 2.5f
@@ -1,140 +0,0 @@
package com.ts3client.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 com.ts3client.android.Picture
import com.ts3client.android.ServerImages
import com.ts3client.gfx.CountryFlags
import com.ts3client.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))
}
@@ -1,584 +0,0 @@
package com.ts3client.android.ui
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
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.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ts3client.android.ChatKey
import com.ts3client.android.ChatMatch
import com.ts3client.android.ServerController
import com.ts3client.android.ServerTree
import com.ts3client.android.SessionController
import com.ts3client.android.SessionState
import com.ts3client.android.TreeFind
import com.ts3client.android.findIn
import com.ts3client.config.Settings
import com.ts3client.net.ClientStatus
import com.ts3client.text.TsLink
import kotlinx.coroutines.flow.MutableStateFlow
private val ChatKeySaver = Saver<ChatKey, String>(
save = { key ->
when (key) {
ChatKey.Server -> "server"
ChatKey.Channel -> "channel"
is ChatKey.Private -> "private:${key.clientId}"
}
},
restore = { saved ->
when {
saved == "server" -> ChatKey.Server
saved.startsWith("private:") -> ChatKey.Private(saved.substringAfter(':').toInt())
else -> ChatKey.Channel
}
},
)
/** A connection: the channel tree and the chat, with the voice controls underneath. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ServerScreen(
vm: SessionController,
server: ServerController,
snackbar: SnackbarHostState,
onSettings: () -> Unit,
/** Opens the given client's contact page. */
onEditContact: (String) -> Unit,
onEnableMicrophone: () -> Unit,
onConnectOther: () -> Unit,
) {
val state by server.state.collectAsStateWithLifecycle()
val tree by server.tree.collectAsStateWithLifecycle()
val chats by server.chats.collectAsStateWithLifecycle()
val collapsed by server.collapsed.collectAsStateWithLifecycle()
var showChat by rememberSaveable { mutableStateOf(false) }
var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf<ChatKey>(ChatKey.Channel) }
val conversation = chats[chatKey] ?: chats.channel
var clientSheet by remember { mutableStateOf<Int?>(null) }
var clientSheetFromTree by remember { mutableStateOf(false) }
/** A row to show in the tree. */
var reveal by remember { mutableStateOf<TreeRef?>(null) }
var channelSheet by remember { mutableStateOf<Int?>(null) }
var serverSheet by remember { mutableStateOf(false) }
var banList by rememberSaveable { mutableStateOf(false) }
/** The client to move, while a channel for them is being picked. */
var moving by remember { mutableStateOf<Int?>(null) }
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
LaunchedEffect(chatRequest) {
val key = chatRequest ?: return@LaunchedEffect
chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId)
showChat = true
server.chatRequestHandled()
}
val viewing = if (showChat) conversation.key else null
LifecycleResumeEffect(viewing) {
server.viewing = viewing
onPauseOrDispose { server.viewing = null }
}
val uriHandler = LocalUriHandler.current
val onLink: (String) -> Unit = { href ->
val ref = TsLink.parse(href)
when {
ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false }
else -> channelSheet = ref.id
}
}
// Find: in the tree, clients or channels; in the chat, the conversation on screen.
val find = rememberSaveable(saver = FindState.Saver) { FindState() }
val treeFind = TreeFind(find.usable, find.channels)
val treeHits = remember(tree, treeFind) { tree.hits(treeFind) }
val treeFiltering = find.filter && !treeFind.query.isEmpty
val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree }
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet<Int>()) }
/** The match the tree is on. */
var treeAt by remember { mutableStateOf<Int?>(null) }
// Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured.
val showTreeHit = { id: Int? ->
if (id != null) {
treeAt = id
val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(treeFind.channels, id)
}
}
LaunchedEffect(treeFind, showChat) {
treeAt = null
if (!showChat) showTreeHit(treeHits.firstOrNull())
}
val chatQuery = find.usable
val chatLines = remember(conversation.lines, chatQuery, find.filter) {
if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines
}
val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) }
/** The match the chat is on; a new search starts from the newest. */
var chatAt by remember { mutableStateOf<ChatMatch?>(null) }
var chatReveal by remember { mutableStateOf<Long?>(null) }
LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) {
chatAt = if (showChat) chatHits.lastOrNull() else null
chatReveal = chatAt?.line
}
val step = { delta: Int ->
if (showChat && chatHits.isNotEmpty()) {
chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)]
chatReveal = chatAt?.line
} else if (!showChat && treeHits.isNotEmpty()) {
showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)])
}
}
if (banList) {
BanListScreen(server, vm.banReasons, onBack = { banList = false })
return
}
BackHandler(showChat) { showChat = false }
BackHandler(moving != null && !showChat) { moving = null }
BackHandler(find.open) { find.open = false }
Scaffold(
// A hardware keyboard's Ctrl+F, as on the desktop.
modifier = Modifier.onPreviewKeyEvent { e ->
val ctrlF = e.isCtrlPressed && e.key == Key.F
if (ctrlF && e.type == KeyEventType.KeyDown) find.show()
ctrlF
},
topBar = {
if (find.open) {
if (showChat) {
FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size,
chatHits.size == MAX_CHAT_MATCHES, step)
} else {
FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step)
}
} else {
TopAppBar(
title = { ServerSwitcher(vm, server, state, onConnectOther) },
expandedHeight = 48.dp,
actions = {
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
},
)
}
},
bottomBar = {
// Push-to-talk talks on whichever server holds the microphone, which need not be this one.
val owner by vm.micOwner.collectAsStateWithLifecycle()
val ownerState by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }
.collectAsStateWithLifecycle()
val ownerTree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }
.collectAsStateWithLifecycle()
val self = ownerTree.client(ownerState.selfClientId)
val talking = self?.status == ClientStatus.TALKING || self?.status == ClientStatus.COMMANDER_TALKING
VoiceBar(state, owner != null, talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) {
showChat = !showChat
}
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) {
if (!showChat) {
moving?.let { id ->
val client = tree.client(id)
if (client == null) {
LaunchedEffect(id) { moving = null }
} else {
MovePrompt(client.name) { moving = null }
}
}
ChannelTree(
serverName = state.title,
tree = shownTree,
collapsed = if (treeFiltering) filterCollapsed else collapsed,
currentChannel = state.channelId,
onToggle = {
if (!treeFiltering) server.toggleCollapsed(it.id)
else if (it.id in filterCollapsed) filterCollapsed -= it.id
else filterCollapsed += it.id
},
onChannel = { channel ->
val client = moving
when {
channel.spacer != null -> {}
client != null -> { server.moveClient(client, channel.id); moving = null }
else -> channelSheet = channel.id
}
},
onClient = { clientSheet = it.id; clientSheetFromTree = true },
onServer = { serverSheet = true },
modifier = Modifier.weight(1f),
reveal = reveal,
onRevealed = { reveal = null },
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) },
)
} else {
ChatPane(
chats = chats,
selected = conversation,
canSend = state.connected,
onSelect = { chatKey = it },
onClose = { key ->
if (chatKey == key) chatKey = ChatKey.Channel
server.closePrivateChat(key)
},
onSend = { server.send(conversation.key, it) },
onLink = onLink,
modifier = Modifier.weight(1f),
lines = chatLines,
find = chatQuery,
current = chatAt,
reveal = chatReveal,
onRevealed = { chatReveal = null },
)
}
}
}
// A sheet goes with its client or channel when that leaves the tree.
clientSheet?.let { id ->
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = { clientSheet = null },
onMessage = {
clientSheet = null
chatKey = server.openPrivateChat(id)
showChat = true
},
onPoke = { server.poke(id, it); clientSheet = null },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); clientSheet = null },
onAddContact = { server.addContact(id, it) },
onEditContact = { clientSheet = null; onEditContact(client.uniqueId) },
onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null,
onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
{ server.moveClient(id, state.channelId); clientSheet = null }
} else null,
onFindInTree = if (clientSheetFromTree) null else ({
clientSheet = null
tree.pathTo(id)?.let { server.expand(it) }
showChat = false
reveal = TreeRef(false, id)
}),
moderation = { ClientModeration(server, client) { clientSheet = null } },
)
}
}
channelSheet?.let { id ->
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = { channelSheet = null },
onJoin = { server.joinChannel(id, it); channelSheet = null },
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
)
}
}
if (serverSheet) {
remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = { serverSheet = false },
onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null)
}
}
}
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
private fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
vm: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = vm.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth())
!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() }
}
@Composable
private fun PushToTalk(talking: Boolean, onPressed: (Boolean) -> Unit, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
Surface(
modifier
.height(48.dp)
.pointerInput(Unit) {
detectTapGestures(onPress = {
onPressed(true)
try {
awaitRelease()
} finally {
onPressed(false)
}
})
},
shape = RoundedCornerShape(24.dp),
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 = MaterialTheme.typography.titleMedium)
}
}
}
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by vm.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; vm.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -1,98 +0,0 @@
package com.ts3client.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.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 com.ts3client.android.IconTheme
import com.ts3client.android.SessionController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
private enum class SettingsPage { SOUND, DESIGN, IDENTITIES, MY_TEAMSPEAK }
/**
* The settings, by category. Every change is saved and put into effect at once,
* as there is no dialog to confirm.
*/
@Composable
fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) {
var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
when (page) {
SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null })
SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null })
SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null })
SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null })
null -> {}
}
SubScreen("Settings", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
LinkRow("Contacts", "Friends and blocked users", "CONTACT", onContacts)
LinkRow("Sound Settings", "Devices, transmission, voice activation, processing, volume", "PLAYBACK") {
page = SettingsPage.SOUND
}
LinkRow("Design", "Icon pack, country flags, description pictures", "GUISETUP") {
page = SettingsPage.DESIGN
}
LinkRow("Identities", "Create, import, export, security level",
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
LinkRow("myTeamSpeak",
if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}"
else "Sign in to bring over your synchronised bookmarks and identities",
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
}
}
}
@Composable
private fun DesignScreen(vm: SessionController, onBack: () -> Unit) {
SubScreen("Design", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
IconPackPicker(vm.icons)
var flags by remember { mutableStateOf(vm.settings.countryFlags) }
Toggle("Show country flags in the channel tree", flags) {
flags = it
vm.setCountryFlags(it)
}
var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) }
Toggle("Show pictures in descriptions", pictures) {
pictures = it
vm.setDescriptionPictures(it)
}
}
}
}
/** 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) }
}
@@ -1,175 +0,0 @@
package com.ts3client.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) })
}
}
@@ -1,221 +0,0 @@
package com.ts3client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import com.ts3client.android.ChannelItem
import com.ts3client.android.ClientItem
import com.ts3client.contacts.ContactType
import com.ts3client.net.Details
import kotlin.math.roundToInt
/** What can be done with a client: the private chat, a poke, a move, their volume, filing them as a contact. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ClientSheet(
client: ClientItem,
details: Details?,
onLink: (String) -> Unit,
away: Boolean,
initialVolume: Double,
onDismiss: () -> Unit,
onMessage: () -> Unit,
onPoke: (String) -> Unit,
onVolume: (Double) -> Unit,
onAway: (Boolean) -> Unit,
onAddContact: (ContactType) -> Unit,
onEditContact: () -> Unit,
/** Null when the client cannot be moved. */
onMove: (() -> Unit)?,
/** Null when the client cannot be moved, or is in our channel already. */
onMoveToOwnChannel: (() -> Unit)?,
/** Null when the sheet was opened from the tree. */
onFindInTree: (() -> Unit)?,
/** Kicks, bans and groups, as far as we may use them. */
moderation: @Composable () -> Unit = {},
) {
var poking by remember { mutableStateOf(false) }
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
StatusIcon(client.status)
Column(Modifier.weight(1f)) {
// The country's flag goes before the name, as in TeamSpeak's info frame.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CountryFlag(client.country)
Text(client.name, style = MaterialTheme.typography.titleLarge)
}
if (client.name != client.nickname) Text(client.nickname, style = MaterialTheme.typography.bodyMedium)
if (client.awayMessage.isNotEmpty()) Text(client.awayMessage, style = MaterialTheme.typography.bodyMedium)
}
val viewer = LocalPictureViewer.current
val images = LocalServerImages.current
Avatar(client.uniqueId, client.avatarFlag, Modifier.clickable(enabled = viewer != null && images != null) {
viewer?.invoke(ViewedPicture("avatar_${client.nickname}", ownAvatar = client.self) {
images?.avatarData(client.uniqueId, client.avatarFlag)
})
})
}
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) }
if (client.self) {
Action("AWAY", if (away) "Back" else "Away") { onAway(!away) }
moderation()
} else {
Action("PLAYER_CHAT", "Send message", onClick = onMessage)
Action("POKE", "Poke") { poking = true }
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) }
moderation()
if (client.contactType == null) {
Row {
Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) }
Action("ADD_FOE", "Block", Modifier.weight(1f)) { onAddContact(ContactType.BLOCKED) }
}
} else {
Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact)
}
var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) }
Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB",
Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium)
Slider(
volume, { volume = it.roundToInt().toFloat() },
Modifier.padding(horizontal = 24.dp),
valueRange = -30f..20f,
onValueChangeFinished = { onVolume(volume.toDouble()) },
)
}
}
}
if (poking) {
TextPrompt(
title = "Poke ${client.name}",
label = "Message",
confirm = "Poke",
onDismiss = { poking = false },
onConfirm = { poking = false; onPoke(it) },
)
}
}
/** What can be done with a channel: join it, and whether to hear who is in it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChannelSheet(
channel: ChannelItem,
details: Details?,
onLink: (String) -> Unit,
current: Boolean,
onDismiss: () -> Unit,
onJoin: (String?) -> Unit,
onSubscribe: (Boolean) -> Unit,
) {
var askPassword by remember { mutableStateOf(false) }
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") {
if (channel.locked) askPassword = true else onJoin(null)
}
}
if (channel.subscribed) {
Action("UNSUBSCRIBE_FROM_CHANNEL", "Unsubscribe") { onSubscribe(false) }
} else {
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
}
}
}
if (askPassword) {
TextPrompt(
title = "Join ${channel.name}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = { askPassword = false },
onConfirm = { askPassword = false; onJoin(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, onBanList: (() -> 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)
onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) }
}
}
}
@Composable
internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifier.fillMaxWidth(), onClick: () -> Unit) {
ListItem(
headlineContent = { Text(label) },
leadingContent = { PackIcon(iconKey, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = modifier.clickable(onClick = onClick).padding(horizontal = 8.dp),
)
}
/** Asks for one line of text. */
@Composable
fun TextPrompt(
title: String,
label: String,
confirm: String,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
initial: String = "",
password: Boolean = false,
) {
var text by remember { mutableStateOf(initial) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
OutlinedTextField(text, { text = it }, label = { Text(label) }, singleLine = true,
visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None)
},
confirmButton = { TextButton(onClick = { onConfirm(text) }) { Text(confirm) } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@@ -1,260 +0,0 @@
package com.ts3client.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 com.ts3client.android.MicLevel
import com.ts3client.android.SessionController
import com.ts3client.android.audio.AudioRoute
import com.ts3client.audio.AudioDevice
import com.ts3client.audio.InputLevel
import com.ts3client.config.Settings
import kotlin.math.roundToInt
private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB")
/** Audio devices, transmission, voice activation, processing and playback. */
@Composable
fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
val settings = vm.settings
fun change(edit: Settings.() -> Unit) {
settings.edit()
vm.applySettings()
}
var inputMode by remember { mutableStateOf(settings.inputMode) }
var vadMode by remember { mutableStateOf(settings.vadMode) }
var agc by remember { mutableStateOf(settings.agc) }
var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) }
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) }
var inputDevice by remember { mutableStateOf(settings.inputDevice) }
var outputDevice by remember { mutableStateOf(settings.outputDevice) }
val inputs by vm.inputDevices.collectAsStateWithLifecycle()
val outputs by vm.outputDevices.collectAsStateWithLifecycle()
val route by vm.route.collectAsStateWithLifecycle()
val level by vm.micLevel.collectAsStateWithLifecycle()
val packs by vm.soundPacks.collectAsStateWithLifecycle()
var pack by remember { mutableStateOf(vm.soundPack?.id()) }
LifecycleStartEffect(Unit) {
vm.watchLevel(true)
onStopOrDispose { vm.watchLevel(false) }
}
SubScreen("Sound Settings", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Devices")
DevicePicker("Microphone", inputs, inputDevice) {
inputDevice = it
change { this.inputDevice = it }
}
DevicePicker("Speaker", outputs, outputDevice) {
outputDevice = it
change { this.outputDevice = it }
}
Picker(
"Microphone preset",
INPUT_PRESETS.map { (preset, label) ->
val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !vm.unprocessedSupported
preset to if (unsupported) "$label (not supported here)" else label
},
route.inputPreset(),
) { vm.setRoute(AudioRoute(it, route.usage())) }
Hint(PRESET_HINTS.getValue(route.inputPreset()))
Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp))
for ((usage, label) in USAGES) {
Choice(label, route.usage() == usage) { vm.setRoute(AudioRoute(route.inputPreset(), usage)) }
}
Section("Transmission")
for ((mode, label) in INPUT_MODES) {
Choice(label, inputMode == mode) {
inputMode = mode
change { this.inputMode = mode }
}
}
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm)
val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC
LevelMeter(level, threshold.takeIf { gated })
if (!level.live) {
Hint(if (vm.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.")
}
if (inputMode == Settings.InputMode.VOICE_ACTIVATION) {
Section("Voice activation")
for ((mode, label) in VAD_MODES) {
Choice(label, vadMode == mode) {
vadMode = mode
change { this.vadMode = mode }
}
}
if (vadMode != Settings.VadMode.AUTOMATIC) {
Level("Volume threshold", settings.vadThresholdDb.toFloat(), -50f..50f, { "${it.roundToInt()}" },
onChange = { threshold = it }) {
change { vadThresholdDb = it.roundToInt().toDouble() }
}
}
if (vadMode != Settings.VadMode.VOLUME_GATE) {
Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change { speechThreshold = it.toDouble() }
}
}
}
Section("Processing")
val suppression = if (settings.denoise) settings.denoiserLevel + 1 else 0
Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(),
{ DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) {
val step = it.roundToInt()
change {
denoise = step > 0
if (step > 0) denoiserLevel = step - 1
}
}
Toggle("Automatic gain control", agc) {
agc = it
change { this.agc = it }
}
if (agc) {
Level("Boost quiet speech", settings.agcBoostDb.toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(),
{ "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) {
change { agcBoostDb = it.roundToInt() }
}
}
Section("Playback")
Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) {
change { outputVolume = it.toDouble() }
}
Section("Notification sounds")
if (packs.isEmpty()) {
Hint("This build of the app came without sound packs.")
} else {
Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id ->
packs.firstOrNull { it.id() == id }?.let(vm::setSoundPack)
pack = id
}
}
Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change { soundVolume = it.toDouble() }
}
Toggle("Beep when talking while muted", mutedTalkWarning) {
mutedTalkWarning = it
change { this.mutedTalkWarning = it }
}
}
}
}
private val INPUT_MODES = listOf(
Settings.InputMode.VOICE_ACTIVATION to "Voice activation",
Settings.InputMode.PUSH_TO_TALK to "Push to talk",
Settings.InputMode.CONTINUOUS to "Continuous",
)
private val INPUT_PRESETS = listOf(
AudioRoute.InputPreset.VOICE_RECOGNITION to "Voice recognition",
AudioRoute.InputPreset.VOICE_COMMUNICATION to "Voice communication",
AudioRoute.InputPreset.UNPROCESSED to "Unprocessed",
AudioRoute.InputPreset.VOICE_PERFORMANCE to "Voice performance",
AudioRoute.InputPreset.GENERIC to "Generic",
AudioRoute.InputPreset.CAMCORDER to "Camcorder",
)
private val PRESET_HINTS = mapOf(
AudioRoute.InputPreset.VOICE_RECOGNITION to "Little or no processing by the phone; the client's own does the rest.",
AudioRoute.InputPreset.VOICE_COMMUNICATION to
"The phone's call processing: echo cancellation, noise suppression and gain. Works best with voices played as a call.",
AudioRoute.InputPreset.UNPROCESSED to "The raw microphone signal.",
AudioRoute.InputPreset.VOICE_PERFORMANCE to "Low latency and no processing, meant for live performance.",
AudioRoute.InputPreset.GENERIC to "The phone's default microphone source, with whatever it applies to it.",
AudioRoute.InputPreset.CAMCORDER to "Tuned for recording video, often with the rear microphone.",
)
private val USAGES = listOf(
AudioRoute.Usage.MEDIA to "As media (Bluetooth stays in high quality)",
AudioRoute.Usage.VOICE_COMMUNICATION to "As a call (lets the phone cancel echo)",
)
private val VAD_MODES = listOf(
Settings.VadMode.AUTOMATIC to "Automatic",
Settings.VadMode.VOLUME_GATE to "Volume gate",
Settings.VadMode.HYBRID to "Hybrid",
)
/** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */
@Composable
private fun FloatingButtonToggle(vm: SessionController) {
val context = LocalContext.current
val enabled by vm.pttOverlay.collectAsStateWithLifecycle()
val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (canDrawOverlays(context)) vm.setPttOverlay(true)
}
Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on ->
if (!on || canDrawOverlays(context)) vm.setPttOverlay(on)
else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")))
}
Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.")
}
/** Picks a device by its settings id; one that is not plugged in now still shows as chosen. */
@Composable
private fun DevicePicker(label: String, devices: List<AudioDevice>, selected: String, onSelect: (String) -> Unit) {
val options = devices.map { it.id() to it.label() }.let { list ->
if (list.any { it.first == selected }) list else list + (selected to "Not connected")
}
Picker(label, options, selected, onSelect)
}
/** The microphone level, lit while it would be sent, with the volume gate's threshold marked. */
@Composable
private fun LevelMeter(level: MicLevel, thresholdDb: Float?) {
val track = MaterialTheme.colorScheme.surfaceVariant
val fill = if (level.transmitting) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline
val marker = MaterialTheme.colorScheme.onSurface
fun fraction(db: Double) =
((db - InputLevel.MIN_DB) / (InputLevel.MAX_DB - InputLevel.MIN_DB)).toFloat().coerceIn(0f, 1f)
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Row {
Text("Microphone level", Modifier.weight(1f))
if (level.live) Text("${level.db.roundToInt()}", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Canvas(Modifier.fillMaxWidth().padding(top = 6.dp).height(12.dp)) {
val radius = CornerRadius(size.height / 2)
drawRoundRect(track, cornerRadius = radius)
if (level.live) {
drawRoundRect(fill, size = Size(size.width * fraction(level.db), size.height), cornerRadius = radius)
}
if (thresholdDb != null) {
val x = size.width * fraction(thresholdDb.toDouble())
drawLine(marker, Offset(x, -2.dp.toPx()), Offset(x, size.height + 2.dp.toPx()), strokeWidth = 2.dp.toPx())
}
}
}
}
@@ -1,38 +0,0 @@
package com.ts3client.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,30 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.android.audio.AudioRoute
/** Where the Android-only audio choices are kept; the rest live in the shared settings. */
class AudioRoutePrefs(context: Context) {
private val prefs = context.getSharedPreferences("audio", Context.MODE_PRIVATE)
fun load(): AudioRoute = AudioRoute(
enumOr(prefs.getString(INPUT_PRESET, null), AudioRoute.DEFAULT.inputPreset()),
enumOr(prefs.getString(USAGE, null), AudioRoute.DEFAULT.usage()),
)
fun save(route: AudioRoute) {
prefs.edit()
.putString(INPUT_PRESET, route.inputPreset().name)
.putString(USAGE, route.usage().name)
.apply()
}
private inline fun <reified E : Enum<E>> enumOr(name: String?, default: E): E =
enumValues<E>().firstOrNull { it.name == name } ?: default
private companion object {
const val INPUT_PRESET = "inputPreset"
const val USAGE = "usage"
}
}
@@ -0,0 +1,80 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Icon
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.net.IconRepository
/**
* Home-screen shortcuts that connect to a bookmark in one tap. A shortcut names its bookmark by
* [Bookmark.id], so editing the bookmark carries over and removing it disables the shortcut.
*/
internal class BookmarkShortcuts(private val context: Context, private val icons: IconTheme) {
private val manager = context.getSystemService(ShortcutManager::class.java)
val supported: Boolean get() = manager?.isRequestPinShortcutSupported == true
/** Asks the launcher to pin a shortcut; it confirms with the user itself. */
fun pin(bookmark: Bookmark) {
manager?.requestPinShortcut(info(bookmark), null)
}
/** Pinned shortcuts take on their bookmarks' current names and icons; those of removed ones stop working. */
fun sync(bookmarks: List<Bookmark>) {
val manager = manager ?: return
val byId = bookmarks.associateBy { shortcutId(it.id) }
val pinned = manager.pinnedShortcuts
val gone = pinned.map { it.id }.filter { it !in byId }
if (gone.isNotEmpty()) manager.disableShortcuts(gone, "Bookmark removed")
val kept = pinned.mapNotNull { byId[it.id] }
if (kept.isNotEmpty()) {
manager.enableShortcuts(kept.map { shortcutId(it.id) })
manager.updateShortcuts(kept.map(::info))
}
}
private fun info(bookmark: Bookmark): ShortcutInfo =
ShortcutInfo.Builder(context, shortcutId(bookmark.id))
.setShortLabel(bookmark.displayName())
.setLongLabel(listOfNotNull(bookmark.displayName(), bookmark.channel.ifBlank { null }).joinToString(" · "))
.setIcon(icon(bookmark.iconId))
.setIntent(Intent(context, MainActivity::class.java)
.setAction(ACTION_CONNECT)
.putExtra(EXTRA_BOOKMARK, bookmark.id))
.build()
/** The server's own icon as last seen there, else the pack's server icon, inside the adaptive icon's safe zone. */
private fun icon(iconId: Long): Icon {
val art = IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }
?: icons.render(listOf("SERVER_GREEN", "BOOKMARK_MANAGER"), ART_PX, 0x202020)
val canvas = Bitmap.createBitmap(ADAPTIVE_PX, ADAPTIVE_PX, Bitmap.Config.ARGB_8888)
Canvas(canvas).apply {
drawColor(BACKGROUND)
if (art != null) {
val inset = (ADAPTIVE_PX - ART_PX) / 2
drawBitmap(art, null, Rect(inset, inset, inset + ART_PX, inset + ART_PX), null)
}
}
return Icon.createWithAdaptiveBitmap(canvas)
}
companion object {
const val ACTION_CONNECT = "eu.lixko.ts3j.client.android.CONNECT_BOOKMARK"
const val EXTRA_BOOKMARK = "bookmark"
/** 108 dp at xxxhdpi; the inner 72 dp always shows, the art sits well within. */
private const val ADAPTIVE_PX = 432
private const val ART_PX = 192
private const val BACKGROUND = 0xFFE8EEF4.toInt()
private fun shortcutId(bookmarkId: String) = "bookmark:$bookmarkId"
}
}
@@ -0,0 +1,88 @@
package eu.lixko.ts3j.client.android
import androidx.compose.runtime.Immutable
import eu.lixko.ts3j.client.text.HtmlText
import eu.lixko.ts3j.client.text.TextQuery
/** Which conversation a chat line belongs to. */
sealed interface ChatKey {
data object Server : ChatKey
data object Channel : ChatKey
data class Private(val clientId: Int) : ChatKey
}
/** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */
@Immutable
data class ChatLine(val id: Long, val html: String) {
/** The text to find in. */
val plain: String by lazy { HtmlText.plain(html) }
}
@Immutable
data class Conversation(
val key: ChatKey,
val title: String,
/** The peer's unique id in a private chat, once known. */
val uniqueId: String = "",
val lines: List<ChatLine> = emptyList(),
val unread: Boolean = false,
)
/** Every conversation of the session: the server's, the channel's, then the private ones. */
@Immutable
data class Chats(
val server: Conversation = Conversation(ChatKey.Server, "Server"),
val channel: Conversation = Conversation(ChatKey.Channel, "Channel"),
val private: List<Conversation> = emptyList(),
) {
val all: List<Conversation> get() = listOf(server, channel) + private
val anyUnread: Boolean get() = all.any { it.unread }
operator fun get(key: ChatKey): Conversation? = when (key) {
ChatKey.Server -> server
ChatKey.Channel -> channel
is ChatKey.Private -> private.firstOrNull { it.key == key }
}
/** Applies [change] to a conversation, opening a private one titled [title] if needed. */
fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) {
ChatKey.Server -> copy(server = change(server))
ChatKey.Channel -> copy(channel = change(channel))
is ChatKey.Private -> {
val existing = private.indexOfFirst { it.key == key }
if (existing < 0) {
copy(private = private + change(Conversation(key, title)))
} else {
copy(private = private.toMutableList().also { it[existing] = change(it[existing]) })
}
}
}
fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key })
companion object {
/** As many lines as a log history loads; older ones leave the conversation. */
const val MAX_LINES = 1000
}
}
fun Conversation.append(line: ChatLine, read: Boolean): Conversation =
copy(lines = (lines + line).takeLast(Chats.MAX_LINES), unread = unread || !read)
/** The [nth] match of the find bar's query in the line [line]. */
data class ChatMatch(val line: Long, val nth: Int)
/** Every match of [query] in [lines], oldest first; past [limit], only the newest. */
fun findIn(lines: List<ChatLine>, query: TextQuery, limit: Int): List<ChatMatch> {
if (query.isEmpty) return emptyList()
val out = ArrayList<ChatMatch>()
for (line in lines) {
val m = query.matcher(line.plain) ?: return emptyList()
var n = 0
while (m.find()) {
if (m.end() > m.start()) out += ChatMatch(line.id, n++)
}
}
return if (out.size > limit) out.subList(out.size - limit, out.size) else out
}
@@ -0,0 +1,238 @@
package eu.lixko.ts3j.client.android
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.graphics.Color
import android.graphics.drawable.Icon
import android.net.wifi.WifiManager
import android.os.PowerManager
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.net.ClientStatus
import eu.lixko.ts3j.client.session.SelfState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/**
* Keeps the process in the foreground while connected, so the connection and its audio
* survive the app leaving the screen, and offers the essentials in its notification.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ConnectionService : LifecycleService() {
private lateinit var sessions: SessionController
private lateinit var wifiLock: WifiManager.WifiLock
private lateinit var wifiBackgroundLock: WifiManager.WifiLock
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var overlay: PttOverlay
private var foregroundTypes = 0
private var shown: ServerController? = null
override fun onCreate() {
super.onCreate()
sessions = (application as Ts3Application).sessions
getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
)
// Voice goes out every 20 ms; Wi-Fi power saving and a sleeping CPU would stretch that.
// Low-latency mode only holds while we are in the foreground with the screen on, so the
// high-performance lock keeps power saving off the rest of the time.
val wifi = getSystemService(WifiManager::class.java)
wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "ts3j:voice")
.apply { setReferenceCounted(false); acquire() }
@Suppress("DEPRECATION")
wifiBackgroundLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ts3j:voice-background")
.apply { setReferenceCounted(false); acquire() }
wakeLock = getSystemService(PowerManager::class.java)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ts3j:connection")
.apply { setReferenceCounted(false); acquire() }
show(sessions.current.value?.state?.value ?: SessionState(), capturing = false)
lifecycleScope.launch {
// The server count shows in the notification too.
combine(shownServer(), sessions.micOwner, sessions.servers) { shown, owner, _ -> shown to (owner != null) }
.conflate()
.collect { (shown, capturing) ->
if (shown != null) {
this@ConnectionService.shown = shown.first
show(shown.second, capturing)
// Talking flips the icon often, and Android drops updates that come too fast.
delay(MIN_UPDATE_MS)
}
}
}
lifecycleScope.launch {
sessions.current.flatMapLatest { it?.state ?: flowOf(null) }.collectLatest { state ->
if (state == null) {
// A reconnect leaves the server briefly; only stop once it stays gone.
delay(STOP_DELAY_MS)
stopSelf()
}
}
}
lifecycleScope.launch {
sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
}
overlay = PttOverlay(this, sessions.icons, sessions::setPushToTalk)
lifecycleScope.launch {
val owner = sessions.micOwner.flatMapLatest { server ->
server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null)
}
combine(owner, sessions.onScreen, sessions.pttOverlay) { held, onScreen, enabled ->
val (state, tree) = held ?: return@combine null
val wanted = enabled && !onScreen && state.connected && state.micActive &&
state.inputMode == Settings.InputMode.PUSH_TO_TALK
val status = tree.client(state.selfClientId)?.status
when {
!wanted -> null
state.micMuted -> PttOverlay.Look.MUTED
status == ClientStatus.TALKING || status == ClientStatus.COMMANDER_TALKING -> PttOverlay.Look.TALKING
else -> PttOverlay.Look.IDLE
}
}.distinctUntilChanged().collect { look ->
if (look == null) overlay.hide() else overlay.show(look)
}
}
}
/**
* The server the notification speaks for, as the desktop tray icon does: the one
* holding the microphone, or the visible one when nobody is capturing.
*/
private fun shownServer(): Flow<Pair<ServerController, SessionState>?> =
combine(sessions.current, sessions.micOwner) { current, owner -> current to owner }
.flatMapLatest { (current, owner) ->
combine(current?.state ?: flowOf(null), owner?.state ?: flowOf(null)) { currentState, ownerState ->
when {
owner != null && ownerState?.connected == true -> owner to ownerState
current != null && currentState != null -> current to currentState
else -> null
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val server = shown ?: sessions.current.value ?: return START_NOT_STICKY
val state = server.state.value
when (intent?.action) {
ACTION_TOGGLE_MUTE -> server.setMicMuted(!state.micMuted)
ACTION_TOGGLE_DEAFEN -> server.setDeafened(!state.deafened)
ACTION_DISCONNECT -> server.disconnect()
}
return START_NOT_STICKY
}
/**
* The user swiped the app away: they are done with it, connection included. Leaving
* properly spares the server a ghost that would hold our identity until it times out.
*/
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
lifecycleScope.launch(Dispatchers.IO) {
sessions.leave()
stopSelf()
}
}
override fun onDestroy() {
overlay.hide()
wifiLock.release()
wifiBackgroundLock.release()
wakeLock.release()
super.onDestroy()
}
/** Posts the notification, re-declaring what the service uses when that changed. */
private fun show(state: SessionState, capturing: Boolean) {
val types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or
if (capturing && hasMicPermission()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0
val notification = notification(state)
if (types != foregroundTypes) {
startForeground(NOTIFICATION_ID, notification, types)
foregroundTypes = types
} else {
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification)
}
}
private fun hasMicPermission() =
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
private fun notification(state: SessionState): Notification {
val open = PendingIntent.getActivity(
this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE
)
val others = sessions.servers.value.size - 1
return Notification.Builder(this, CHANNEL)
.setSmallIcon(statusIcon(state.self))
.setLargeIcon(largeIcon(state.self))
.setContentTitle(if (others > 0) "${state.title} +$others" else state.title)
.setContentText(state.status)
.setContentIntent(open)
.setOngoing(true)
.addAction(action(ACTION_TOGGLE_MUTE, if (state.micMuted) "Unmute" else "Mute"))
.addAction(action(ACTION_TOGGLE_DEAFEN, if (state.deafened) "Undeafen" else "Deafen"))
.addAction(action(ACTION_DISCONNECT, "Disconnect"))
.build()
}
/**
* The status bar shows only the shape of an icon, which pack art loses, so it is
* drawn from the Material pack whatever pack is chosen.
*/
private fun statusIcon(self: SelfState): Icon {
val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt()
val bitmap = sessions.icons.renderMaterial(key, size, Color.WHITE)
?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
return Icon.createWithBitmap(bitmap)
}
/** The expanded notification has room for the chosen pack's own art, as the tree draws it. */
private fun largeIcon(self: SelfState): Icon? {
val key = self.iconKey() ?: return null
val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt()
return sessions.icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500))
?.let(Icon::createWithBitmap)
}
private fun action(action: String, label: String): Notification.Action {
val intent = PendingIntent.getService(
this, action.hashCode(), Intent(this, ConnectionService::class.java).setAction(action),
PendingIntent.FLAG_IMMUTABLE
)
return Notification.Action.Builder(null, label, intent).build()
}
private companion object {
const val CHANNEL = "connection"
const val NOTIFICATION_ID = 1
const val STOP_DELAY_MS = 3_000L
const val MIN_UPDATE_MS = 250L
const val STATUS_ICON_DP = 24
const val LARGE_ICON_DP = 48
const val ACTION_TOGGLE_MUTE = "eu.lixko.ts3j.client.android.TOGGLE_MUTE"
const val ACTION_TOGGLE_DEAFEN = "eu.lixko.ts3j.client.android.TOGGLE_DEAFEN"
const val ACTION_DISCONNECT = "eu.lixko.ts3j.client.android.DISCONNECT"
}
}
@@ -0,0 +1,132 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.net.TeamspeakConnection
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.util.concurrent.atomic.AtomicLong
/** One upload or download as the file browser shows it. */
data class TransferRow(
val id: Long,
val name: String,
val upload: Boolean,
val channelId: Int,
/** The directory an upload goes into, to list again once it is there. */
val directory: String,
val transferred: Long,
val total: Long,
val state: FileTransfer.State,
val error: String?,
) {
val done: Boolean get() = state != FileTransfer.State.PENDING && state != FileTransfer.State.ACTIVE
val progress: Float get() = if (total > 0) (transferred.toFloat() / total).coerceIn(0f, 1f) else 0f
}
/**
* The channel file transfers of one server. Transfers go through files of our own in the cache,
* as the core reads and writes plain files: a download is copied where the user picked once
* complete, an upload is copied out of the picked document first. They outlive the browser page.
*/
class FileTransfers internal constructor(private val context: Context, private val conn: () -> TeamspeakConnection) {
private val ids = AtomicLong()
private val handles = HashMap<Long, FileTransfer>()
private val _rows = MutableStateFlow(emptyList<TransferRow>())
val rows: StateFlow<List<TransferRow>> = _rows
/** Downloads [file] into the document at [target]. */
fun download(channelId: Int, password: String, file: RemoteFile, target: Uri) {
val temp = File.createTempFile("download", null, context.cacheDir)
val row = add(file.name, upload = false, channelId, file.parentPath, file.size)
start(row, temp, onComplete = {
context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } }
?: throw IOException("Could not write the file")
}) { listener -> conn().downloadFile(channelId, password, file.fullPath, temp, listener) }
}
/** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */
suspend fun upload(channelId: Int, password: String, directory: String, source: Uri) {
val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) }
val row = add(name, upload = true, channelId, directory, temp.length())
start(row, temp, onComplete = {}) { listener ->
conn().uploadFile(channelId, password, directory + name, temp, true, listener)
}
}
fun cancel(id: Long) {
synchronized(handles) { handles[id] }?.cancel()
}
fun clearFinished() = _rows.update { rows -> rows.filterNot { it.done } }
private fun add(name: String, upload: Boolean, channelId: Int, directory: String, total: Long): TransferRow {
val row = TransferRow(ids.incrementAndGet(), name, upload, channelId, directory, 0, total,
FileTransfer.State.PENDING, null)
_rows.update { it + row }
return row
}
/** Runs a transfer through [temp], which goes once it is done with; [onComplete] finishes a successful one. */
private fun start(row: TransferRow, temp: File, onComplete: () -> Unit,
begin: (FileTransfer.Listener) -> FileTransfer) {
var lastUpdate = 0L
val listener = FileTransfer.Listener { t ->
val now = System.nanoTime()
// Progress comes per buffer; the list need not redraw that often.
if (!t.isDone && now - lastUpdate < UPDATE_NANOS) return@Listener
lastUpdate = now
var error = t.errorMessage
if (t.state == FileTransfer.State.COMPLETED) {
error = runCatching(onComplete).exceptionOrNull()?.let { it.message ?: "Could not save the file" }
}
if (t.isDone) {
temp.delete()
synchronized(handles) { handles.remove(row.id) }
}
val state = if (error != null) FileTransfer.State.FAILED else t.state
update(row.id) { it.copy(transferred = t.transferredBytes, total = maxOf(t.totalBytes, 0), state = state, error = error) }
}
try {
val handle = begin(listener)
synchronized(handles) { if (!handle.isDone) handles[row.id] = handle }
} catch (e: RuntimeException) {
temp.delete()
update(row.id) { it.copy(state = FileTransfer.State.FAILED, error = e.message ?: "Not connected") }
}
}
private fun update(id: Long, change: (TransferRow) -> TransferRow) =
_rows.update { rows -> rows.map { if (it.id == id) change(it) else it } }
private fun copyIn(uri: Uri): Pair<String, File> {
val resolver = context.contentResolver
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
}?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "file"
val temp = File.createTempFile("upload", null, context.cacheDir)
try {
resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } }
?: throw IOException("Could not read the file")
} catch (e: IOException) {
temp.delete()
throw e
}
// A server path takes no slashes in a file name.
return name.replace('/', '_') to temp
}
private companion object {
const val UPDATE_NANOS = 200_000_000L
}
}
@@ -0,0 +1,143 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.net.Uri
import android.provider.OpenableColumns
import android.util.LruCache
import com.caverock.androidsvg.RenderOptions
import com.caverock.androidsvg.SVG
import eu.lixko.ts3j.client.config.AppDirs
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.gfx.IconPack
import eu.lixko.ts3j.client.gfx.IconPacks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File
/**
* The icon packs the app draws with: the Material pack it ships, and TeamSpeak packs
* imported into its `gfx` folder, which are the very zips a TeamSpeak 3 install keeps in
* its own. Whatever the chosen pack lacks comes from the Material one.
*/
class IconTheme(private val context: Context, private val settings: Settings) {
private val folder = File(AppDirs.profile(), "gfx")
private val material: IconPack = IconPacks.material()
@Volatile
private var lookupOrder = listOf(material)
private val cache = LruCache<String, Bitmap>(256)
private val _packs = MutableStateFlow(emptyList<IconPack>())
val packs: StateFlow<List<IconPack>> = _packs
private val _active = MutableStateFlow(material)
val active: StateFlow<IconPack> = _active
init {
reload()
}
fun select(pack: IconPack) {
settings.iconPack = pack.id()
settings.save()
reload()
}
/**
* Copies a pack's zip into the app and switches to it.
*
* @return the pack, or `null` when the file is no icon pack
*/
fun import(uri: Uri): IconPack? {
folder.mkdirs()
val target = File(folder, displayName(uri).substringAfterLast('/').let {
if (it.endsWith(".zip", ignoreCase = true)) it else "$it.zip"
})
val staged = File(folder, target.name + ".part")
context.contentResolver.openInputStream(uri)?.use { input ->
staged.outputStream().use { input.copyTo(it) }
} ?: return null
target.delete()
staged.renameTo(target)
val pack = IconPack.load(target)
if (pack == null) {
target.delete()
return null
}
select(pack)
return _active.value
}
/**
* Draws the first of [keys] the packs have.
*
* @param rgb the colour for art that paints in the text colour
*/
fun render(keys: List<String>, size: Int, rgb: Int): Bitmap? = render(lookupOrder, keys, size, rgb)
/** Draws from the Material pack whatever pack is chosen, for chrome that must stay legible on its own colours. */
fun renderMaterial(key: String, size: Int, rgb: Int): Bitmap? = render(listOf(material), listOf(key), size, rgb)
private fun render(order: List<IconPack>, keys: List<String>, size: Int, rgb: Int): Bitmap? {
val cacheKey = "${order.first().id()}/${keys.joinToString(",")}@$size#$rgb"
cache.get(cacheKey)?.let { return it }
for (key in keys) {
for (pack in order) {
val data = pack.icon(key, size) ?: continue
val bitmap = (if (pack.isVector(key, size)) rasterize(IconPack.withCurrentColor(data, rgb), size)
else decode(data, size)) ?: continue
cache.put(cacheKey, bitmap)
return bitmap
}
}
return null
}
private fun reload() {
val packs = IconPacks.findAll(folder, null)
val active = IconPacks.select(packs, settings.iconPack) ?: material
lookupOrder = IconPacks.lookupOrder(active, packs, material)
cache.evictAll()
_packs.value = packs
_active.value = active
}
private fun displayName(uri: Uri): String =
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
if (it.moveToFirst()) it.getString(0) else null
} ?: uri.lastPathSegment ?: "iconpack.zip"
private fun rasterize(svg: ByteArray, size: Int): Bitmap? = try {
val document = SVG.getFromString(String(svg, Charsets.UTF_8))
if (document.documentViewBox == null && document.documentWidth > 0 && document.documentHeight > 0) {
document.setDocumentViewBox(0f, 0f, document.documentWidth, document.documentHeight)
}
// Otherwise the art keeps the size it was authored at inside the viewport.
document.setDocumentWidth("100%")
document.setDocumentHeight("100%")
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
document.renderToCanvas(Canvas(it), RenderOptions().viewPort(0f, 0f, size.toFloat(), size.toFloat()))
}
} catch (e: Exception) {
null
}
/** Scales a bitmap icon into the square, keeping the aspect ratio of art that is not. */
private fun decode(data: ByteArray, size: Int): Bitmap? {
val source = BitmapFactory.decodeByteArray(data, 0, data.size) ?: return null
if (source.width == size && source.height == size) return source
val factor = minOf(size.toFloat() / source.width, size.toFloat() / source.height)
val w = source.width * factor
val h = source.height * factor
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
val left = (size - w) / 2
val top = (size - h) / 2
Canvas(it).drawBitmap(source, null, RectF(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG))
}
}
}
@@ -0,0 +1,170 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityEntry
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
/** What the identity manager shows of one identity. */
data class IdentityInfo(
val id: String,
val name: String,
val uniqueId: String,
val securityLevel: Int,
val isDefault: Boolean,
val nickname: String,
val phoneticNickname: String,
)
/** A search for a better key offset under way. */
data class Improvement(val id: String, val target: Int, val reached: Int)
/**
* The identities, as TeamSpeak's Tools → Identities manages them: create, import, export,
* rename, remove, pick the default and raise the security level. Raising the level runs
* on until it is reached or stopped, whichever page is on screen.
*/
class IdentityManager(
private val context: Context,
private val store: IdentityStore,
private val settings: Settings,
private val bookmarks: Bookmarks,
private val onBookmarksChanged: () -> Unit,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val _all = MutableStateFlow(snapshot())
val all: StateFlow<List<IdentityInfo>> = _all
private val _improving = MutableStateFlow<Improvement?>(null)
val improving: StateFlow<Improvement?> = _improving
private var improvement: Job? = null
/** Picks up identities added elsewhere, such as by an import or a first connect. */
fun refresh() {
_all.value = snapshot()
}
private fun snapshot(): List<IdentityInfo> = store.all().map {
IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId,
it.nickname, it.phoneticNickname)
}
/** Generates an identity at TeamSpeak's default security level; the first one becomes the default. */
suspend fun generate(name: String): IdentityInfo = added {
store.generate(name, IdentityStore.DEFAULT_SECURITY_LEVEL)
}
/** Imports a TeamSpeak identity file, under the name it carries. */
suspend fun importFile(uri: Uri): IdentityInfo = added {
context.contentResolver.openInputStream(uri)?.use { store.importStream(it, null) }
?: throw IOException("Cannot open the file")
}
/** Imports the identities of a TeamSpeak 3 `settings.db`. */
suspend fun importFromTeamSpeak(uri: Uri): TeamSpeakImporter.Result = withContext(Dispatchers.IO) {
withLocalCopy(context, uri) { TeamSpeakImporter(store, bookmarks, settings).importIdentities(it) }
}.also {
adoptDefault(null)
refresh()
}
private suspend fun added(create: () -> IdentityEntry): IdentityInfo {
val entry = withContext(Dispatchers.IO) { create() }
adoptDefault(entry)
refresh()
return _all.value.first { it.id == entry.id }
}
/** Makes [entry], or else the first identity, the default while there is none. */
private fun adoptDefault(entry: IdentityEntry?) {
if (store.byId(settings.defaultIdentityId) != null) return
val fallback = entry ?: store.all().firstOrNull() ?: return
settings.defaultIdentityId = fallback.id
settings.save()
}
/** Writes the identity out in TeamSpeak's format, for the official client or another device. */
suspend fun export(id: String, uri: Uri) = withContext(Dispatchers.IO) {
val entry = store.byId(id) ?: return@withContext
val out = context.contentResolver.openOutputStream(uri, "wt") ?: throw IOException("Cannot write the file")
store.exportTo(entry, out)
}
fun rename(id: String, name: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
store.rename(entry, name)
refresh()
}
}
fun setNicknames(id: String, nickname: String, phoneticNickname: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
store.setNicknames(entry, nickname, phoneticNickname)
refresh()
}
}
/** The nickname of the identity a connect with [id] uses; empty when it has none. */
fun nicknameOf(id: String): String =
(store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty()
fun setDefault(id: String) {
settings.defaultIdentityId = id
settings.save()
refresh()
}
/** Deletes the identity; bookmarks that connected with it fall back to the default. */
fun remove(id: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
// Else the search would write the file back once it ends.
if (_improving.value?.id == id) improvement?.cancelAndJoin()
store.remove(entry, settings, bookmarks)
onBookmarksChanged()
refresh()
}
}
/** Searches for a key offset reaching [target], keeping the best found when stopped. */
fun improve(id: String, target: Int) {
if (improvement?.isActive == true) return
val entry = store.byId(id) ?: return
_improving.value = Improvement(id, target, entry.securityLevel)
improvement = scope.launch {
try {
store.improveSecurity(entry, target) { reached, _ ->
_improving.value = Improvement(id, target, reached)
isActive
}
} catch (e: IOException) {
// The level reached stays in memory for this run.
} finally {
_improving.value = null
refresh()
}
}
}
fun stopImproving() {
improvement?.cancel()
}
}
@@ -0,0 +1,95 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.audio.AudioBackend
import eu.lixko.ts3j.client.audio.InputLevel
import eu.lixko.ts3j.client.audio.VoiceInput
import eu.lixko.ts3j.client.config.Settings
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The microphone's level on [InputLevel]'s scale, and whether that would be sent. */
data class MicLevel(
val db: Double = InputLevel.SILENCE_DB,
val transmitting: Boolean = false,
/** Whether a microphone is being listened to at all. */
val live: Boolean = false,
)
/**
* The level meter behind the voice-activation settings. While connected it listens to the
* connection's own microphone, so it shows exactly what gets sent; otherwise it runs a test
* microphone of its own for as long as someone watches.
*/
class LevelMonitor(private val settings: Settings, private val audio: AudioBackend) {
private val _level = MutableStateFlow(MicLevel())
val level: StateFlow<MicLevel> = _level
/** The connection's microphone, when that is the one listened to. */
private var borrowed: VoiceInput? = null
private var test: VoiceInput? = null
/**
* Starts or stops listening.
*
* @param source the connection's microphone while it captures, else null
* @param busy whether a connection is under way, which will bring its own microphone
*/
@Synchronized
fun update(watching: Boolean, source: VoiceInput?, busy: Boolean, mayCapture: Boolean) {
when {
!watching -> release()
source != null -> if (borrowed !== source) {
release()
source.setLevelListener(::onLevel)
borrowed = source
}
busy || !mayCapture -> release()
test == null -> startTest()
}
}
/** The own microphone's transmit state, which the connection reports. */
fun talking(transmitting: Boolean) {
if (borrowed != null) _level.value = _level.value.copy(transmitting = transmitting)
}
/** Puts changed voice settings into effect on the test microphone. */
@Synchronized
fun apply() {
test?.let {
it.apply(settings)
it.setMode(testMode())
}
}
private fun startTest() {
release()
val input = audio.createInput(settings)
input.setMode(testMode())
input.setLevelListener(::onLevel)
input.setTalkListener { _level.value = _level.value.copy(transmitting = it) }
try {
input.start()
} catch (e: RuntimeException) {
return // no microphone to be had; the meter stays idle
}
test = input
}
private fun release() {
borrowed?.setLevelListener(null)
borrowed = null
test?.stop()
test = null
_level.value = MicLevel()
}
private fun onLevel(db: Double) {
_level.value = _level.value.copy(db = db, live = true)
}
/** Push-to-talk would never open without the button, and the test is there to tune the gate. */
private fun testMode() =
if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode
}
@@ -0,0 +1,21 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import java.io.File
import java.io.IOException
/**
* Hands [read] a temporary copy of the document at [uri], for readers that need a file they
* can seek in, which a content URI is not.
*/
internal fun <T> withLocalCopy(context: Context, uri: Uri, read: (File) -> T): T {
val copy = File.createTempFile("import", null, context.cacheDir)
try {
val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open the file")
input.use { copy.outputStream().use { out -> it.copyTo(out) } }
return read(copy)
} finally {
copy.delete()
}
}
@@ -0,0 +1,56 @@
package eu.lixko.ts3j.client.android
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import eu.lixko.ts3j.client.android.ui.App
import eu.lixko.ts3j.client.android.ui.Ts3Theme
import eu.lixko.ts3j.client.session.ServerLink
class MainActivity : ComponentActivity() {
private val sessions get() = (application as Ts3Application).sessions
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent))
setContent {
Ts3Theme { App(sessions) }
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handle(intent)
}
override fun onStart() {
super.onStart()
sessions.foreground = true
}
override fun onStop() {
sessions.foreground = false
super.onStop()
}
/** A notification opens its conversation; a `ts3server://` link or a bookmark shortcut connects, returning where. */
private fun handle(intent: Intent): ServerLink? = when (intent.action) {
Intent.ACTION_VIEW -> ServerLink.parse(intent.dataString)?.also { sessions.open(it) }
BookmarkShortcuts.ACTION_CONNECT -> intent.getStringExtra(BookmarkShortcuts.EXTRA_BOOKMARK)
?.let(sessions::openBookmark)
else -> {
openRequestedChat(intent)
null
}
}
private fun openRequestedChat(intent: Intent) {
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
if (serverId >= 0 && clientId >= 0) sessions.requestChat(serverId, clientId)
}
}
@@ -0,0 +1,141 @@
package eu.lixko.ts3j.client.android
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Person
import android.app.RemoteInput
import android.content.Context
import android.content.Intent
/**
* Tells the user about pokes and private messages while the app is out of sight. The
* notifications themselves are silent: the sound pack already plays TeamSpeak's own sound
* for either, as it does in the app.
*/
class MessageNotifier(private val context: Context) {
private val manager = context.getSystemService(NotificationManager::class.java)
private val me = Person.Builder().setName("You").build()
/** What each private conversation's notification shows, by [id] of server and peer. */
private val conversations = HashMap<Int, Conversation>()
private class Conversation(val peer: Person, val messages: MutableList<Notification.MessagingStyle.Message>)
init {
manager.createNotificationChannels(listOf(
channel(MESSAGES, R.string.messages_channel),
channel(POKES, R.string.pokes_channel),
))
}
private fun channel(id: String, name: Int) =
NotificationChannel(id, context.getString(name), NotificationManager.IMPORTANCE_HIGH).apply {
setSound(null, null)
enableVibration(true)
}
fun poke(from: String, message: String) {
val notification = Notification.Builder(context, POKES)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setContentTitle("$from poked you")
.setContentText(message.ifBlank { null })
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentIntent(open(null, null))
.setAutoCancel(true)
.build()
manager.notify(POKE_TAG, from.hashCode(), notification)
}
fun clearPokes() {
for (active in manager.activeNotifications) {
if (active.tag == POKE_TAG) manager.cancel(POKE_TAG, active.id)
}
}
/** A message the peer sent, which starts the conversation's notification if it had none. */
@Synchronized
fun received(serverId: Int, clientId: Int, from: String, text: String) {
val id = id(serverId, clientId)
val conversation = conversations[id]?.takeIf { it.peer.name == from }
?: Conversation(Person.Builder().setName(from).setKey("client:$serverId:$clientId").build(), ArrayList())
conversations[id] = conversation
add(serverId, clientId, conversation, text, conversation.peer, alert = true)
}
/** Our own reply, shown in a conversation already notified of; answers the reply action too. */
@Synchronized
fun sent(serverId: Int, clientId: Int, text: String) {
val conversation = conversations[id(serverId, clientId)] ?: return
add(serverId, clientId, conversation, text, me, alert = false)
}
private fun add(serverId: Int, clientId: Int, conversation: Conversation, text: String, sender: Person, alert: Boolean) {
conversation.messages += Notification.MessagingStyle.Message(text, System.currentTimeMillis(), sender)
if (conversation.messages.size > MAX_MESSAGES) conversation.messages.removeAt(0)
val style = Notification.MessagingStyle(me)
conversation.messages.forEach(style::addMessage)
val notification = Notification.Builder(context, MESSAGES)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setStyle(style)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentIntent(open(serverId, clientId))
.setOnlyAlertOnce(!alert)
.setAutoCancel(true)
.addAction(replyAction(serverId, clientId))
.build()
manager.notify(MESSAGE_TAG, id(serverId, clientId), notification)
}
/** The conversation came on screen, or ended with the connection. */
@Synchronized
fun clear(serverId: Int, clientId: Int) {
val id = id(serverId, clientId)
conversations.remove(id)
manager.cancel(MESSAGE_TAG, id)
}
/** The server's conversations, as its connection ended. */
@Synchronized
fun clearServer(serverId: Int) {
conversations.keys.filter { it ushr 16 == serverId }.forEach { clear(serverId, it and 0xFFFF) }
}
private fun open(serverId: Int?, clientId: Int?): PendingIntent {
val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
if (serverId != null && clientId != null) {
intent.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId)
}
return PendingIntent.getActivity(context, if (serverId != null && clientId != null) id(serverId, clientId) else -1,
intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun replyAction(serverId: Int, clientId: Int): Notification.Action {
val intent = Intent(context, ReplyReceiver::class.java)
.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId)
// Mutable: the system fills the typed reply into it.
val pending = PendingIntent.getBroadcast(context, id(serverId, clientId), intent,
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return Notification.Action.Builder(null, "Reply", pending)
.addRemoteInput(RemoteInput.Builder(KEY_REPLY).setLabel("Message").build())
.setSemanticAction(Notification.Action.SEMANTIC_ACTION_REPLY)
.build()
}
/** Client ids are 16 bits, and only unique on their server. */
private fun id(serverId: Int, clientId: Int) = serverId shl 16 or clientId
companion object {
/** The server and the client id of the private chat a notification opens or replies to. */
const val EXTRA_SERVER = "eu.lixko.ts3j.client.android.SERVER"
const val EXTRA_CHAT = "eu.lixko.ts3j.client.android.CHAT"
const val KEY_REPLY = "reply"
private const val MESSAGES = "messages"
private const val POKES = "pokes"
private const val MESSAGE_TAG = "message"
private const val POKE_TAG = "poke"
private const val MAX_MESSAGES = 25
}
}
@@ -0,0 +1,220 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import eu.lixko.ts3j.client.session.ServerSession
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.CopyOnWriteArrayList
/**
* Keeps the connections on the network Android routes over.
*
* A TS3 server knows its clients by address, so once the phone moves from Wi-Fi to mobile
* data (or back) an old connection is dead weight: it can only time out. This notices the
* move, says goodbye over the old network while that still works, and connects again over
* the new one, back into the channel we were in. A server that still holds our old
* connection may refuse the new one for a while as a clone, so a failed attempt is retried.
*
* The process's sockets are bound to the network a connection was made over. Otherwise the
* old connection would silently follow the new default network, and its goodbye would come
* from an address the server does not know. A socket keeps the network it was made on, so
* each connection remembers its own.
*/
class NetworkFollower(context: Context) {
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val follows = CopyOnWriteArrayList<Follow>()
/** The system's default network; null while there is none. */
@Volatile
private var network: Network? = null
init {
connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(available: Network) {
network = available
follows.forEach(Follow::reconsider)
}
override fun onLost(lost: Network) {
if (network == lost) network = null
follows.forEach(Follow::reconsider)
}
})
}
/** Follows [session] until [Follow.forget]. */
fun follow(session: ServerSession, onChange: () -> Unit, system: (String) -> Unit): Follow =
Follow(session, onChange, system).also(follows::add)
/** Binds new sockets to [to], or lets them go by the default network once no connection wants one. */
private fun bind(to: Network?) {
connectivity.bindProcessToNetwork(to ?: follows.firstNotNullOfOrNull { f -> f.bound.takeIf { f.wanted } })
}
inner class Follow internal constructor(
private val session: ServerSession,
private val onChange: () -> Unit,
private val system: (String) -> Unit,
) {
/** The network the connection was made over. */
@Volatile
internal var bound: Network? = null
/** The user wants to be on the server: from their connect until they, or the server, end it. */
@Volatile
internal var wanted = false
private var settle: Job? = null
@Volatile
private var recovery: Job? = null
@Volatile
private var attempt: CompletableDeferred<Boolean>? = null
/** What to show in place of the session's status while getting back on the server. */
@Volatile
var status: String? = null
private set
val isRecovering: Boolean get() = recovery?.isActive == true
/** Before a connect the user asked for, which goes over the network there is now. */
fun connecting() {
recovery?.cancel()
wanted = true
bindHere(connectivity.activeNetwork)
}
/** The user leaves the server. */
fun leaving() {
wanted = false
recovery?.cancel()
unbind()
}
/** The session is thrown away. */
fun forget() {
leaving()
follows.remove(this)
}
fun onConnected() {
attempt?.complete(true)
}
fun onDisconnected() {
val pending = attempt
when {
pending != null -> pending.complete(false)
isRecovering -> {}
// A socket on a network that went away fails at once, before we hear of the change.
wanted && networkGone() -> synchronized(this) {
if (!isRecovering) recovery = recover()
}
// The server let us go (a kick, a shutdown, a failed first connect): leave it at that.
else -> {
wanted = false
unbind()
}
}
}
/** Waits for the network to settle: a handover often shows several changes in a row. */
internal fun reconsider() {
synchronized(this) {
settle?.cancel()
settle = scope.launch {
delay(SETTLE_MS)
synchronized(this@Follow) {
if (wanted && bound != network && !isRecovering) recovery = recover()
}
}
}
}
private fun recover() = scope.launch {
try {
val back = withTimeoutOrNull(GIVE_UP_MS) {
system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…")
if (session.isBusy) session.connection().disconnectBlocking("Network changed")
var retry = RETRY_MS
while (true) {
val current = awaitNetwork()
bindHere(current)
show("Reconnecting…")
val done = CompletableDeferred<Boolean>()
attempt = done
session.reconnect()
val connected = done.await()
attempt = null
if (connected) break
if (session.connection().connectErrorId == ERROR_BANNED) break
show("Reconnecting, retrying soon…")
delay(retry)
retry = (retry * 2).coerceAtMost(MAX_RETRY_MS)
}
}
if (session.connection().connectErrorId == ERROR_BANNED) {
wanted = false
unbind()
} else if (back == null) {
system("Could not get back on the server.")
wanted = false
unbind()
}
} finally {
attempt = null
status = null
onChange()
// The network may have moved again while we were busy.
reconsider()
}
}
private fun networkGone(): Boolean {
val on = bound ?: return false
return connectivity.getNetworkCapabilities(on) == null || connectivity.activeNetwork != on
}
private suspend fun awaitNetwork(): Network {
while (true) {
connectivity.activeNetwork?.let { return it }
show("Waiting for network…")
delay(POLL_MS)
}
}
private fun show(text: String) {
status = text
onChange()
}
private fun bindHere(to: Network?) {
bound = to
bind(to)
}
private fun unbind() {
bound = null
bind(null)
}
}
private companion object {
const val SETTLE_MS = 1_500L
/** The server's refusal for a banned client; asking again will not help. */
const val ERROR_BANNED = 3329
const val RETRY_MS = 5_000L
const val MAX_RETRY_MS = 30_000L
const val POLL_MS = 500L
const val GIVE_UP_MS = 5 * 60_000L
}
}
@@ -0,0 +1,42 @@
package eu.lixko.ts3j.client.android
import android.graphics.ImageDecoder
import android.graphics.drawable.AnimatedImageDrawable
import android.graphics.drawable.BitmapDrawable
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import java.nio.ByteBuffer
/** An avatar or a picture from a description: still, or moving like an animated GIF. */
sealed interface Picture {
val width: Int
val height: Int
data class Still(val bitmap: ImageBitmap) : Picture {
override val width get() = bitmap.width
override val height get() = bitmap.height
}
/** Shared by whatever shows it: one animation, drawn wherever it is on screen. */
data class Moving(val drawable: AnimatedImageDrawable) : Picture {
override val width get() = drawable.intrinsicWidth
override val height get() = drawable.intrinsicHeight
}
}
/** Decodes any image Android knows, no larger than [maxPx] on its longer side; null if it is none. */
internal fun decodePicture(data: ByteArray, maxPx: Int): Picture? = try {
val drawable = ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ ->
val largest = maxOf(info.size.width, info.size.height)
if (largest > maxPx) {
decoder.setTargetSize(info.size.width * maxPx / largest, info.size.height * maxPx / largest)
}
}
when (drawable) {
is AnimatedImageDrawable -> Picture.Moving(drawable)
is BitmapDrawable -> Picture.Still(drawable.bitmap.asImageBitmap())
else -> null
}
} catch (e: Exception) {
null
}
@@ -0,0 +1,176 @@
package eu.lixko.ts3j.client.android
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.provider.Settings
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
/**
* A push-to-talk button floating over other apps. Holding it talks; a double tap whose
* second touch is held moves it instead, so moving never transmits more than the first tap.
*/
class PttOverlay(
private val context: Context,
private val icons: IconTheme,
private val onPressed: (Boolean) -> Unit,
) {
enum class Look { IDLE, TALKING, MUTED }
private val windows = context.getSystemService(WindowManager::class.java)
private val prefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val size = (SIZE_DP * context.resources.displayMetrics.density).toInt()
private var button: Button? = null
/** Shows the button, or updates it when it is up; nothing while the app may not draw over others. */
fun show(look: Look) {
button?.let {
it.look = look
return
}
if (!Settings.canDrawOverlays(context)) return
val params = WindowManager.LayoutParams(
size, size,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT,
).apply {
gravity = Gravity.TOP or Gravity.START
val screen = windows.currentWindowMetrics.bounds
x = prefs.getInt(POS_X, screen.width() - size - size / 4)
y = prefs.getInt(POS_Y, screen.height() / 2)
}
val view = Button(params).also { it.look = look }
try {
windows.addView(view, params)
} catch (e: WindowManager.BadTokenException) {
// The permission went away since the check.
return
}
button = view
}
fun hide() {
val view = button ?: return
button = null
view.release()
windows.removeView(view)
}
@SuppressLint("ViewConstructor")
private inner class Button(private val params: WindowManager.LayoutParams) : View(context) {
var look = Look.IDLE
set(value) {
field = value
restyle()
}
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout().toLong()
private var pressed = false
private var dragging = false
private var lastTapUp = 0L
private var grabX = 0f
private var grabY = 0f
init {
contentDescription = "Push to talk"
alpha = RESTING_ALPHA
}
/** Half see-through at rest, so it hides less of the app beneath; solid while it talks. */
private fun restyle() {
alpha = if (pressed || look == Look.TALKING) 1f else RESTING_ALPHA
invalidate()
}
override fun onDraw(canvas: Canvas) {
val radius = width / 2f
val lit = pressed || look == Look.TALKING
paint.color = when {
look == Look.MUTED -> MUTED
lit -> TALKING
else -> IDLE
}
canvas.drawCircle(radius, radius, radius, paint)
if (lit) {
paint.color = Color.WHITE
paint.style = Paint.Style.STROKE
paint.strokeWidth = radius / 12
canvas.drawCircle(radius, radius, radius - paint.strokeWidth, paint)
paint.style = Paint.Style.FILL
}
val iconSize = width / 2
icon(iconSize)?.let {
val offset = (width - iconSize) / 2f
canvas.drawBitmap(it, offset, offset, null)
}
}
private fun icon(size: Int): Bitmap? =
icons.renderMaterial(if (look == Look.MUTED) "INPUT_MUTED" else "CAPTURE", size, Color.WHITE)
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(e: MotionEvent): Boolean {
when (e.actionMasked) {
MotionEvent.ACTION_DOWN -> {
dragging = e.eventTime - lastTapUp < doubleTapTimeout
if (dragging) {
grabX = e.rawX - params.x
grabY = e.rawY - params.y
} else {
press(true)
}
}
MotionEvent.ACTION_MOVE -> if (dragging) moveTo(e.rawX - grabX, e.rawY - grabY)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
val tap = !dragging && e.eventTime - e.downTime < doubleTapTimeout
lastTapUp = if (tap) e.eventTime else 0L
if (dragging) {
dragging = false
prefs.edit().putInt(POS_X, params.x).putInt(POS_Y, params.y).apply()
} else {
press(false)
}
}
}
return true
}
private fun moveTo(x: Float, y: Float) {
val screen = windows.currentWindowMetrics.bounds
params.x = x.toInt().coerceIn(0, screen.width() - width)
params.y = y.toInt().coerceIn(0, screen.height() - height)
windows.updateViewLayout(this, params)
}
private fun press(down: Boolean) {
if (pressed == down) return
pressed = down
onPressed(down)
restyle()
}
/** Lets go of the microphone should the button vanish under the finger. */
fun release() = press(false)
}
private companion object {
const val SIZE_DP = 64
const val RESTING_ALPHA = 0.5f
const val POS_X = "x"
const val POS_Y = "y"
val IDLE = Color.rgb(0x1C, 0x6F, 0xB8)
val TALKING = Color.rgb(0x2E, 0x9B, 0xF0)
val MUTED = Color.rgb(0x42, 0x42, 0x42)
}
}
@@ -0,0 +1,17 @@
package eu.lixko.ts3j.client.android
import android.app.RemoteInput
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
/** Sends what the user typed into a private message notification. */
class ReplyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
val text = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(MessageNotifier.KEY_REPLY)?.toString()
if (serverId < 0 || clientId < 0 || text.isNullOrBlank()) return
(context.applicationContext as Ts3Application).sessions.reply(serverId, clientId, text)
}
}
@@ -0,0 +1,39 @@
package eu.lixko.ts3j.client.android
import android.content.ContentValues
import android.content.Context
import android.graphics.BitmapFactory
import android.os.Environment
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/** Puts pictures into the shared Pictures collection, in a TeamSpeak album, where galleries find them. */
object SavedPictures {
/** Saves [data] as [name], its extension following what the data is; false if it could not be. */
suspend fun save(context: Context, name: String, data: ByteArray): Boolean = withContext(Dispatchers.IO) {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
val mime = bounds.outMimeType ?: return@withContext false
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, if (extension == null) name else "$name.$extension")
put(MediaStore.Images.Media.MIME_TYPE, mime)
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/TeamSpeak")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), values)
?: return@withContext false
try {
resolver.openOutputStream(uri)!!.use { it.write(data) }
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
true
} catch (e: Exception) {
resolver.delete(uri, null, null)
false
}
}
}
@@ -0,0 +1,582 @@
package eu.lixko.ts3j.client.android
import android.net.Uri
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.net.ChannelNode
import eu.lixko.ts3j.client.net.ClientEntry
import eu.lixko.ts3j.client.net.ChannelSettings
import eu.lixko.ts3j.client.net.ConnectionStats
import eu.lixko.ts3j.client.net.Details
import eu.lixko.ts3j.client.net.GroupChoice
import eu.lixko.ts3j.client.net.Whisper
import eu.lixko.ts3j.client.net.ban.BanEntry
import eu.lixko.ts3j.client.net.ban.BanRule
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope
import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.text.ChatHtml
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* One server the app is on: its [ServerSession], and the snapshots the UI shows of it. Session
* callbacks arrive on connection threads and are turned into immutable snapshots.
*/
class ServerController internal constructor(
/** Unique among the servers of this process run. */
val id: Int,
private val app: SessionController,
) {
internal val session = ServerSession(
app.settings, app.identityStore, app.audio, app.sounds, app.contactStore, Listener()
)
internal val conn get() = session.connection()
private val network = app.network.follow(session, ::refresh, ::system)
/** Whether this server holds the microphone; set by [SessionController] as it moves. */
@Volatile
internal var micOwner = false
/** Set once connecting began, so a session that never started is not taken for one that ended. */
@Volatile
private var started = false
/** Set when the user left, so the end needs no telling. */
@Volatile
internal var left = false
private val _state = MutableStateFlow(SessionState())
val state: StateFlow<SessionState> = _state
private val _tree = MutableStateFlow(ServerTree())
val tree: StateFlow<ServerTree> = _tree
private val _chats = MutableStateFlow(Chats())
val chats: StateFlow<Chats> = _chats
/** Channels the user folded away in the tree. */
private val _collapsed = MutableStateFlow(emptySet<Int>())
val collapsed: StateFlow<Set<Int>> = _collapsed
/** The conversation on screen, whose new lines are read as they come. */
@Volatile
var viewing: ChatKey? = null
set(value) {
field = value
if (value != null) markRead(value)
if (value is ChatKey.Private) app.notifier.clear(id, value.clientId)
}
/** Counts the answers to info requests, for the details on screen to be read again. */
private val _infoUpdates = MutableStateFlow(0)
val infoUpdates: StateFlow<Int> = _infoUpdates
val images = ServerImages(conn)
/** A private chat a notification asked to show, until the UI took it up. */
private val _chatRequest = MutableStateFlow<ChatKey.Private?>(null)
val chatRequest: StateFlow<ChatKey.Private?> = _chatRequest
private val lineIds = AtomicLong()
/** Tree snapshots are taken one at a time, at most once per [TREE_FRAME_MS]. */
private val treeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default.limitedParallelism(1))
private val treePending = AtomicBoolean()
private val structureChanged = AtomicBoolean(true)
private var roots: List<ChannelNode> = emptyList()
val isConnected: Boolean get() = session.isConnected
internal val isBusy: Boolean get() = session.isBusy || network.isRecovering
internal val microphone get() = if (session.isConnected) conn.microphone else null
internal val playback get() = if (session.isConnected) conn.playback else null
/** Not on the server and not trying to get back on it: done with. */
internal val ended: Boolean get() = started && !isBusy
// ---- connection ----
internal fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
channel: String, channelPassword: String) {
network.connecting()
started = true
session.connect(host, port, nickname, password, identityId, channel, channelPassword)
refresh()
}
internal fun open(link: ServerLink, identityId: String) {
network.connecting()
started = true
session.open(link, identityId)
refresh()
}
/** A bookmark leading back to this server, joining [channelId]; not yet saved. */
fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId))
fun disconnect() {
left = true
network.leaving()
session.disconnect()
}
/** Before the app goes away with the connection, which [SessionController.leave] then ends. */
internal fun leaving() {
left = true
network.leaving()
}
internal fun dispose() {
network.forget()
treeScope.cancel()
session.dispose()
}
// ---- the local client ----
fun setMicMuted(muted: Boolean) = session.setMicMuted(muted)
fun setDeafened(deafened: Boolean) = session.setDeafened(deafened)
fun setAway(away: Boolean) = session.setAway(away, null)
// ---- channels and clients ----
fun joinChannel(channelId: Int, password: String? = null) {
if (session.isConnected) conn.joinChannel(channelId, password)
}
fun setSubscribed(channelId: Int, subscribed: Boolean) {
if (session.isConnected) conn.setChannelsSubscribed(listOf(channelId), subscribed)
}
fun toggleCollapsed(channelId: Int) =
_collapsed.update { if (channelId in it) it - channelId else it + channelId }
fun expand(channelIds: Collection<Int>) = _collapsed.update { it - channelIds.toSet() }
val canMoveClients: Boolean get() = session.canMoveClients()
fun moveClient(clientId: Int, channelId: Int) {
if (session.isConnected) conn.moveClient(clientId, channelId, null)
}
fun poke(clientId: Int, message: String) {
if (session.isConnected) conn.poke(clientId, message)
}
/** The client's playback volume change in dB; 0 when unchanged. */
fun clientVolume(clientId: Int): Double =
conn.model.getClient(clientId)?.let { conn.getClientVolumeModifier(it) } ?: 0.0
fun setClientVolume(clientId: Int, decibels: Double) {
conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) }
}
// ---- whisper ----
fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper)
fun whisperToChannel(channelId: Int) = conn.model.getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) }
fun whisperToClient(clientId: Int) = conn.model.getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) }
/** The client who whispered to us last, while on the server. */
fun lastWhisperer(): ClientEntry? = session.lastWhisperer()
/** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */
fun channelRef(channelId: Int): String? = conn.model.getChannel(channelId)?.let { conn.model.channelPath(it.id) }
fun clientRef(clientId: Int): WhisperList.Client? =
conn.model.getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) }
/** The clients on the server, for adding to a whisper list; ourselves left out. */
fun clientRefs(): List<WhisperList.Client> = if (!session.isConnected) emptyList()
else conn.model.allClients().filter { it.id != conn.selfClientId && !it.uniqueId.isNullOrEmpty() }
.sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) }
fun channelPaths(): List<String> = session.channelPaths()
// ---- channel administration ----
val canCreateChannels: Boolean get() = session.canCreateChannels()
val canEditChannels: Boolean get() = session.canEditChannels()
val canDeleteChannels: Boolean get() = session.canDeleteChannels()
/** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */
fun sortChoices(channelId: Int, parentId: Int): List<ChannelNode> =
if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId)
/** A channel's editable properties as the server has them. */
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = suspendCoroutine { done ->
conn.requestChannelSettings(channelId) { settings, error ->
done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */
suspend fun editChannel(channelId: Int, changes: Map<String, String>): String? =
if (changes.isEmpty()) null
else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } }
suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done ->
conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) }
}
/** Deletes a channel, with its sub-channels and the clients in it moved out. */
suspend fun deleteChannel(channelId: Int): String? =
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
// ---- files ----
val files = app.fileTransfers { conn }
/** The files in a directory of a channel's repository; empty for an empty one. */
suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> =
withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } }
/** Each of these answers null once done, else why not. */
suspend fun createDirectory(channelId: Int, password: String, path: String): String? =
fileCall { conn.createDirectory(channelId, password, path) }
suspend fun deleteFile(channelId: Int, password: String, path: String): String? =
fileCall { conn.deleteFile(channelId, password, path) }
suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? =
fileCall { conn.renameFile(channelId, password, from, to) }
private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) {
runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName }
}
// ---- moderation ----
val canKickFromChannel: Boolean get() = session.canKickFromChannel()
val canKickFromServer: Boolean get() = session.canKickFromServer()
val canBanClients: Boolean get() = session.canBanClients()
val canViewBanList: Boolean get() = session.canViewBanList()
val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create")
/** The longest ban we may hand out in seconds; 0 or -1 for no limit. */
val maxBanSeconds: Long get() = conn.model.maxBanSeconds()
fun kickFromChannel(clientId: Int, reason: String) {
if (session.isConnected) conn.kickFromChannel(clientId, reason)
}
fun kickFromServer(clientId: Int, reason: String) {
if (session.isConnected) conn.kickFromServer(clientId, reason)
}
/** Bans a client for [seconds], or for good with 0. */
fun ban(clientId: Int, seconds: Long, reason: String) {
if (session.isConnected) conn.banClient(clientId, seconds, reason)
}
fun serverGroupChoices(clientId: Int): List<GroupChoice> =
conn.model.getClient(clientId)?.let(conn.model::serverGroupChoices).orEmpty()
fun channelGroupChoices(clientId: Int): List<GroupChoice> =
conn.model.getClient(clientId)?.let(conn.model::channelGroupChoices).orEmpty()
fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) {
val client = conn.model.getClient(clientId) ?: return
if (session.isConnected) conn.setClientServerGroup(client.databaseId, groupId, assign)
}
/** Gives a client [groupId] in the channel they are in. */
fun setChannelGroup(clientId: Int, groupId: Int) {
val client = conn.model.getClient(clientId) ?: return
if (session.isConnected) conn.setClientChannelGroup(client.databaseId, client.channelId, groupId)
}
// ---- ban list ----
/** The server's bans, or why they could not be read. */
/** One reading of a client's connection figures, or null when not connected. */
suspend fun connectionStats(clientId: Int): ConnectionStats? =
if (!session.isConnected) null
else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } }
suspend fun banList(): Result<List<BanEntry>> = suspendCoroutine { done ->
conn.requestBanList { bans, error ->
done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */
suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } }
suspend fun replaceBan(banId: Int, rule: BanRule): String? =
suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } }
suspend fun deleteBans(banIds: Collection<Int>): String? =
suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } }
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId)
fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId)
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId)
/** Uploads [data] as our avatar; null once it is set, else why not. */
suspend fun setAvatar(data: ByteArray): String? {
if (!session.isConnected) return "Not connected"
val file = withContext(Dispatchers.IO) {
File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) }
}
return try {
suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } }
} finally {
file.delete()
}
}
// ---- details ----
fun serverDetails(): Details? =
if (session.isConnected) Details.server(conn.model, "${conn.serverHost}:${conn.serverPort}") else null
fun channelDetails(channelId: Int): Details? = conn.model.getChannel(channelId)?.let(Details::channel)
fun clientDetails(clientId: Int): Details? = conn.model.getClient(clientId)?.let {
Details.client(it, conn.model, app.contactStore.find(it.uniqueId))
}
/** Asks the server for what the channel's details lack; they change once it answers. */
fun requestChannelDetails(channelId: Int) {
val channel = conn.model.getChannel(channelId) ?: return
if (session.isConnected && !channel.descriptionLoaded) conn.requestChannelInfo(channelId)
}
fun requestClientDetails(clientId: Int) {
if (session.isConnected) conn.requestClientInfo(clientId)
}
/** Files a client on the server as a contact; a new entry takes the type's defaults. */
fun addContact(clientId: Int, type: ContactType) {
val client = conn.model.getClient(clientId) ?: return
app.contactStore.add(client.uniqueId, client.nickname, type, app.settings.contactDefaults)
}
internal fun contactsChanged() {
treeScope.launch { conn.applyContacts() }
scheduleTree(structure = false)
}
// ---- chat ----
/** Opens the private chat with a client, loading what was said before. */
fun openPrivateChat(clientId: Int): ChatKey.Private {
val key = ChatKey.Private(clientId)
val client = conn.model.getClient(clientId)
if (client != null) {
_chats.update { chats ->
chats.update(key, conn.displayName(client)) { it.copy(uniqueId = client.uniqueId) }
}
conn.loadPrivateChatHistory(clientId, client.uniqueId)
}
return key
}
fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) }
fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text)
/** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */
suspend fun sendFile(key: ChatKey, uri: Uri) {
app.openShared(uri)
.onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) }
.onFailure { app.error(it.message ?: "Could not read the file") }
}
private fun scope(key: ChatKey) = when (key) {
ChatKey.Server -> ChatScope.SERVER
ChatKey.Channel -> ChatScope.CHANNEL
is ChatKey.Private -> ChatScope.PRIVATE
}
private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0
/** Where files shared on this server lie; empty before it is known. */
private val room: String get() = conn.serverUniqueId().orEmpty()
fun markRead(key: ChatKey) {
if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } }
}
internal fun requestChat(clientId: Int) {
_chatRequest.value = ChatKey.Private(clientId)
}
fun chatRequestHandled() {
_chatRequest.value = null
}
/** Answers a private message from its notification. */
internal fun reply(clientId: Int, text: String) {
if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId)
}
private fun append(key: ChatKey, title: String, html: String) {
if (html.isEmpty()) return
val line = ChatLine(lineIds.incrementAndGet(), html)
_chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } }
}
private fun setHistory(key: ChatKey, title: String, entries: List<String>) {
val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() }
.map { ChatLine(lineIds.incrementAndGet(), it) }
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
}
private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text))
// ---- snapshots ----
private fun snapshotState(): SessionState {
val self = conn.model.getClient(conn.selfClientId)
return SessionState(
title = session.title(),
status = network.status ?: session.status(),
connected = session.isConnected,
busy = isBusy,
micActive = micOwner && app.hasMicPermission(),
micPermission = app.hasMicPermission(),
micMuted = session.isMicMuted,
deafened = session.isDeafened,
away = session.isAway,
selfClientId = if (session.isConnected) conn.selfClientId else 0,
channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
inputMode = app.settings.inputMode,
hostButton = if (session.isConnected) conn.model.hostButton() else null,
self = session.selfState(),
whisper = session.whisper()?.label,
whisperNobody = session.isWhisperingToNobody,
)
}
internal fun refresh() {
_state.value = snapshotState()
app.serverChanged(this)
}
/** Takes a new tree snapshot soon; [structure] when channels or clients came, went or moved. */
internal fun scheduleTree(structure: Boolean) {
if (structure) structureChanged.set(true)
if (!treePending.compareAndSet(false, true)) return
treeScope.launch {
delay(TREE_FRAME_MS)
treePending.set(false)
if (structureChanged.getAndSet(false)) roots = conn.model.buildTree()
_tree.value = ServerTree.of(roots, conn.model, conn.contacts, app.settings.colorContacts,
app.settings.countryFlags, app.settings.clientRowColors)
val serverName = if (session.isConnected) conn.model.serverName.orEmpty() else ""
val channelName = session.currentChannel()?.name.orEmpty()
_chats.update {
it.copy(
server = it.server.copy(title = serverName.ifBlank { "Server" }),
channel = it.channel.copy(title = channelName.ifBlank { "Channel" }),
)
}
refresh()
}
}
private inner class Listener : ServerSession.Listener {
override fun onSessionChanged() = refresh()
override fun onSystemMessage(text: String) = system(text)
override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) {
val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname
val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text, room)
append(key(scope, peerClientId), peerName, html)
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text))
}
override fun onStatus(status: String) {}
override fun onConnected() {
network.onConnected()
app.connected(this@ServerController)
refresh()
}
override fun onDisconnected(reason: String?) {
network.onDisconnected()
app.notifier.clearServer(id)
_chats.update { it.copy(private = emptyList()) }
app.disconnected(this@ServerController)
scheduleTree(structure = true)
refresh()
}
override fun onModelChanged() {
scheduleTree(structure = true)
// A server edit may have changed it.
if (session.isConnected && conn.model.hostButton() != _state.value.hostButton) refresh()
}
override fun onServerIconChanged(iconId: Long) =
app.serverIconChanged(session.address(), session.port(), iconId)
override fun onInfoUpdated() {
_infoUpdates.update { it + 1 }
// Avatars announce their arrival as info updates.
images.loaded()
}
override fun onIconsUpdated() = images.loaded()
override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) {
append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room))
if (scope == ChatScope.PRIVATE && !app.foreground) {
app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
}
}
override fun onChatHistory(scope: ChatScope, htmlEntries: List<String>) {
if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries)
}
override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List<String>) =
setHistory(ChatKey.Private(clientId), nickname, htmlEntries)
override fun onTalkStateChanged(clientId: Int, talking: Boolean) {
if (clientId == conn.selfClientId && micOwner) app.talking(talking)
scheduleTree(structure = false)
}
override fun onError(message: String) = app.error(message)
override fun onPoke(fromName: String, message: String) = app.poked(fromName, message)
override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message))
override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room))
}
private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) {
ChatScope.SERVER -> ChatKey.Server
ChatScope.CHANNEL -> ChatKey.Channel
ChatScope.PRIVATE -> ChatKey.Private(peerClientId)
}
private companion object {
const val TREE_FRAME_MS = 30L
}
}
@@ -0,0 +1,61 @@
package eu.lixko.ts3j.client.android
import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import eu.lixko.ts3j.client.net.TeamspeakConnection
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.util.concurrent.ConcurrentHashMap
/**
* One server's icons and its clients' avatars, decoded once. What is still
* downloading reads as null until [version] moves on.
*/
class ServerImages internal constructor(private val conn: TeamspeakConnection) {
private val icons = ConcurrentHashMap<Long, ImageBitmap>()
private val avatars = ConcurrentHashMap<String, Picture>()
private val _version = MutableStateFlow(0)
val version: StateFlow<Int> = _version
internal fun loaded() = _version.update { it + 1 }
fun icon(id: Long): ImageBitmap? {
if (id == 0L) return null
icons[id]?.let { return it }
val bitmap = conn.icons.get(id)?.let { decode(it, ICON_PX) } ?: return null
icons[id] = bitmap
return bitmap
}
fun avatar(uniqueId: String, flag: String): Picture? {
if (flag.isEmpty()) return null
avatars[flag]?.let { return it }
val picture = conn.avatars.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null
avatars[flag] = picture
return picture
}
/** The avatar's file as the server keeps it; null while it has none or it is still downloading. */
fun avatarData(uniqueId: String, flag: String): ByteArray? =
if (flag.isEmpty()) null else conn.avatars.get(uniqueId, flag)?.data()
/** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */
private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2
val options = BitmapFactory.Options().apply { inSampleSize = sample }
return BitmapFactory.decodeByteArray(data, 0, data.size, options)?.asImageBitmap()
}
private companion object {
const val ICON_PX = 64
const val AVATAR_PX = 512
}
}
@@ -0,0 +1,192 @@
package eu.lixko.ts3j.client.android
import androidx.compose.runtime.Immutable
import eu.lixko.ts3j.client.config.ClientRowColors
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.net.ChannelNode
import eu.lixko.ts3j.client.net.ClientEntry
import eu.lixko.ts3j.client.net.ClientStatus
import eu.lixko.ts3j.client.net.ServerModel
import eu.lixko.ts3j.client.net.Spacers
import eu.lixko.ts3j.client.net.TreeMatch
import eu.lixko.ts3j.client.text.TextQuery
/**
* A copy of the channel tree taken at one moment. The model's own nodes change in place
* on connection threads, which Compose cannot observe; these never change.
*/
@Immutable
data class ServerTree(
val channels: List<ChannelItem> = emptyList(),
/** The server's own icon; 0 for none. */
val serverIconId: Long = 0,
/** Whether client rows show their country's flag. */
val countryFlags: Boolean = false,
) {
fun channel(id: Int): ChannelItem? = find(channels) { it.id == id }
fun client(id: Int): ClientItem? {
var found: ClientItem? = null
find(channels) { c -> found = c.clients.firstOrNull { it.id == id }; found != null }
return found
}
/** The channels from the root down to the one [clientId] is in; null when they are not in the tree. */
fun pathTo(clientId: Int): List<Int>? {
fun walk(items: List<ChannelItem>): List<Int>? {
for (c in items) {
if (c.clients.any { it.id == clientId }) return listOf(c.id)
walk(c.children)?.let { return listOf(c.id) + it }
}
return null
}
return walk(channels)
}
/** The channels from the root down to [channelId]'s parent; null when it is not in the tree. */
fun parentsOf(channelId: Int): List<Int>? {
fun walk(items: List<ChannelItem>, above: List<Int>): List<Int>? {
for (c in items) {
if (c.id == channelId) return above
walk(c.children, above + c.id)?.let { return it }
}
return null
}
return walk(channels, emptyList())
}
/** The ids of what [find] matches, in reading order. */
fun hits(find: TreeFind): List<Int> {
val out = ArrayList<Int>()
fun walk(items: List<ChannelItem>) {
for (c in items) {
if (find.matches(c)) out += c.id
c.clients.forEach { if (find.matches(it)) out += it.id }
walk(c.children)
}
}
if (!find.query.isEmpty) walk(channels)
return out
}
/** Only what [find] matches: a matching channel with its clients, a matching client, and the channels leading to either. */
fun only(find: TreeFind): ServerTree {
fun keep(c: ChannelItem): ChannelItem? {
val matches = find.matches(c)
val clients = if (matches) c.clients else c.clients.filter(find::matches)
val children = c.children.mapNotNull(::keep)
return if (matches || clients.isNotEmpty() || children.isNotEmpty()) c.copy(clients = clients, children = children) else null
}
return copy(channels = channels.mapNotNull(::keep))
}
private fun find(items: List<ChannelItem>, test: (ChannelItem) -> Boolean): ChannelItem? {
for (c in items) {
if (test(c)) return c
find(c.children, test)?.let { return it }
}
return null
}
companion object {
fun of(roots: List<ChannelNode>, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
countryFlags: Boolean, rowColors: ClientRowColors): ServerTree =
ServerTree(
roots.map { channel(it, model, contacts, colorContacts, rowColors) },
model.serverIconId(),
countryFlags,
)
private fun channel(c: ChannelNode, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
rowColors: ClientRowColors): ChannelItem {
val clients = c.clients
val spacer = Spacers.parse(c.name)
return ChannelItem(
id = c.id,
name = c.name ?: "",
spacer = spacer,
iconId = if (spacer == null) c.iconId else 0,
locked = c.hasPassword,
full = c.maxClients >= 0 && clients.size >= c.maxClients,
subscribed = c.subscribed,
clients = clients.map { client(it, model, contacts, colorContacts, rowColors) },
children = c.children.map { channel(it, model, contacts, colorContacts, rowColors) },
)
}
private fun client(c: ClientEntry, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
rowColors: ClientRowColors): ClientItem {
val contact = contacts.find(c.uniqueId)
val away = c.away && c.awayMessage.isNotEmpty() && contact?.ignoreAwayMessage != true
val status = ClientStatus.of(c)
return ClientItem(
id = c.id,
uniqueId = c.uniqueId,
nickname = c.nickname ?: "",
name = contact?.displayName(c.nickname) ?: c.nickname ?: "",
awayMessage = if (away) c.awayMessage else "",
status = status,
background = rowColors.of(status),
self = c.self,
contactType = contact?.type,
highlight = if (colorContacts) contact?.type ?: ContactType.NEUTRAL else ContactType.NEUTRAL,
groupIconIds = (model.serverGroupsOf(c.serverGroupIds) + listOfNotNull(model.channelGroup(c.channelGroupId)))
.map { it.iconId }.filter { it != 0L },
avatarFlag = c.avatarFlag.orEmpty(),
country = c.country.orEmpty(),
serverGroupIds = c.serverGroupIds.toList(),
channelGroupId = c.channelGroupId,
)
}
}
}
/** What the find bar looks for in the tree: clients, or with [channels] channels. */
@Immutable
data class TreeFind(val query: TextQuery, val channels: Boolean) {
fun matches(c: ChannelItem) = channels && TreeMatch.channel(query, c.name)
fun matches(c: ClientItem) = !channels && TreeMatch.client(query, c.nickname, c.name)
}
@Immutable
data class ChannelItem(
val id: Int,
val name: String,
/** Set for a spacer: a cosmetic separator rather than a channel to join. */
val spacer: Spacers.Spacer?,
val locked: Boolean,
val full: Boolean,
val subscribed: Boolean,
/** 0 for none. */
val iconId: Long,
val clients: List<ClientItem>,
val children: List<ChannelItem>,
)
@Immutable
data class ClientItem(
val id: Int,
val uniqueId: String,
val nickname: String,
/** The name shown: the contact's own name for them where there is one. */
val name: String,
val awayMessage: String,
val status: ClientStatus,
/** The row's background colour, ARGB; 0 for none. */
val background: Int,
val self: Boolean,
/** How the client is filed in the contacts; null when it is not one. */
val contactType: ContactType?,
/** The contact colour the name is drawn in, NEUTRAL when contacts are not coloured. */
val highlight: ContactType,
/** The icons of the client's server groups, then of its channel group, as TeamSpeak lines them up. */
val groupIconIds: List<Long>,
/** The MD5 of the client's avatar; empty for none. */
val avatarFlag: String,
/** The code of the country the server places the client in; empty when it cannot tell. */
val country: String,
val serverGroupIds: List<Int>,
val channelGroupId: Int,
)
@@ -0,0 +1,657 @@
package eu.lixko.ts3j.client.android
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.net.HostButton
import eu.lixko.ts3j.client.net.TeamspeakConnection
import eu.lixko.ts3j.client.session.SelfState
import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.session.Sessions
import eu.lixko.ts3j.client.sound.SoundNotifier
import eu.lixko.ts3j.client.sound.SoundPack
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import eu.lixko.ts3j.client.text.BBCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.concurrent.atomic.AtomicInteger
/** What the app shows of a connection and the local client on it. */
data class SessionState(
val title: String = "",
val status: String = "Not connected",
val connected: Boolean = false,
val busy: Boolean = false,
/** Whether this server holds the microphone, which only one server can at a time. */
val micActive: Boolean = false,
val micPermission: Boolean = false,
val micMuted: Boolean = false,
val deafened: Boolean = false,
val away: Boolean = false,
val selfClientId: Int = 0,
val channelId: Int = 0,
val inputMode: Settings.InputMode = Settings.InputMode.VOICE_ACTIVATION,
val hostButton: HostButton? = null,
/** What the tree shows for the local client, and the connection notification too. */
val self: SelfState = SelfState.DISCONNECTED,
/** Who the microphone whispers to instead of the channel; null when it talks in the channel. */
val whisper: String? = null,
/** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */
val whisperNobody: Boolean = false,
)
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/** Something that happened once, for the UI to tell the user about. */
sealed interface SessionEvent {
data class Poke(val from: String, val message: String) : SessionEvent
data class Error(val message: String) : SessionEvent
/** A link or shortcut brought a server on screen, in front of whatever page was open. */
data object ServerOpened : SessionEvent
}
/**
* The servers the app is on and what they share, outliving any activity: [ConnectionService]
* keeps the process in the foreground while any is connected. Only one server captures with
* the microphone at a time; [Sessions] hands it over.
*/
class SessionController(private val context: Context) {
val settings: Settings = Settings.load()
val icons = IconTheme(context, settings)
private val shortcuts = BookmarkShortcuts(context, icons)
val pictures = WebPictures(context.cacheDir, settings)
internal val cacheDir: File get() = context.cacheDir
internal fun fileTransfers(conn: () -> TeamspeakConnection) = FileTransfers(context, conn)
private val bookmarkStore = Bookmarks.load()
internal val identityStore = IdentityStore.load(settings)
val identities = IdentityManager(context, identityStore, settings, bookmarkStore) {
_bookmarks.value = bookmarkStore.all().toList()
}
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
internal val notifier = MessageNotifier(context)
internal val contactStore = ContactStore.load()
/** The reasons offered when adding a ban; shared by every server. */
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
internal val network = NetworkFollower(context)
private val main = Handler(Looper.getMainLooper())
private val nextId = AtomicInteger()
/** Touched on the main thread only, as [Sessions] wants. */
private val sessions = Sessions { main.post(::microphoneMoved) }
private val _servers = MutableStateFlow(emptyList<ServerController>())
/** Every server the app is on or getting on, in the order they were connected. */
val servers: StateFlow<List<ServerController>> = _servers
private val _current = MutableStateFlow<ServerController?>(null)
/** The server on screen; null when there is none. */
val current: StateFlow<ServerController?> = _current
private val _micOwner = MutableStateFlow<ServerController?>(null)
/** The server capturing with the microphone; null when none is. */
val micOwner: StateFlow<ServerController?> = _micOwner
/** Why the last connection that ended did, for the connect form to show; null when it was left. */
private val _lastEnd = MutableStateFlow<String?>(null)
val lastEnd: StateFlow<String?> = _lastEnd
/** Copies of the contacts, as the store's own entries change in place. */
private val _contacts = MutableStateFlow(contactCopies())
val contacts: StateFlow<List<Contact>> = _contacts
private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList())
val bookmarks: StateFlow<List<Bookmark>> = _bookmarks
private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16)
val events: SharedFlow<SessionEvent> = _events
private val _onScreen = MutableStateFlow(false)
val onScreen: StateFlow<Boolean> = _onScreen
/** Whether the app is on screen; pokes and private messages are notified of while it is not. */
var foreground: Boolean
get() = _onScreen.value
set(value) {
_onScreen.value = value
if (value) notifier.clearPokes()
// The process may be let go of any time once out of sight.
else contactStore.flush()
}
private val levels = LevelMonitor(settings, audio)
val micLevel: StateFlow<MicLevel> = levels.level
@Volatile
private var watchingLevel = false
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
// Mutations report on whichever thread made them, a connection thread included.
contactStore.addListener {
_contacts.value = contactCopies()
_servers.value.forEach(ServerController::contactsChanged)
}
}
/** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */
fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname }
val lastAddress: String get() = settings.lastAddress
// ---- connection ----
/** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */
fun connect(address: String, nickname: String, password: String = "", identityId: String = "") {
val (host, port) = parseAddress(address)
settings.lastAddress = address
if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname
settings.save()
start(host, port, nickname, password, identityId, "", "")
}
fun connect(bookmark: Bookmark) {
start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password,
bookmark.identityId, bookmark.channel, bookmark.channelPassword) }
}
private fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
channel: String, channelPassword: String) {
start { it.start(host, port, nickname, password, identityId, channel, channelPassword) }
}
private fun start(connect: (ServerController) -> Unit) {
val server = ServerController(nextId.incrementAndGet(), this)
sessions.add(server.session)
_servers.update { it + server }
_current.value = server
_lastEnd.value = null
context.startForegroundService(Intent(context, ConnectionService::class.java))
connect(server)
}
/**
* Goes where a `ts3server://` link leads: on a server we are on already, to the channel it
* names; else connects there as another server.
*/
fun open(link: ServerLink, identityId: String = "") {
if (link.bookmarkLabel.isNotEmpty()) {
bookmarkStore.add(link.toBookmark())
saveBookmarks()
}
val on = _servers.value.firstOrNull { it.session.isOn(link) }
if (on != null) {
_current.value = on
on.session.follow(link)
} else {
start { it.open(link, identityId) }
}
_events.tryEmit(SessionEvent.ServerOpened)
}
/** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */
fun openBookmark(id: String): ServerLink? {
val bookmark = bookmarkStore.find(id)
if (bookmark == null) {
error("That bookmark no longer exists")
return null
}
return ServerLink.of(bookmark).also { open(it, bookmark.identityId) }
}
private var startedUp = false
/** Connects the bookmarks flagged for startup, once per process; [opened] is a server the launch already went to. */
fun connectStartupBookmarks(opened: ServerLink?) {
if (startedUp) return
startedUp = true
for (b in bookmarkStore.startupBookmarks()) {
if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) }
}
}
fun select(server: ServerController) {
if (server in _servers.value) _current.value = server
}
/** Leaves every server before returning, for when the app goes away with the connections. */
fun leave() {
val servers = _servers.value
servers.forEach(ServerController::leaving)
ServerSession.shutdownAll(servers.map { it.session })
contactStore.flush()
attachments.close()
}
fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id }
/** A server's state changed; one that is done with goes from the list. */
internal fun serverChanged(server: ServerController) {
if (server.micOwner) updateLevels()
if (server.ended) main.post { remove(server) }
}
private fun remove(server: ServerController) {
if (server !in _servers.value || !server.ended) return
sessions.remove(server.session)
val rest = _servers.value - server
_servers.value = rest
if (_current.value == server) _current.value = rest.lastOrNull()
server.dispose()
val reason = server.state.value.status
_lastEnd.value = if (server.left) null else reason
if (!server.left && rest.isNotEmpty()) error("${server.state.value.title}: $reason")
}
internal fun connected(server: ServerController) {
// The first connect generates an identity when there was none.
identities.refresh()
main.post {
// Without the permission yet, the UI hands the microphone over once it is granted.
if (hasMicPermission()) sessions.connected(server.session)
}
}
internal fun disconnected(server: ServerController) {
main.post { sessions.disconnected(server.session) }
}
internal fun error(message: String) {
_events.tryEmit(SessionEvent.Error(message))
}
internal fun poked(from: String, message: String) {
_events.tryEmit(SessionEvent.Poke(from, message))
if (!foreground) notifier.poke(from, BBCode.toPlain(message))
}
internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
// ---- bookmarks ----
/** A bookmark to [address] as typed into the connect form, not yet saved. */
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark {
val (host, port) = parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != nicknameFor(identityId) }.orEmpty()
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
}
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */
fun saveBookmark(index: Int, edited: Bookmark) {
val all = bookmarkStore.all()
if (index !in all.indices) {
bookmarkStore.add(edited)
} else {
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
all[index] = edited
}
saveBookmarks()
}
/** The channels of a server we are on at [host]:[port], to pick one to join. */
fun channelPathsAt(host: String, port: Int): List<String> =
_servers.value.firstOrNull {
it.isConnected && it.session.port() == port && it.session.address().equals(host.trim(), ignoreCase = true)
}?.session?.channelPaths().orEmpty()
fun removeBookmark(bookmark: Bookmark) {
val index = bookmarkStore.all().indexOf(bookmark)
if (index < 0) return
bookmarkStore.remove(index)
saveBookmarks()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
main.post {
val all = bookmarkStore.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) saveBookmarks()
}
}
private fun saveBookmarks() {
bookmarkStore.save()
_bookmarks.value = bookmarkStore.all().toList()
shortcuts.sync(_bookmarks.value)
}
val canPinShortcuts: Boolean get() = shortcuts.supported
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
fun pinShortcut(bookmark: Bookmark) {
// A bookmark not saved since ids came in has a new one on every load until it is.
bookmarkStore.save()
shortcuts.pin(bookmark)
}
// ---- whisper lists ----
private val whisperListStore = WhisperLists.load()
private val _whisperLists = MutableStateFlow(whisperListCopies())
val whisperLists: StateFlow<List<WhisperList>> = _whisperLists
private fun whisperListCopies() = whisperListStore.all().map { it.copy() }
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
fun saveWhisperList(index: Int, list: WhisperList) {
val all = whisperListStore.all()
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
whisperListStore.save()
_whisperLists.value = whisperListCopies()
}
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) {
val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName)
add(list)
saveWhisperList(index, list)
}
fun removeWhisperList(index: Int) {
val all = whisperListStore.all()
if (index !in all.indices) return
all.removeAt(index)
whisperListStore.save()
_whisperLists.value = whisperListCopies()
}
// ---- contacts ----
private fun contactCopies(): List<Contact> = contactStore.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [saveContact]. */
fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy()
fun saveContact(contact: Contact) = contactStore.put(contact)
fun removeContact(uniqueId: String) = contactStore.remove(uniqueId)
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun importContacts(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else contactStore.merge(found)
}
// ---- myTeamSpeak ----
/** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings)
private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn)
val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn
/** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */
internal val attachments = ChatAttachments(myTeamSpeak).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) }
.also {
_myTeamSpeakSignedIn.value = true
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { myTeamSpeak.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_myTeamSpeakSignedIn.value = myTeamSpeak.isSignedIn
}
suspend fun signOutMyTeamSpeak() {
myTeamSpeak.signOut()
_myTeamSpeakSignedIn.value = false
withContext(Dispatchers.IO) { attachments.close() }
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */
suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
_bookmarks.value = bookmarkStore.all().toList()
identities.refresh()
}
// ---- sound packs ----
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setCountryFlags(shown: Boolean) {
settings.countryFlags = shown
settings.save()
servers.value.forEach { it.scheduleTree(structure = false) }
}
/** Puts new client row colours, already set in [settings], into effect. */
fun clientRowColorsChanged() {
settings.save()
servers.value.forEach { it.scheduleTree(structure = false) }
}
fun setDescriptionPictures(shown: Boolean) {
settings.descriptionPictures = shown
settings.save()
}
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
// ---- the local client ----
fun hasMicPermission() =
context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
/** Moves the microphone to [server]; needs RECORD_AUDIO granted. */
fun giveMicrophoneTo(server: ServerController) {
if (server.isConnected) sessions.giveMicrophoneTo(server.session)
}
/** Opens the microphone of the server holding it while push-to-talk is held. */
fun setPushToTalk(pressed: Boolean) = sessions.setPushToTalk(pressed)
/** Transmits on the server holding the microphone while held, past the voice-activation gate too. */
fun setForceTransmit(pressed: Boolean) = sessions.setForceTransmit(pressed)
private fun microphoneMoved() {
val owner = sessions.microphoneOwner()
for (server in _servers.value) {
server.micOwner = server.session == owner
server.refresh()
}
_micOwner.value = _servers.value.firstOrNull { it.micOwner }
updateLevels()
}
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
/** Switches between push to talk and voice activation; returns the new mode. */
fun toggleInputMode(): Settings.InputMode {
settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK)
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK
applySettings()
return settings.inputMode
}
/** Saves the settings and puts the voice and device ones into effect at once. */
fun applySettings() {
settings.save()
soundPlayer.setOutputDevice(settings.outputDevice)
try {
for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume)
server.playback?.setOutputDevice(settings.outputDevice)
server.playback?.setReceiveBuffer(settings.receiveBuffer)
server.microphone?.apply(settings)
server.refresh()
server.scheduleTree(structure = false)
}
levels.apply()
} catch (e: RuntimeException) {
error(e.message ?: "Microphone unavailable")
}
}
/** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) {
routePrefs.save(route)
_route.value = route
audio.setRoute(route)
}
/** Listens to the microphone for the level meter while [on]. */
fun watchLevel(on: Boolean) {
watchingLevel = on
updateLevels()
}
private fun updateLevels() {
val owner = _micOwner.value
levels.update(watchingLevel, owner?.microphone, owner?.isBusy == true, hasMicPermission())
}
// ---- notifications ----
/** Shows a private chat a notification was tapped for. */
fun requestChat(serverId: Int, clientId: Int) {
val server = server(serverId) ?: return
_current.value = server
server.requestChat(clientId)
}
/** Answers a private message from its notification. */
fun reply(serverId: Int, clientId: Int, text: String) {
server(serverId)?.reply(clientId, text) ?: notifier.clear(serverId, clientId)
}
companion object {
const val DEFAULT_PORT = 9987
private const val OVERLAY_ENABLED = "enabled"
/** `host[:port]` as typed, the port defaulting to TeamSpeak's. */
fun parseAddress(address: String): Pair<String, Int> {
val host = address.substringBefore(':').trim()
val port = address.substringAfter(':', "").trim().toIntOrNull() ?: DEFAULT_PORT
return host to port
}
}
}
@@ -0,0 +1,53 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.content.res.AssetManager
import eu.lixko.ts3j.client.config.AppDirs
import java.io.File
/**
* Unpacks the sound packs bundled in the APK into the profile's `sound` folder, where
* [eu.lixko.ts3j.client.sound.SoundNotifier] finds packs, as they are read as plain files.
* It happens once per installed version of the app; packs of other origins in the
* folder are left alone.
*/
class SoundPackInstaller(private val context: Context) {
private val root = File(AppDirs.profile(), ASSET_DIR)
private val marker = File(root, ".bundled")
/** Where a pack is unpacked first, outside [root] so it is never seen half written. */
private val staging = File(AppDirs.profile(), ".sound-staging")
/** @return whether the packs were (re)installed, so the list of them has to be read again */
fun install(): Boolean {
val version = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime.toString()
if (marker.isFile && marker.readText() == version) return false
val assets = context.assets
for (pack in assets.list(ASSET_DIR).orEmpty()) {
staging.deleteRecursively()
copy(assets, "$ASSET_DIR/$pack", staging)
val target = File(root, pack)
target.deleteRecursively()
root.mkdirs()
check(staging.renameTo(target)) { "Cannot install sound pack $pack" }
}
root.mkdirs()
marker.writeText(version)
return true
}
private fun copy(assets: AssetManager, path: String, to: File) {
val children = assets.list(path).orEmpty()
if (children.isEmpty()) {
to.parentFile?.mkdirs()
assets.open(path).use { input -> to.outputStream().use { input.copyTo(it) } }
return
}
to.mkdirs()
for (child in children) copy(assets, "$path/$child", File(to, child))
}
private companion object {
const val ASSET_DIR = "sound"
}
}
@@ -0,0 +1,31 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.os.Bundle
import android.speech.tts.TextToSpeech
import eu.lixko.ts3j.client.sound.SoundPlayer
/**
* Adds the phone's text-to-speech to a wave player, for packs that speak their
* notifications. Sentences asked for before the engine is up are dropped: they
* would come out late, past what they announce.
*/
class SpeakingSoundPlayer(context: Context, private val waves: SoundPlayer) : SoundPlayer by waves {
@Volatile
private var ready = false
private val tts = TextToSpeech(context.applicationContext) { status -> ready = status == TextToSpeech.SUCCESS }
override fun canSpeak() = true
override fun say(text: String, volume: Double) {
if (!ready) return
val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, volume.toFloat()) }
tts.speak(text, TextToSpeech.QUEUE_ADD, params, null)
}
override fun shutdown() {
tts.shutdown()
waves.shutdown()
}
}
@@ -0,0 +1,18 @@
package eu.lixko.ts3j.client.android
import android.app.Application
import eu.lixko.ts3j.client.config.AppDirs
class Ts3Application : Application() {
lateinit var sessions: SessionController
private set
override fun onCreate() {
super.onCreate()
// Before any store loads: there is no home directory to find them in.
AppDirs.init(filesDir, filesDir.toPath().resolve("chats"))
sessions = SessionController(this)
Thread(sessions::installSoundPacks, "sound-packs").start()
}
}
@@ -0,0 +1,64 @@
package eu.lixko.ts3j.client.android
import android.util.LruCache
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.net.PictureDownloads
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.ConcurrentHashMap
/** The pictures descriptions show, fetched by core's downloads and decoded while there is room. */
class WebPictures(cacheDir: File, private val settings: Settings) {
sealed interface State {
data object Loading : State
data object Broken : State
data class Shown(val picture: Picture) : State
}
private val downloads = PictureDownloads(File(cacheDir, "pictures"), false)
private val decoded = LruCache<String, Picture>(CACHED)
private val undecodable = ConcurrentHashMap.newKeySet<String>()
private val _version = MutableStateFlow(0)
/** Moves on whenever a download has come or failed. */
val version: StateFlow<Int> = _version
init {
downloads.addListener { _version.update { it + 1 } }
}
/** Fetches pictures whose addresses start with [scheme] from [source] rather than the web. */
fun addSource(scheme: String, source: PictureDownloads.Source) = downloads.addSource(scheme, source)
/** Asks again for the pictures that could not be had. */
fun retryFailed() = downloads.retryFailed()
/** Whether pictures are shown at all, rather than links to them. */
val enabled: Boolean get() = settings.descriptionPictures
suspend fun state(url: String): State {
decoded.get(url)?.let { return State.Shown(it) }
if (url in undecodable) return State.Broken
val file = downloads.get(url) ?: return if (downloads.failed(url)) State.Broken else State.Loading
val picture = withContext(Dispatchers.IO) { decodePicture(file.readBytes(), MAX_PX) }
if (picture == null) {
undecodable += url
return State.Broken
}
decoded.put(url, picture)
return State.Shown(picture)
}
/** The picture's file as downloaded; null while it is not there. */
suspend fun data(url: String): ByteArray? = withContext(Dispatchers.IO) { downloads.get(url)?.readBytes() }
private companion object {
const val CACHED = 32
const val MAX_PX = 1024
}
}
@@ -0,0 +1,118 @@
package eu.lixko.ts3j.client.android.ui
import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionEvent
@Composable
fun App(vm: SessionController) {
val current by vm.current.collectAsStateWithLifecycle()
// Each server keeps its own screen state (chat open, conversation) while another is shown.
val serverStates = rememberSaveableStateHolder()
var connectOpen by rememberSaveable { mutableStateOf(false) }
val snackbar = remember { SnackbarHostState() }
var settingsOpen by rememberSaveable { mutableStateOf(false) }
var contactsOpen by rememberSaveable { mutableStateOf(false) }
var myTeamSpeakOpen by rememberSaveable { mutableStateOf(false) }
var editingContact by rememberSaveable { mutableStateOf<String?>(null) }
// Set when a contact's page was opened from a client, so leaving it goes back there.
var contactDirect by rememberSaveable { mutableStateOf(false) }
var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) }
var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) }
LaunchedEffect(vm) {
vm.events.collect { event ->
when (event) {
is SessionEvent.Poke -> poke = event
is SessionEvent.Error -> snackbar.showSnackbar(event.message)
SessionEvent.ServerOpened -> {
connectOpen = false
settingsOpen = false
contactsOpen = false
myTeamSpeakOpen = false
editingBookmark = null
}
}
}
}
val context = LocalContext.current
val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo)
}
fun missing(vararg names: String) =
names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
// The connection runs without either permission, just silent or without its notification.
val connectAsking: (() -> Unit) -> Unit = { connect ->
connect()
connectOpen = false
val ask = missing(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS)
if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray())
}
val enableMicrophone: () -> Unit = {
if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo)
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
}
val openContacts: (String?) -> Unit = { uniqueId ->
contactsOpen = true
editingContact = uniqueId
contactDirect = uniqueId != null
}
CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) {
val server = current
val bookmark = editingBookmark
when {
bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null })
contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId ->
if (uniqueId == null && contactDirect) contactsOpen = false
contactDirect = false
editingContact = uniqueId
}, onBack = { contactsOpen = false })
myTeamSpeakOpen -> MyTeamSpeakScreen(vm, onBack = { myTeamSpeakOpen = false })
settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
server != null && !connectOpen -> {
serverStates.SaveableStateProvider(server.id) {
CompositionLocalProvider(LocalServerImages provides server.images) {
PictureViewerHost(server) {
ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it })
}
}
}
}
else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking,
onEditBookmark = { editingBookmark = it },
onBack = if (current != null) ({ connectOpen = false }) else null)
}
}
poke?.let { p ->
AlertDialog(
onDismissRequest = { poke = null },
title = { Text("${p.from} poked you") },
text = if (p.message.isNotBlank()) ({ Text(p.message) }) else null,
confirmButton = { TextButton(onClick = { poke = null }) { Text("OK") } },
)
}
}
@@ -0,0 +1,102 @@
package eu.lixko.ts3j.client.android.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChatKey
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.MyTsException
import kotlinx.coroutines.launch
import java.io.IOException
/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */
class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
/**
* Shared files for [server]'s chat: a picture opens full size, anything else is saved where
* the user picks; sharing picks a file to send into the conversation [shown] gives.
*/
@Composable
fun rememberAttachmentActions(
vm: SessionController,
server: ServerController,
snackbar: SnackbarHostState,
shown: ChatKey,
): AttachmentActions {
val scope = rememberCoroutineScope()
val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle()
val key by rememberUpdatedState(shown)
val viewer = LocalPictureViewer.current
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
var saving by rememberSaveable { mutableStateOf<String?>(null) }
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
val ref = ChatAttachment.Ref.parse(saving)
saving = null
if (uri == null || ref == null) return@rememberLauncherForActivityResult
scope.launch {
val error = try {
vm.saveAttachment(ref, uri)
null
} catch (e: MyTsException) {
e.message
} catch (e: IOException) {
e.message
}
snackbar.showSnackbar(if (error == null) "Saved ${ref.fileName}." else "Could not save ${ref.fileName}: $error")
}
}
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) scope.launch { server.sendFile(key, uri) }
}
return AttachmentActions(
open = open@{ href ->
val ref = ChatAttachment.Ref.parse(href) ?: return@open
when {
!signedIn -> tell(SIGN_IN)
ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) {
vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull()
})
else -> {
saving = href
saver.launch(ref.fileName)
}
}
},
share = { if (signedIn) picker.launch("*/*") else tell(SIGN_IN) },
)
}
private const val SIGN_IN = "Sign in to myTeamSpeak to share files"
/** Asks where to save a file of the given name, typed by its extension. */
internal object SaveAs : ActivityResultContract<String, Uri?>() {
override fun createIntent(context: Context, input: String): Intent {
val extension = input.substringAfterLast('.', "").lowercase()
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
return Intent(Intent.ACTION_CREATE_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType(type)
.putExtra(Intent.EXTRA_TITLE, input)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri? =
intent?.data.takeIf { resultCode == Activity.RESULT_OK }
}
@@ -0,0 +1,313 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.net.ban.BanEntry
import eu.lixko.ts3j.client.net.ban.BanPattern
import eu.lixko.ts3j.client.net.ban.BanRule
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
/** What the ban list shows instead of itself: a ban's editor, a new or an existing ban's. */
private sealed interface BanEdit {
data object New : BanEdit
data class Existing(val ban: BanEntry) : BanEdit
}
/** The server's ban list, as TeamSpeak's Ban List window: searchable, own bans apart, add, edit and remove. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: () -> Unit) {
val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
var bans by remember { mutableStateOf<List<BanEntry>?>(null) }
var status by remember { mutableStateOf("Loading…") }
/** Bumped to read the list again. */
var generation by remember { mutableIntStateOf(0) }
var query by rememberSaveable { mutableStateOf("") }
var onlyOwn by rememberSaveable { mutableStateOf(false) }
var shown by remember { mutableStateOf<BanEntry?>(null) }
var edit by remember { mutableStateOf<BanEdit?>(null) }
LaunchedEffect(generation) {
status = "Loading…"
server.banList()
.onSuccess {
bans = it
status = if (it.size == 1) "1 ban" else "${it.size} bans"
}
.onFailure {
bans = emptyList()
status = "Failed to request ban list: ${it.message}"
}
}
/** Reports a failed change, or re-reads the list to show what the server now holds. */
val change = { action: suspend () -> String?, failure: String ->
scope.launch {
val error = action()
if (error != null) snackbar.showSnackbar("$failure: $error")
generation++
}
Unit
}
edit?.let { e ->
val existing = (e as? BanEdit.Existing)?.ban
BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule ->
edit = null
if (existing == null) change({ server.addBan(rule) }, "Error adding ban")
else change({ server.replaceBan(existing.id, rule) }, "Error editing ban")
}
return
}
SubScreen(
"Ban list", onBack,
actions = {
if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") }
IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") }
},
snackbar = snackbar,
) { padding ->
val needle = query.trim().lowercase(Locale.ROOT)
val filtered = remember(bans, needle, onlyOwn) {
bans.orEmpty().filter { ban ->
(!onlyOwn || server.isOwnBan(ban)) && (needle.isEmpty() || searchText(ban).contains(needle))
}
}
Column(Modifier.padding(padding).imePadding().fillMaxSize()) {
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(query, { query = it }, Modifier.weight(1f), placeholder = { Text("Search") },
singleLine = true, leadingIcon = { PackIcon("SEARCH", null) })
FilterChip(onlyOwn, { onlyOwn = !onlyOwn }, label = { Text("Own") })
}
Text(status, Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
LazyColumn(Modifier.weight(1f)) {
items(filtered, key = { it.id }) { ban ->
ListItem(
headlineContent = { Text(ban.targets(), maxLines = 2, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Column {
if (ban.reason.isNotEmpty()) Text(ban.reason, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text("${ban.invokerName} · ${expiry(ban)}", style = MaterialTheme.typography.bodySmall)
}
},
modifier = Modifier.clickable { shown = ban },
)
HorizontalDivider()
}
}
}
}
shown?.let { ban ->
BanSheet(
ban,
onDismiss = { shown = null },
onEdit = if (server.canEditBan(ban)) ({ shown = null; edit = BanEdit.Existing(ban) }) else null,
onDelete = if (server.canDeleteBans(listOf(ban))) ({
shown = null
change({ server.deleteBans(listOf(ban.id)) }, "Error deleting ban")
}) else null,
)
}
}
private fun searchText(ban: BanEntry): String =
listOf(ban.targets(), ban.reason, ban.invokerName, date(ban.createdEpochSeconds), expiry(ban))
.joinToString("\n").lowercase(Locale.ROOT)
private val DATE: DateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
private fun date(epochSeconds: Long): String =
if (epochSeconds <= 0) "" else DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault()))
private fun expiry(ban: BanEntry): String = if (ban.isPermanent) "Never expires" else "Expires ${date(ban.expiresEpochSeconds())}"
/** Everything about one ban, and what may be done with it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun BanSheet(ban: BanEntry, onDismiss: () -> Unit, onEdit: (() -> Unit)?, onDelete: (() -> Unit)?) {
var confirmDelete by remember { mutableStateOf(false) }
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Fact("Name", ban.name)
Fact("IP", ban.ip)
Fact("Unique ID", ban.uid)
Fact("Last nickname", ban.lastNickname)
Fact("myTeamSpeak ID", ban.mytsid)
Fact("Reason", ban.reason)
Fact("Creator", ban.invokerName)
Fact("Created", date(ban.createdEpochSeconds))
Fact("Expires", if (ban.isPermanent) "Never" else date(ban.expiresEpochSeconds()))
Fact("Enforced", ban.enforcements.toString())
}
onEdit?.let { Action("EDIT", "Edit", onClick = it) }
onDelete?.let { Action("DELETE", "Delete") { confirmDelete = true } }
}
}
if (confirmDelete && onDelete != null) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete ban?") },
text = { Text(ban.targets()) },
confirmButton = { TextButton(onClick = { confirmDelete = false; onDelete() }) { Text("Delete") } },
dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } },
)
}
}
@Composable
private fun Fact(label: String, value: String) {
if (value.isEmpty()) return
Column {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, style = MaterialTheme.typography.bodyMedium)
}
}
/** Adds a ban, or rewrites [existing]: what it matches, why, and for how long. */
@Composable
private fun BanEditor(
existing: BanEntry?,
presets: BanReasonPresets,
maxSeconds: Long,
onBack: () -> Unit,
onSave: (BanRule) -> Unit,
) {
val decoded = remember { BanPattern.decode(existing?.ip, existing?.name) }
var ip by remember { mutableStateOf(decoded.ip) }
var name by remember { mutableStateOf(decoded.name) }
var pattern by remember { mutableStateOf(if (existing == null) BanPattern.WILDCARD_IPV4 else decoded.pattern) }
var uid by remember { mutableStateOf(existing?.uid.orEmpty()) }
var mytsid by remember { mutableStateOf(existing?.mytsid.orEmpty()) }
var reason by remember { mutableStateOf(existing?.reason.orEmpty()) }
val duration = remember { BanDurationState(existing?.durationSeconds ?: DEFAULT_BAN_SECONDS) }
val rule = BanRule(pattern.ipToRegex(ip), pattern.nameToRegex(name), uid, mytsid, duration.seconds, reason)
val ipValid = BanPattern.isValidRegex(rule.ipRegex)
val nameValid = BanPattern.isValidRegex(rule.nameRegex)
val valid = rule.hasTarget() && ipValid && nameValid && duration.valid
SubScreen(
if (existing == null) "Add ban" else "Edit ban", onBack,
actions = { TextButton(onClick = { onSave(rule) }, enabled = valid) { Text("Save") } },
) { padding ->
Column(
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(ip, { ip = it }, Modifier.fillMaxWidth(), label = { Text("IP") }, singleLine = true,
isError = !ipValid)
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true,
isError = !nameValid)
PatternField(pattern) { pattern = it }
OutlinedTextField(uid, { uid = it }, Modifier.fillMaxWidth(), label = { Text("Unique ID") }, singleLine = true)
OutlinedTextField(mytsid, { mytsid = it }, Modifier.fillMaxWidth(), label = { Text("myTeamSpeak ID") },
singleLine = true)
ReasonField(reason, { reason = it }, presets)
BanDurationField(duration, maxSeconds)
}
}
}
/** How the IP and name are written: wildcards, fixed strings or regular expressions. */
@Composable
private fun PatternField(pattern: BanPattern, onSelect: (BanPattern) -> Unit) {
var open by remember { mutableStateOf(false) }
Row(verticalAlignment = Alignment.CenterVertically) {
Text("Interpret as", Modifier.weight(1f))
Box {
OutlinedButton(onClick = { open = true }) { Text(pattern.label()) }
DropdownMenu(open, { open = false }) {
for (p in BanPattern.entries) DropdownMenuItem({ Text(p.label()) }, onClick = { open = false; onSelect(p) })
}
}
}
}
/** The reason, with the saved presets to pick from and the reason typed to save as one. */
@Composable
private fun ReasonField(reason: String, onChange: (String) -> Unit, presets: BanReasonPresets) {
var open by remember { mutableStateOf(false) }
var saved by remember { mutableStateOf(presets.all().toList()) }
Box {
Row(verticalAlignment = Alignment.Top) {
LimitedField(reason, onChange, "Reason", BanRule.REASON_LIMIT, Modifier.weight(1f))
IconButton(onClick = { open = true }, Modifier.padding(top = 8.dp)) { Icon(Icons.Filled.ArrowDropDown, "Presets") }
}
DropdownMenu(open, { open = false }, Modifier.align(Alignment.TopEnd)) {
for (preset in saved) {
DropdownMenuItem({ Text(preset, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; onChange(preset.take(BanRule.REASON_LIMIT)) },
trailingIcon = {
IconButton(onClick = {
presets.remove(preset)
presets.save()
saved = presets.all().toList()
}) { PackIcon("DELETE", "Remove preset") }
})
}
if (saved.isNotEmpty()) HorizontalDivider()
DropdownMenuItem({ Text("Save as preset") }, enabled = reason.isNotBlank(), onClick = {
open = false
presets.add(reason)
presets.save()
saved = presets.all().toList()
})
}
}
}
@@ -0,0 +1,152 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark
/** A bookmark on the edit page: [index] among the saved ones, -1 for a new one. */
class BookmarkEdit(val index: Int, val bookmark: Bookmark)
val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
save = { edit ->
val b = edit?.bookmark ?: return@listSaver emptyList()
listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password,
b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id)
},
restore = { saved ->
if (saved.isEmpty()) null
else BookmarkEdit(saved[0] as Int, Bookmark(saved[1] as String, saved[2] as String, saved[3] as Int,
saved[4] as String, saved[5] as String).apply {
identityId = saved[6] as String
channel = saved[7] as String
channelPassword = saved[8] as String
connectOnStartup = saved[9] as Boolean
iconId = saved[10] as Long
id = saved[11] as String
})
},
)
/** Every setting of one bookmark, saved only on Save. */
@Composable
fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit) {
val b = edit.bookmark
val identities by vm.identities.all.collectAsStateWithLifecycle()
var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) }
var address by rememberSaveable {
mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}")
}
var nickname by rememberSaveable { mutableStateOf(b.nickname.orEmpty()) }
var password by rememberSaveable { mutableStateOf(b.password.orEmpty()) }
var identityId by rememberSaveable { mutableStateOf(b.identityId.orEmpty()) }
var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) }
var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) }
var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) }
val save = {
val (host, port) = SessionController.parseAddress(address)
vm.saveBookmark(edit.index, b.copy().also {
it.label = label.trim().ifEmpty { host }
it.address = host
it.port = port
it.nickname = nickname.trim()
it.password = password
it.identityId = identityId
it.channel = channel.trim()
it.channelPassword = channelPassword
it.connectOnStartup = connectOnStartup
})
onDone()
}
SubScreen(if (edit.index < 0) "New bookmark" else "Edit bookmark", onBack = onDone, actions = {
TextButton(onClick = save, enabled = address.isNotBlank()) { Text("Save") }
}) { padding ->
Column(
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(label, { label = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true)
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
label = { Text("Server password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) { identityId = it }
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
placeholder = { Text(vm.nicknameFor(identityId)) }, singleLine = true)
val paths = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) }
}
ChannelField(channel, paths) { channel = it }
OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(),
label = { Text("Channel password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
Row(Modifier.fillMaxWidth().clickable { connectOnStartup = !connectOnStartup },
verticalAlignment = Alignment.CenterVertically) {
Text("Connect on startup", Modifier.weight(1f))
Switch(connectOnStartup, { connectOnStartup = it })
}
}
}
}
/** The channel to join, typed or picked among [paths] of the server when we are on it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ChannelField(channel: String, paths: List<String>, onChange: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
// A channel already picked lists them all, for picking another.
val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) }
val expanded = open && matches.isNotEmpty()
ExposedDropdownMenuBox(expanded, { open = it }) {
OutlinedTextField(
channel, { onChange(it); open = true }, singleLine = true,
label = { Text("Channel") },
placeholder = { Text("Default") },
trailingIcon = if (paths.isEmpty()) null else ({ ExposedDropdownMenuDefaults.TrailingIcon(expanded) }),
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
)
ExposedDropdownMenu(expanded, { open = false }) {
for (path in matches) {
DropdownMenuItem({ Text(path) }, onClick = {
open = false
onChange(path)
})
}
}
}
}
@@ -0,0 +1,211 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.ChannelCodec
import eu.lixko.ts3j.client.net.ChannelSettings
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/** The channel being edited ([channelId] > 0), or one to create below [parentId] (0: the top level). */
data class ChannelEdit(val channelId: Int, val parentId: Int = 0)
/**
* TeamSpeak's channel editor on one page: name, password, topic and description, then the
* channel's type, sorting, audio and limits. Only what changed is sent, as the server refuses
* an edit carrying one property we may not change.
*/
@Composable
fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> Unit) {
val creating = edit.channelId <= 0
val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
/** The channel as the server described it, which changes are measured against. */
var original by remember { mutableStateOf<ChannelSettings?>(null) }
var edited by remember { mutableStateOf<ChannelSettings?>(null) }
var passwordText by remember { mutableStateOf("") }
var saving by remember { mutableStateOf(false) }
LaunchedEffect(edit) {
if (creating) {
// Made from a channel's sheet, a channel is usually a throwaway one, as in TeamSpeak;
// the server puts a new channel after its siblings.
val fresh = ChannelSettings().apply {
type = ChannelSettings.Type.TEMPORARY
parentId = edit.parentId
order = server.sortChoices(0, edit.parentId).lastOrNull()?.id ?: 0
}
original = fresh
edited = fresh.copy()
} else {
server.channelSettings(edit.channelId)
.onSuccess { original = it; edited = it.copy() }
.onFailure { snackbar.showSnackbar("Could not read the channel: ${it.message}"); onDone() }
}
}
val change = { f: ChannelSettings.() -> Unit -> edited = edited?.copy()?.apply(f) }
val save = save@{
val e = edited ?: return@save
val o = original ?: return@save
if (e.name.isBlank()) {
scope.launch { snackbar.showSnackbar("The channel needs a name.") }
return@save
}
saving = true
scope.launch {
val trimmed = e.copy().apply { name = name.trim() }
val error = if (creating) server.createChannel(edit.parentId, trimmed)
else server.editChannel(edit.channelId, trimmed.changesFrom(o))
saving = false
if (error == null) onDone()
else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error)
}
}
val title = when {
!creating -> "Edit channel"
edit.parentId > 0 -> "New sub-channel"
else -> "New channel"
}
SubScreen(title, onBack = onDone, snackbar = snackbar, actions = {
TextButton(onClick = save, enabled = edited != null && !saving) { Text(if (creating) "Create" else "Save") }
}) { padding ->
val e = edited
if (e == null) {
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
return@SubScreen
}
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(e.name, { change { name = it } }, Modifier.fillMaxWidth(), label = { Text("Name") },
singleLine = true)
OutlinedTextField(passwordText, {
passwordText = it
change { password = it }
}, Modifier.fillMaxWidth(), label = { Text("Password") }, singleLine = true,
placeholder = if (e.hasPassword && e.password == null) ({ Text("Unchanged") }) else null,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
if (e.hasPassword && e.password == null) {
TextButton(onClick = { change { password = "" } }) { Text("Remove password") }
}
OutlinedTextField(e.topic, { change { topic = it } }, Modifier.fillMaxWidth(), label = { Text("Topic") },
singleLine = true)
OutlinedTextField(e.description, { change { description = it } }, Modifier.fillMaxWidth(),
label = { Text("Description") }, minLines = 3, maxLines = 10)
}
Section("Channel type")
Segments(listOf(
ChannelSettings.Type.TEMPORARY to "Temporary",
ChannelSettings.Type.SEMI_PERMANENT to "Semi-permanent",
ChannelSettings.Type.PERMANENT to "Permanent",
), e.type) { change { type = it } }
// The default channel cannot stop being one; another has to take over.
if (original?.defaultChannel != true) {
Toggle("Default channel", e.defaultChannel) { change { defaultChannel = it } }
}
val siblings = remember(edit) {
server.sortChoices(edit.channelId, edit.parentId).filter { it.id != edit.channelId }
}
Picker("Sort after", listOf(0 to "(first)") + siblings.map { it.id to it.name },
e.order.takeIf { o -> o == 0 || siblings.any { it.id == o } } ?: 0) { change { order = it } }
NumberField("Needed talk power", e.neededTalkPower, 0..9999) { change { neededTalkPower = it } }
Section("Audio")
val preset = ChannelCodec.Preset.of(e.codec, e.codecQuality)
var custom by remember { mutableStateOf(preset == null) }
val presets: List<Pair<ChannelCodec.Preset?, String>> =
ChannelCodec.Preset.entries.map { it to it.label } + (null to "Custom")
Segments(presets, if (custom) null else preset) { picked ->
custom = picked == null
if (picked != null) change { codec = picked.codec; codecQuality = picked.quality }
}
if (custom) {
Picker("Codec", ChannelCodec.NAMES.indices.map { it to ChannelCodec.NAMES[it] },
ChannelCodec.clampCodec(e.codec)) { change { codec = it } }
Level("Quality", e.codecQuality.toFloat(), 0f..ChannelCodec.MAX_QUALITY.toFloat(),
{ it.roundToInt().toString() }, steps = ChannelCodec.MAX_QUALITY - 1) {
change { codecQuality = it.roundToInt() }
}
}
Hint("Bandwidth: ${ChannelCodec.bandwidthText(e.codec, e.codecQuality)} per talking client")
Section("Advanced")
Column(Modifier.padding(horizontal = 16.dp)) {
OutlinedTextField(e.phoneticName, { change { phoneticName = it } }, Modifier.fillMaxWidth(),
label = { Text("Phonetic name") }, singleLine = true)
}
if (e.type == ChannelSettings.Type.TEMPORARY) {
NumberField("Delete delay (seconds)", e.deleteDelay, 0..ChannelSettings.MAX_DELETE_DELAY) {
change { deleteDelay = it }
}
}
Toggle("Voice encrypted", e.encrypted) { change { encrypted = it } }
Text("Max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
Segments(listOf(true to "Unlimited", false to "Limited"), e.maxClientsUnlimited) {
change { maxClientsUnlimited = it }
}
if (!e.maxClientsUnlimited) NumberField("Users", e.maxClients, 0..65535) { change { maxClients = it } }
Text("Family max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
val family = when {
e.familyInherited -> FamilyLimit.INHERITED
e.familyUnlimited -> FamilyLimit.UNLIMITED
else -> FamilyLimit.LIMITED
}
Segments(FamilyLimit.entries.map { it to it.label }, family) {
change {
familyInherited = it == FamilyLimit.INHERITED
familyUnlimited = it == FamilyLimit.UNLIMITED
}
}
if (family == FamilyLimit.LIMITED) {
NumberField("Users", e.maxFamilyClients, 0..65535) { change { maxFamilyClients = it } }
}
}
}
}
private enum class FamilyLimit(val label: String) { INHERITED("Inherited"), UNLIMITED("Unlimited"), LIMITED("Limited") }
/** A whole number within [range]; what does not parse leaves the value alone. */
@Composable
private fun NumberField(label: String, value: Int, range: IntRange, onChange: (Int) -> Unit) {
var text by remember(value) { mutableStateOf(value.toString()) }
Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(text, {
text = it.filter(Char::isDigit).take(7)
text.toIntOrNull()?.let { n -> onChange(n.coerceIn(range)) }
}, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
}
@@ -0,0 +1,349 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Surface
import androidx.compose.runtime.derivedStateOf
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.gfx.IconKeys
import eu.lixko.ts3j.client.net.ClientStatus
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
/** A channel's or a client's row. */
data class TreeRef(val channel: Boolean, val id: Int)
/** One line of the tree as the list shows it. */
private sealed interface TreeRow {
val ref: TreeRef
val key: String get() = (if (ref.channel) "c" else "u") + ref.id
data class Channel(val channel: ChannelItem, val depth: Int, val expanded: Boolean, val current: Boolean) : TreeRow {
override val ref get() = TreeRef(true, channel.id)
val expandable get() = channel.clients.isNotEmpty() || channel.children.isNotEmpty()
}
data class Client(val client: ClientItem, val depth: Int) : TreeRow {
override val ref get() = TreeRef(false, client.id)
}
}
/** The tree's channels and clients in reading order, leaving out what sits in folded channels. */
private fun flatten(tree: ServerTree, collapsed: Set<Int>, currentChannel: Int): List<TreeRow> {
val rows = ArrayList<TreeRow>()
fun add(channel: ChannelItem, depth: Int) {
val expanded = channel.id !in collapsed
rows += TreeRow.Channel(channel, depth, expanded, channel.id == currentChannel)
if (!expanded) return
channel.clients.forEach { rows += TreeRow.Client(it, depth + 1) }
channel.children.forEach { add(it, depth + 1) }
}
tree.channels.forEach { add(it, 0) }
return rows
}
private fun ChannelItem.holdsSelf(): Boolean = clients.any { it.self } || children.any { it.holdsSelf() }
/** Where the list shows our own client: its row, or the folded channel hiding it; -1 when it shows nowhere. */
private fun selfAnchor(rows: List<TreeRow>): Int = rows.indexOfFirst { row ->
when (row) {
is TreeRow.Client -> row.client.self
is TreeRow.Channel -> !row.expanded && row.channel.holdsSelf()
}
}
/** Which way our own row lies off screen. */
private enum class Offscreen { ABOVE, BELOW }
/** Floats over the tree's edge on the side our own row went off. */
@Composable
private fun BoxScope.ScrollToSelf(where: Offscreen?, onClick: () -> Unit) {
AnimatedVisibility(where == Offscreen.ABOVE, Modifier.align(Alignment.TopCenter).padding(top = 8.dp),
enter = slideInVertically { -it * 2 } + fadeIn(), exit = slideOutVertically { -it * 2 } + fadeOut()) {
ScrollToSelfChip(up = true, onClick)
}
AnimatedVisibility(where == Offscreen.BELOW, Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
enter = slideInVertically { it * 2 } + fadeIn(), exit = slideOutVertically { it * 2 } + fadeOut()) {
ScrollToSelfChip(up = false, onClick)
}
}
@Composable
private fun ScrollToSelfChip(up: Boolean, onClick: () -> Unit) {
Surface(onClick = onClick, shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer,
shadowElevation = 4.dp) {
Row(Modifier.padding(start = 10.dp, end = 14.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(18.dp).rotate(if (up) 180f else 0f))
Text("Me", style = MaterialTheme.typography.labelLarge)
}
}
}
@Composable
fun ChannelTree(
serverName: String,
tree: ServerTree,
collapsed: Set<Int>,
currentChannel: Int,
onToggle: (ChannelItem) -> Unit,
onChannel: (ChannelItem) -> Unit,
onChannelDoubleTap: (ChannelItem) -> Unit,
onClient: (ClientItem) -> Unit,
onServer: () -> Unit,
modifier: Modifier = Modifier,
/** A row to scroll to and flash, once the channels above it are expanded. */
reveal: TreeRef? = null,
onRevealed: () -> Unit = {},
/** The rows the find bar matched, and the one it is on, which a reveal does not flash. */
found: Set<TreeRef> = emptySet(),
foundCurrent: TreeRef? = null,
listState: LazyListState = rememberLazyListState(),
/** Brings our own client into view; its row may sit in folded channels. */
onShowSelf: () -> Unit = {},
) {
val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) }
var flashing by remember { mutableStateOf<TreeRef?>(null) }
LaunchedEffect(reveal, rows) {
val ref = reveal ?: return@LaunchedEffect
val index = rows.indexOfFirst { it.ref == ref }
if (index < 0) return@LaunchedEffect
// Index 0 is the server's row. The row ends up in the middle of the list.
val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2
listState.animateScrollToItem(index + 1, -middle)
if (ref != foundCurrent) flashing = ref
onRevealed()
}
LaunchedEffect(flashing) {
if (flashing != null) {
delay(1500)
flashing = null
}
}
val anchor = remember(rows) { selfAnchor(rows) }
val offscreen by remember(anchor) {
derivedStateOf {
if (anchor < 0) return@derivedStateOf null
val info = listState.layoutInfo
val index = anchor + 1 // past the server's row
val item = info.visibleItemsInfo.firstOrNull { it.index == index }
when {
item != null && item.offset >= info.viewportStartOffset &&
item.offset + item.size <= info.viewportEndOffset -> null
item != null -> if (item.offset < info.viewportStartOffset) Offscreen.ABOVE else Offscreen.BELOW
info.visibleItemsInfo.isEmpty() -> null
index < info.visibleItemsInfo.first().index -> Offscreen.ABOVE
else -> Offscreen.BELOW
}
}
}
Box(modifier.fillMaxSize()) {
LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 4.dp)) {
item(key = "server") {
RowLayout(depth = 0, onClick = onServer) {
PackIcon("SERVER_GREEN", null, size = ICON)
Text(serverName, Modifier.weight(1f), fontWeight = FontWeight.Bold, maxLines = 1,
overflow = TextOverflow.Ellipsis)
ServerIcon(tree.serverIconId, size = ICON)
}
}
items(rows, key = { it.key }) { row ->
val background = rowBackground(
when (row.ref) {
flashing -> FLASH
foundCurrent -> findCurrentColor()
in found -> findMatchColor()
else -> Color.Transparent
},
)
when (row) {
is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap)
is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient)
}
}
}
ScrollToSelf(offscreen, onShowSelf)
}
}
private val ICON = 16.dp
private val INDENT = 14.dp
private val ROW = 26.dp
/** Amber, see-through so the row's text keeps its own colour and contrast. */
private val FLASH = Color(0x80FFB300)
/** Fades in fast and out slowly, so a flash is seen. */
@Composable
private fun rowBackground(target: Color): Color {
val color by animateColorAsState(target, tween(if (target == FLASH) 150 else 600), label = "row")
return color
}
@Composable
private fun RowLayout(
depth: Int,
onClick: (() -> Unit)?,
background: Color = Color.Transparent,
/** The colour under [background], which a flash or find match goes over. */
tint: Color = Color.Transparent,
onDoubleClick: (() -> Unit)? = null,
content: @Composable RowScope.() -> Unit,
) {
Row(
Modifier
.fillMaxWidth()
.background(tint)
.background(background)
.height(ROW)
.then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onClick = onClick) else Modifier)
.padding(start = 4.dp + INDENT * depth, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
ProvideTextStyle(MaterialTheme.typography.bodyMedium, content = { content() })
}
}
@Composable
private fun ChannelRow(
row: TreeRow.Channel,
background: Color,
onToggle: (ChannelItem) -> Unit,
onChannel: (ChannelItem) -> Unit,
onDoubleTap: (ChannelItem) -> Unit,
) {
val channel = row.channel
val spacer = channel.spacer
RowLayout(row.depth, onClick = { onChannel(channel) }, background = background,
onDoubleClick = if (spacer == null) ({ onDoubleTap(channel) }) else null) {
Box(
Modifier.fillMaxHeight().width(ICON + 4.dp)
.then(if (row.expandable) Modifier.clickable { onToggle(channel) } else Modifier),
contentAlignment = Alignment.Center,
) {
if (row.expandable) {
Icon(Icons.Filled.KeyboardArrowDown, if (row.expanded) "Collapse" else "Expand",
Modifier.size(ICON + 2.dp).rotate(if (row.expanded) 0f else -90f))
}
}
if (spacer != null) {
SpacerLabel(spacer.align(), spacer.caption().orEmpty(), Modifier.weight(1f))
} else {
PackIcon(IconKeys.channel(channel.locked, channel.full, channel.subscribed).asList(), null, size = ICON)
Text(
channel.name,
Modifier.weight(1f),
color = if (row.current) MaterialTheme.colorScheme.primary else Color.Unspecified,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
ServerIcon(channel.iconId, size = ICON)
}
}
}
/** A spacer's caption, placed as its tag asks; a repeated one of dashes or the like becomes a rule. */
@Composable
private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) {
if (align == '*') {
if (caption.isNotEmpty() && caption.all { it in "-_=.~" }) {
HorizontalDivider(modifier)
} else {
Text(caption.repeat(200 / caption.length.coerceAtLeast(1)), modifier, maxLines = 1, overflow = TextOverflow.Clip)
}
return
}
val textAlign = when (align) {
'c' -> TextAlign.Center
'r' -> TextAlign.End
else -> TextAlign.Start
}
Text(caption, modifier, textAlign = textAlign, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) {
val client = row.client
RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background)) {
Spacer(Modifier.width(ICON + 4.dp))
StatusIcon(client.status)
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
client.name,
fontWeight = if (client.self) FontWeight.Bold else FontWeight.Normal,
color = when (client.highlight) {
ContactType.FRIEND -> StatusColors.friend
ContactType.BLOCKED -> StatusColors.blocked
else -> Color.Unspecified
},
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (client.awayMessage.isNotEmpty()) {
Text("[${client.awayMessage}]", Modifier.weight(1f, fill = false),
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
for (id in client.groupIconIds) ServerIcon(id, size = ICON)
// The country's flag comes last, at the row's edge.
if (countryFlags) CountryFlag(client.country)
}
}
@Composable
fun StatusIcon(status: ClientStatus, modifier: Modifier = Modifier) {
PackIcon(IconKeys.client(status), status.name, modifier, size = ICON)
}
@@ -0,0 +1,195 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Badge
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ChatKey
import eu.lixko.ts3j.client.android.ChatLine
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.Chats
import eu.lixko.ts3j.client.android.Conversation
import eu.lixko.ts3j.client.text.TextQuery
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
@Composable
fun ChatPane(
chats: Chats,
selected: Conversation,
canSend: Boolean,
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit,
onSend: (String) -> Unit,
/** Picks a file to share in [selected]. */
onAttach: () -> Unit,
onLink: (String) -> Unit,
modifier: Modifier = Modifier,
/** The lines to show, when not all of [selected]'s. */
lines: List<ChatLine> = selected.lines,
find: TextQuery = TextQuery.EMPTY,
/** The match the find bar is on. */
current: ChatMatch? = null,
/** A line to scroll to. */
reveal: Long? = null,
onRevealed: () -> Unit = {},
) {
Column(modifier) {
LazyRow(
contentPadding = PaddingValues(horizontal = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(chats.all, key = { it.key.toString() }) { conversation ->
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
}
}
// Each conversation opens at its newest line.
key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) }
// One unsent message per conversation, kept while another one is on screen.
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
val draftKey = selected.key.toString()
val draft = drafts[draftKey].orEmpty()
val send = {
if (draft.isNotBlank()) {
onSend(draft.trim())
drafts.remove(draftKey)
}
}
Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onAttach, enabled = canSend) {
Icon(Icons.Filled.AttachFile, "Share file")
}
OutlinedTextField(
draft, { drafts[draftKey] = it },
Modifier.weight(1f).onPreviewKeyEvent { e ->
// A hardware keyboard's Enter sends, as on the desktop; Shift+Enter starts a new line.
val enter = e.key == Key.Enter && !e.isShiftPressed
if (enter && e.type == KeyEventType.KeyDown) send()
enter
},
placeholder = { Text("Message ${selected.title}", maxLines = 1, overflow = TextOverflow.Ellipsis) },
enabled = canSend,
maxLines = 4,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
)
IconButton(onClick = send, enabled = canSend && draft.isNotBlank()) {
Icon(Icons.AutoMirrored.Filled.Send, "Send")
}
}
}
}
private val DraftsSaver = Saver<SnapshotStateMap<String, String>, HashMap<String, String>>(
save = { HashMap(it) },
restore = { mutableStateMapOf<String, String>().apply { putAll(it) } },
)
@Composable
private fun ConversationChip(
conversation: Conversation,
selected: Boolean,
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit,
) {
val key = conversation.key
FilterChip(
selected = selected,
onClick = { onSelect(key) },
label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingIcon = if (conversation.unread) ({ Badge() }) else null,
trailingIcon = if (key is ChatKey.Private) ({
Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) })
}) else null,
)
}
/** The conversation's lines, following new ones while the newest is in view. */
@Composable
private fun Lines(
lines: List<ChatLine>,
onLink: (String) -> Unit,
modifier: Modifier,
find: TextQuery,
current: ChatMatch?,
reveal: Long?,
onRevealed: () -> Unit,
) {
val listState = rememberLazyListState(initialFirstVisibleItemIndex = (lines.size - 1).coerceAtLeast(0))
val link by rememberUpdatedState(onLink)
// Following the end until the user scrolls away from it, so a restored log, new lines
// and pictures that load late all keep the newest line in view.
var follow by remember { mutableStateOf(true) }
LaunchedEffect(listState) {
snapshotFlow { listState.isScrollInProgress }.drop(1).filter { !it }
.collect { follow = !listState.canScrollForward }
}
LaunchedEffect(listState) {
snapshotFlow { follow && listState.canScrollForward && !listState.isScrollInProgress }.filter { it }
.collect { listState.scrollToItem(listState.layoutInfo.totalItemsCount - 1, Int.MAX_VALUE) }
}
LaunchedEffect(reveal, lines) {
val id = reveal ?: return@LaunchedEffect
val index = lines.indexOfFirst { it.id == id }
if (index < 0) return@LaunchedEffect
val info = listState.layoutInfo
if (info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
// The line's top ends up in the middle of the list.
val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2
listState.animateScrollToItem(index, -middle)
}
onRevealed()
}
LazyColumn(modifier.fillMaxWidth(), state = listState, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) {
items(lines, key = { it.id }) { line ->
RichText(line.html, { link(it) }, Modifier.padding(vertical = 2.dp), MaterialTheme.typography.bodyMedium,
find, if (current?.line == line.id) current.nth else -1)
}
}
}
@@ -0,0 +1,318 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.fromHtml
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.WebPictures
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.text.BBCode
import eu.lixko.ts3j.client.text.ChatHtml
import eu.lixko.ts3j.client.text.TextQuery
/**
* HTML as [BBCode][eu.lixko.ts3j.client.text.BBCode] and [ChatHtml] write it, with its rules as dividers
* and its pictures fetched from the web: Android's HTML parser shows neither, so the text is
* split at them.
*/
@Composable
fun RichText(
html: String,
onLink: (String) -> Unit,
modifier: Modifier = Modifier,
style: TextStyle = LocalTextStyle.current,
/** Matches to highlight: [current] is the index of the one the find bar is on, if it is here. */
find: TextQuery = TextQuery.EMPTY,
current: Int = -1,
) {
val link by rememberUpdatedState(onLink)
val color = linkColor()
val parsed = remember(html, color) { split(html) { chatText(it, color) { href -> link(href) } } }
val match = findMatchColor()
val currentMatch = findCurrentColor()
val pieces = remember(parsed, find, current, match, currentMatch) {
if (find.isEmpty) parsed else highlight(parsed, find, current, match, currentMatch)
}
Column(modifier) {
for (piece in pieces) {
when (piece) {
Piece.Rule -> HorizontalDivider(Modifier.padding(vertical = 6.dp))
is Piece.Image -> WebPicture(piece, style) { link(it) }
// As wide as there is room, for aligned paragraphs to have somewhere to go.
is Piece.Text -> if (piece.text.isNotEmpty()) Text(piece.text, Modifier.fillMaxWidth(), style = style)
}
}
}
}
/** [pieces] with [find]'s matches behind [match], and the [current]th of them, counting across pieces, behind [currentMatch]. */
private fun highlight(pieces: List<Piece>, find: TextQuery, current: Int, match: Color, currentMatch: Color): List<Piece> {
var n = 0
return pieces.map { piece ->
if (piece !is Piece.Text) return@map piece
val m = find.matcher(piece.text.text) ?: return@map piece
val text = AnnotatedString.Builder(piece.text)
while (m.find()) {
if (m.end() == m.start()) continue
text.addStyle(SpanStyle(background = if (n == current) currentMatch else match), m.start(), m.end())
n++
}
Piece.Text(text.toAnnotatedString())
}
}
/** The web pictures descriptions show. */
val LocalWebPictures = staticCompositionLocalOf<WebPictures?> { null }
private sealed interface Piece {
data class Text(val text: AnnotatedString) : Piece
data object Rule : Piece
/** @param href where the picture links to, if it sits in a link */
data class Image(val url: String, val href: String?, val align: Alignment.Horizontal) : Piece
}
/**
* [html] cut at its rules and pictures. Each piece of text is closed where it is cut and the
* next reopens what it was in, so an aligned block or a link carries on past a picture.
*/
private fun split(html: String, text: (String) -> AnnotatedString): List<Piece> {
val pieces = ArrayList<Piece>()
val divs = ArrayList<String>()
var anchor: String? = null
var href: String? = null
val current = StringBuilder()
fun cut() {
if (anchor != null) current.append("</a>")
repeat(divs.size) { current.append("</div>") }
pieces += Piece.Text(text(current.toString()))
current.setLength(0)
divs.forEach { current.append(it) }
anchor?.let { current.append(it) }
}
var last = 0
for (m in CUT_TAG.findAll(html)) {
current.append(html, last, m.range.first)
last = m.range.last + 1
val tag = m.value
when {
tag.startsWith("<hr", ignoreCase = true) -> {
cut()
pieces += Piece.Rule
}
tag.startsWith("<img", ignoreCase = true) -> {
cut()
pieces += Piece.Image(unescape(m.groupValues[1]), href?.let(::unescape), alignment(divs))
}
tag.startsWith("<div", ignoreCase = true) -> {
divs += tag
current.append(tag)
}
tag.equals("</div>", ignoreCase = true) -> {
divs.removeLastOrNull()
current.append(tag)
}
tag.startsWith("<a", ignoreCase = true) -> {
anchor = tag
href = m.groupValues[2]
current.append(tag)
}
else -> {
anchor = null
href = null
current.append(tag)
}
}
}
current.append(html, last, html.length)
pieces += Piece.Text(text(current.toString()))
return pieces
}
/** Where the innermost aligned block puts what is in it. */
private fun alignment(divs: List<String>): Alignment.Horizontal {
val align = divs.asReversed().firstNotNullOfOrNull { ALIGN.find(it)?.groupValues?.get(1) }
return when (align) {
"center" -> Alignment.CenterHorizontally
"right" -> Alignment.End
else -> Alignment.Start
}
}
private fun unescape(s: String) =
s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&amp;", "&")
/**
* A picture at its own size, a pixel to a dp as TeamSpeak shows it, narrowed to fit. With
* pictures turned off, or when one cannot be had, its address as a link behind a picture icon.
*/
@Composable
private fun WebPicture(image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) {
val pictures = LocalWebPictures.current
Column(Modifier.fillMaxWidth().padding(vertical = 2.dp), horizontalAlignment = image.align) {
if (pictures == null || !pictures.enabled) {
PictureLink("ICONVIEWER", image, style, onLink)
return@Column
}
val version by pictures.version.collectAsStateWithLifecycle()
val state by produceState<WebPictures.State>(WebPictures.State.Loading, image.url, version) {
value = pictures.state(image.url)
}
when (val shown = state) {
WebPictures.State.Loading -> PackIcon("LOADING_IMAGE", "Loading picture", size = 16.dp)
WebPictures.State.Broken -> PictureLink("BROKEN_IMAGE", image, style, onLink)
is WebPictures.State.Shown -> {
val picture = shown.picture
val viewer = LocalPictureViewer.current
Image(
rememberPicturePainter(picture),
null,
Modifier
.widthIn(max = picture.width.dp)
.aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1))
.then(if (viewer != null) Modifier.clickable {
viewer(viewedPicture(image, onLink) { pictures.data(image.url) })
} else if (image.href != null) Modifier.clickable { onLink(image.href) } else Modifier),
)
}
}
}
}
/** [image] to open full size; a file shared in chat has no address to copy or link to follow but itself. */
private fun viewedPicture(image: Piece.Image, onLink: (String) -> Unit, read: suspend () -> ByteArray?): ViewedPicture {
val attachment = ChatAttachment.Ref.parse(image.url)
if (attachment != null) return ViewedPicture(attachment.fileName.substringBeforeLast('.'), read = read)
val openLink = image.href?.let { href -> { onLink(href) } }
return ViewedPicture(pictureName(image.url), image.url, openLink, read = read)
}
/** The picture's address as a link behind [iconKey], then the link it sat in, if any, so neither is lost. */
@Composable
private fun PictureLink(iconKey: String, image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) {
val color = linkColor()
val text = remember(image, color) {
val links = listOfNotNull(image.url, image.href?.takeIf { it != image.url })
chatText(links.joinToString(" ") { "<a href=\"${BBCode.escape(it)}\">${BBCode.escape(linkText(it))}</a>" }, color, onLink)
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
PackIcon(iconKey, "Picture", size = 16.dp)
Text(text, style = style)
}
}
/** A shared file goes by its name, anything else by its address. */
private fun linkText(url: String): String = ChatAttachment.Ref.parse(url)?.fileName ?: BBCode.shortAddress(url)
/**
* HTML without rules as styled text. Android's parser knows no stylesheets, tables,
* numbered lists, font sizes or `align`, so the classes [ChatHtml] marks lines with become
* inline colours, table rows lines of their cells, numbered items numbered lines, sizes
* `<big>`/`<small>`, and alignment the style it does know.
*/
fun chatText(html: String, linkColor: Color, onLink: (String) -> Unit): AnnotatedString {
val styled = sizes(numbered(CLASS.replace(html) { m ->
CLASS_COLORS[m.groupValues[1]]?.let { "style=\"color:$it\"" } ?: ""
}))
.replace(ALIGN) { m -> "style=\"text-align:${ALIGNS.getValue(m.groupValues[1])}\"" }
.replace(CELL_END, " ")
.replace(ROW_END, "<br>")
val text = AnnotatedString.fromHtml(
styled,
TextLinkStyles(SpanStyle(color = linkColor, fontWeight = FontWeight.SemiBold)),
) { link -> (link as? LinkAnnotation.Url)?.let { onLink(it.url) } }
// Block elements leave line breaks around the text.
val start = text.text.indexOfFirst { !it.isWhitespace() }.coerceAtLeast(0)
val end = text.text.indexOfLast { !it.isWhitespace() } + 1
return if (end <= start) AnnotatedString("") else text.subSequence(start, end)
}
/** Numbers the items of each `<ol>`, innermost first. */
private fun numbered(html: String): String {
var out = html
while (true) {
val list = INNER_OL.find(out) ?: return out
val letters = list.groupValues[1].isNotEmpty()
var n = 0
val items = LI.replace(list.groupValues[2]) { m ->
if (m.value.startsWith("</")) "" else {
n++
"<br>" + (if (letters) ('a' + (n - 1) % 26).toString() else n.toString()) + ". "
}
}
out = out.replaceRange(list.range, "<div>$items</div>")
}
}
/**
* Turns each font-size span into `<big>`s or `<small>` (or a plain span), closing it alike.
* Sizes are TeamSpeak's, around its 11 px text.
*/
private fun sizes(html: String): String {
val closes = ArrayDeque<String>()
return SPAN.replace(html) { m ->
if (m.value.startsWith("</")) {
closes.removeLastOrNull() ?: m.value
} else {
val px = m.groupValues[1].toIntOrNull()
val tags = when {
px == null -> listOf("span")
px >= BIGGER_PX -> listOf("big", "big")
px >= BIG_PX -> listOf("big")
px <= SMALL_PX -> listOf("small")
else -> listOf("span")
}
closes.addLast(tags.reversed().joinToString("") { "</$it>" })
if (px == null) m.value else tags.joinToString("") { "<$it>" }
}
}
}
private const val BIGGER_PX = 18
private const val BIG_PX = 13
private const val SMALL_PX = 9
private val INNER_OL = Regex("<ol( type=\"a\")?>((?:(?!<ol[ >]).)*?)</ol>", RegexOption.DOT_MATCHES_ALL)
private val LI = Regex("</?li>")
private val SPAN = Regex("<span style=\"font-size:(\\d+)px\">|<span[^>]*>|</span>")
private val ALIGNS = mapOf("left" to "start", "justify" to "start", "center" to "center", "right" to "end")
/** Where the text is cut, and what it has to carry across: aligned blocks and links. */
private val CUT_TAG = Regex(
"<hr\\s*/?>|<img src=\"([^\"]*)\">|<div[^>]*>|</div>|<a [^>]*href=\"([^\"]*)\"[^>]*>|</a>",
RegexOption.IGNORE_CASE,
)
private val CLASS = Regex("class=\"([a-z]+)\"")
private val ALIGN = Regex("align=\"(left|center|right|justify)\"")
private val CELL_END = Regex("</t[dh]>")
private val ROW_END = Regex("</tr>")
private val CLASS_COLORS = mapOf(
ChatHtml.MUTED_CLASS to "#8c8c8c",
ChatHtml.EVENT_CLASS to "#7a8fa6",
)
@@ -0,0 +1,240 @@
package eu.lixko.ts3j.client.android.ui
import android.graphics.BitmapFactory
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.Icon
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.IdentityInfo
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.net.IconRepository
/** Where to connect to: an address typed in, or a bookmark. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConnectScreen(
vm: SessionController,
snackbar: SnackbarHostState,
onSettings: () -> Unit,
onMyTeamSpeak: () -> Unit,
onConnect: (() -> Unit) -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
/** Back to the servers already connected; null when there are none. */
onBack: (() -> Unit)?,
) {
val lastEnd by vm.lastEnd.collectAsStateWithLifecycle()
val bookmarks by vm.bookmarks.collectAsStateWithLifecycle()
val identities by vm.identities.all.collectAsStateWithLifecycle()
val myTeamSpeakSignedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle()
var address by rememberSaveable { mutableStateOf(vm.lastAddress) }
var identityId by rememberSaveable { mutableStateOf("") }
var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) }
var password by rememberSaveable { mutableStateOf("") }
if (onBack != null) BackHandler(onBack = onBack)
Scaffold(
topBar = {
TopAppBar(
title = { Text("TeamSpook TS3j") },
navigationIcon = {
if (onBack != null) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
},
actions = {
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
},
)
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
LazyColumn(
Modifier.padding(padding).imePadding(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
item {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
singleLine = true)
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
label = { Text("Server password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) {
identityId = it
nickname = vm.nicknameFor(it)
}
lastEnd?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(
onClick = { onConnect { vm.connect(address.trim(), nickname.trim(), password, identityId) } },
enabled = address.isNotBlank() && nickname.isNotBlank(),
) { Text("Connect") }
TextButton(onClick = {
onEditBookmark(BookmarkEdit(-1, vm.newBookmark(address.trim(), nickname.trim(), password, identityId)))
}, enabled = address.isNotBlank()) { Text("Add bookmark") }
}
}
}
if (bookmarks.isNotEmpty()) {
item {
Text("Bookmarks", Modifier.padding(top = 16.dp), style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary)
}
} else {
item {
OutlinedButton(onClick = onMyTeamSpeak, Modifier.padding(top = 16.dp)) {
Text(if (myTeamSpeakSignedIn) "Import from myTeamSpeak" else "Sign in to myTeamSpeak")
}
}
}
itemsIndexed(bookmarks) { index, bookmark ->
BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } },
onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) },
onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null,
onRemove = { vm.removeBookmark(bookmark) })
}
}
}
}
/** The identities to connect with, the default one first as an empty id. */
private fun identityChoices(identities: List<IdentityInfo>): List<Pair<String, String>> {
val default = identities.firstOrNull { it.isDefault }?.name
return listOf("" to (default?.let { "Default ($it)" } ?: "Default")) + identities.map { it.id to it.name }
}
/** An id no longer among the identities connects with the default, and shows as such. */
private fun shownId(identities: List<IdentityInfo>, id: String) = id.takeIf { i -> identities.any { it.id == i } } ?: ""
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun IdentityField(identities: List<IdentityInfo>, selected: String, onSelect: (String) -> Unit) {
val choices = identityChoices(identities)
val shown = shownId(identities, selected)
var open by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(open, { open = it }) {
OutlinedTextField(
choices.first { it.first == shown }.second, {}, readOnly = true, singleLine = true,
label = { Text("Identity") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) },
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
)
ExposedDropdownMenu(open, { open = false }) {
for ((id, name) in choices) {
DropdownMenuItem({ Text(name) }, onClick = {
open = false
onSelect(id)
})
}
}
}
}
/** The server's icon as last seen there, else the pack's bookmark icon. */
@Composable
private fun BookmarkIcon(iconId: Long) {
val cached = remember(iconId) {
IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }
}
if (cached != null) Image(cached, null, Modifier.size(24.dp))
else PackIcon("BOOKMARK_MANAGER", null)
}
private val AUTOCONNECT = Color(0xFF3A9D4A)
@Composable
private fun BookmarkRow(
bookmark: Bookmark,
identities: List<IdentityInfo>,
onConnect: () -> Unit,
onEdit: () -> Unit,
/** Null when the launcher takes no shortcuts. */
onPin: (() -> Unit)?,
onRemove: () -> Unit,
) {
val identity = identities.firstOrNull { it.id == bookmark.identityId }
var menu by remember { mutableStateOf(false) }
ListItem(
headlineContent = {
Text(buildAnnotatedString {
if (bookmark.connectOnStartup) {
withStyle(SpanStyle(color = AUTOCONNECT, fontWeight = FontWeight.Bold)) { append("AC") }
append(' ')
}
append(bookmark.displayName())
})
},
supportingContent = {
Text(listOfNotNull(bookmark.hostPort(), bookmark.channel.ifBlank { null }, identity?.name)
.joinToString(" · "))
},
leadingContent = { BookmarkIcon(bookmark.iconId) },
trailingContent = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Bookmark options") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Edit") }, onClick = { menu = false; onEdit() })
onPin?.let { DropdownMenuItem({ Text("Add to home screen") }, onClick = { menu = false; it() }) }
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; onRemove() })
}
}
},
modifier = Modifier.clickable(onClick = onConnect),
)
}
@@ -0,0 +1,150 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.ConnectionStats
import eu.lixko.ts3j.client.net.ConnectionStatsFormat
import kotlinx.coroutines.delay
private const val REFRESH_MS = 1000L
private val TABS = ConnectionStatsFormat.TRAFFIC_TABS.map { it.title() } +
listOf(ConnectionStatsFormat.QUOTA_TAB, ConnectionStatsFormat.VOICE_TAB)
/**
* A client's connection figures, read again every second while shown, laid out as TeamSpeak's
* Connection Info window: name, times, ping and address beside the avatar, then a tab per
* traffic category with Total / In / Out columns, Quota, and what our playback made of their voice.
*/
@Composable
fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) {
var stats by remember { mutableStateOf<ConnectionStats?>(null) }
LaunchedEffect(clientId) {
while (true) {
stats = server.connectionStats(clientId) ?: break
delay(REFRESH_MS)
}
}
var tab by rememberSaveable { mutableIntStateOf(0) }
val s = stats
SubScreen("Connection info", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Summary(s, client?.nickname ?: "", Modifier.weight(1f))
if (client != null && client.avatarFlag.isNotEmpty()) {
Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp)
}
}
PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) {
TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) }
}
val traffic = ConnectionStatsFormat.TRAFFIC_TABS
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
when {
tab < traffic.size -> TrafficTable(ConnectionStatsFormat.trafficRows(s, traffic[tab].kind()))
tab == traffic.size -> Figures(ConnectionStatsFormat.quotaGroups(s))
else -> Figures(listOf(ConnectionStatsFormat.voiceRows(s?.voiceReceived)))
}
}
}
}
}
@Composable
private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) {
val context = LocalContext.current
val address = ConnectionStatsFormat.copyableAddress(s)
val rows = ConnectionStatsFormat.summaryRows(s, nickname)
Column(modifier) {
rows.forEachIndexed { i, row ->
Row(Modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(row.value, textAlign = TextAlign.End)
if (i == rows.lastIndex) {
IconButton(
onClick = {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Client address", address))
},
enabled = address != null,
modifier = Modifier.size(32.dp),
) { PackIcon("COPY", "Copy client address", size = 18.dp) }
}
}
}
}
}
/** Labelled figures in groups set apart by a rule. */
@Composable
private fun Figures(groups: List<List<ConnectionStatsFormat.Row>>) {
groups.forEachIndexed { g, rows ->
if (g > 0) HorizontalDivider(Modifier.padding(vertical = 8.dp))
for (row in rows) {
Row(Modifier.padding(vertical = 4.dp)) {
Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(row.value, textAlign = TextAlign.End)
}
}
}
}
@Composable
private fun TrafficTable(rows: List<ConnectionStatsFormat.TrafficRow>) {
Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
LabelCell("")
ConnectionStatsFormat.COLUMNS.forEachIndexed { i, column -> ValueCell(column, i == 0, FontStyle.Italic) }
}
for (row in rows) {
Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
LabelCell(row.label)
ValueCell(row.total, narrow = true)
ValueCell(row.`in`)
ValueCell(row.out)
}
}
}
@Composable
private fun RowScope.LabelCell(text: String) =
Text(text, Modifier.weight(1.5f), color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall)
/** The Total column only ever holds the loss percentage. */
@Composable
private fun RowScope.ValueCell(text: String, narrow: Boolean = false, fontStyle: FontStyle? = null) =
Text(text, Modifier.weight(if (narrow) 0.7f else 1f), style = MaterialTheme.typography.bodySmall, fontStyle = fontStyle,
textAlign = TextAlign.End)
@@ -0,0 +1,271 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.contacts.NicknameDisplay
import kotlinx.coroutines.launch
import java.time.format.DateTimeFormatter
import kotlin.math.roundToInt
private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
private val DISPLAYS = listOf(
NicknameDisplay.ONLY_NICKNAME to "Nickname",
NicknameDisplay.ONLY_CUSTOM to "Custom name",
NicknameDisplay.BOTH to "Both",
)
private val GROUPS = listOf(
ContactType.FRIEND to "Friends",
ContactType.BLOCKED to "Blocked",
ContactType.NEUTRAL to "Neutral",
)
/**
* The contact list, grouped as TeamSpeak's Contacts window groups it, with each
* contact's own page and the defaults new contacts start out with.
*
* @param editing the unique id of the contact whose page is open, if any
*/
@Composable
fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) {
var defaults by rememberSaveable { mutableStateOf(false) }
when {
editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) })
defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false })
}
val contacts by vm.contacts.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
var imported by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
imported = runCatching { vm.importContacts(uri) }.fold(
{ (found, added) ->
if (found == 0) "That file holds no contacts."
else "Imported $found contacts, $added of them new."
},
{ "That file is not a TeamSpeak 3 settings.db." },
)
}
}
SubScreen("Contacts", onBack, actions = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Defaults for new contacts") }, onClick = { menu = false; defaults = true })
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
menu = false
importer.launch(arrayOf("*/*"))
})
}
}
}) { padding ->
LazyColumn(Modifier.padding(padding)) {
imported?.let { item { Hint(it) } }
if (contacts.isEmpty()) {
item {
Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " +
"or import the contacts of TeamSpeak 3 from its settings.db.")
}
}
for ((type, title) in GROUPS) {
val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() }
if (group.isEmpty()) continue
item(key = type) { Section(title) }
items(group, key = { it.uniqueId }) { contact ->
ListItem(
headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
supportingContent = { Text(lastSeen(contact)) },
modifier = Modifier.clickable { onEdit(contact.uniqueId) },
)
}
}
}
}
}
/** One contact's settings; each is stored as it is changed, the names once the page is left. */
@Composable
private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) {
val contacts by vm.contacts.collectAsStateWithLifecycle()
val contact = contacts.firstOrNull { it.uniqueId == uniqueId }
if (contact == null) {
LaunchedEffect(Unit) { onBack() }
return
}
// Starts from the stored entry, which may have been seen again since this page opened.
fun edit(change: Contact.() -> Unit) {
vm.contact(uniqueId)?.let { vm.saveContact(it.apply(change)) }
}
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
var removing by remember { mutableStateOf(false) }
val leave = {
if (customName.trim() != contact.nickname || phoneticName.trim() != contact.phoneticNickname) {
edit {
nickname = customName.trim()
phoneticNickname = phoneticName.trim()
}
}
onBack()
}
SubScreen(label(contact), leave, actions = {
IconButton(onClick = { removing = true }) { PackIcon(if (contact.type == ContactType.BLOCKED) "REMOVE_FOE" else "REMOVE_FRIEND", "Remove from contacts") }
}) { padding ->
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
OutlinedTextField(customName, { customName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
label = { Text("Custom nickname") }, singleLine = true)
OutlinedTextField(phoneticName, { phoneticName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
label = { Text("Phonetic nickname") }, singleLine = true)
Section("Contact")
Segments(GROUPS.map { (type, _) -> type to type.label() }, contact.type) { edit { type = it } }
Section("Show as")
Segments(DISPLAYS, contact.nicknameDisplay) { edit { nicknameDisplay = it } }
Section("Ignore")
Toggle("Mute", contact.automute) { edit { automute = it } }
Toggle("Ignore server and channel chat", contact.ignorePublicMessages) { edit { ignorePublicMessages = it } }
Toggle("Ignore private chat", contact.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
Toggle("Ignore pokes", contact.ignorePokes) { edit { ignorePokes = it } }
Toggle("Hide avatar", contact.ignoreAvatar) { edit { ignoreAvatar = it } }
Toggle("Hide away message", contact.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
Toggle("Deny whisper", !contact.whisperAllowed) { edit { whisperAllowed = !it } }
Section("Playback")
val volume = if (contact.hasVolumeModifier) contact.volumeModifier.toFloat() else 0f
Level("Volume", volume, -30f..20f, ::formatVolume) { db ->
val rounded = db.roundToInt().toDouble()
edit {
hasVolumeModifier = rounded != 0.0
volumeModifier = rounded
}
}
Section("Details")
val context = LocalContext.current
LinkRow("Unique ID", contact.uniqueId) {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId))
}
ListItem(headlineContent = { Text(lastSeen(contact)) })
}
}
if (removing) {
AlertDialog(
onDismissRequest = { removing = false },
title = { Text("Remove ${label(contact)}?") },
text = { Text("Their settings here are forgotten; they show as anyone else again.") },
confirmButton = {
TextButton(onClick = {
removing = false
vm.removeContact(uniqueId)
onBack()
}) { Text("Remove") }
},
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
)
}
}
/** What a client starts out with when added as a friend, blocked or neutral. */
@Composable
private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) {
val defaults = vm.settings.contactDefaults
var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) }
var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) }
fun edit(change: ContactDefaults.Entry.() -> Unit) {
val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() }
defaults.of(tab).copyFrom(changed)
vm.settings.save()
entry = changed
}
SubScreen("Defaults for new contacts", onBack) { padding ->
Column(Modifier.padding(padding)) {
PrimaryTabRow(selectedTabIndex = GROUPS.indexOfFirst { it.first == tab }) {
for ((type, title) in GROUPS) Tab(tab == type, onClick = { tab = type }, text = { Text(title) })
}
Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Show as")
Segments(DISPLAYS, entry.nicknameDisplay) { edit { nicknameDisplay = it } }
Section("Ignore")
Toggle("Mute", entry.automute) { edit { automute = it } }
Toggle("Ignore server and channel chat", entry.ignorePublicMessages) { edit { ignorePublicMessages = it } }
Toggle("Ignore private chat", entry.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
Toggle("Ignore pokes", entry.ignorePokes) { edit { ignorePokes = it } }
Toggle("Hide avatar", entry.ignoreAvatar) { edit { ignoreAvatar = it } }
Toggle("Hide away message", entry.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
Toggle("Deny whisper", entry.ignoreWhisper) { edit { ignoreWhisper = it } }
}
}
}
}
private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId }
private fun lastSeen(contact: Contact): String {
val seen = contact.lastSeen ?: return "Never seen"
val where = contact.lastSeenServerName.ifBlank { contact.lastSeenServerAddress }
return "Last seen ${SEEN.format(seen)}" + if (where.isNotBlank()) " on $where" else ""
}
private fun formatVolume(db: Float): String {
val rounded = db.roundToInt()
return if (rounded == 0) "Unchanged" else "${if (rounded > 0) "+" else ""}$rounded dB"
}
private fun typeColor(type: ContactType): Color = when (type) {
ContactType.FRIEND -> StatusColors.friend
ContactType.BLOCKED -> StatusColors.blocked
ContactType.NEUTRAL -> Color.Unspecified
}
@@ -0,0 +1,137 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.net.Details
import eu.lixko.ts3j.client.text.BBCode
/**
* The facts of the server, a channel or a client, then its description, for the top of its sheet.
* The minor facts wait behind "more…".
*/
@Composable
fun DetailsSection(details: Details, onLink: (String) -> Unit, modifier: Modifier = Modifier) {
var all by rememberSaveable(details.title()) { mutableStateOf(false) }
val shown = if (all) details.fields() else details.fields().filterNot { it.minor() }
val more = !all && shown.size < details.fields().size
Column(modifier.padding(horizontal = 24.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (shown.isNotEmpty() || more) {
Column(Modifier.animateContentSize(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
for (field in shown) Fact(field)
if (more) {
Text("more…", Modifier.clickable { all = true }.padding(vertical = 2.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
}
}
}
when {
details.description().isNotBlank() -> Description(details.description(), onLink)
details.pending() -> Text("Loading description…", style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun Fact(field: Details.Field) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(field.label(), Modifier.width(96.dp), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (field.groups().isEmpty()) {
Text(field.value(), style = MaterialTheme.typography.bodySmall)
} else {
// Each group with its icon, as TeamSpeak's info frame lists them.
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
// A nameless group shows only its icon, and takes no comma.
val lastNamed = field.groups().indexOfLast { it.name.isNotBlank() }
field.groups().forEachIndexed { i, group ->
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
ServerIcon(group.iconId, size = 14.dp)
if (group.name.isNotBlank()) {
Text(group.name.trim() + if (i < lastNamed) "," else "", style = MaterialTheme.typography.bodySmall)
}
}
}
}
}
}
}
/** The description in a box that opens up, when there is more of it than fits folded. */
@Composable
private fun Description(bbcode: String, onLink: (String) -> Unit) {
val html = remember(bbcode) { BBCode.toHtml(bbcode, true) }
var expanded by rememberSaveable(bbcode) { mutableStateOf(false) }
var overflows by remember(bbcode) { mutableStateOf(false) }
val expandable = overflows || expanded
val background = MaterialTheme.colorScheme.surfaceContainerHigh
Surface(
Modifier.fillMaxWidth().then(if (expandable) Modifier.clickable { expanded = !expanded } else Modifier),
shape = RoundedCornerShape(12.dp),
color = background,
) {
Column(Modifier.animateContentSize().padding(12.dp)) {
Box {
Folded(FOLDED_HEIGHT, expanded, onOverflow = { overflows = it }) {
RichText(html, onLink, style = MaterialTheme.typography.bodyMedium)
}
if (overflows && !expanded) {
Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(24.dp)
.background(Brush.verticalGradient(listOf(Color.Transparent, background))))
}
}
if (expandable) {
Text(if (expanded) "Less" else "More", Modifier.padding(top = 4.dp),
style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
}
}
}
}
/** Its content cut to [height] unless [open], telling whether there is more of it than that. */
@Composable
private fun Folded(height: Dp, open: Boolean, onOverflow: (Boolean) -> Unit, content: @Composable () -> Unit) {
val report by rememberUpdatedState(onOverflow)
Layout(content, Modifier.clipToBounds()) { measurables, constraints ->
val placeable = measurables.first().measure(constraints.copy(maxHeight = Constraints.Infinity))
val limit = height.roundToPx()
report(placeable.height > limit)
val shown = if (open) placeable.height else minOf(placeable.height, limit)
layout(placeable.width, shown) { placeable.place(0, 0) }
}
}
private val FOLDED_HEIGHT = 128.dp
@@ -0,0 +1,239 @@
package eu.lixko.ts3j.client.android.ui
import android.text.format.DateUtils
import android.text.format.Formatter
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.TransferRow
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import kotlinx.coroutines.launch
/** A channel's file repository: folders to walk, files to download, upload, rename and delete. */
@Composable
fun FilesScreen(server: ServerController, channelId: Int, channelName: String, password: String, onBack: () -> Unit) {
val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
var path by rememberSaveable { mutableStateOf("/") }
var files by remember { mutableStateOf<List<RemoteFile>?>(null) }
var failure by remember { mutableStateOf<String?>(null) }
var reloads by remember { mutableIntStateOf(0) }
val transfers by server.files.rows.collectAsStateWithLifecycle()
var downloading by remember { mutableStateOf<RemoteFile?>(null) }
var creatingFolder by remember { mutableStateOf(false) }
var renaming by remember { mutableStateOf<RemoteFile?>(null) }
var deleting by remember { mutableStateOf<RemoteFile?>(null) }
LaunchedEffect(path, reloads) {
failure = null
server.listFiles(channelId, password, path)
.onSuccess { list -> files = list.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) }
.onFailure { files = emptyList(); failure = it.message ?: "Could not list the files" }
}
// An upload into the folder on screen shows up once it is there.
val uploadedHere = transfers.count { it.upload && it.channelId == channelId && it.directory == path && it.state == FileTransfer.State.COMPLETED }
LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ }
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
val act = { call: suspend () -> String? ->
scope.launch {
val error = call()
if (error != null) snackbar.showSnackbar(error) else reloads++
}
Unit
}
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
val file = downloading
downloading = null
if (uri != null && file != null) server.files.download(channelId, password, file, uri)
}
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
runCatching { server.files.upload(channelId, password, path, uri) }
.onFailure { tell("Could not read the file: ${it.message}") }
}
}
SubScreen(channelName, onBack = { if (path == "/") onBack() else path = parentOf(path) }, snackbar = snackbar, actions = {
IconButton(onClick = { creatingFolder = true }) { PackIcon("ADD_FOLDER", "New folder") }
IconButton(onClick = { picker.launch(arrayOf("*/*")) }) { PackIcon("UPLOAD", "Upload") }
IconButton(onClick = { reloads++ }) { PackIcon(listOf("FILE_REFRESH", "REFRESH"), "Refresh") }
}) { padding ->
Column(Modifier.padding(padding).fillMaxSize()) {
Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { path = parentOf(path) }, enabled = path != "/") { PackIcon("FILE_UP", "Up") }
Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium)
}
HorizontalDivider()
Box(Modifier.weight(1f).fillMaxWidth()) {
val list = files
when {
list == null -> CircularProgressIndicator(Modifier.align(Alignment.Center))
list.isEmpty() -> Text(failure ?: "No files", Modifier.align(Alignment.Center).padding(24.dp),
color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
else -> LazyColumn {
items(list, key = { it.fullPath }) { file ->
FileRow(file,
onOpen = {
if (file.isDirectory) path = file.fullPath + "/"
else { downloading = file; saver.launch(file.name) }
},
onRename = { renaming = file },
onDelete = { deleting = file })
}
}
}
}
if (transfers.isNotEmpty()) Transfers(transfers, server.files::cancel, server.files::clearFinished)
}
}
if (creatingFolder) {
TextPrompt("New folder", "Name", "Create", onDismiss = { creatingFolder = false }, onConfirm = { name ->
creatingFolder = false
if (name.isNotBlank()) act { server.createDirectory(channelId, password, path + name.trim()) }
})
}
renaming?.let { file ->
TextPrompt("Rename", "Name", "Rename", initial = file.name, onDismiss = { renaming = null }, onConfirm = { name ->
renaming = null
if (name.isNotBlank() && name != file.name) {
act { server.renameFile(channelId, password, file.fullPath, file.parentPath + name.trim()) }
}
})
}
deleting?.let { file ->
AlertDialog(
onDismissRequest = { deleting = null },
title = { Text("Delete ${file.name}?") },
text = if (file.isDirectory) ({ Text("Everything in the folder goes with it.") }) else null,
confirmButton = {
TextButton(onClick = {
deleting = null
act { server.deleteFile(channelId, password, file.fullPath) }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } },
)
}
}
private fun parentOf(path: String): String {
val trimmed = path.removeSuffix("/")
val slash = trimmed.lastIndexOf('/')
return if (slash <= 0) "/" else trimmed.substring(0, slash + 1)
}
@Composable
private fun FileRow(file: RemoteFile, onOpen: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) {
val context = LocalContext.current
var menu by remember { mutableStateOf(false) }
val modified = if (file.lastModifiedEpochSec > 0) {
DateUtils.formatDateTime(context, file.lastModifiedEpochSec * 1000,
DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH)
} else null
ListItem(
headlineContent = { Text(file.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Text(listOfNotNull(if (file.isDirectory) null else Formatter.formatShortFileSize(context, file.size), modified)
.joinToString(" · "))
},
leadingContent = { PackIcon(if (file.isDirectory) listOf("FOLDER") else listOf("FILE", "FILETRANSFER"), null) },
trailingContent = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "File options") }
DropdownMenu(menu, { menu = false }) {
if (!file.isDirectory) DropdownMenuItem({ Text("Download") }, onClick = { menu = false; onOpen() })
DropdownMenuItem({ Text("Rename") }, onClick = { menu = false; onRename() })
DropdownMenuItem({ Text("Delete") }, onClick = { menu = false; onDelete() })
}
}
},
modifier = Modifier.clickable(onClick = onOpen),
)
}
/** The transfers under way and done, newest last. */
@Composable
private fun Transfers(rows: List<TransferRow>, onCancel: (Long) -> Unit, onClear: () -> Unit) {
val context = LocalContext.current
Surface(tonalElevation = 3.dp) {
Column(Modifier.fillMaxWidth().heightIn(max = 220.dp)) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text("Transfers", Modifier.weight(1f), style = MaterialTheme.typography.titleSmall)
if (rows.any { it.done }) TextButton(onClick = onClear) { Text("Clear finished") }
}
LazyColumn {
items(rows, key = { it.id }) { row ->
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically) {
PackIcon(if (row.upload) "UPLOAD" else "DOWNLOAD", null)
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
Text(row.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
when (row.state) {
FileTransfer.State.PENDING, FileTransfer.State.ACTIVE ->
LinearProgressIndicator({ row.progress }, Modifier.fillMaxWidth().padding(vertical = 4.dp))
else -> Text(status(row, context), style = MaterialTheme.typography.bodySmall,
color = if (row.state == FileTransfer.State.FAILED) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant)
}
}
if (!row.done) IconButton(onClick = { onCancel(row.id) }) { Icon(Icons.Default.Close, "Cancel") }
}
}
}
}
}
}
private fun status(row: TransferRow, context: android.content.Context): String = when (row.state) {
FileTransfer.State.COMPLETED -> (if (row.upload) "Uploaded" else "Downloaded") + " · " +
Formatter.formatShortFileSize(context, row.total)
FileTransfer.State.CANCELLED -> "Cancelled"
else -> row.error ?: "Failed"
}
@@ -0,0 +1,190 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.gfx.IconKeys
import eu.lixko.ts3j.client.net.ClientStatus
import eu.lixko.ts3j.client.text.TextQuery
/** What the find bar holds: the text, how to match it, and whether it is [open]. */
@Stable
class FindState(text: String = "", flags: Int = 0) {
var open by mutableStateOf(false)
var input by mutableStateOf(TextFieldValue(text))
var matchCase by mutableStateOf(flags and 1 != 0)
var wholeWord by mutableStateOf(flags and 2 != 0)
var regex by mutableStateOf(flags and 4 != 0)
/** Counts the times it was asked to show, for the field to take the focus each time. */
var shown by mutableStateOf(0)
private set
/** Show only what matches. */
var filter by mutableStateOf(flags and 8 != 0)
/** In the tree, find channels rather than clients. */
var channels by mutableStateOf(flags and 16 != 0)
/** What is typed, as it is to be matched; empty while the bar is closed. */
val query: TextQuery
get() = if (open) TextQuery(input.text, matchCase, wholeWord, regex) else TextQuery.EMPTY
/** [query], but nothing when it is not a valid regular expression. */
val usable: TextQuery
get() = query.let { if (it.isInvalid) TextQuery.EMPTY else it }
/** Opens the bar with what it holds selected, to be typed over. */
fun show() {
input = input.copy(selection = TextRange(0, input.text.length))
open = true
shown++
}
companion object {
val Saver = listSaver<FindState, Any>(
save = {
val flags = (if (it.matchCase) 1 else 0) or (if (it.wholeWord) 2 else 0) or (if (it.regex) 4 else 0) or
(if (it.filter) 8 else 0) or (if (it.channels) 16 else 0)
listOf(it.input.text, flags, it.open)
},
restore = { FindState(it[0] as String, it[1] as Int).apply { open = it[2] as Boolean } },
)
}
}
/**
* The find bar, in the place of the top bar: the field, where the view is among the matches,
* previous/next, and the options. Enter goes to the next match, Shift+Enter to the previous.
*
* @param inTree whether it finds in the tree, which offers finding channels instead of clients
* @param position the 1-based match the view is on, or 0 for none
* @param more whether there are more matches than [total]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FindBar(state: FindState, inTree: Boolean, position: Int, total: Int, more: Boolean, onStep: (Int) -> Unit) {
val focus = remember { FocusRequester() }
LaunchedEffect(state.shown) { focus.requestFocus() }
val query = state.query
TopAppBar(
expandedHeight = 48.dp,
navigationIcon = { IconButton(onClick = { state.open = false }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Close") } },
title = {
TextField(
state.input, { state.input = it },
Modifier.focusRequester(focus).onPreviewKeyEvent { e ->
when {
e.key == Key.Enter -> {
if (e.type == KeyEventType.KeyDown) onStep(if (e.isShiftPressed) -1 else 1)
true
}
e.key == Key.Escape && e.type == KeyEventType.KeyDown -> {
state.open = false
true
}
else -> false
}
},
placeholder = {
Text(if (!inTree) "Find" else if (state.channels) "Find channels" else "Find clients", maxLines = 1)
},
leadingIcon = if (inTree) ({
IconButton(onClick = { state.channels = !state.channels }) {
if (state.channels) PackIcon(IconKeys.channel(false, false, true).asList(), "Finding channels", size = 18.dp)
else PackIcon(IconKeys.client(ClientStatus.IDLE), "Finding clients", size = 18.dp)
}
}) else null,
trailingIcon = if (state.input.text.isNotEmpty()) ({
IconButton(onClick = { state.input = TextFieldValue() }) { Icon(Icons.Filled.Close, "Clear", Modifier.size(18.dp)) }
}) else null,
isError = query.isInvalid,
singleLine = true,
textStyle = MaterialTheme.typography.bodyLarge,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { onStep(1) }),
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
errorContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
)
},
actions = {
Row(verticalAlignment = Alignment.CenterVertically) {
if (!query.isEmpty) {
Text(
if (query.isInvalid) "!" else "${if (position > 0) "$position/" else ""}$total${if (more) "+" else ""}",
Modifier.padding(horizontal = 4.dp),
color = if (query.isInvalid || total == 0) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelMedium,
)
}
val navigable = total > 1 || (total == 1 && position == 0)
IconButton(onClick = { onStep(-1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowUp, "Previous") }
IconButton(onClick = { onStep(1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowDown, "Next") }
FindOptions(state)
}
},
)
}
@Composable
private fun FindOptions(state: FindState) {
var open by remember { mutableStateOf(false) }
IconButton(onClick = { open = true }) { Icon(Icons.Filled.MoreVert, "Options") }
DropdownMenu(open, onDismissRequest = { open = false }) {
@Composable
fun option(label: String, checked: Boolean, set: (Boolean) -> Unit) = DropdownMenuItem(
text = { Text(label) },
onClick = { set(!checked) },
leadingIcon = { Checkbox(checked, set) },
)
option("Only matches", state.filter) { state.filter = it }
option("Match case", state.matchCase) { state.matchCase = it }
option("Whole words", state.wholeWord) { state.wholeWord = it }
option("Regular expression", state.regex) { state.regex = it }
}
}
@@ -0,0 +1,64 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.Picture
import eu.lixko.ts3j.client.android.WebPictures
import eu.lixko.ts3j.client.net.HostButton
/**
* The server's host button in the top bar: its own picture fitted to the bar's icons, or
* the pack's host button icon while there is none (yet).
*/
@Composable
fun HostButtonAction(button: HostButton, onOpen: (String) -> Unit) {
val label = button.tooltip.ifEmpty { button.url }.ifEmpty { null }
val picture = hostPicture(button.gfxUrl)
Box(
Modifier
.fillMaxHeight()
.clickable(enabled = button.url.isNotEmpty()) { onOpen(button.url) }
.padding(horizontal = 12.dp),
contentAlignment = Alignment.Center,
) {
if (picture == null) {
PackIcon("HOSTER_BUTTON", label)
} else {
Image(
rememberPicturePainter(picture),
label,
Modifier
.widthIn(max = 24.dp * MAX_ASPECT)
.height(24.dp)
.aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)),
)
}
}
}
@Composable
private fun hostPicture(url: String): Picture? {
val pictures = LocalWebPictures.current
if (pictures == null || url.isEmpty()) return null
val version by pictures.version.collectAsStateWithLifecycle()
val state by produceState<WebPictures.State>(WebPictures.State.Loading, url, version) {
value = pictures.state(url)
}
return (state as? WebPictures.State.Shown)?.picture
}
/** Keeps a banner-shaped picture from crowding out the server's name. */
private const val MAX_ASPECT = 6
@@ -0,0 +1,282 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.IdentityInfo
import eu.lixko.ts3j.client.android.IdentityManager
import kotlinx.coroutines.launch
/** Beyond this a search takes years; TeamSpeak's own dialog stops there too. */
private const val MAX_SECURITY_LEVEL = 40
/**
* The identities a server knows this client by, as TeamSpeak's Tools → Identities
* manages them, with each identity's own page.
*/
@Composable
fun IdentitiesScreen(manager: IdentityManager, onBack: () -> Unit) {
var editing by rememberSaveable { mutableStateOf<String?>(null) }
editing?.let { id -> return IdentityScreen(manager, id, onBack = { editing = null }) }
val identities by manager.all.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
var creating by remember { mutableStateOf(false) }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
fun work(failure: String, block: suspend () -> String?) {
busy = true
scope.launch {
message = try {
block()
} catch (e: Exception) {
"$failure: ${e.message ?: e}"
}
busy = false
}
}
val fileImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) work("That file is not a TeamSpeak identity") {
editing = manager.importFile(uri).id
null
}
}
val dbImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) work("That file is not a TeamSpeak 3 settings.db") {
val r = manager.importFromTeamSpeak(uri)
if (r.identities() == 0) "That file holds no identities."
else "Imported ${r.identitiesAdded()} of ${r.identities()} identities."
}
}
SubScreen("Identities", onBack, actions = {
IconButton(onClick = { creating = true }, enabled = !busy) { PackIcon("IDENTITY_ADD", "New identity") }
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Import identity file") }, onClick = {
menu = false
fileImporter.launch(arrayOf("*/*"))
})
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
menu = false
dbImporter.launch(arrayOf("*/*"))
})
}
}
}) { padding ->
LazyColumn(Modifier.padding(padding)) {
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
message?.let { item { Hint(it) } }
if (identities.isEmpty()) {
item {
Hint("No identities. One is created on the first connect.")
}
}
items(identities, key = { it.id }) { identity ->
ListItem(
headlineContent = { Text(identity.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Text("Security level ${identity.securityLevel}", maxLines = 1)
},
trailingContent = if (identity.isDefault) ({ PackIcon("IDENTITY_DEFAULT", "Default") }) else null,
modifier = Modifier.clickable { editing = identity.id },
)
}
}
}
if (creating) {
NewIdentityDialog(onDismiss = { creating = false }) { name ->
creating = false
work("Could not create the identity") {
editing = manager.generate(name).id
null
}
}
}
}
/** One identity: its name, whether it is the default, its security level and unique ID. */
@Composable
private fun IdentityScreen(manager: IdentityManager, id: String, onBack: () -> Unit) {
val identities by manager.all.collectAsStateWithLifecycle()
val improving by manager.improving.collectAsStateWithLifecycle()
val identity = identities.firstOrNull { it.id == id }
if (identity == null) {
LaunchedEffect(Unit) { onBack() }
return
}
val scope = rememberCoroutineScope()
var name by rememberSaveable(id) { mutableStateOf(identity.name) }
var nickname by rememberSaveable(id) { mutableStateOf(identity.nickname) }
var phonetic by rememberSaveable(id) { mutableStateOf(identity.phoneticNickname) }
var removing by remember { mutableStateOf(false) }
var raising by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
val leave = {
val trimmed = name.trim()
if (trimmed.isNotEmpty() && trimmed != identity.name) manager.rename(id, trimmed)
if (nickname.trim() != identity.nickname || phonetic.trim() != identity.phoneticNickname) {
manager.setNicknames(id, nickname.trim(), phonetic.trim())
}
onBack()
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
if (uri != null) scope.launch {
message = runCatching { manager.export(id, uri) }.fold(
{ "Exported." },
{ "Could not export: ${it.message ?: it}" },
)
}
}
val mine = improving?.takeIf { it.id == id }
SubScreen(identity.name, leave, actions = {
IconButton(onClick = { exporter.launch(fileName(name.ifBlank { identity.name })) }) {
PackIcon("IDENTITY_EXPORT", "Export")
}
IconButton(onClick = { removing = true }) { PackIcon("DELETE", "Remove") }
}) { padding ->
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
label = { Text("Name") }, singleLine = true, isError = name.isBlank())
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp),
label = { Text("Nickname") }, placeholder = { Text("Global nickname") }, singleLine = true)
OutlinedTextField(phonetic, { phonetic = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
label = { Text("Phonetic nickname") }, singleLine = true)
message?.let { Hint(it) }
Section("Use")
if (identity.isDefault) {
Hint("Default identity")
} else {
LinkRow("Make default", null, "IDENTITY_DEFAULT") {
manager.setDefault(id)
}
}
Section("Security level")
if (mine != null) {
ListItem(
headlineContent = { Text("Improving to ${mine.target}: reached ${mine.reached}") },
supportingContent = { LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) },
trailingContent = { TextButton(onClick = manager::stopImproving) { Text("Stop") } },
)
} else {
LinkRow("Level ${identity.securityLevel}",
if (improving != null) "Another identity is being improved" else "Improve",
"SECURITY") { if (improving == null) raising = true }
}
Section("Details")
val context = LocalContext.current
LinkRow("Unique ID", identity.uniqueId) {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Unique ID", identity.uniqueId))
}
}
}
if (raising) {
LevelDialog(identity, onDismiss = { raising = false }) { target ->
raising = false
manager.improve(id, target)
}
}
if (removing) {
AlertDialog(
onDismissRequest = { removing = false },
title = { Text("Remove ${identity.name}?") },
text = {
Text("Server groups and permissions tied to it are lost. Export it first to keep it.")
},
confirmButton = {
TextButton(onClick = {
removing = false
manager.remove(id)
}) { Text("Remove") }
},
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
)
}
}
@Composable
private fun NewIdentityDialog(onDismiss: () -> Unit, onConfirm: (String) -> Unit) {
var name by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("New identity") },
text = {
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true)
},
confirmButton = { TextButton(onClick = { onConfirm(name.trim()) }, enabled = name.isNotBlank()) { Text("Create") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@Composable
private fun LevelDialog(identity: IdentityInfo, onDismiss: () -> Unit, onConfirm: (Int) -> Unit) {
var text by remember { mutableStateOf((identity.securityLevel + 1).toString()) }
val level = text.trim().toIntOrNull()?.takeIf { it in identity.securityLevel + 1..MAX_SECURITY_LEVEL }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Improve security level") },
text = {
Column {
Text("Current level: ${identity.securityLevel}", style = MaterialTheme.typography.bodyMedium)
OutlinedTextField(text, { text = it }, Modifier.fillMaxWidth().padding(top = 8.dp),
label = { Text("Target level") }, singleLine = true, isError = level == null,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
},
confirmButton = { TextButton(onClick = { level?.let(onConfirm) }, enabled = level != null) { Text("Start") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
private fun fileName(name: String) = name.replace(Regex("[^\\w.-]+"), "_") + ".ini"
@@ -0,0 +1,235 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.GroupChoice
import eu.lixko.ts3j.client.net.TeamspeakConnection
import eu.lixko.ts3j.client.net.ban.BanRule
import eu.lixko.ts3j.client.net.ban.BanUnit
/** Asks to confirm a kick, with an optional reason. */
@Composable
fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) {
var reason by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = { LimitedField(reason, { reason = it }, "Reason", TeamspeakConnection.KICK_REASON_LIMIT) },
confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** Asks for a ban's reason and length. */
@Composable
fun BanPrompt(name: String, maxSeconds: Long, onDismiss: () -> Unit, onBan: (seconds: Long, reason: String) -> Unit) {
var reason by remember { mutableStateOf("") }
val duration = remember { BanDurationState(DEFAULT_BAN_SECONDS) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Ban $name") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
LimitedField(reason, { reason = it }, "Reason", BanRule.REASON_LIMIT)
BanDurationField(duration, maxSeconds)
}
},
confirmButton = {
TextButton(onClick = { onBan(duration.seconds, reason.trim()) }, enabled = duration.valid) { Text("Ban") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** Thirty minutes, as the official client starts its ban dialog. */
internal const val DEFAULT_BAN_SECONDS = 30 * 60L
/** A one-line field that takes no more than [limit] characters, counting them as they come. */
@Composable
internal fun LimitedField(value: String, onChange: (String) -> Unit, label: String, limit: Int, modifier: Modifier = Modifier) {
OutlinedTextField(
value, { onChange(it.take(limit)) },
modifier.fillMaxWidth(),
label = { Text(label) },
singleLine = true,
supportingText = { Text("${value.length}/$limit", Modifier.fillMaxWidth(), textAlign = TextAlign.End) },
)
}
/** A ban's length as typed: an amount of a [BanUnit]. */
internal class BanDurationState(seconds: Long) {
var unit by mutableStateOf(BanUnit.largestFor(seconds))
var amount by mutableStateOf(BanUnit.largestFor(seconds).amountOf(seconds).takeIf { it > 0 }?.toString() ?: "30")
val valid: Boolean get() = unit == BanUnit.PERMANENT || (amount.toLongOrNull() ?: 0) > 0
/** The length in seconds; 0 for permanent. */
val seconds: Long get() = unit.toSeconds(amount.toLongOrNull() ?: 0)
fun set(seconds: Long) {
unit = BanUnit.largestFor(seconds)
if (unit != BanUnit.PERMANENT) amount = unit.amountOf(seconds).toString()
}
}
/** The amount, its unit, and a jump to the longest ban the server lets us hand out. */
@Composable
internal fun BanDurationField(state: BanDurationState, maxSeconds: Long, modifier: Modifier = Modifier) {
var units by remember { mutableStateOf(false) }
Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
if (state.unit == BanUnit.PERMANENT) "" else state.amount,
{ text -> state.amount = text.filter(Char::isDigit).take(9) },
Modifier.width(120.dp),
enabled = state.unit != BanUnit.PERMANENT,
label = { Text("Duration") },
singleLine = true,
isError = !state.valid,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
Box(Modifier.weight(1f)) {
OutlinedButton(onClick = { units = true }, Modifier.fillMaxWidth()) { Text(state.unit.label()) }
DropdownMenu(units, { units = false }) {
for (unit in BanUnit.entries) {
DropdownMenuItem({ Text(unit.label()) }, onClick = { units = false; state.unit = unit })
}
}
}
if (maxSeconds != 0L) TextButton(onClick = { state.set(maxSeconds) }) { Text("Max") }
}
}
/**
* A client's groups to tick: several server groups, or with [single] the one channel group.
* Groups we may not assign are listed only when the client is in them, greyed out; a change shows once the server
* made it.
*/
@Composable
fun GroupsDialog(
title: String,
choices: List<GroupChoice>,
single: Boolean,
onDismiss: () -> Unit,
onChange: (groupId: Int, assign: Boolean) -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides Dp.Unspecified) {
LazyColumn {
items(choices.filter { it.allowed() || it.assigned() }, key = { it.group().id }) { choice ->
val group = choice.group()
// A client always has one channel group: picking another is the only change.
val changeable = choice.allowed() && !(single && choice.assigned())
val toggle = { if (changeable) onChange(group.id, !choice.assigned()) }
Row(
Modifier.fillMaxWidth()
.clickable(enabled = changeable, onClick = toggle)
.alpha(if (choice.allowed()) 1f else 0.38f)
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (single) {
RadioButton(choice.assigned(), onClick = toggle, enabled = choice.allowed())
} else {
Checkbox(choice.assigned(), onCheckedChange = { toggle() }, enabled = choice.allowed())
}
Box(Modifier.width(24.dp), contentAlignment = Alignment.Center) {
if (group.iconId != 0L) ServerIcon(group.iconId)
}
Text(group.name, Modifier.padding(start = 8.dp))
}
}
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } },
)
}
/** The kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out. */
@Composable
fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit) {
var kick by remember { mutableStateOf<Boolean?>(null) }
var banning by remember { mutableStateOf(false) }
var groups by remember { mutableStateOf<Boolean?>(null) }
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
if (!client.self) {
if (server.canKickFromChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false }
if (server.canKickFromServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true }
if (server.canBanClients) Action("BAN_CLIENT", "Ban") { banning = true }
}
val showServerGroups = serverGroups.any { it.allowed() }
val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() }
if (showServerGroups || showChannelGroups) {
Row {
if (showServerGroups) Action("PERMISSIONS_SERVER_GROUPS", "Server groups", Modifier.weight(1f)) { groups = true }
if (showChannelGroups) Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group", Modifier.weight(1f)) { groups = false }
}
}
kick?.let { fromServer ->
KickPrompt(
if (fromServer) "Kick ${client.name} from the server?" else "Kick ${client.name} from the channel?",
onDismiss = { kick = null },
) { reason ->
kick = null
if (fromServer) server.kickFromServer(client.id, reason) else server.kickFromChannel(client.id, reason)
onDone()
}
}
if (banning) {
BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason ->
banning = false
server.ban(client.id, seconds, reason)
onDone()
}
}
groups?.let { ofServer ->
GroupsDialog(
if (ofServer) "Server groups" else "Channel group",
if (ofServer) serverGroups else channelGroups,
single = !ofServer,
onDismiss = { groups = null },
) { groupId, assign ->
if (ofServer) server.setServerGroup(client.id, groupId, assign) else server.setChannelGroup(client.id, groupId)
}
}
}
@@ -0,0 +1,265 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.myts.AccountInfo
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTsException
import eu.lixko.ts3j.client.teamspeak.SyncItem
import kotlinx.coroutines.launch
import java.io.IOException
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
/**
* The myTeamSpeak account: sign in and out, and pick what the account synchronises to
* import. Signing in lasts until signing out; the password itself is not kept.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
val login = vm.myTeamSpeak
val scope = rememberCoroutineScope()
var signedIn by remember { mutableStateOf(login.isSignedIn) }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf(false) }
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var info by remember { mutableStateOf<AccountInfo?>(null) }
var all by remember { mutableStateOf(emptyList<SyncItem>()) }
var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
BackHandler(onBack = onBack)
fun show(account: MyTeamSpeak.Account) {
info = account.info()
all = account.items()
rows = all.filter { it !is SyncItem.Folder }.map {
val imported = vm.isImported(it)
ItemRow(it, imported, !imported)
}
message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null
error = false
}
fun work(block: suspend () -> Unit) {
busy = true
message = null
scope.launch {
try {
block()
} catch (e: MyTsException) {
message = e.message
error = true
} catch (e: IOException) {
message = "Could not reach myTeamSpeak: ${e.message}"
error = true
}
// A sign-in the server no longer takes has signed out.
signedIn = login.isSignedIn
busy = false
}
}
LaunchedEffect(Unit) {
if (signedIn) work { show(vm.fetchMyTeamSpeak()) }
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("myTeamSpeak") },
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = {
if (signedIn) {
IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) {
PackIcon("REFRESH", "Refresh")
}
}
},
)
},
) { padding ->
LazyColumn(
Modifier.padding(padding).imePadding(),
contentPadding = PaddingValues(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
if (!signedIn) {
item {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Sign in to bring over the bookmarks and identities your account synchronises. " +
"The app stays signed in; your password itself is not kept.")
OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") },
singleLine = true, enabled = !busy,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email))
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), label = { Text("Password") },
singleLine = true, enabled = !busy, visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
Button(
onClick = {
work {
show(vm.signInMyTeamSpeak(email.trim(), password))
password = ""
}
},
enabled = !busy && email.isNotBlank() && password.isNotEmpty(),
) { Text("Sign in") }
}
}
} else {
item {
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Signed in as ${login.username()}", style = MaterialTheme.typography.titleMedium)
Text(login.email(), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
OutlinedButton(onClick = {
scope.launch { vm.signOutMyTeamSpeak() }
signedIn = false
rows = emptyList()
all = emptyList()
info = null
message = null
}) { Text("Sign out") }
}
}
info?.let { details ->
item {
Column(Modifier.padding(horizontal = 16.dp)) {
if (details.userId().isNotEmpty()) Detail("ID", details.userId())
if (details.uuid().isNotEmpty()) Detail("UUID", details.uuid())
details.created()?.let { Detail("Created", dateFormat.format(it)) }
}
}
}
if (rows.isNotEmpty()) {
item {
Text("Synchronised by the account", Modifier.padding(start = 16.dp, top = 16.dp),
style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
}
}
for ((title, section) in listOf(
"Identities" to rows.filter { it.item is SyncItem.Identity },
"Bookmarks" to rows.filter { it.item is SyncItem.Bookmark },
)) {
if (section.isEmpty()) continue
item {
val select = section.any { !it.selected }
Row(Modifier.padding(start = 16.dp, top = 8.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(title, Modifier.weight(1f),
style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
TextButton(onClick = {
rows = rows.map { if (it in section) it.copy(selected = select) else it }
}) { Text(if (select) "Select all" else "Deselect all") }
}
}
items(section, key = { it.item.uuid() }) { row ->
val toggle = { rows = rows.map { if (it === row) it.copy(selected = !it.selected) else it } }
ListItem(
headlineContent = { Text(name(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = { Text(details(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingContent = { Checkbox(row.selected, { toggle() }) },
trailingContent = if (row.imported) ({ Text("Imported", style = MaterialTheme.typography.labelMedium) }) else null,
modifier = Modifier.clickable(onClick = toggle),
)
}
}
if (rows.isNotEmpty()) {
item {
Button(
onClick = {
work {
val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item })
rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) }
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " +
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")}."
}
},
enabled = !busy && rows.any { it.selected },
modifier = Modifier.padding(horizontal = 16.dp),
) { Text("Import selected") }
}
}
}
message?.let { text ->
item {
Text(text, Modifier.padding(horizontal = 16.dp),
color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface)
}
}
}
}
}
private val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault())
/** A labelled value that can be selected and copied. */
@Composable
private fun Detail(label: String, value: String) {
Column(Modifier.padding(top = 8.dp)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
SelectionContainer { Text(value, style = MaterialTheme.typography.bodyMedium) }
}
}
private fun name(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> item.name().ifBlank { item.address() }
is SyncItem.Identity -> item.name()
else -> ""
}
private fun details(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port())
is SyncItem.Identity -> item.nickname()
else -> ""
}
private fun count(n: Int, one: String, many: String) = "$n ${if (n == 1) one else many}"
@@ -0,0 +1,88 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Settings
import kotlin.math.abs
import kotlin.math.roundToInt
private const val MIN_BITRATE_KBITS = 8f
private const val MAX_BITRATE_KBITS = 160f
/** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */
@Composable
fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) {
val settings = vm.settings
fun change(edit: Settings.() -> Unit) {
settings.edit()
vm.applySettings()
}
var vbr by remember { mutableStateOf(settings.vbr) }
var fec by remember { mutableStateOf(settings.fec) }
var music by remember { mutableStateOf(settings.music) }
var redundancy by remember { mutableStateOf(settings.redundancyDelay) }
var copies by remember { mutableStateOf(settings.redundancyCopies) }
var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) }
SubScreen("Network", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Encoder")
Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) {
change { bitrate = it.roundToInt() * 1000 }
}
Toggle("Variable bitrate (VBR)", vbr) {
vbr = it
change { this.vbr = it }
}
Toggle("Forward error correction (FEC)", fec) {
fec = it
change { this.fec = it }
}
Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) {
change { complexity = it.roundToInt() }
}
Toggle("Music codec (stereo, higher fidelity)", music) {
music = it
change { this.music = it }
}
Section("Redundancy")
ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) {
redundancy = it
change { redundancyDelay = it }
}
if (redundancy > 0) {
Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" },
steps = Settings.MAX_REDUNDANCY_COPIES - 2) {
copies = it.roundToInt()
change { redundancyCopies = copies }
}
}
Section("Receive")
ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) {
receiveBuffer = it
change { this.receiveBuffer = it }
}
}
}
}
/** A slider stepping through the millisecond [choices], starting at the one nearest [ms]. */
@Composable
private fun ChoiceLevel(label: String, choices: IntArray, ms: Int, onDone: (Int) -> Unit) {
val index = choices.indices.minBy { abs(choices[it] - ms) }
fun at(position: Float) = choices[position.roundToInt()]
Level(label, index.toFloat(), 0f..(choices.size - 1).toFloat(), { at(it).let { v -> if (v == 0) "Off" else "$v ms" } },
steps = choices.size - 2) { onDone(at(it)) }
}
@@ -0,0 +1,42 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.IconTheme
val LocalIconTheme = staticCompositionLocalOf<IconTheme> { error("No icon theme provided") }
/** An icon of the active pack, named by its TeamSpeak key; art in the text colour takes [LocalContentColor]. */
@Composable
fun PackIcon(key: String, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) =
PackIcon(listOf(key), contentDescription, modifier, size)
/** The first of [keys] the pack has, for icons packs need not ship in every variant. */
@Composable
fun PackIcon(keys: List<String>, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) {
val theme = LocalIconTheme.current
val active by theme.active.collectAsStateWithLifecycle()
val pixels = with(LocalDensity.current) { size.roundToPx() }
val color = LocalContentColor.current
val rgb = color.copy(alpha = 1f).toArgb()
val bitmap = remember(keys, pixels, rgb, active) { theme.render(keys, pixels, rgb)?.asImageBitmap() }
if (bitmap == null) {
Spacer(modifier.size(size))
} else {
// Disabled controls fade their content colour; the pack's own colours fade with it.
Image(bitmap, contentDescription, modifier.size(size), alpha = color.alpha)
}
}
@@ -0,0 +1,220 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import eu.lixko.ts3j.client.android.Picture
import eu.lixko.ts3j.client.android.SavedPictures
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.decodePicture
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** A picture to open full size. */
class ViewedPicture(
/** What to call it when saved, without an extension. */
val name: String,
/** Where it is on the web; null for an avatar. */
val url: String? = null,
/** Follows the link it sits in; null when it sits in none. */
val openLink: (() -> Unit)? = null,
/** Our own avatar, which there is no taking. */
val ownAvatar: Boolean = false,
/** Its file; null when it is not there. */
val read: suspend () -> ByteArray?,
)
/** Opens a picture full size; null where nothing can. */
val LocalPictureViewer = staticCompositionLocalOf<((ViewedPicture) -> Unit)?> { null }
/** Lets [content] open pictures full size, over everything, with [server] to take one as our avatar on. */
@Composable
fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) {
var viewed by remember { mutableStateOf<ViewedPicture?>(null) }
CompositionLocalProvider(LocalPictureViewer provides { viewed = it }, content = content)
val context = LocalContext.current
viewed?.let { picture ->
PictureViewer(
picture,
onSteal = if (picture.ownAvatar) null else { data ->
val error = server.setAvatar(data)
Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show()
},
onDismiss = { viewed = null },
)
}
}
/** A name to save the picture at [url] under: its file's, or "picture" when it has none. */
fun pictureName(url: String): String =
url.substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/')
.substringBeforeLast('.').ifBlank { "picture" }
/** The picture on black, filling the screen; pinch or double-tap to zoom, tap to hide the bar. */
@Composable
private fun PictureViewer(
picture: ViewedPicture,
/** Takes the picture as our avatar; null when it cannot be. */
onSteal: (suspend (ByteArray) -> Unit)?,
onDismiss: () -> Unit,
) {
val state by produceState<Shown?>(null, picture) {
val data = picture.read()
value = Shown(data, data?.let { withContext(Dispatchers.Default) { decodePicture(it, MAX_PX) } })
}
val data = state?.data
var bar by remember { mutableStateOf(true) }
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
var size by remember { mutableStateOf(IntSize.Zero) }
fun panTo(target: Offset) {
val maxX = size.width * (scale - 1) / 2
val maxY = size.height * (scale - 1) / 2
offset = Offset(target.x.coerceIn(-maxX, maxX), target.y.coerceIn(-maxY, maxY))
}
Dialog(onDismiss, DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
Box(
Modifier.fillMaxSize().background(Color.Black).onSizeChanged { size = it }
.pointerInput(Unit) {
detectTapGestures(
onTap = { bar = !bar },
onDoubleTap = { scale = if (scale > 1f) 1f else DOUBLE_TAP_SCALE; panTo(Offset.Zero) },
)
}
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(1f, MAX_SCALE)
panTo(offset + pan)
}
},
contentAlignment = Alignment.Center,
) {
val shown = state?.picture
when {
state == null -> PackIcon("LOADING_IMAGE", "Loading picture")
shown == null -> PackIcon("BROKEN_IMAGE", "Broken picture")
else -> Image(
rememberPicturePainter(shown), null,
Modifier.fillMaxSize().graphicsLayer {
scaleX = scale
scaleY = scale
translationX = offset.x
translationY = offset.y
},
contentScale = ContentScale.Fit,
)
}
if (bar) {
CompositionLocalProvider(LocalContentColor provides Color.White) {
Bar(picture, data, onSteal, onDismiss, Modifier.align(Alignment.TopCenter))
}
}
}
}
}
@Composable
private fun Bar(
picture: ViewedPicture,
data: ByteArray?,
onSteal: (suspend (ByteArray) -> Unit)?,
onDismiss: () -> Unit,
modifier: Modifier,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
Row(
modifier.fillMaxWidth()
.background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.6f), Color.Transparent)))
.statusBarsPadding(),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
Box(Modifier.weight(1f))
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Picture options") }
DropdownMenu(menu, onDismissRequest = { menu = false }) {
DropdownMenuItem({ Text("Save") }, enabled = data != null, onClick = {
menu = false
val bytes = data ?: return@DropdownMenuItem
scope.launch {
val saved = SavedPictures.save(context, picture.name, bytes)
Toast.makeText(context, if (saved) "Saved." else "Could not save.", Toast.LENGTH_SHORT).show()
}
})
if (onSteal != null) {
DropdownMenuItem({ Text("Steal for avatar") }, enabled = data != null, onClick = {
menu = false
val bytes = data ?: return@DropdownMenuItem
scope.launch { onSteal(bytes) }
})
}
picture.url?.let { url ->
DropdownMenuItem({ Text("Copy URL") }, onClick = {
menu = false
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("URL", url))
})
}
picture.openLink?.let { open ->
DropdownMenuItem({ Text("Open link") }, onClick = {
menu = false
onDismiss()
open()
})
}
}
}
}
}
/** The picture's file, and the picture when the file is one; both null when it is not there. */
private class Shown(val data: ByteArray?, val picture: Picture?)
private const val MAX_PX = 4096
private const val MAX_SCALE = 8f
private const val DOUBLE_TAP_SCALE = 2.5f
@@ -0,0 +1,95 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.net.ClientStatus
import kotlinx.coroutines.flow.MutableStateFlow
/** What push-to-talk would talk on: the server holding the microphone, which need not be the one on screen. */
internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean)
@Composable
internal fun rememberPttTarget(vm: SessionController): PttTarget {
val owner by vm.micOwner.collectAsStateWithLifecycle()
val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle()
val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle()
val self = tree.client(state.selfClientId)
val talking = self?.status == ClientStatus.TALKING || self?.status == ClientStatus.COMMANDER_TALKING
return PttTarget(owner, state, talking)
}
/** Talks while held. */
@Composable
internal fun PushToTalk(
talking: Boolean,
onPressed: (Boolean) -> Unit,
modifier: Modifier,
shape: Shape = RoundedCornerShape(24.dp),
textStyle: TextStyle = MaterialTheme.typography.titleMedium,
) {
val colors = MaterialTheme.colorScheme
Surface(
modifier.pointerInput(Unit) {
// Held until the finger lifts, wherever it wanders; a tap gesture would end once it left the button.
awaitEachGesture {
awaitFirstDown()
onPressed(true)
try {
do {
val event = awaitPointerEvent()
event.changes.forEach { it.consume() }
} while (event.changes.any { it.pressed })
} finally {
onPressed(false)
}
}
},
shape = shape,
color = if (talking) StatusColors.talking else colors.primaryContainer,
contentColor = if (talking) Color.White else colors.onPrimaryContainer,
) {
Box(contentAlignment = Alignment.Center) {
Text(if (talking) "Talking…" else "Hold to talk", style = textStyle)
}
}
}
/** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */
@Composable
fun GiantPttScreen(vm: SessionController, onBack: () -> Unit) {
val target = rememberPttTarget(vm)
SubScreen("Giant PTT", onBack) { padding ->
val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp)
if (target.owner != null && target.state.connected) {
PushToTalk(target.talking, vm::setForceTransmit, fill, RoundedCornerShape(32.dp),
MaterialTheme.typography.displaySmall)
} else {
Box(fill, contentAlignment = Alignment.Center) {
Text("Not connected",
style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
}
@@ -0,0 +1,120 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.config.ClientRowColors
/** A row background: none, a preset, or a custom colour. [argb] is 0 for none. */
@Composable
internal fun RowColorPicker(label: String, argb: Int, onChange: (Int) -> Unit) {
var open by remember { mutableStateOf(false) }
var custom by remember { mutableStateOf(false) }
Box {
Row(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(label)
Text(nameOf(argb), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Swatch(argb, 28.dp)
}
DropdownMenu(open, { open = false }) {
DropdownMenuItem({ Text("None") }, leadingIcon = { Swatch(0) }, onClick = {
open = false
onChange(0)
})
for (p in ClientRowColors.PRESETS) {
DropdownMenuItem({ Text(p.name()) }, leadingIcon = { Swatch(p.argb()) }, onClick = {
open = false
onChange(p.argb())
})
}
DropdownMenuItem({ Text("Custom…") }, onClick = {
open = false
custom = true
})
}
}
if (custom) {
CustomColorDialog(if (argb != 0) argb else 0x59808080, onDismiss = { custom = false }) {
custom = false
onChange(it)
}
}
}
private fun nameOf(argb: Int): String =
if (argb == 0) "None" else ClientRowColors.presetOf(argb)?.name() ?: "Custom"
@Composable
private fun CustomColorDialog(initial: Int, onDismiss: () -> Unit, onPick: (Int) -> Unit) {
var alpha by remember { mutableIntStateOf(initial ushr 24) }
var red by remember { mutableIntStateOf(initial shr 16 and 0xFF) }
var green by remember { mutableIntStateOf(initial shr 8 and 0xFF) }
var blue by remember { mutableIntStateOf(initial and 0xFF) }
val argb = (alpha shl 24) or (red shl 16) or (green shl 8) or blue
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Custom colour") },
text = {
Column {
Box(Modifier.fillMaxWidth().height(40.dp).clip(RoundedCornerShape(6.dp))
.background(MaterialTheme.colorScheme.surface)) {
Box(Modifier.fillMaxWidth().height(40.dp).background(Color(argb)))
}
Channel("Red", red) { red = it }
Channel("Green", green) { green = it }
Channel("Blue", blue) { blue = it }
Channel("Opacity", alpha) { alpha = it }
}
},
confirmButton = { TextButton({ onPick(argb) }, enabled = argb != 0) { Text("OK") } },
dismissButton = { TextButton(onDismiss) { Text("Cancel") } },
)
}
@Composable
private fun Channel(label: String, value: Int, onChange: (Int) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, Modifier.width(64.dp), style = MaterialTheme.typography.bodySmall)
Slider(value.toFloat(), { onChange(it.toInt()) }, Modifier.weight(1f), valueRange = 0f..255f)
}
}
/** The colour over the screen's background, as a row would show it; outlined so "none" shows too. */
@Composable
private fun Swatch(argb: Int, size: Dp = 20.dp) {
val shape = RoundedCornerShape(4.dp)
Box(Modifier.size(size).clip(shape).background(MaterialTheme.colorScheme.surface).background(Color(argb))
.border(1.dp, MaterialTheme.colorScheme.outline, shape))
}
@@ -0,0 +1,140 @@
package eu.lixko.ts3j.client.android.ui
import android.graphics.BitmapFactory
import android.graphics.drawable.AnimatedImageDrawable
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.Picture
import eu.lixko.ts3j.client.android.ServerImages
import eu.lixko.ts3j.client.gfx.CountryFlags
import eu.lixko.ts3j.client.net.IconRepository
import java.util.Optional
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.roundToInt
/** The images of the server on screen. */
val LocalServerImages = staticCompositionLocalOf<ServerImages?> { null }
/**
* A group, channel or server icon; nothing while it has none or it is still downloading.
* TeamSpeak's default group icons are the pack's, drawn in its style, as on the desktop.
*/
@Composable
fun ServerIcon(id: Long, modifier: Modifier = Modifier, size: Dp = 16.dp) {
if (id == 0L) return
if (id in 1..IconRepository.MAX_BUNDLED_ID) {
val theme = LocalIconTheme.current
val active by theme.active.collectAsStateWithLifecycle()
val pixels = with(LocalDensity.current) { size.roundToPx() }
val rgb = LocalContentColor.current.copy(alpha = 1f).toArgb()
val themed = remember(id, pixels, rgb, active) { theme.render(listOf("GROUP_$id"), pixels, rgb)?.asImageBitmap() }
if (themed != null) {
Image(themed, null, modifier.size(size))
return
}
}
val images = LocalServerImages.current ?: return
val version by images.version.collectAsStateWithLifecycle()
val bitmap = remember(id, version) { images.icon(id) } ?: return
Image(bitmap, null, modifier.size(size))
}
/** A client's avatar, moving if it is an animated GIF; nothing while they have none or it is still downloading. */
@Composable
fun Avatar(uniqueId: String, flag: String, modifier: Modifier = Modifier, size: Dp = 64.dp) {
val images = LocalServerImages.current ?: return
val version by images.version.collectAsStateWithLifecycle()
val picture = remember(flag, version) { images.avatar(uniqueId, flag) } ?: return
Image(rememberPicturePainter(picture), "Avatar", modifier.size(size).clip(RoundedCornerShape(8.dp)))
}
/** Draws [picture], playing it while on screen if it moves. */
@Composable
fun rememberPicturePainter(picture: Picture): Painter = when (picture) {
is Picture.Still -> remember(picture) { BitmapPainter(picture.bitmap) }
is Picture.Moving -> rememberMovingPainter(picture.drawable)
}
@Composable
private fun rememberMovingPainter(drawable: AnimatedImageDrawable): Painter {
val painter = remember(drawable) { MovingPainter(drawable) }
DisposableEffect(drawable) {
drawable.callback = painter
drawable.start()
onDispose {
drawable.stop()
if (drawable.callback === painter) drawable.callback = null
}
}
return painter
}
private class MovingPainter(private val drawable: AnimatedImageDrawable) : Painter(), Drawable.Callback {
/** Read while drawing, so that each new frame draws again. */
private var frame by mutableIntStateOf(0)
private val main = Handler(Looper.getMainLooper())
override val intrinsicSize = Size(drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat())
override fun DrawScope.onDraw() {
frame
drawIntoCanvas { canvas ->
drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt())
drawable.draw(canvas.nativeCanvas)
}
}
override fun invalidateDrawable(who: Drawable) {
frame++
}
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
main.postAtTime(what, `when`)
}
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
main.removeCallbacks(what)
}
}
private val flags = ConcurrentHashMap<String, Optional<ImageBitmap>>()
/** The flag of a country, at TeamSpeak's 16×11; nothing for no country or one without a flag. */
@Composable
fun CountryFlag(code: String, modifier: Modifier = Modifier) {
if (code.isEmpty()) return
val bitmap = remember(code) {
flags.getOrPut(code) {
Optional.ofNullable(CountryFlags.png(code)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() })
}.orElse(null)
} ?: return
Image(bitmap, CountryFlags.name(code), modifier.size(16.dp, 11.dp))
}
@@ -0,0 +1,686 @@
package eu.lixko.ts3j.client.android.ui
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ChatKey
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.TreeFind
import eu.lixko.ts3j.client.android.findIn
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.text.TsLink
import kotlinx.coroutines.launch
private val ChatKeySaver = Saver<ChatKey, String>(
save = { key ->
when (key) {
ChatKey.Server -> "server"
ChatKey.Channel -> "channel"
is ChatKey.Private -> "private:${key.clientId}"
}
},
restore = { saved ->
when {
saved == "server" -> ChatKey.Server
saved.startsWith("private:") -> ChatKey.Private(saved.substringAfter(':').toInt())
else -> ChatKey.Channel
}
},
)
private val ChannelEditSaver = Saver<ChannelEdit?, IntArray>(
save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } },
restore = { ChannelEdit(it[0], it[1]) },
)
/** A channel whose files are browsed, with the password they take. */
private data class FilesOf(val channelId: Int, val name: String, val password: String)
private val FilesOfSaver = Saver<FilesOf?, List<Any>>(
save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } },
restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) },
)
/** A connection: the channel tree and the chat, with the voice controls underneath. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ServerScreen(
vm: SessionController,
server: ServerController,
snackbar: SnackbarHostState,
onSettings: () -> Unit,
/** Opens the given client's contact page. */
onEditContact: (String) -> Unit,
onEnableMicrophone: () -> Unit,
onConnectOther: () -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
) {
val state by server.state.collectAsStateWithLifecycle()
val tree by server.tree.collectAsStateWithLifecycle()
val chats by server.chats.collectAsStateWithLifecycle()
val collapsed by server.collapsed.collectAsStateWithLifecycle()
var showChat by rememberSaveable { mutableStateOf(false) }
// Out here, so the tree keeps its place while the chat or another screen replaces it.
val treeList = rememberLazyListState()
var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf<ChatKey>(ChatKey.Channel) }
val conversation = chats[chatKey] ?: chats.channel
var clientSheet by remember { mutableStateOf<Int?>(null) }
var clientSheetFromTree by remember { mutableStateOf(false) }
/** A row to show in the tree. */
var reveal by remember { mutableStateOf<TreeRef?>(null) }
var channelSheet by remember { mutableStateOf<Int?>(null) }
/** A locked channel being joined, while its password is asked for. */
var joinLocked by remember { mutableStateOf<Int?>(null) }
val join = { channel: ChannelItem ->
if (channel.locked) joinLocked = channel.id else server.joinChannel(channel.id)
}
var serverSheet by remember { mutableStateOf(false) }
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
var banList by rememberSaveable { mutableStateOf(false) }
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf<FilesOf?>(null) }
/** A locked channel whose files are wanted, while its password is asked for. */
var filesLocked by remember { mutableStateOf<Int?>(null) }
var deletingChannel by remember { mutableStateOf<Int?>(null) }
var whisperLists by rememberSaveable { mutableStateOf(false) }
/** What is being added to a whisper list, while the list is picked: its name and how to add it. */
var toWhisperList by remember { mutableStateOf<Pair<String, (WhisperList) -> Unit>?>(null) }
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
/** The client to move, while a channel for them is being picked. */
var moving by remember { mutableStateOf<Int?>(null) }
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
LaunchedEffect(chatRequest) {
val key = chatRequest ?: return@LaunchedEffect
chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId)
showChat = true
server.chatRequestHandled()
}
val viewing = if (showChat) conversation.key else null
LifecycleResumeEffect(viewing) {
server.viewing = viewing
onPauseOrDispose { server.viewing = null }
}
val uriHandler = LocalUriHandler.current
val attachments = rememberAttachmentActions(vm, server, snackbar, conversation.key)
val onLink: (String) -> Unit = { href ->
val ref = TsLink.parse(href)
when {
ChatAttachment.isHref(href) -> attachments.open(href)
ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) }
ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false }
else -> channelSheet = ref.id
}
}
// Find: in the tree, clients or channels; in the chat, the conversation on screen.
val find = rememberSaveable(saver = FindState.Saver) { FindState() }
val treeFind = TreeFind(find.usable, find.channels)
val treeHits = remember(tree, treeFind) { tree.hits(treeFind) }
val treeFiltering = find.filter && !treeFind.query.isEmpty
val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree }
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet<Int>()) }
/** The match the tree is on. */
var treeAt by remember { mutableStateOf<Int?>(null) }
// Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured.
val showTreeHit = { id: Int? ->
if (id != null) {
treeAt = id
val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(treeFind.channels, id)
}
}
LaunchedEffect(treeFind, showChat) {
treeAt = null
if (!showChat) showTreeHit(treeHits.firstOrNull())
}
val chatQuery = find.usable
val chatLines = remember(conversation.lines, chatQuery, find.filter) {
if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines
}
val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) }
/** The match the chat is on; a new search starts from the newest. */
var chatAt by remember { mutableStateOf<ChatMatch?>(null) }
var chatReveal by remember { mutableStateOf<Long?>(null) }
LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) {
chatAt = if (showChat) chatHits.lastOrNull() else null
chatReveal = chatAt?.line
}
val step = { delta: Int ->
if (showChat && chatHits.isNotEmpty()) {
chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)]
chatReveal = chatAt?.line
} else if (!showChat && treeHits.isNotEmpty()) {
showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)])
}
}
if (banList) {
BanListScreen(server, vm.banReasons, onBack = { banList = false })
return
}
channelEdit?.let {
ChannelEditScreen(server, it, onDone = { channelEdit = null })
return
}
files?.let {
FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null })
return
}
if (whisperLists) {
WhisperListsScreen(vm, server, onBack = { whisperLists = false })
return
}
connectionInfo?.let { id ->
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
return
}
BackHandler(showChat) { showChat = false }
BackHandler(moving != null && !showChat) { moving = null }
BackHandler(find.open) { find.open = false }
Scaffold(
// A hardware keyboard's Ctrl+F, as on the desktop.
modifier = Modifier.onPreviewKeyEvent { e ->
val ctrlF = e.isCtrlPressed && e.key == Key.F
if (ctrlF && e.type == KeyEventType.KeyDown) find.show()
ctrlF
},
topBar = {
if (find.open) {
if (showChat) {
FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size,
chatHits.size == MAX_CHAT_MATCHES, step)
} else {
FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step)
}
} else {
TopAppBar(
title = { ServerSwitcher(vm, server, state, onConnectOther) },
expandedHeight = 48.dp,
actions = {
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
if (state.connected) WhisperMenu(vm, server, state) { whisperLists = true }
IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
},
)
}
},
bottomBar = {
Column {
val ptt = rememberPttTarget(vm)
WhisperBanner(state) { server.setWhisper(null) }
VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) {
showChat = !showChat
}
}
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) {
if (!showChat) {
moving?.let { id ->
val client = tree.client(id)
if (client == null) {
LaunchedEffect(id) { moving = null }
} else {
MovePrompt(client.name) { moving = null }
}
}
ChannelTree(
serverName = state.title,
tree = shownTree,
collapsed = if (treeFiltering) filterCollapsed else collapsed,
currentChannel = state.channelId,
onToggle = {
if (!treeFiltering) server.toggleCollapsed(it.id)
else if (it.id in filterCollapsed) filterCollapsed -= it.id
else filterCollapsed += it.id
},
onChannel = { channel ->
val client = moving
when {
channel.spacer != null -> {}
client != null -> { server.moveClient(client, channel.id); moving = null }
else -> channelSheet = channel.id
}
},
onChannelDoubleTap = { channel ->
val client = moving
when {
client != null -> { server.moveClient(client, channel.id); moving = null }
channel.id == state.channelId -> {}
else -> join(channel)
}
},
onClient = { clientSheet = it.id; clientSheetFromTree = true },
onServer = { serverSheet = true },
modifier = Modifier.weight(1f),
reveal = reveal,
onRevealed = { reveal = null },
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) },
listState = treeList,
onShowSelf = {
val path = tree.pathTo(state.selfClientId).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(false, state.selfClientId)
},
)
} else {
ChatPane(
chats = chats,
selected = conversation,
canSend = state.connected,
onSelect = { chatKey = it },
onClose = { key ->
if (chatKey == key) chatKey = ChatKey.Channel
server.closePrivateChat(key)
},
onSend = { server.send(conversation.key, it) },
onAttach = attachments.share,
onLink = onLink,
modifier = Modifier.weight(1f),
lines = chatLines,
find = chatQuery,
current = chatAt,
reveal = chatReveal,
onRevealed = { chatReveal = null },
)
}
}
}
// A sheet goes with its client or channel when that leaves the tree.
clientSheet?.let { id ->
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = { clientSheet = null },
onMessage = {
clientSheet = null
chatKey = server.openPrivateChat(id)
showChat = true
},
onPoke = { server.poke(id, it); clientSheet = null },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); clientSheet = null },
onAddContact = { server.addContact(id, it) },
onEditContact = { clientSheet = null; onEditContact(client.uniqueId) },
onConnectionInfo = { clientSheet = null; connectionInfo = id },
onWhisper = { clientSheet = null; server.whisperToClient(id) },
onAddToWhisperList = {
clientSheet = null
server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } }
},
onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null,
onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
{ server.moveClient(id, state.channelId); clientSheet = null }
} else null,
onFindInTree = if (clientSheetFromTree) null else ({
clientSheet = null
tree.pathTo(id)?.let { server.expand(it) }
showChat = false
reveal = TreeRef(false, id)
}),
moderation = { ClientModeration(server, client) { clientSheet = null } },
)
}
}
channelSheet?.let { id ->
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = { channelSheet = null },
onJoin = { join(channel); channelSheet = null },
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
onBookmark = { channelSheet = null; bookmarkHere(id) },
onWhisper = { channelSheet = null; server.whisperToChannel(id) },
onAddToWhisperList = {
channelSheet = null
server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } }
},
onFiles = {
channelSheet = null
if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "")
},
onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null,
)
}
}
joinLocked?.let { id ->
TextPrompt(
title = "Join ${tree.channel(id)?.name.orEmpty()}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = { joinLocked = null },
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
)
}
filesLocked?.let { id ->
TextPrompt(
title = "Files of ${tree.channel(id)?.name.orEmpty()}",
label = "Channel password",
confirm = "Open",
password = true,
onDismiss = { filesLocked = null },
onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) },
)
}
deletingChannel?.let { id ->
val channel = tree.channel(id)
val scope = rememberCoroutineScope()
AlertDialog(
onDismissRequest = { deletingChannel = null },
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = {
deletingChannel = null
scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } },
)
}
toWhisperList?.let { (name, add) ->
AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName ->
toWhisperList = null
vm.addToWhisperList(index, newName, add)
}
}
if (serverSheet) {
remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = { serverSheet = false },
onBookmark = { serverSheet = false; bookmarkHere(state.channelId) },
onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null,
onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null)
}
}
}
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
private fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
vm: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = vm.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
}
}
}
val away = @Composable {
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
}
}
val chat = @Composable {
IconToggleButton(showChat, { onChat() }) {
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
Modifier.alpha(if (showChat) 1f else 0.7f))
}
}
}
Surface(tonalElevation = 3.dp) {
// The same places whatever shows: sides of three buttons each keep the talk button centred.
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
Slot { mic() }; Slot { deafen() }; Slot { activate() }
}
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
Slot { away() }; Slot { chat() }
}
}
}
}
private val SLOT = 48.dp
private val SIDE = SLOT * 3
/** One button's place in the bar, kept whether or not the button shows. */
@Composable
private fun Slot(content: @Composable () -> Unit) {
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
}
/** An icon button that also answers a long press. */
@Composable
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
Box(
Modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(CircleShape)
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.alpha(if (enabled) 1f else 0.38f),
contentAlignment = Alignment.Center,
) { content() }
}
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by vm.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; vm.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -0,0 +1,127 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.IconTheme
import eu.lixko.ts3j.client.android.SessionController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES, MY_TEAMSPEAK }
/**
* The settings, by category. Every change is saved and put into effect at once,
* as there is no dialog to confirm.
*/
@Composable
fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) {
var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
when (page) {
SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null })
SettingsPage.NETWORK -> return NetworkSettingsScreen(vm, onBack = { page = null })
SettingsPage.GIANT_PTT -> return GiantPttScreen(vm, onBack = { page = null })
SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null })
SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null })
SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null })
null -> {}
}
SubScreen("Settings", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
LinkRow("Contacts", "Friends and blocked users", "CONTACT", onContacts)
LinkRow("Sound Settings", "Devices, transmission, voice activation, processing, volume", "PLAYBACK") {
page = SettingsPage.SOUND
}
LinkRow("Network", "Bitrate, error correction, redundancy, buffering", "PING_4") {
page = SettingsPage.NETWORK
}
LinkRow("Giant PTT", "A push-to-talk button filling the screen", "CAPTURE") {
page = SettingsPage.GIANT_PTT
}
LinkRow("Design", "Icon pack, country flags, client colours, description pictures", "GUISETUP") {
page = SettingsPage.DESIGN
}
LinkRow("Identities", "Create, import, export, security level",
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
LinkRow("myTeamSpeak",
if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}"
else "Sign in to bring over your synchronised bookmarks and identities",
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
}
}
}
@Composable
private fun DesignScreen(vm: SessionController, onBack: () -> Unit) {
SubScreen("Design", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
IconPackPicker(vm.icons)
var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) }
Toggle("Show pictures in descriptions", pictures) {
pictures = it
vm.setDescriptionPictures(it)
}
Section("Channel tree")
var flags by remember { mutableStateOf(vm.settings.countryFlags) }
Toggle("Show country flags in the channel tree", flags) {
flags = it
vm.setCountryFlags(it)
}
val colors = vm.settings.clientRowColors
var any by remember { mutableIntStateOf(colors.any) }
var talking by remember { mutableIntStateOf(colors.talking) }
var mutedAway by remember { mutableIntStateOf(colors.mutedAway) }
RowColorPicker("Client background", any) {
any = it
colors.any = it
vm.clientRowColorsChanged()
}
RowColorPicker("While talking", talking) {
talking = it
colors.talking = it
vm.clientRowColorsChanged()
}
RowColorPicker("Muted / away", mutedAway) {
mutedAway = it
colors.mutedAway = it
vm.clientRowColorsChanged()
}
}
}
}
/** Chooses the icon pack, and brings in TeamSpeak packs from a file. */
@Composable
private fun IconPackPicker(theme: IconTheme) {
val packs by theme.packs.collectAsStateWithLifecycle()
val active by theme.active.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var failed by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
val pack = withContext(Dispatchers.IO) { runCatching { theme.import(uri) }.getOrNull() }
failed = if (pack == null) "That file is not an icon pack." else null
}
}
Picker("Icon pack", packs.map { it to it.name() }, active) { theme.select(it) }
LinkRow("Import icon pack", "A TeamSpeak 3 pack (.zip), such as those in the gfx folder of a TeamSpeak 3 install") {
importer.launch(arrayOf("application/zip", "application/octet-stream"))
}
failed?.let { Hint(it) }
}
@@ -0,0 +1,175 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Slider
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
/** The width a segment needs for a label of a word or two; narrower screens get a list instead. */
private val SEGMENT_WIDTH = 110.dp
/** A full-screen page with a back arrow; the system back gesture leaves it the same way. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SubScreen(
title: String,
onBack: () -> Unit,
actions: @Composable RowScope.() -> Unit = {},
snackbar: SnackbarHostState? = null,
content: @Composable (PaddingValues) -> Unit,
) {
BackHandler(onBack = onBack)
Scaffold(
snackbarHost = { snackbar?.let { SnackbarHost(it) } },
topBar = {
TopAppBar(
title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = actions,
)
},
content = content,
)
}
/** A row that opens another page, or does one thing when tapped. */
@Composable
internal fun LinkRow(title: String, summary: String?, iconKey: String? = null, onClick: () -> Unit) {
ListItem(
headlineContent = { Text(title) },
supportingContent = summary?.let { { Text(it) } },
leadingContent = iconKey?.let { { PackIcon(it, null) } },
modifier = Modifier.clickable(onClick = onClick),
)
}
@Composable
internal fun Section(title: String) {
Text(title, Modifier.padding(start = 16.dp, top = 24.dp, bottom = 4.dp),
style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
}
@Composable
internal fun Choice(label: String, selected: Boolean, onSelect: () -> Unit) {
Row(Modifier.fillMaxWidth().clickable(onClick = onSelect).padding(horizontal = 16.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically) {
RadioButton(selected, onClick = onSelect)
Text(label, Modifier.padding(start = 8.dp))
}
}
/** One of [options] as a row of segments, or as radio buttons where the segments would not fit. */
@Composable
internal fun <T> Segments(options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth - 32.dp < SEGMENT_WIDTH * options.size) {
Column { for ((value, label) in options) Choice(label, value == selected) { onSelect(value) } }
return@BoxWithConstraints
}
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) {
options.forEachIndexed { index, (value, label) ->
SegmentedButton(
selected = value == selected,
onClick = { onSelect(value) },
shape = SegmentedButtonDefaults.itemShape(index, options.size),
) { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }
}
}
}
}
@Composable
internal fun Toggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
Row(Modifier.fillMaxWidth().clickable { onChange(!checked) }.padding(horizontal = 16.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically) {
Text(label, Modifier.weight(1f))
Switch(checked, onChange)
}
}
@Composable
internal fun Hint(text: String) {
Text(text, Modifier.padding(horizontal = 16.dp, vertical = 2.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
/** One of [options], shown as its label and picked from a menu. */
@Composable
internal fun <T> Picker(label: String, options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {
var open by remember { mutableStateOf(false) }
Box {
Column(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(label)
Text(options.firstOrNull { it.first == selected }?.second ?: "", style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(open, { open = false }) {
for ((value, text) in options) {
DropdownMenuItem({ Text(text) }, onClick = {
open = false
onSelect(value)
})
}
}
}
}
/** A slider that applies its value once let go of. */
@Composable
internal fun Level(
label: String,
value: Float,
range: ClosedFloatingPointRange<Float>,
format: (Float) -> String,
steps: Int = 0,
onChange: (Float) -> Unit = {},
onDone: (Float) -> Unit,
) {
var current by remember(value) { mutableFloatStateOf(value) }
Column(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) {
Row {
Text(label, Modifier.weight(1f))
Text(format(current), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Slider(current, {
current = it
onChange(it)
}, valueRange = range, steps = steps, onValueChangeFinished = { onDone(current) })
}
}
@@ -0,0 +1,238 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.net.Details
import kotlin.math.roundToInt
/** What can be done with a client: the private chat, a poke, a move, their volume, filing them as a contact. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ClientSheet(
client: ClientItem,
details: Details?,
onLink: (String) -> Unit,
away: Boolean,
initialVolume: Double,
onDismiss: () -> Unit,
onMessage: () -> Unit,
onPoke: (String) -> Unit,
onVolume: (Double) -> Unit,
onAway: (Boolean) -> Unit,
onAddContact: (ContactType) -> Unit,
onEditContact: () -> Unit,
onConnectionInfo: () -> Unit,
onWhisper: () -> Unit,
onAddToWhisperList: () -> Unit,
/** Null when the client cannot be moved. */
onMove: (() -> Unit)?,
/** Null when the client cannot be moved, or is in our channel already. */
onMoveToOwnChannel: (() -> Unit)?,
/** Null when the sheet was opened from the tree. */
onFindInTree: (() -> Unit)?,
/** Kicks, bans and groups, as far as we may use them. */
moderation: @Composable () -> Unit = {},
) {
var poking by remember { mutableStateOf(false) }
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
StatusIcon(client.status)
Column(Modifier.weight(1f)) {
// The country's flag goes before the name, as in TeamSpeak's info frame.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CountryFlag(client.country)
Text(client.name, style = MaterialTheme.typography.titleLarge)
}
if (client.name != client.nickname) Text(client.nickname, style = MaterialTheme.typography.bodyMedium)
if (client.awayMessage.isNotEmpty()) Text(client.awayMessage, style = MaterialTheme.typography.bodyMedium)
}
val viewer = LocalPictureViewer.current
val images = LocalServerImages.current
Avatar(client.uniqueId, client.avatarFlag, Modifier.clickable(enabled = viewer != null && images != null) {
viewer?.invoke(ViewedPicture("avatar_${client.nickname}", ownAvatar = client.self) {
images?.avatarData(client.uniqueId, client.avatarFlag)
})
})
}
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) }
Action("INFO", "Connection info", onClick = onConnectionInfo)
if (client.self) {
Action("AWAY", if (away) "Back" else "Away") { onAway(!away) }
moderation()
} else {
Action("PLAYER_CHAT", "Send message", onClick = onMessage)
Action("POKE", "Poke") { poking = true }
Action("PLAYER_WHISPER", "Whisper", onClick = onWhisper)
Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList)
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) }
moderation()
if (client.contactType == null) {
Row {
Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) }
Action("ADD_FOE", "Block", Modifier.weight(1f)) { onAddContact(ContactType.BLOCKED) }
}
} else {
Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact)
}
var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) }
Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB",
Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium)
Slider(
volume, { volume = it.roundToInt().toFloat() },
Modifier.padding(horizontal = 24.dp),
valueRange = -30f..20f,
onValueChangeFinished = { onVolume(volume.toDouble()) },
)
}
}
}
if (poking) {
TextPrompt(
title = "Poke ${client.name}",
label = "Message",
confirm = "Poke",
onDismiss = { poking = false },
onConfirm = { poking = false; onPoke(it) },
)
}
}
/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChannelSheet(
channel: ChannelItem,
details: Details?,
onLink: (String) -> Unit,
current: Boolean,
onDismiss: () -> Unit,
onJoin: () -> Unit,
onSubscribe: (Boolean) -> Unit,
onBookmark: () -> Unit,
onWhisper: () -> Unit,
onAddToWhisperList: () -> Unit,
onFiles: () -> Unit,
/** Each null when we may not. */
onCreateSub: (() -> Unit)?,
onEdit: (() -> Unit)?,
onDelete: (() -> Unit)?,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Text(channel.name, Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
style = MaterialTheme.typography.titleLarge)
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
if (!current) {
Action("CHANNEL_SWITCH", "Join", onClick = onJoin)
}
if (channel.subscribed) {
Action("UNSUBSCRIBE_FROM_CHANNEL", "Unsubscribe") { onSubscribe(false) }
} else {
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
}
Action("WHISPER", "Whisper", onClick = onWhisper)
Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList)
Action("FILETRANSFER", "Browse files", onClick = onFiles)
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) }
}
}
}
/** The server's details: its version, who is on it, its welcome message. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ServerSheet(
details: Details,
onLink: (String) -> Unit,
onDismiss: () -> Unit,
onBookmark: () -> Unit,
onBanList: (() -> Unit)?,
onCreateChannel: (() -> Unit)?,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
PackIcon("SERVER_GREEN", null)
Text(details.title(), style = MaterialTheme.typography.titleLarge)
}
DetailsSection(details, onLink)
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
onCreateChannel?.let { Action("CHANNEL_CREATE", "Create channel", onClick = it) }
onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) }
}
}
}
@Composable
internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifier.fillMaxWidth(), onClick: () -> Unit) {
ListItem(
headlineContent = { Text(label) },
leadingContent = { PackIcon(iconKey, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = modifier.clickable(onClick = onClick).padding(horizontal = 8.dp),
)
}
/** Asks for one line of text. */
@Composable
fun TextPrompt(
title: String,
label: String,
confirm: String,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
initial: String = "",
password: Boolean = false,
) {
var text by remember { mutableStateOf(initial) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
OutlinedTextField(text, { text = it }, label = { Text(label) }, singleLine = true,
visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None)
},
confirmButton = { TextButton(onClick = { onConfirm(text) }) { Text(confirm) } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}

Some files were not shown because too many files have changed in this diff Show More