Compare commits

..
267 Commits
Author SHA1 Message Date
erikbrockoandClaude Opus 5.5 d96339b72b Desktop: Customize Toolbar window
test / test (push) Has been cancelled
Right-clicking the toolbar now offers Customize Toolbar…, laid out like
the official window: a searchable tree of available actions by category,
the selected actions list, arrow buttons, drag and drop, and Reset to
Defaults. Changes apply live and are kept in the toolbarLayout setting,
empty standing for the default layout.

The toolbar is built from that layout out of 68 actions over connection,
self, dialogs, permissions, recording, channel, client and misc. Channel
actions act on the selected channel (or the selected client's, else our
own), client actions on the selected clients; buttons follow the tree
selection. Actions without a pack icon show their name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 07:08:19 +00:00
erikbrockoandClaude Opus 5.5 212a4bcdbb myTeamSpeak docs: the synced config item, sync edge cases and limits
CONFIG_SYNC.md lists the class 5 config item's fields; none maps onto a
setting of ours, so sync leaves it alone. IMPLEMENTATION.md covers the
session lock, duplicate keys in the account, bookmarks following an
identity's conflict, interrupted runs, and what sync cannot catch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:04:26 +00:00
erikbrockoandClaude Opus 5.5 f6fbc6e40c myTeamSpeak: sign-ins no longer block the UI; sync fixes
Signing in held the login's lock across its requests, so asking whether
we are signed in waited for the network, up to a minute and more on a
throttled account; the session now has a lock of its own.

An identity whose key another account item already stands for is left as
the account has it, instead of merged into ours and written back over the
other. A bookmark that only lost an identity deleted here follows how
that identity's conflict is settled, rather than dropping the link even
when the identity is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:45:59 +00:00
erikbrockoandClaude Opus 5.5 1f61ad0b29 Android: Synchronize with myTeamSpeak; keep each installation's default identity
Settings → myTeamSpeak gets Synchronize, with conflicts settled in
SyncConflictsScreen. The default identity is no longer a synced field:
an identity new to the account carries it only when the account has
none, and one brought here takes it only when we have none, so
installations stop flipping each other's default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:37:04 +00:00
erikbrockoandClaude Opus 5.5 116986c6fc Desktop: Synchronize with myTeamSpeak, with a conflicts window
Options -> myTeamSpeak gains Synchronize. Items changed here and in the
account since the last run are listed field by field, the differences in
bold, each kept from one side; nothing changes until all are settled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:37:50 +00:00
erikbrockoandClaude Opus 5.5 756e3850a3 myTeamSpeak: two-way sync of bookmarks and identities
MyTeamSpeakSync compares each item against what the last run left: a
change on one side goes to the other, deletions too, and an item changed
on both sides is a conflict for the user. The first run pairs items up by
identity key or bookmark name and address. Edits are written over the
item's Item_Data field by field, so what we do not model survives.

The protocol was probed live and checked against the official client:
the server stores whatever revisions it is sent and never reports a
collision, so the client re-reads the cursors before writing. Edits carry
last_known_version like the official client's, which applies them within
its one-minute poll. All requests now share one session; signing in for
each got the account's logins throttled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:37:50 +00:00
erikbrockoandClaude Opus 5.5 ab6bf30003 Link addresses written without a scheme, over https
Servers write [url=www.teamspeak.com]; it showed as raw BBCode. An address
without a scheme now opens over https, as bare www. text in a message does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:32:18 +00:00
erikbrockoandClaude Opus 5.5 0043c03410 Desktop: no exceptions when servers report leaving after shutdown
Quitting from the shutdown hook (SIGTERM) leaves every server, whose
disconnects then reach the mic hand-over and the notifier after their
threads have stopped. Both now drop work that comes in that late.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:30:11 +00:00
erikbrockoandClaude Opus 5.5 e9110c2767 Audit: note that an upload counts as done before the server has it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 d61e96a07f ts3j: pad a short RSA puzzle answer instead of failing the connect
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 8239a41c6a Report leaving a server once
Our own leave also fires the socket's disconnect event, queued, so it was
reported twice, and a late one could tear down a reconnect already under way.
The event now counts only for the current socket, and not while we leave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 cdbf051ca6 Android: don't crash on connect on Android 13
ChatFeed used Stream.toList(), which Android only has from API 34.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 902f036ba0 Structural audit: record 12's commit; defer 13 and 14
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:47:16 +00:00
erikbrockoandClaude Opus 5.5 7e794ffffe Swing ui package split by feature
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:34:12 +00:00
erikbrockoandClaude Opus 5.5 6070160fb6 Android servers get their shared parts from ServerParts, not SessionController
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:25:51 +00:00
erikbrockoandClaude Opus 5.5 382d76c3d8 Android app-wide stores out of SessionController; screens take only their parts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:55:08 +00:00
erikbrockoandClaude Opus 5.5 78b66ef346 Android ServerScreen state in holders: nav, find, picking; overlays apart
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:35:45 +00:00
erikbrockoandClaude Opus 5.5 a2a12804ad Chat lines are routed once, in core
session.ChatFeed decides which conversation a message, history, server
event or notice goes to and renders it; frontends get the lines through
chat.ChatSink and key conversations by chat.ChatKey. ServerSession.Listener
no longer passes on raw chat events. Swing now labels our own messages
with our nickname on the server and links our name to us in private chats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 23:37:33 +00:00
erikbrockoandClaude Opus 5.5 53585994a8 One byte-size format and one chat scope
text.ByteSize writes sizes and rates as TeamSpeak does and replaces the
formatters in ChatHtml, FileBrowserDialog and ConnectionStatsFormat.
chat.ChatScope replaces ConnectionListener.ChatScope, ChatLogScope and
ChatPanel.Target, and the mappings between them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 23:01:42 +00:00
erikbrockoandClaude Opus 5.5 203082d040 Settings values are Setting<T>: one key each, change listeners
Each setting is declared once with its key, type and range, and loaded
and saved from that list. Output device, volume and receive buffer, the
status bar and the master volume slider take effect through listeners
instead of calls wherever they change; Android does the same for output
settings and country flags. The Playback page previews voice volume with
the master volume applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 22:53:37 +00:00
erikbrockoandClaude Opus 5.5 bbe741d5cf Name abstract base classes Abstract*; no null as "nothing" in list windows
ServerListDialog, ListEditorDialog and CtlOpusEncoder gain the Abstract
prefix. The list windows blank their status line with clearStatus() and
make icon-less menu items with item(text, action), instead of passing null.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:36:37 +00:00
erikbrockoandClaude Opus 5.5 e214f2141e Server list windows share one ServerListDialog base
The ban list, complaints, privilege keys, offline messages and server
log windows each built the same frame, title, status line, key bindings,
load guard and reload-after-change. ServerListDialog does that once;
ServerTab keeps the open windows in one map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:36:16 +00:00
erikbrockoandClaude Opus 5.5 f7cf0401e4 Menu bar, toolbar and hotkeys share one set of commands
MainCommands holds each command once: the plain ones act on the server
on screen, the ones taking a list of sessions serve hotkeys, which reach
the selected server or every connected one. The menu bar, toolbar and
HotkeyActions call it directly, so both Listener interfaces and the
forwarding in MainFrame are gone.

The menu's mute items no longer click the toolbar's buttons, and its
commander toggle now repaints the toolbar and tray.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:14:31 +00:00
erikbrockoandClaude Opus 5.5 de42429d08 Frontends reach a server only through ServerSession
session.connection() is gone: the session hands out the model, our ids,
the microphone and speakers, ping and connection info, the server's
unique id, icon and avatar stores, myTeamSpeak, the connect error and a
blocking disconnectNow. The connection's remaining actions move into
helpers the session hands out instead of forwarding each method:
ClientAdmin (move, kick, ban, groups, talk power, poke, client details),
ChannelFiles (listing, mkdir, rename, delete, transfers and their
sounds) and ClientContacts (display names, volume, auto-mute, whisper
policy, sightings); ChannelAdmin also takes join, move, subscribe and
description requests. Dialogs take the session instead of the
connection.

Android's network handover now uses disconnectNow, which also cancels a
pending auto-reconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:58:25 +00:00
erikbrockoandClaude Opus 5.5 9107bdd02e Move our own state out of TeamspeakConnection: OwnClient, Recording
OwnClient owns the microphone and speakers and our flags (mute, deafen,
away, commander, talk request, phonetic nickname, input hardware) and
publishes them; Recording owns the recorder. ServerSession reads the
flags from OwnClient instead of keeping its own copy, and they are now
cleared when a connect starts rather than once it is done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:04:01 +00:00
erikbrockoandClaude Opus 5.5 c2090d8122 Keep ini4j's reflectively created constructors in release builds
R8 stripped IniParser's no-arg constructor, which ini4j's ServiceFinder
instantiates by reflection, so reading identities (myTeamSpeak login,
import) crashed the release build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:48:59 +00:00
erikbrockoandClaude Opus 5.5 959f7ed97a Frontends call the admin helpers directly, not through the connection
The channel, ban, privilege key, complaint, server log, offline message
and avatar helpers are public, each method running in the background and
answering a future; only the connection creates them. TeamspeakConnection
and ServerSession hand them out, which drops 30 one-line forwarders from
the connection. What the forwarders added moves into the helpers: the
stop-at-the-first-refusal loops, the "sent" log lines, re-reading an
edited channel's description and showing our own new avatar. The
complaint and offline message length limits move with them.

The icon chooser and the offline message composer take only their
helper; the other dialogs still need the connection for the model.

The connection's request runner is renamed Uplink, since
session.ServerLink is the ts3server:// link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:45:21 +00:00
erikbrockoandClaude Opus 5.5 da908f77bd Run server requests through ServerLink, not the whole connection
ServerLink owns what lives from one connect to its teardown: the socket,
the thread ts3j dispatches events on, the threads requests run on and
the file transfer channel. It runs requests in the background and says
whether we are connected. The *Admin helpers take it, plus the model,
permissions or avatar store where they need them, instead of the whole
TeamspeakConnection; the connection's file transfer calls share its
"not connected" check instead of repeating it.

A myTeamSpeak refresh that fails because we left meanwhile is no longer
reported, as for every other request.

Also corrects 4a's commit hash in AUDIT-STRUCTURE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:40:11 +00:00
erikbrockoandClaude Opus 5.5 1bc7eb58c1 Move the chat log and announcements out of TeamspeakConnection
ChatLog opens the on-disk log once the server is known, hands frontends
the server and channel history, and saves sent and received messages and
the server tab's log lines; with logging off, everything still reaches
the app unsaved. Announcer tells the user what happened as TeamSpeak
does: the server-tab line with linked channels and clients, the sound
pack's sound with its name variables, and errors with the matching
"insufficient permissions" or "error" sound.

ConnectionEventHandler uses both directly instead of nine helpers on the
connection, which no longer holds the sound notifier. The connection's
public API is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:11:23 +00:00
erikbrockoandClaude Opus 5.5 13e3a62042 Answer what we may do in one place: Permissions
The rules were spread over ServerSession's can* methods, ServerModel's
permits/mayHavePower/canDelete*, TeamspeakConnection and AvatarAdmin, and
Swing dialogs and Android's ServerController passed raw permission names.
Permissions now holds the server's permission table and the rules (offered
until the server says, unreported powers unknown until asked) and answers
one named question per capability. ServerSession.permissions() is the gate
for frontends: Permissions.NONE, allowing nothing, while disconnected.
ServerController's forwarding properties go the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:53:11 +00:00
erikbrockoandClaude Opus 5.5 e255a4669c Parse a client's properties once, for joins and updates alike
onClientJoin set every field and onClientChanged set the same ones again
behind presence checks, so the two drifted: a client entering as channel
commander showed as none until they toggled it, and the description they
entered with was dropped. applyClientProperties now maps each field once,
only when the event carries it, as applyChannelProperties does for
channels; the update keeps its side effects (info refresh, contacts,
unread count, announcements).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:47:34 +00:00
erikbrockoandClaude Opus 5.5 0552ed8be6 Requests return futures that fail with a typed RequestException
Server requests on TeamspeakConnection took callbacks given a value and an
error string, null on success, so frontends told a permission refusal from
other failures by the message's wording (ban list, server log) and core
needed a sentinel message for a refused search. They now return a
CompletableFuture that fails with a RequestException carrying the kind
(not connected, permission, failed) and the server's reason.

Replies hands the outcome to a success or a failure handler on a given
executor; Swing's Edt runs them on the event thread, so call sites no
longer marshal by hand. Android's ServerController, whose suspend calls
answered a String? that was null once done, returns Result instead.
lookupDatabaseClient answers an Optional rather than null.

Starts the structural audit in AUDIT-STRUCTURE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:25:07 +00:00
erikbrockoandClaude Opus 5.5 985c54a362 Android: one APK for both ABIs in releases too
Drops the per-ABI release splits for abiFilters on arm64-v8a and x86_64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:56:34 +00:00
erikbrockoandClaude Opus 5.5 4ce78e9b29 Android: swipe between tree and chat, servers, and chat tabs
A sideways swipe over the channel tree turns to the chat (lying to its
right) or to the neighbouring connected server, as picked in Design
settings ("Swipe sideways": off, channel tree and chat, connected
servers). A swipe over the chat lines goes to the neighbouring tab, on
by default, and the tab row scrolls it into view. The page beside the
one on show follows the finger (SwipeHost); a swipe with nowhere to go
is left to the host further out, so the chat's tabs hand over to the
chat/tree swipe at either end. The choices are Android-only, kept in
their own SharedPreferences (SwipePrefs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:56:34 +00:00
erikbrockoandClaude Opus 5.5 13c1e8a659 Reconnect on desktop after a dropped connection
After a timeout or a server shutdown the session counts down and connects
again, back to the channel it was in, waiting 5, 10, 20, 40 and then 60 s
between attempts. A kick, a ban, leaving, or connecting elsewhere ends it, as
does a retry refused with a ban. The status bar shows the countdown with a
Cancel link. Off by default in core, so Android keeps its own NetworkFollower.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:30:14 +00:00
erikbrockoandClaude Opus 5.5 b7a5828c43 Remember the window's place and the tree/chat divider
The main window comes back at its last size and position, maximised if it was;
a place no longer on any screen falls back to the default. The tree/chat
divider is saved like the tree/info one, and both keep their share of the
window as it is resized.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:30:14 +00:00
erikbrockoandClaude Opus 5.5 a57700959f Request, grant and revoke talk power
Core keeps client_is_talker, the request's time and reason, and each
channel's needed talk power; clientedit grants or revokes, and "grant
next" picks whoever in our channel asked first, optionally revoking the
rest. The server refuses a request or a grant ("invalid parameter") from
or for a client that can already talk, so both are offered only to those
short of talk power. Grants dropped without an invoker (leaving the
channel, the channel's need changing) are not announced. Verified on a
local 3.13.7 server.

Desktop: Grant/Revoke Talk Power in the client menu, also for several
selected clients; the tree's badges in TeamSpeak's order (granted or
insufficient ahead of the groups, a request after them); the request's
reason in the info panel; log lines; the three talk power hotkeys. The
Self menu's request item shows only while it is needed.
Android: grant/revoke among the client sheet's admin actions, request or
cancel on our own sheet, the same badges in the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:15:39 +00:00
erikbrockoandClaude Opus 5.5 204cbd6048 Android: client sheet's admin actions behind "Admin actions…"
Move to channel, the kicks, the ban and the group pickers move under one
row that, once tapped, gives its place to them, raises the sheet and
scrolls them into view (ExpandableAction). The row shows only when one of
them is ours to use; "Move to own channel" stays in the main list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:51:05 +00:00
erikbrockoandClaude Opus 5.5 7fde4f502a Offer move/kick/ban when the server won't tell our powers
Asking for i_client_move_power and the like (permget) needs
b_client_permissionoverview_own, which custom moderator groups often lack
although they hold the powers; servergrouppermlist is refused too. A
refusal counted as 0, so Android hid actions the official client allows.
Now a refusal means unknown and the actions are offered, as the official
client always does, leaving the server to judge; only an answered 0 hides
them. Verified with such a group on a local 3.13.7 server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:50:58 +00:00
erikbrockoandClaude Opus 5.5 c41b86f704 Select several clients in the tree to move or kick them together
Desktop: Ctrl/Shift in the tree (ClientSelectionModel keeps a selection to
one row of any kind or several clients; a Shift range keeps its clients),
drag them onto a channel, or right-click for Kick Clients from Channel /
Server and Move Clients to own Channel. The selection survives rebuilds.
Android: long-press a client, tap more; a bar offers Move to…, Move to my
channel and both kicks (as far as we may), Back clears it.

Core sends one piped clientmove / clientkick. The server refuses the whole
pipe when one row fails ("already member of channel"), so it leaves out
clients already in the target, and for a channel kick those already in
the default channel, which the model now tracks (channel_flag_default).
Verified on a local 3.13.7 server with both frontends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:50:32 +00:00
erikbrockoandClaude Opus 5.5 96e926168c Android: reorder the client sheet
Connection info moves to the end, just above the volume slider, which
stays last; "Add to whisper list…" is left out of the sheet for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:13:39 +00:00
erikbrockoandClaude Opus 5.5 3948db69bb Bookmarks: "this channel" button instead of the channel's "Add to bookmarks"
The bookmark editors (desktop dialog, Android screen) get TeamSpeak's
button beside the default channel, with its MAKE_CURRENT_CHANNEL_DEFAULT
icon: it takes the channel we are in, enabled while we are on the server
the form's address and port lead to (Sessions.connectedTo). The Android
channel sheet drops "Add to bookmarks"; the server sheet keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:03:04 +00:00
erikbrockoandClaude Opus 5.5 173e710960 Android: per-bookmark "Show whisper controls", off by default
Whispering can't be gated on permissions: our i_client_whisper_power is
never reported (and guests may not permget it), and whether a whisper gets
through depends on the target's needed whisper power, which clients can't
see. So the whisper menu and the Whisper / Add to whisper list actions are
shown only for servers connected from a bookmark that asks for them; an
edit of that bookmark applies without reconnecting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:03:00 +00:00
erikbrockoandClaude Opus 5.5 d3731e297b Hide "Browse files" without the permission to list files
The channel menu (desktop) and channel sheet (Android) leave the entry out
when i_ft_file_browse_power is 0. Unlike move/kick/ban powers it is among the
needed permissions the server reports, and with it at 0 ftgetfilelist is
refused even where the channel needs no power (verified on a local 3.13.7).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:02:45 +00:00
erikbrockoandClaude Opus 5.5 801dfa39ab myTeamSpeak: announce the account ID to servers
Signs clientinit with the account's Ed25519 key over the connection
challenge, honours the per-bookmark switch, sends updatemytsid on
sign-in/out, and connects without the ID when myTeamSpeak is unreachable.
Verified live against server.lixko.eu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:04:59 +00:00
erikbrockoandClaude Opus 5.5 ca86c510b7 myTeamSpeak: import TeamSpeak 6 contacts; bookmark myTeamSpeak switch
TeamSpeak 6 syncs chat contacts as item class 8 (Item_Data field 25). They
are imported as friends keyed by myTeamSpeak ID, taken from the item or from
the partner's chat ID (@<base32 id>:<homeserver>), the same bytes servers
report as base64 client_myteamspeak_id. The contact list matches them to
clients through the ID each client carries.

Bookmarks gain TeamSpeak's "Enable myTeamSpeak features" switch
(send_mytsid_on_server), stored and imported but not yet sent; what is
still missing is noted in docs/myteamspeak/myteamspeak_server_signin.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:56:29 +00:00
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
erikbrockoandClaude Opus 5.5 2351b174f8 Leave all servers in parallel on shutdown
test / test (push) Has been cancelled
Quitting tells every server goodbye at once, so leaving takes as long as
the slowest server rather than all of them together. Desktop and Android
both go through ServerSession.shutdownAll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 06:55:15 +00:00
erikbrockoandClaude Opus 5.5 5fd2a612b9 Show the local client's state in the Android connection notification, like the tray icon
The notification follows the server holding the microphone, as the desktop tray
does, and draws its state: the Material glyph in the status bar, the chosen
pack's art as the large icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:21:42 +00:00
erikbrockoandClaude Opus 5.5 2d83eafffd Android: Design settings page, Contacts in Settings, server icons in the switcher
Appearance options move to their own Design page. Contacts is the first
Settings entry instead of a top-bar button. The top bar and the server
switcher show each server's own icon, else the pack's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:12:16 +00:00
erikbrockoandClaude Opus 5.5 4911542d39 Add a Permissions menu with privilege keys: list, create, remove and use
Permissions > Use Privilege Key redeems a key (tokenuse). Permissions >
Privilege Keys opens a per-tab window listing the server's keys with
their group, channel, creation date and description; keys can be created,
removed, copied and reloaded. The create dialog takes a server group, or a
channel group in a chosen channel, plus a description, offers only groups
we have the power to add members to, and shows each new key for copying.

tokenlist and tokenadd answer with notifytokenlist / notifytokenadd ahead
of the command's completion, so core collects them the way it does the
ban list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:00:27 +00:00
erikbrockoandClaude Opus 5.5 2c1b37ee30 Show servers' icons on bookmarks, and their host button in the toolbar's corner
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 22:28:35 +00:00
erikbrockoandClaude Opus 5.5 cf1db61a4a Kick, ban and set groups from the Android client sheet, with a ban list
The client sheet offers kicking from the channel or the server (asking to
confirm, with an optional reason), banning with a reason and duration, and
the client's server groups and channel group. The server sheet opens the ban
list: search, own bans only, and adding, editing and deleting bans, with the
reason presets the desktop keeps.

Kick and ban powers, like move power, never come with the needed
permissions, so core now asks for all four in one piped permget. The ban
permission checks, a ban's summary, the duration units, the group choices
for a client and the kick reason limit move into core, and Swing uses them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:27:29 +00:00
erikbrockoandClaude Opus 5.5 76f6a9feed Drop the Options dialog's page banner
It only repeated the page selected in the sidebar, and took vertical
space from the page itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:11:43 +00:00
erikbrockoandClaude Opus 5.5 e06bb82299 Lay out the Options dialog like TeamSpeak 3's
A sidebar of pages with large icons replaces the tabs, and each page
opens under a banner with its title, subtitle and icon. OK, Cancel and
Apply sit below, and the dialog reopens on the last page used.

The pages follow TS3's: Application (muted-microphone warning, reported
client version), myTeamSpeak, Playback, Capture, Design, Hotkeys,
Contacts, Chat and Notifications. Capture now holds everything from the
microphone to the server: the device and gain, activation with the
microphone test, signal processing and the encoder, laid out in one
grid so its columns line up. Forms are grouped under section headings.

Cancel now goes back to what was last applied, and closing the window
cancels too, so a theme or icon pack being tried out is put back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:07:13 +00:00
erikbrockoandClaude Opus 5.5 0ad56671af Stop double-click from expanding channels in the server tree
Double-click joins a channel; expanding is left to the handles and the
keyboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:07:13 +00:00
erikbrockoandClaude Opus 5.5 d2de76f534 Zoom chat and descriptions with Ctrl+mouse wheel
Text and pictures in the chat tabs and the info panel zoom in browser
steps (50-300 %), keeping the line at the top in view. The chat and the
info panel each have their own level, shared by every server tab and
saved in the settings.

The HTML documents now take their fonts from a stylesheet that applies
the zoom. The old ScaledStyleSheet never reached the document, and
FlatLaf already applies the interface scale, so it only zooms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:44:04 +00:00
erikbrockoandClaude Opus 5.5 0ff0919db2 Keep the server tab strip in step with theme switches
The strip is out of the component tree while one server is open, so a
look-and-feel switch missed it and it came back in the old theme's colours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:31:43 +00:00
erikbrockoandClaude Opus 5.5 bda114d2c0 Let admins delete other clients' avatars
With b_client_avatar_delete_other, the client's context menu and the
menu on their avatar offer "Delete Avatar", as in TeamSpeak 3. The
server takes the deletion as ftdeletefile on /avatar_<unique id> (not
the stored file's name, which it refuses with "convert error") and
clears the client's avatar flag for everyone. Our own avatar's file is
now deleted the same way, which only such clients are allowed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:27:41 +00:00
erikbrockoandClaude Opus 5.5 b1890cbf79 Set and delete our avatar from the Self menu and the avatar's menu
As in TeamSpeak 3, Self offers "Set avatar…", which picks an image and
uploads it, and "Delete avatar" while we have one; the old avatar
dialog is gone. Setting (and stealing) is offered only while the server
grants i_client_max_avatar_filesize. Right-clicking our own avatar in
the info panel offers the same two beside saving it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:01:16 +00:00
erikbrockoandClaude Opus 5.5 e7d338ce28 Save or steal other people's avatars from the info panel
Right-clicking a client's avatar offers to save it to a file or to take
it as our own avatar on that server, as the Android picture viewer does.
Our own avatar only offers saving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:56:11 +00:00
erikbrockoandClaude Opus 5.5 8fc7be826c Let the noise removal slider move freely like the AGC boost slider
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:51:34 +00:00
erikbrockoandClaude Opus 5.5 662e031b6b Find in the channel tree and the chat on Android
A find button in the top bar opens a find bar over the tree (clients or
channels) or the conversation on screen, with match stepping, highlights,
only-matches filtering and the desktop's matching options. The tree's
match rule moves to core TreeMatch, which the desktop now uses too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 09:54:02 +00:00
erikbrockoandClaude Opus 5.5 66ef62913a Find a client in the channel tree from their sheet on Android
Offered, as on desktop, when the sheet was opened from outside the tree
(a name in the chat): expands the client's channels, scrolls to them and
flashes their row amber.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 09:13:49 +00:00
erikbrockoandClaude Opus 5.5 f80f619a65 Put friend and block on one line in the Android client sheet; remove contacts from their page
The client sheet keeps only "Edit contact" for contacts. The contact page's
remove button takes the remove-friend/foe icon instead of the trash can.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 08:52:41 +00:00
erikbrockoandClaude Opus 5.5 7f30a27d73 Open avatars and description pictures full size on Android; fold minor client facts
A client's sheet now shows only their server and channel groups, with
the rest (contact, talk power, version, microphone, unique ID, ...)
behind "more…". Core marks those facts minor, for frontends short of
room; groups without a name or an icon are left out on both clients.

Tapping an avatar or a picture in a description opens it on black, to
pinch or double-tap zoom. Its menu saves it to Pictures/TeamSpeak, takes
it as our avatar (not on our own), copies its address, and opens the
link it sat in, which a tap used to do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 08:27:50 +00:00
erikbrockoandClaude Opus 5.5 e799218444 Show clients' country flags beside their names, and optionally in the tree
The server places each client in a country (client_country, from its GeoIP
database); a client's details now show that country's flag left of their
name, as TeamSpeak's info frame does, on both clients. "Show country flags
in the channel tree" (off by default, as TeamSpeak's EnableCountryFlags)
also puts it last on client rows.

The flags are TeamSpeak's countries.zip, which now ships with the icon
packs; core's CountryFlags reads it, else a TeamSpeak 3 install's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:40:44 +00:00
erikbrockoandClaude Opus 5.5 4ca5534ef4 Ship TeamSpeak's icon packs with both clients
Default, Default Colored 2014 and Default Mono 2014 now come inside the
desktop JAR and the APK, so the default pack is there without a TeamSpeak 3
install; before, a desktop without one had no icons at all. As with the
sound packs, the builds take them from the TeamSpeak 3 client next to the
repository (ts3.client.dir to point elsewhere) and ship none without it.

Core reads them from the classpath in memory; a pack of the same name found
on disk, in an install or imported, still comes first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:16:48 +00:00
erikbrockoandClaude Opus 5.5 af0564702e Show pictures in descriptions, or links to them when turned off
[img] in a channel, client or server description is now a picture on both
clients, as TeamSpeak shows it; chat keeps it a link. Only web addresses
become pictures. While one loads it is TeamSpeak's loading icon; one that
cannot be had is its address behind the broken-picture icon.

"Show pictures in descriptions" (desktop: Chat settings; Android: Appearance)
turns them into links behind a picture icon instead, fetching nothing. A
picture that was itself a link keeps that link beside it.

Core's PictureDownloads fetches them for both clients: kept on disk for a
month after last shown, at most 8 MB, redirects followed across http and
https, and on Android plain http asked for over https. The desktop draws
them narrowed to the info panel, Android at a pixel to a dp, animated GIFs
playing on both; long addresses are shortened to host and file name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:06:13 +00:00
erikbrockoandClaude Opus 5.5 fd86d9e638 Show server, channel and group icons and client avatars on Android
The tree lines icons up at the right of each row as TeamSpeak does: the
server's own icon, a channel's icon, and a client's server group icons then
their channel group's. The details list each group with its icon, and the
client sheet shows the avatar; an animated GIF plays while it is on screen.

TeamSpeak's default group icons come from the icon pack, as on the desktop;
a server's own uploads are downloaded by core's repositories and decoded
once per server, redrawn as they arrive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:34:52 +00:00
erikbrockoandClaude Opus 5.5 b678805c37 Offer the server groups we have the power for, not only those needing none
canToggleGroup compared a group's needed member add/remove power with our own
i_group_needed_member_*_power, which the server never reports for us: our
power is i_group_member_add_power and i_group_member_remove_power. An admin
was only ever offered groups that need no power at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:21:43 +00:00
erikbrockoandClaude Opus 5.5 b1ad403fdf Move clients to another channel or our own from the Android client sheet
"Move to channel…" closes the sheet and marks the client, and the next
channel tapped is where they go; a bar above the tree names them and cancels.
"Move to own channel" shows while they are elsewhere.

Both show only with some i_client_move_power. The server's needed
permissions never carry it, even for an admin, so core asks for it with
permget on connect and whenever our own groups change; a refusal (guests may
not ask) counts as none. Whether it beats the client's needed move power only
the server knows, and it refuses when not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:16:21 +00:00
erikbrockoandClaude Opus 5.5 cd02e4b2d8 Show server, channel and client details on Android, and the server's on the desktop
Core's Details says what the info box tells, as TeamSpeak's info frame does:
labelled facts, then a BBCode description. The desktop info panel now lays it
out instead of building its own, and selecting the server row shows the
server: address, version, clients, channels, creation date and its welcome
and host messages, from the virtualserver_* properties kept since initserver.

On Android the channel and client sheets show the same details, asking the
server for a missing channel description or a client's variables; tapping
the server row opens a server sheet. Descriptions render as TeamSpeak's do:
BBCode now knows [hr], [left]/[right]/[justify], numbered and lettered lists
and tables, which Android's HTML parser approximates — rules as dividers,
table rows as lines, list items numbered, font sizes as big/small. Links are
blue whatever the wallpaper.

Push-to-talk in the bottom bar follows whichever server holds the microphone,
and a server without it keeps its button to take it in a fixed slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:52:28 +00:00
erikbrockoandClaude Opus 5.5 9b1aa45611 Connect to several servers at once on Android, in a denser TeamSpeak-like layout
The server name in the top bar opens the servers the app is on, "Connect…" for
another one and "Disconnect from current". Only one server captures with the
microphone at a time, handed over by core's Sessions as on the desktop; a
server without it shows a button to bring it there. Push-to-talk, the floating
button and the level meter follow the server holding it.

Each server has its own controller (session, tree, chats, network recovery);
the app-wide one keeps what they share. Private message notifications carry
their server, as client ids repeat across servers.

The layout follows TeamSpeak's own: 26 dp tree rows with smaller icons and
text, a lower top bar, and no tabs — the chat is a button in the bottom bar,
whose buttons keep fixed places around the push-to-talk button's space.
Holding the mute button switches between push-to-talk and voice activation.

A server that drops the connection now lets go of the microphone too, so a
reconnect cannot capture alongside the server that took it over meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:08:36 +00:00
erikbrockoandClaude Opus 5.5 9f2e5087ce Stop two servers taking turns claiming a contact's last sighting
A contact on two servers at once was marked seen by each in turn: a sighting
announced a contact change, every connection re-applied its contacts, and
each re-application recorded the contact on its own server — another change,
round and round, rewriting contacts.txt every time. Re-applying now only marks
a contact that was never seen; the last sighting moves when the client appears.

Sightings no longer write the file on their own either: they reach it in one
save half a minute later, or with the next edit's save, and are flushed when
the client closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:08:36 +00:00
erikbrockoandClaude Opus 5.5 1dda20d1b2 Manage identities on Android, pick one per bookmark, and give identities their own nicknames
Settings -> Identities lists them and creates, imports (an identity file or a
TeamSpeak 3 settings.db), exports, renames and removes them, picks the
default and improves an identity's security level; the search runs on until
reached or stopped, whichever page is on screen. The Connect screen and each
bookmark choose the identity to connect with.

An identity keeps a nickname and phonetic nickname, in TeamSpeak's own INI
keys, on both clients. A connect goes by the bookmark's nickname, else the
identity's, else the global one; the phonetic one is sent in clientinit.
Imported bookmarks no longer copy their identity's nickname.

IdentityStore is now safe to share with the thread a connect resolves its
identity on, and imports and exports through streams for Android's document
picker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 00:17:14 +00:00
erikbrockoandClaude Opus 5.5 6aa4be38ee Fold the Android noise suppression toggle into its slider, and let the muted-talk beep be turned off
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:42:43 +00:00
erikbrockoandClaude Opus 5.5 f1e7c93594 Float a push-to-talk button over other apps on Android
Held, it talks; a double tap whose second touch is held drags it. It shows
while the app is off screen in push-to-talk mode, half see-through at rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:38:59 +00:00
erikbrockoandClaude Opus 5.5 4b50f37735 Ship the Android sound packs as Opus
The build encodes TeamSpeak's packs to Ogg Opus at 64 kbps before bundling
them, which takes the sounds from 21.3 MB to 2.0 MB, in the APK and again
once unpacked on the phone. The encoding runs the desktop code's libopus
on the build machine, through a build-only :desktop module compiled from
the same sources as the Maven one.

Both clients play Opus sounds: the sound player (now PackSoundPlayer, as it
no longer plays only wave files) decodes Ogg Opus with the platform's
libopus, and a pack's play("x.wav") finds x.opus, so converted packs keep
their scripts. SoundPackConverter turns any pack folder into Opus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 17:12:50 +00:00
erikbrockoandClaude Opus 5.5 02ff63341e Notify of pokes and private messages on the desktop
While none of the client's windows has the focus, a poke or a private
message shows a desktop notification, which the desktop's notification
centre keeps. A private conversation keeps one notification, updated as
messages come; clicking it brings the window forward with that chat open,
and they all go once a window of the client is in front again.

On Linux they go to the freedesktop.org notification service, spoken to
over the session bus by a small D-Bus client of our own on Java's Unix
sockets, so no library or native code is involved; Plasma also takes a
reply typed into the notification. Elsewhere they are AWT tray messages,
which Windows and macOS put in their notification centres. The options
can turn them off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 15:20:51 +00:00
erikbrockoandClaude Opus 5.5 a6efc0b8da Notify of pokes and private messages on Android, with TeamSpeak's sounds
While the app is out of sight, a poke or a private message posts a
notification; a message's one gathers the conversation, takes a reply
inline and opens its chat. The notifications are silent, as the sound
pack already plays TeamSpeak's own sound for either.

The build bundles the sound packs of the TeamSpeak 3 client found next
to the checkout (or at ts3.client.dir / TS3_CLIENT_DIR), unpacked into
the profile once per app version. Sound Settings picks the pack and its
volume, and speech packs talk through the phone's text-to-speech.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 15:12:16 +00:00
erikbrockoandClaude Opus 5.5 002b1ac7ce Dock the tray icon once the window is on screen
Docking waits for the panel to adopt the icon, which held up the main
window; wait at most half a second for it before falling back to AWT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 12:25:44 +00:00
erikbrockoandClaude Opus 5.5 75df46a03a Narrow the desktop contact list
Each contact shows just the date it was last seen, without the client
dot and at half the usual nesting; the full time and server move under
the phonetic nickname as "Last seen … on …".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 11:39:15 +00:00
erikbrockoandClaude Opus 5.5 fedb7b4385 Show all of a contact's options at once on desktop
The contacts window drops its tabs for one column of short groups beside
the list: contact type, display and ignore, where whisper becomes a
"Deny whisper" box, since allowing is the default. The names get their
labels on a line of their own, and the window is never shorter than the
options, leaving the list the only thing that scrolls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 10:52:56 +00:00
erikbrockoandClaude Opus 5.5 570feffc25 Keep contacts on Android
A contacts page lists friends, blocked and neutral clients with when and
where each was last seen, and opens each one's settings: custom and
phonetic nickname, type, how the name is shown, what to ignore, whether
it may whisper, a volume change, and its unique ID, copied on a tap.
Changes are stored at once. Another page holds the defaults new contacts
start from, and a TeamSpeak 3 settings.db can be imported.

A client's sheet on a server adds them as a friend or blocks them, or
edits and removes the contact they already are. Everything else runs on
core's contact store as on desktop, so a change reaches the server's
playback and tree straight away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 10:52:56 +00:00
erikbrockoandClaude Opus 5.5 5c0a5e4bcf Sort the Android settings into categories
Settings opens on a list of categories, for now Sound Settings (devices,
transmission, voice activation, processing, playback) and myTeamSpeak,
each a page of its own, with the icon pack beneath them. The nickname
field goes, as the connect screen already keeps it. The rows the pages
share move into their own file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 10:52:56 +00:00
erikbrockoandClaude Opus 5.5 e7741e8b34 Give the Material pack every icon TeamSpeak's packs have
The rest of default_colored_2014's keys get Material counterparts:
talk power, whisper, recording, text formatting, identities, add-ons,
permissions and the like. Ping levels are drawn as signal bars, since
Material's own tell their levels apart by a hairline, and the default
group icons as lettered badges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 09:43:07 +00:00
erikbrockoandClaude Opus 5.5 cdf81f3258 Share icon packs between desktop and Android
The Android app's Material icons become a TeamSpeak-format pack shipped in
core, which the desktop offers next to the TeamSpeak packs. Android now
draws its icons from packs too and imports TeamSpeak's own zips, falling
back to the Material pack for what they lack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 09:39:42 +00:00
erikbrockoandClaude Opus 5.5 a7aa122728 Sign in to myTeamSpeak and import what the account synchronises
The myTeamSpeak client protocol and its end-to-end encryption are
reverse-engineered (docs/myteamspeak): an HTTP POST of a framed protobuf,
a PBKDF2-HMAC-SHA512 login token and account key, an AES-GCM wrapped
item key and AES-CTR items with a SHA-512 trailer.

Options on desktop and Settings on Android gain a myTeamSpeak page: sign
in and out, and the account's bookmarks and identities, each picked for
import and marked when already here. The client stays signed in the way
the official one does, keeping the derived token and key rather than the
password; each read signs in afresh, and a sign-in the server no longer
takes signs out. Nothing is written to the account.

Items are the same Item_Data as the local TeamSpeak store, so they go
through the existing decoder and importer; a bookmark chosen alone brings
the identity it connects with, found by UUID or, as some name it, by
the identity's name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 01:07:17 +00:00
erikbrockoandClaude Opus 5.5 73a15a8cfc Let AGC raise the noise floor further to bring up a distant voice
AGC2 won't amplify the background noise above -50 dBFS, which also caps
the gain for a voice barely above that noise: a distant talker ended up
5 dB quieter than a near one with noise suppression on, 12 dB with it
off. A "Boost quiet speech" setting (0-20 dB, default 0) raises the cap,
live, on desktop and Android.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 22:08:50 +00:00
erikbrockoandClaude Opus 5.5 491cbcb259 Leave the server when the app is swiped away
The process lived on without a screen, or was killed without a word, and
the server held our identity as a ghost until it timed out, refusing a
reconnect in the meantime as a clone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:31:50 +00:00
erikbrockoandClaude Opus 5.5 5fa7024bcb Follow the phone from one network to another
A server knows its clients by address, so moving between Wi-Fi and mobile
data leaves the connection with nothing to do but time out. The process's
sockets are now bound to the network a connection was made over: on a
change, the goodbye still leaves through the old network while it lasts,
and the connection is made again over the new one, back into the channel
we were in. A drop because the network vanished counts as a change too.

A server still holding the old connection refuses the new one as a clone
until it times out, so attempts are retried with a growing pause; a ban
ends it, and so do five minutes without getting back on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:31:41 +00:00
erikbrockoandClaude Opus 5.5 c8e99c8946 Show the microphone level for tuning voice activation
The settings show the level on TeamSpeak's scale, lit while it would be
sent, with the volume gate's threshold marked as the slider moves. While
connected it listens to the connection's own microphone, so it shows
exactly what goes out; otherwise it runs a test microphone of its own for
as long as the settings are on screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:31:31 +00:00
erikbrockoandClaude Opus 5.5 62ced89701 Pick the Android audio devices, microphone preset and playback usage
Microphone and speaker are chosen separately, so a Bluetooth headset can
play in media quality while the phone's own microphone listens, instead of
the headset dropping into its call profile. Devices are kept by type and
address: Android hands out new ids whenever one reconnects, and a line that
lost its device comes back to it when it returns.

The microphone preset (voice recognition by default, or the platform's
call processing, unprocessed, ...) and whether voices play as media or as
a call are Android's own settings. Changing either reopens the open
streams in place. Communication mode, and the headset's call link that a
Bluetooth microphone needs, are held only while a stream needs them, and
are set up before that stream opens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:31:22 +00:00
erikbrockoandClaude Opus 5.5 2281c125fa Keep the error id a server refused the last connect with
The message alone does not tell a ban from a refusal worth retrying.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:30:23 +00:00
erikbrockoandClaude Opus 5.5 25ca586a50 Let a disconnect give up a connect still under way
Disconnecting only acted once connected, so a connect that was stuck or
retrying could not be called off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:30:23 +00:00
erikbrockoandClaude Opus 5.5 ed526897dc Switch audio devices without reopening the connection
A new input device used to wait for the next connect, and the shared mixer
kept its line on the old output until it went idle for good. The microphone
now reopens on the new device as the settings are applied, and the mixer
moves its line over when the output device changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:30:23 +00:00
erikbrockoandClaude Opus 5.5 967fcadf77 Keep chat drafts per conversation and open each at its newest line
Switching conversations dropped the message being written, and showed
the next one at the scroll position of the last.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:12:50 +00:00
erikbrockoandClaude Opus 5.5 70c6eb769c Say why a connection ended, and mark the channel we are in subscribed
- A failed connect keeps its reason in the status instead of a bare
  "Disconnected", as does a disconnect the server gave a reason for.
- The server never announces the subscription to the channel we start
  out in, although it keeps us subscribed after we leave it, so the
  channel we enter counts as subscribed.
- A client connecting or leaving the server is logged as that, not as
  switching from or to "channel #0": the server gives both the same
  reason, only with no channel on one side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:12:50 +00:00
erikbrockoandClaude Opus 5.5 f2c9143997 Pick up ts3j's refused-connect reason
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:12:50 +00:00
erikbrockoandClaude Opus 5.5 941365cab0 Give the Android app its real UI
- Connect screen with an address or a bookmark, which can be added and
  removed there.
- Server screen: the channel tree with each client's status, folding
  channels, joining (asking for a password where needed) and
  subscribing from a channel's sheet; private message, poke and volume
  from a client's sheet.
- Chat: the server log, the channel and private conversations with
  their history, unread marks, BBCode and clickable client, channel and
  web links. Chat lines are the HTML the desktop shows, turned into
  styled text.
- Voice bar: mute, deafen, away, and a hold-to-talk button in
  push-to-talk mode. The microphone permission is asked for on connect.
- Settings: nickname, transmission mode, voice activation, noise
  suppression, gain control and playback volume, in effect at once.

The session's state reaches Compose as immutable snapshots: the tree
at most every 30 ms, rebuilt only when channels or clients changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:21:51 +00:00
erikbrockoandClaude Opus 5.5 d83ba1145b Make a parsed spacer a value
So a frontend comparing snapshots of the tree sees an unchanged spacer
as unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:21:51 +00:00
erikbrockoandClaude Opus 5.5 35d6427456 Apply voice settings to a live microphone in one place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:10:35 +00:00
erikbrockoandClaude Opus 5.5 d206b12a30 Move spacers, client status and chat entries into core
The Android client needs them too: which state a client's icon shows,
how spacer channels are named, and the HTML a chat line is written as.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:09:43 +00:00
erikbrockoandClaude Opus 5.5 c5a49fc7b3 Avoid JDK APIs newer than Android's minSdk 33 in core
Files.readString/writeString (API 36.1), Path.of, ByteBuffer.slice(int, int)
and Matcher.appendReplacement(StringBuilder) (API 34) threw NoSuchMethodError
on Android; connecting crashed in ChatLogStore. Each replacement keeps the
original desktop code in a comment above it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:05:39 +00:00
erikbrockoandClaude Opus 5.5 5d67b0c1e3 Record what came of the codebase audit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:39 +00:00
erikbrockoandClaude Opus 5.5 51f19c2d03 Bring the README's architecture and features up to date
The architecture tree predated the session, chatlog, contacts, text,
file transfer and voice pipeline packages, and named a backend that no
longer exists. The feature list still described the first speech
detector and processing chain rather than the WebRTC ports, and knew
nothing of the jitter buffer; the limitations listed file transfers,
avatars and administration as missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 85c3ae6c8d Require Java 25, not 26
Nothing in the desktop client needs more than the FFM API, final since
Java 22. It builds, passes its tests and runs on OpenJDK 25, the current
LTS, which reaches more distributions. CI now tests on that minimum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 acb3efabd8 Pick up ts3j's DNS test that works offline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 b6c5a772e6 Run the tests on every push
A Gitea Actions workflow that builds ts3j and the client and runs every
test; none needs a display or the native Opus library.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 71ac2c817c Test the channel tree, the event handler and settings
- the tree's sibling chain: arrival order, broken links, removal,
  reordering and reparenting, orphans, client order, path lookup
- the event handler, fed events parsed from the server's own wording:
  joins, moves, leaves, partial and clearing updates, server groups,
  and a channel's life from creation to deletion
- settings: saving and loading back, unknown values, and the one-time
  conversion of the old dBFS voice threshold

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 bf07f0bf49 Move what the servers share out of the main window
Which server captures with the microphone, handing it over, push-to-talk
and key presses reaching the right microphones, and away state and
nickname applied everywhere were all worked out in MainFrame. They move
to a Sessions class in core, next to ServerSession, where another
frontend can use them; the window keeps only the tabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 f30cecf51c Keep channels the user collapsed collapsed
Every tree rebuild, which any join, leave or talk-power change causes,
expanded every row again, so a collapsed channel reopened within
seconds. The tree now remembers which channels were collapsed and
opens everything else; reopening one restores what is below it. While
the find bar filters, everything opens so every match shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 ae8d1f7083 Fail a download whose file server stops sending
The data socket had no read timeout, so a file server that went quiet
left the transfer, and its thread, waiting until the user cancelled.
Thirty seconds without data now fails it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 48a0032848 Parse every enum setting with the one generic parser
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:26 +00:00
erikbrockoandClaude Opus 5.5 3cdade9ad7 Keep the profile private and write it all at once
Settings, bookmarks (server passwords) and identities (private keys)
were written in place with the default permissions, readable by every
user on the machine, and a crash mid-write left a truncated file that
the next start silently replaced with defaults.

Every profile file is now written to a private temporary file, synced
and moved over the old one in one step. The profile folder itself is
made accessible to its owner only, which also covers files written
before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 d7261c906d Let chat logs be turned off or kept elsewhere
Chat logs always went into the TeamSpeak 3 client's own folder. A new
Chat page in Options can turn them off, or point them at another
folder; left empty, they are still shared with the TeamSpeak 3 client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 1a3a3e37c1 Write both kinds of chat message through one method
appendMessage and appendPrivateMessage built the same entry twice; they
now differ only in which log they pick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 a5c4ba1eb5 Load chat history from the end of the log only
Chat logs grow forever, and every connect and every private chat opened
read the whole log to keep its last 1000 entries. History now reads the
last 4 MiB, which holds far more than that; searching still reads the
whole log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 f9b2f4d7cb Keep every line of a multi-line message in chat history
The text log has a message's line breaks in it, but history was read one
line at a time, so every line after the first failed to parse and was
dropped. A line that starts no entry of its own now continues the
message before it, which also recovers what earlier versions wrote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 8e9c461424 Wait for the capture loop when the microphone stops
stop() closed the encoder and cleared the transmit state while the
capture loop could still be in its last frame, which could turn the
transmit indicator back on, or overlap the loop of a quick restart on
the same speech detector and processing chain. It now closes the line
to wake the loop and waits for it to finish before tearing down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 12ca585d90 Open a new line when a speaker's playback line dies
Both desktop backends dropped writes to a line whose device had gone
away, and the per-speaker playout ignored any failure, so that speaker
stayed silent for the rest of the session. A write to a dead line now
throws; the playout drops that line and the speaker's next packet
opens a fresh one. Sound effects and the microphone test's loopback
reopen their line the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 6234ec6d97 Give back a speaker's line after 30 s of silence
Every client that ever spoke kept an open playback line and a thread
until it left the server. A speaker silent for 30 s now has both
released, and its next talk burst opens them again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 0083dc8ad6 Play incoming voice through TeamSpeak's adaptive jitter buffer
Each speaker's stream held a fixed 60 ms and gave up after 200 ms of
concealment, so a jittery connection concealed constantly and a stall
ended the burst. It now runs through a port of the libspeex jitter
buffer the official client links, configured and driven as it does:

- the delay adapts to the measured jitter, aiming for at most 1% of
  packets arriving late
- a speaker keeps one timeline, never re-anchored between talk bursts,
  so what the buffer learned carries over; only 5 s without packets
  drops it
- the talker's stop marker never enters the buffer; playback ends when
  it reaches it, and its slot is played as silence, not concealed

A pull now always hands out one 20 ms frame: what a longer packet or a
delay increase produces beyond that is played on the following pulls,
which Android's mixer used to cut off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 7cb4f47a81 Show an avatar, description or away message being cleared
Client and channel updates were only applied when the field had a
value, since ts3j reads a missing field back as an empty string. A
removed avatar, an emptied description or a cleared away message
arrives as the field without a value, so they stayed as they were. Such
fields are now applied whenever the update carries them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 8c735a05b8 Look permissions up by name directly
selfPermissionValue scanned every permission the server lists, several
times per context menu. The model now keeps a name index next to the
id one. Also drops primaryServerGroupName, which nothing calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 67f8f46cab Publish the channel tree's lists whole instead of refilling them
buildTree() cleared and refilled the children and client lists inside
the shared channel nodes, so a UI still walking the previous tree could
see them change under it. It now builds new lists and publishes them
unmodifiable. The node fields, written by the event and audio threads
and read by the UI, are volatile.

Whether a channel is full is now counted from the model, rather than
from a tree that may not have been rebuilt since the last join.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 665316d515 Hand the microphone between tabs in the order it was asked
Each hand-over ran on a fresh thread, so two quick tab switches could
start the new tab's capture before the old one stopped, or stop it after
it started. They now run one after another on a single thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 5b1809cc2d Hand out hotkey bindings as a snapshot
Hotkeys.all() returned its synchronised list, and every reader had to
lock it while iterating: a lock owned by one class and taken by four
others. It now returns a copy, and the lock stays inside Hotkeys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:25:25 +00:00
erikbrockoandClaude Opus 5.5 eeccb495eb Name chat logs by the server's unique id for guests too
The id came from initserver, which never carries it, then from
serverinfo and servergetvariables, which a guest may not use; chat logs
only worked with admin rights. ts3j now derives it from the server's
handshake key, as the official client does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:35:41 +00:00
erikbrockoandClaude Opus 5.5 d074ffaa7a Tell permission errors apart by the server's error id
The sound for a refused action was picked by looking for "permission"
or "insufficient" in the message, which also matched errors such as an
invalid permission id. The server's error ids for insufficient client,
group and permission power say it exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:31:28 +00:00
erikbrockoandClaude Opus 5.5 d28bb57598 Release a previous connection's resources on connect
A connect on an instance that was still connected, or still
connecting, replaced the socket and audio pipelines without closing
them. The fields shared between the connect, event, action and UI
threads are now volatile, and read once where they are used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:30:34 +00:00
erikbrockoandClaude Opus 5.5 f350b19d31 Run a connection's requests on its own pool
Each action started a thread that read the socket field once it ran; a
disconnect in between cleared it, and the user saw "Could not join
channel: NullPointerException". Actions now capture the socket when
they are issued and run on a pool that lives as long as the connection.
What fails because the connection went away is no longer reported as an
error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:29:23 +00:00
erikbrockoandClaude Opus 5.5 ba5de5a8a8 Give the importer test a fresh profile every run
The test home under target/ outlives a run, so the identity the first
run imported made every later run fail. The test now points AppDirs at
a temporary directory of its own, which also works when another test
resolved the profile first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:27:11 +00:00
erikbrockoandClaude Opus 5.5 f871a88bce Ignore the bundled TeamSpeak 6 client
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:26:21 +00:00
erikbrockoandClaude Opus 5.5 72057ac1df Pick up ts3j's handling of commands that never get through
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 10:08:09 +00:00
erikbrockoandClaude Opus 5.5 95726d9a8d Pick up ts3j's fix for resends under current BouncyCastle
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:42:48 +00:00
erikbrockoandClaude Opus 5.5 b3ad3ceda0 Keep the Android connection alive in the background
The session moves from the connection screen's ViewModel into an
app-wide SessionController, and a foreground service keeps the process
running while connected:

- Its notification shows the server and status and offers Mute, Deafen
  and Disconnect.
- It declares microphone use only once the microphone is handed to the
  connection, as Android requires that permission to be granted then.
- It holds a low-latency Wi-Fi lock and a CPU wake lock, since voice
  goes out every 20 ms.
- When the system moves to another network, the session reconnects to
  where it was, as its socket stays bound to the old one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:28:36 +00:00
erikbrockoandClaude Opus 5.5 11a2a14c70 Let a session reconnect to where it was
ServerSession.reconnect() connects again to the last server with the
same identity and returns to the channel the client was in: what a
dropped connection or a changed network (Android moving from Wi-Fi to
mobile data) needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:26:03 +00:00
erikbrockoandClaude Opus 5.5 07aa7bd7f9 Don't report a channel join that leaving the server cut short
Connecting with a channel moves there once the channel list is in; if
the connection was left again before that, the move ran against the
closed socket and reported an error nobody could act on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:26:03 +00:00
erikbrockoandClaude Opus 5.5 086b913c8e Add the Android app: Gradle build, Oboe audio, connection screen
android/ builds core and ts3j from the same sources as the desktop's
Maven build, so the app shares all of the client's logic:

- audio: Oboe streams behind AudioCapture/AudioPlayback, with a lock-free
  ring between the real-time callback and the blocking Java side, and
  libopus 1.5.2 built with the NDK behind OpusCodec. Speakers are mixed
  onto one stream. Capture uses the VoiceRecognition preset, leaving
  noise suppression and gain to the client's own processing.
- app: a plain connection screen to try the port out - connect,
  microphone, mute, deafen, channel chat and a log - until the real UI.

Targets Android 13 and up (minSdk 33) on arm64 and x86_64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:24:21 +00:00
erikbrockoandClaude Opus 5.5 e211ffa7b6 Share libopus' encoder controls between bindings
libopus' constants and the encoder settings built on opus_encoder_ctl
(clamping, voice/music signal) move into core, so the Android binding
reuses them rather than copying them from the desktop's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:24:12 +00:00
erikbrockoandClaude Opus 5.5 75d9606231 Conceal a lost voice packet with 20 ms, not 120 ms
A lost packet was concealed by decoding "nothing" into a buffer sized
for the longest Opus frame, and Opus fills whatever it is given: every
lost packet played 120 ms of made-up audio in place of 20 ms, piling up
delay on that speaker's line.

Decoders now conceal through their own call that takes the length to
make up, and the stream asks for the length of the last packet it got.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:18:06 +00:00
erikbrockoandClaude Opus 5.5 cc0243a7c6 Pick up ts3j's SRV lookup that works without JNDI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:13:14 +00:00
erikbrockoandClaude Opus 5.5 fecb2ba8f4 Answer what the local client may do from the model
The Swing client menu decided on its own whether a group can be
(un)assigned and whether a client's channel can be joined, and the
server groups dialog borrowed the menu's check. These are rules about
the server, not about menus, so ServerModel answers them now and any
frontend asks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:10:54 +00:00
erikbrockoandClaude Opus 5.5 8f385b9343 Keep each server's session state in core
What a server tab knows beyond its views - the connection lifecycle,
title and status, the identity used, the microphone/speaker/away and
commander flags, chat sending and the channel lookups - moves from the
Swing ServerTab and ServerTabSelfState into core's ServerSession, so
another frontend gets the same behaviour without copying it.

ServerSession also takes over what the Swing event bridge decided on its
own: clearing the model on disconnect, naming the tab after the server,
showing senders under their contact names, and the chat's system lines.
The bridge now only updates views. SelfState moves along, while its
icons stay with the tray.

A server switch no longer needs to queue behind the UI thread: the
disconnect is reported synchronously, so the session is free again by
the time it reconnects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:09:23 +00:00
erikbrockoandClaude Opus 5.5 24f4b3813d Build core for Java 17
Android will run core as well, and its runtime stops at Java 17. Pinning
the release makes the compiler reject newer language features and APIs
there, while the desktop modules keep the newest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:03:42 +00:00
erikbrockoandClaude Opus 5.5 94748e27ee Play notification sounds from core
The sound player was a desktop class only because it decoded wave files
through Java Sound. A small RIFF reader replaces that, so the player
moves to core and every platform gets it from AudioBackend by default.

The reader takes integer PCM up to 32 bits and 32-bit float, in plain
or extensible headers. It decodes all 151 files of the TS3 sound packs
to the same samples Java Sound does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:03:08 +00:00
erikbrockoandClaude Opus 5.5 7396c4ca40 Move the voice pipelines into core
Capture processing, the jitter buffer and decoding were desktop classes,
so any other platform would have had to copy them. They now live in core
and reach the platform only through two interfaces:

- AudioIo lists devices and opens capture/playback lines; the desktop's
  AudioDevices implements it over PipeWire and Java Sound.
- OpusCodec creates encoders and decoders; the desktop binds libopus
  through the FFM API as before.

DesktopVoiceInput becomes CaptureVoiceInput unchanged in behaviour.
DesktopVoiceOutput splits into VoiceStream, one speaker's jitter buffer
and decoder, paced by whoever pulls it, and StreamingVoiceOutput around
it. Speakers reach the device either on a line each (the desktop, so
each shows up in the PipeWire mixer) or mixed onto one shared line, as
mobile audio APIs want.

The settings dialog's device lists and microphone test now go through
the AudioBackend instead of desktop classes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:01:28 +00:00
erikbrockoandClaude Opus 5.5 3c389de36b Resolve the client's data directories in one place
Stores read their paths from AppDirs instead of user.home, so a platform
without a home directory can point them elsewhere at startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 07:52:32 +00:00
erikbrockoandClaude Opus 5.5 1d61f458ae Process the microphone like TS3, and tell it about key presses
The capture path now runs the ported WebRTC chain in place of the
home-made noise, typing and gain stages, which are removed.

- As in TS3, the speech detector judges the raw microphone signal, while
  the level meter and volume gate see the processed one.
- Noise removal takes TS3's four levels (6, 12, 18 or 21 dB); a stored
  0..1 level falls back to TS3's default of 12 dB.
- Every key press from the global input hook reaches the connected
  microphones and the microphone test, so typing attenuation engages
  while the user types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 20:47:04 +00:00
erikbrockoandClaude Opus 5.5 de5f7da236 Port TS3's WebRTC capture processing to Java
TS3 pre-processes the microphone with WebRTC's audio processing module.
AudioProcessor ports the stages it enables, in APM's order, per 10 ms at
48 kHz:

- The high-pass filter APM forces on with noise suppression, then the
  three-band split and WebRTC's noise suppressor at TS3's four levels.
- The transient suppressor behind "Typing attenuation", which only acts
  while it is told about key presses.
- AGC2 adaptive digital, WebRTC's successor to the AGC1 that TS3 runs.

The tests compare against 16-bit outputs of upstream APM builds
(webrtc-audio-processing 2.1, and 1.3 for the transient suppressor).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 20:46:46 +00:00
erikbrockoandClaude Opus 5.5 ee0f15fb3c Stop tripping the server's flood protection with query commands
channelinfo, clientinfo, channellist and clientlist are query commands
that count heavily against anti-flood; clicking through the tree got
every command refused within seconds. Use what the official client does:

- Channel descriptions via channelgetdescription, whose answer arrives as
  an invoker-less channel edit.
- Client version and platform via clientgetvariables, answered as a
  client update.
- Connection info takes version and platform from the model and idle
  time from notifyconnectioninfo instead of polling clientinfo.
- Drop the channellist/clientlist re-read after connecting: the events
  during connect already carry everything, and more (groups, unique ids,
  away state).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 18:32:05 +00:00
erikbrockoandClaude Opus 5.5 b01ed43d60 Find clients and channels in the server tree
Ctrl+F in the tree opens a find bar below it that washes matching rows,
steps the selection through them and can prune the tree down to the
matches and the channels leading to them. ServerTreePanel becomes a
panel holding the scroll pane and the bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:09:45 +00:00
erikbrockoandClaude Opus 5.5 d05c04afb4 Find in chat with Ctrl+F
A find bar above the conversations highlights matches and steps through
them, or filters the selected tab down to matching messages. New lines
no longer pull the view away while it is open. Ctrl+F opens it from
anywhere the tree doesn't claim the shortcut.

Note tabs are now found by their scroll pane like other tabs, so sending
checks for a target instead of assuming every tab has one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:09:45 +00:00
erikbrockoandClaude Opus 5.5 a4057cd499 Add text queries and whole-log chat search
TextQuery holds a find bar's text and options (match case, whole word,
regex) and matches plain text; HtmlText strips a log entry down to it.
ChatLogStore can now search a whole log rather than only the history
loaded into a chat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:09:45 +00:00
erikbrockoandClaude Opus 5.5 249430efad Hide query clients from the log and name server groups correctly
- Query clients were already left out of the tree, but their joins, moves
  and ping-timeout drops were still logged and could play sounds; TS3 keeps
  them out of sight entirely.
- The name field of notifyservergroupclientadded/deleted is the client's
  nickname, not the group's, so "added to server group" named the wrong
  thing. Resolve the group by id instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:08:18 +00:00
erikbrockoandClaude Opus 5.5 3f65e95afd Fix channel reordering and keep the channel tree in sync
- Sort a channel among its current siblings with channeledit channel_order,
  as the official client does; the server refuses channelmove within the
  same parent ("already member of channel").
- Relink siblings when a channel_order edit arrives: the server never
  re-announces the neighbours, so the tree drifted out of order after any
  reorder.
- Apply password, permanence and max-clients flags from channel list,
  create and edit events, and let an emptied topic clear the old one.
- Log moves like TS3: "..., new parent channel is X".
- Play identical sounds that start within 250 ms only once, so bursts
  (a channel deleted with its subchannels) don't stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:06:53 +00:00
erikbrockoandClaude Opus 5.5 4de3ad4cab Make the talking-while-muted beep optional
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:25:58 +00:00
erikbrockoandClaude Opus 5.5 03ea2c86c3 Give the window its own identity in Linux task bars
AWT names the X11 window class after the thread that first touched the
toolkit, so the client shared java-awt-EventDispatchThread with every other
Swing app. Set it to ts3j-client instead (the jar's manifest opens the AWT
internals this needs), and install a matching .desktop launcher and icon in
the user's data directory: without a launcher claiming the class, Plasma falls
back to the process's command line and files the window under Java.

The window icon is now offered at several sizes instead of 16 px only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:21:10 +00:00
erikbrockoandClaude Opus 5.5 f27cc40755 Build ts3j from source as part of the client build
The client resolved ts3j 1.0.3 from ~/.m2, so a machine that pulled new
ts3j sources without re-running mvn install silently shipped the old
library - here one without the packet generation fix, which fails
connects to busy servers with "mac check in EAX failed".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 12:43:56 +00:00
erikbrockoandClaude Opus 5.5 5fc2405d4a Update ts3j: resend like the official client; clean up failed connects
- ts3j: native resend timing, INIT1 resends, one clientinitiv per handshake,
  non-blocking disconnect.
- Ignore errors from a connect attempt that has been superseded or cancelled.
- Show the whole cause chain in network error messages.
- -Dts3j.debug=true enables ts3j's protocol logging.
- Tests run with a throwaway user.home instead of the real profile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 04:58:21 +00:00
erikbrockoandClaude Opus 5.5 c743efc3b6 Keep the window responsive while the channel tree loads
Connecting to a server with ~560 channels froze the UI for over two
seconds: every model event queued its own full tree rebuild, and each
rebuild expanded row by row with Swing's variable-height layout cache,
which measures every row on each expansion.

Coalesce model-change bursts into one rebuild and switch the tree to the
large-model layout (it already has a fixed row height), which only
measures rows on screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:21:52 +00:00
erikbrockoandClaude Opus 5.5 3187608579 Update ts3j: survive packet loss during the handshake; allow 30 s to connect
Picks up the ts3j fixes for "mac check in EAX failed" disconnects on lossy
links (retransmitted handshake packets now decrypt) and for the handshake
stalling when clientek's ACK is lost, plus tolerating an empty
client_servergroups.

The connect timeout also covers downloading the channel list, which on a
big server over mobile data can take longer than the previous 10 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:21:52 +00:00
erikbrockoandClaude Opus 5.5 9d996f48a2 Scale the interface fractionally on Linux
Java2D on X11 (and so under XWayland) truncates its scale to a whole
number, drawing 150 % at 100 %. On Linux, pin Java2D to 1 and hand the
full factor to FlatLaf, taken from XSETTINGS Xft/DPI, KWin's Xwayland
scale or GDK_SCALE, or chosen in Options → Design.

The client's own sizes now go through UIScale: borders, gaps, dialog and
row sizes, icons (rendered at the scaled size, so they stay crisp),
custom-painted components and font sizes in the HTML views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 22:33:27 +00:00
erikbrockoandClaude Opus 5.5 1fddae3f0b Always rebuild the swing jar before shading it
Without forceCreation, maven-jar-plugin kept the previous shaded
ts3-client.jar when the module's classes were unchanged, and the shade then
used it as input: the stale ts3j classes inside it won over the freshly
installed ts3j, so ts3j fixes never reached the built client without a clean.

Also updates ts3j for the empty server-group parsing fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:30:48 +00:00
erikbrockoandClaude Opus 5.5 33411fcd13 Update ts3j: fix EAX MAC failures on busy servers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:09:09 +00:00
erikbrockoandClaude Opus 5.5 2a73900dcc Show client avatars and let the user set their own
Avatars are fetched from the server's file repository as /avatar_<id>,
verified against client_flag_avatar and cached on disk; animated GIFs play in
the info panel. Self > Set avatar... uploads or removes our own picture within
the server's size limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:03:00 +00:00
erikbrockoandClaude Opus 5.5 dbb425403a Import bookmarks and identities from the TeamSpeak 3 client
The official client keeps what a myTeamSpeak account synchronises as protobuf
Item_Data blobs in the ProtobufItems table of settings.db. Decode them, adopt
them on first run when we have no identity yet, and offer a re-import from
Manage Bookmarks and Identities. The settings.db reader moves from contacts to
a new teamspeak package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:02:52 +00:00
erikbrockoandClaude Opus 5.5 bab89f9b50 Add the chat log store missing from earlier commits
TeamspeakConnection and ChatPanel already use com.ts3client.chatlog, but the
package itself was never committed, so the tree did not build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:02:40 +00:00
erikbrockoandClaude Opus 5 f409f500fd Add the contact list (friends, blocked, neutral)
Mirrors the TeamSpeak 3 client's Contacts: clients can be filed as friend,
blocked or neutral from their context menu or by dragging them into the
Contacts window, given a custom and phonetic nickname, shown under either
name or both, and per contact muted automatically, ignored in server/channel
or private chat and pokes, have their away message hidden and whispers
allowed or denied. Friends are green and blocked clients red in the tree
(optional), new contacts start from per-type defaults ("Set Defaults"), and
the global whisper policy lives in Options -> Contacts. "Change Volume..."
adds a per-client dB gain that a contact entry remembers.

Contacts are stored in ~/.ts3jclient/contacts.txt using the exact record
format the official client keeps in the Contacts table of its settings.db
(field names and codes recovered from the binary), so entries move between
the two verbatim. A small read-only pure-Java SQLite reader imports the
official client's list on first run and on demand, without a driver.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 07:50:58 +00:00
erikbrockoandClaude Opus 5 22e0304f25 Add the Tools > Ban List window
Reimplements the official client's ban list: a searchable table of the
server's bans with Add / Remove / Edit, an own-ban filter and highlight,
choosable columns, and the Add/Edit dialog whose IP and name patterns
can be read as IPv4/IPv6 wildcards, fixed strings or regular expressions
(translated to the regexes banadd takes exactly as the official client
does). Editing is add-then-delete, since the protocol has no banedit.

The ban list is read from the notifybanlist burst that answers banlist,
like channelpermlist. The menu item is only shown where the server grants
b_client_ban_list.

Also fixes ServerModel numbering permissions from 0 instead of 1, which
had every selfPermissionValue() lookup reading the neighbouring
permission — including the group-assignment menus.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 23:00:18 +00:00
erikbrockoandClaude Opus 5 636090d075 Start overlapping notification sounds without delay
The sound mixer rendered as fast as the playback line accepted, running a
full device buffer ahead of real time, so a sound fired while another
played could only join the mix behind all of that queued audio, and each
further one landed later still. Pace the mixer against the clock so it
never commits more than a few frames ahead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 22:54:02 +00:00
erikbrocko ad62f5fc92 Update connection and chat handling 2026-09-06 19:14:42 +00:00
erikbrocko 62d5af7cf9 Smooth incoming voice under jitter 2026-09-06 13:43:11 +00:00
erikbrockoandClaude Opus 5 a01c598fe6 Remember how tall the user made the info panel
Kept as a share of the tree/info column, so it survives new tabs, a resized
window and the next session.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 08:11:29 +00:00
erikbrockoandClaude Opus 5 02533b543d Sit the info panel's link in the viewport's corner
It overlapped the scroll bar; the viewport is what the scroll bars have
already been taken out of. The layered pane also has to report a size now,
or the split pane above it has nothing to size the panel from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 08:11:29 +00:00
erikbrockoandClaude Opus 5 5a00015824 Float the info panel's "Show in chat tab" link in its corner
As a real label over the text, it stays reachable however long a description
runs, instead of trailing off the end of it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 07:46:42 +00:00
erikbrockoandClaude Opus 5 ffe98be649 Trim the info panel's rows
A channel's permanent/temporary type is not worth a row, and a client's
platform reads better on the version line: Version: 3.6.2 … on Linux.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 07:46:36 +00:00
erikbrockoandClaude Opus 5 65f3777673 Let a chat tab grow to fit its name
Its header was pinned to the width it was built with, clipping longer names.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 07:27:17 +00:00
erikbrockoandClaude Opus 5 9101542f0a Switch chat tabs by clicking them, and tighten their padding
A custom tab component swallows the press, so the tabbed pane never selected
the tab itself; the reorder listener already on every tab part now does it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 07:04:26 +00:00
erikbrockoandClaude Opus 5 a4a8b39410 Paint the Away button as flat as its neighbours
Inside its panel it was drawn as a filled button, which read as half-active.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 06:58:08 +00:00
erikbrockoandClaude Opus 5 f480262c39 Drop the chat's Send button
Enter sends; the button only ate width.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 06:57:40 +00:00
erikbrockoandClaude Opus 5 8e3e9401d2 Name the server and channel chat tabs after where we are
Both carry an icon now, as the private chats do.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 06:57:38 +00:00
erikbrockoandClaude Opus 5 966f3fe9b1 Log our own channel switches in the server tab
Every other client's move was logged; ours went by silently.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 06:57:23 +00:00
erikbrockoandClaude Opus 5 b85d1e5076 Connect a left-clicked bookmark on the current tab
Middle-click still opens the server in a new tab.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 06:55:29 +00:00
erikbrockoandClaude Opus 5 50b71eb12e Leave the microphone alone when muting the speakers
Deafening silenced capture too, so coming back needed two clicks.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 06:53:59 +00:00
erikbrockoandClaude Opus 5 98719d717e Darken the dark theme, and hover a tree row like a menu
The client's own look-and-feel defaults now live beside LookAndFeelManager as
FlatLaf properties files, which FlatLaf loads on top of each theme's own,
instead of a handful of UIManager.put calls.

The dark theme is built on three surfaces keyed to the toolbar's #282828: the
window chrome, the tab strips and menu bar one step below it at #232323, and
the content the client shows — channel tree, chat log, text fields, lists — at
#1e1e1e. Selections are #364b6f, and channel names in the tree are white; the
chat lines about server events keep the blue they had, which channel names no
longer carry. Everything FlatLaf derives (borders, scroll bars, hover states)
follows from those.

A read-only editor pane is a chat log or an information view here, not a
disabled input, so it keeps the content background rather than FlatLaf's
inactive one; and since neither a text view nor a tree fills its viewport, the
space below the last line takes their background instead of the window's.

The row under the pointer is now washed in the same colour a hovered menu is,
rather than outlined. FlatLaf states that colour as a shift of the surface
beneath it, so it is resolved against the window background exactly as the
menu bar resolves it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 22:07:19 +00:00
erikbrockoandClaude Opus 5 35f10ed14c Paint the client with FlatLaf, in a light and a dark theme
The look-and-feel is FlatLaf now, chosen light or dark on the new Design
tab and remembered in the settings. Theme keeps only the colours TeamSpeak
gives meaning to (talking, away, muted, channel and server names) and takes
its surfaces and fonts from the look-and-feel, so a switch recolours the
whole window, chat logs included: the HTML panes share one themed stylesheet
and re-parse their content when the theme changes.

Also fixes the channel tree not scrolling: the tree listened for the mouse
wheel to re-check its hover row, and AWT only forwards a wheel event to the
enclosing scroll pane when the component under the pointer has no wheel
listener of its own. The hover row now follows the viewport instead, which
also covers scrollbar drags and keyboard scrolling.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 21:06:55 +00:00
erikbrockoandClaude Opus 5 d952ffd856 Put each client limit's count beside its "Limited" choice
The counts sat on a line of their own below the choices they belong to,
which also made the Advanced tab the tallest of the four and so decided
how much of the dialog the tab strip took. Each box now keeps its
natural height, and the free space collects below them.

Advanced went from 250px to 220px of preferred height, leaving the tab
strip about a third of the dialog rather than half.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 20:11:40 +00:00
erikbrockoandClaude Opus 5 acfe25db15 Show our own name in bold, in the row and in its editor
The renderer asks the panel which id is ours rather than reading
ClientEntry.self: our own row usually arrives among the enter-view events
of the connect handshake, before the connection knows its own client id,
so that flag was left false. It is now stamped once the id is known,
which also fixes the "(you)" marker in the info panel.

The inline editor matches, and sits 2px further left so its text lines up
with the label it replaces rather than with its own border.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 19:59:55 +00:00
erikbrockoandClaude Opus 5 08e6c51e90 Leave a talking client's name alone, and rename from the whole row
Bolding the name of whoever is speaking re-measures the row while the
label keeps its old width, so a nickname spent every utterance clipped to
an ellipsis. Talking already shows in the client's icon, which is where
TeamSpeak shows it too, so the name keeps its normal weight and colour.

Renaming now starts from the tree's own double-click handling, which
works a row by its whole line, instead of Swing's, which only sees clicks
that land on the label.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 19:50:03 +00:00
erikbrockoandClaude Opus 5 acd438dd14 Don't send a rename that changes nothing
Closing the inline editor without touching the name asked the server to
rename us to the name we already hold, which it refuses with "nickname
is already in use".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 19:43:00 +00:00
erikbrockoandClaude Opus 5 6e65797f25 Rename yourself by double-clicking your own tree row
The row turns into a text field holding the current nickname, selected so
typing replaces it; Enter commits, Escape leaves the name alone. Only our
own row edits — every other double click keeps its meaning, and ours no
longer opens a private chat with ourselves.

The editor keeps the row's own icon (the inherited one knows only the
renderer's default leaf icon) and selects the text on a short delay,
after the release that opened it has been turned into a caret placement.
The tree nodes only mirror the connection's model, so the typed name is
sent to the server rather than written into the node; the row follows
when the rename is reported back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 19:38:49 +00:00
erikbrockoandClaude Opus 5 fa99cadc44 Fill the selected tree row across its whole width
The cell renderer paints the selection only behind the label, which now
looks short next to the full-width hover outline and the full-line hit
area. The tree fills the selected rows itself, in the renderer's own
selection colour so the two meet seamlessly, which means it can no
longer clear its background as an opaque component would.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 19:16:06 +00:00
erikbrockoandClaude Opus 5 9ba0982f25 Work tree rows by their whole line, and outline the hovered one
Swing hit-tests a tree row only as far as its label, so a click past the
end of the name did nothing. Rows are now found by their vertical band
alone, which covers selection, the context menus, double-click join and
middle-click info; the expand handle to the left of a label still works
the row without selecting it.

The hovered row is outlined across that same full width, so what a click
would act on is visible before making it. Spacers, which nothing can be
done with, are skipped, and the outline gives way to the drag-and-drop
indicator while a drag is in progress.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 18:56:17 +00:00
erikbrockoandClaude Opus 5 275de77c8b Bold the channel references in the log, as the client ones are
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 18:24:05 +00:00
erikbrockoandClaude Opus 5 189620df7f Link the clients and channels named in server log lines
Log lines now name clients and channels with TeamSpeak's own client:// and
channel:// links, the same ones a dragged-in reference produces, so the
chat log's existing handling turns them into the context menus.

The log is rendered with a links-only pass rather than the full BBCode
renderer: its lines are assembled by the client itself, so nothing else in
them should be interpreted — a channel called "[b]VIP" stays literal.
Channels we no longer have (a deleted one) are still named in plain text.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 18:11:14 +00:00
erikbrockoandClaude Opus 5 cb05b097a6 Add "Change Description" to the client menu
Offered for our own client as well as others, with TS3's edit icon. The
description is read back from the server before prompting, since the
model only carries one for clients whose info has been looked at.

Note that client_description is not a clientupdate property even for
ourselves — the server only takes it through clientedit — and that our
own change is not echoed back to us, so the local entry is updated here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 18:04:35 +00:00
erikbrockoandClaude Opus 5 bcc034e975 Refresh a channel's cached description when it changes
The description is fetched on demand and cached, but nothing invalidated
it: notifychanneledited never carries the text, and the separate
notifychanneldescriptionchanged was ignored. Handle that event, and
refresh locally after our own edit, since the server does not notify the
invoker.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 17:38:53 +00:00
erikbrockoandClaude Opus 5 f68c1e297c Give the channel dialog's spare height to the description
The tabs were the growing half, which left them padding empty space
below their content while the description stayed five rows tall. They
now take their natural height at the bottom of the dialog and every
spare pixel goes to the description instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 16:12:44 +00:00
erikbrockoandClaude Opus 5 52bd180b56 Collect directory listings from the events that carry them
ftgetfilelist is answered with a notifyfilelist event per entry and a
closing notifyfilelistfinished, not with rows of the command's own reply
— and ts3j dispatches anything named notify* as an event, so every
listing came back empty. The entries are now collected for the request
in flight, which is what the icon chooser and the file browser read.

The icons themselves live in the repository's "icons" directory on newer
servers rather than loose in its root, so both places are read. They are
still addressed as /icon_<id> for download, upload and delete, which is
how the server resolves them regardless of where it keeps them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 16:03:03 +00:00
erikbrockoandClaude Opus 5 f2885d33ad Add the Create Channel dialog
The official client creates and edits channels with one dialog, so
ChannelEditDialog becomes ChannelDialog with two entry points. Creating
starts from caller-chosen defaults instead of a channelinfo and sends a
channelcreate carrying only what deviates from a plain new channel —
TeamSpeak checks a create permission per property that is present.

The server row now has a context menu with "Create Channel" and "Create
Spacer" (pre-filled with the lowest free [spacerN], since channel names
must be unique), and a channel's menu offers "Create Channel" and
"Create Sub-Channel", both starting out temporary.

Verified against the test server: a temporary channel is created, and a
permanent one a guest may not create reports the server's refusal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 15:31:07 +00:00
erikbrockoandClaude Opus 5 d8a56566d4 Add the Edit Channel dialog
Recovers the official client's CreateChannelDialog layout so the widget
set, labels and tab order match: name/icon/password/topic/description
above Standard, Audio, Permissions and Advanced tabs.

Core gains ChannelSettings (diffed against the original so channeledit
only carries changed properties) and ChannelAdmin (channelinfo/edit,
channel permissions, the server icon store). TeamspeakConnection now
owns the event executor so it can drain queued notify events before
reading a command's result, which channelpermlist needs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 15:11:49 +00:00
erikbrocko b29f518d59 Hide/gray client-menu items that can't do anything useful right now
"Find Client in Channel Tree" only makes sense when the menu was
opened somewhere other than the tree itself (chat log links, etc.),
so it's hidden when opened from the tree, and disabled elsewhere if
the client's channel isn't currently subscribed (so the tree
wouldn't actually show them). Adds "Join Channel of Client" above
"Move Client to own Channel", disabled under the same visibility
condition plus a full channel. Both use the CHANNEL_SWITCH icon.

Note: TS3 doesn't expose a channel's join-power threshold as a plain
property (only group membership powers work that way); it's a
permission resolved through channel/channel-group/server-group
inheritance that a regular client can't query, so join-power itself
isn't part of this check.
2026-08-18 15:25:41 +00:00
erikbrocko acf0221837 Add Set Server/Channel Group context menus and dialog
Lets moderators assign or revoke server and channel groups for a
client directly from its context menu, with per-group checkboxes
gated by the client's actual TS3 permissions (i_group_needed_member_
add/remove_power vs. each group's n_member_addp/removep, including
TS3's -1 "unlimited" sentinel). A "Server Groups Dialog..." entry
shows every server group, graying out ones the client can't touch.

Group membership changes now update ClientEntry locally instead of
only logging them, so the checkboxes and dialog reflect a change
immediately instead of needing a reconnect. The server's default
channel group (e.g. "Guest") is hidden from the channel-group menu
since it's not something you assign directly.
2026-08-18 15:07:38 +00:00
erikbrockoandClaude Sonnet 5 e5b607fc29 Split ServerTab into focused collaborator classes
Extract mic/speaker/away/commander state handling into
ServerTabSelfState, ServerTreePanel.Actions delegation (context
menus, drag-drop, link clicks) into ServerTabTreeActions, and
ConnectionListener event marshaling onto the EDT into
ServerTabConnectionEvents. ServerTab keeps its full public API
(636 -> 377 lines); no behavior change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 13:37:58 +00:00
erikbrockoandClaude Sonnet 5 d722377508 Split SettingsDialog into focused tab panels
Extract the Playback/Capture and Voice Activation tabs (device pickers,
gain/volume sliders, noise reduction, VAD/PTT tuning, microphone test)
into DevicesPanel and VoiceActivationPanel, alongside the existing
NotificationsPanel/HotkeysPanel/IconPackPanel/ClientVersionPanel. A new
FormPanel base holds the shared GridBagLayout scaffolding. SettingsDialog
is now a thin coordinator (753 -> 187 lines); its public API and all
settings read/write behavior are unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 13:37:51 +00:00
erikbrockoandClaude Sonnet 5 b694845381 Split TeamspeakConnection into focused collaborator classes
Extract notify-event handling and the native-style server log/sound
announcements into ConnectionEventHandler, and getconnectioninfo
request/response + stats-snapshot building into ConnectionStatsCollector.
TeamspeakConnection remains the public facade (1828 -> 1037 lines); its
external API is unchanged. Pure refactor, no protocol/timing changes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 13:37:43 +00:00
erikbrockoandClaude Sonnet 5 cf5ba94092 Add Master Volume slider, status bar toggle, and toolbar customization menu
The toolbar now has a right-click menu to hide/show the status bar and
a short Master Volume slider (drag or scroll) that multiplies both
voice and notification volume via new Settings.effectiveOutputVolume()/
effectiveSoundVolume() helpers.

Also splits MainFrame's toolbar, menu bar and status bar construction
into their own MainToolbar/MainMenuBar/StatusBar classes, each talking
back to MainFrame only through a Listener interface.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 13:37:36 +00:00
erikbrockoandClaude Sonnet 5 e5fb87a796 Split ServerTreePanel into focused collaborator classes
Extract cell rendering, right-aligned group-icon-strip painting, the
drop-indicator JTree subclass, and drag-and-drop handling out of
ServerTreePanel into ServerTreeCellRenderer, DropIndicatorTree, and
ServerTreeDragAndDrop, leaving ServerTreePanel as the coordinator
(706 -> 284 lines). Pure refactor, no behavior change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 13:35:42 +00:00
erikbrockoandClaude Sonnet 5 de02f88f1c Add browser-style drag-to-reorder for chat and server tabs
Dragging a tab shows animated snapshots on the glass pane and swaps
with whichever neighbour it reaches the midpoint of; the real tab
model is only touched once, on release, so an in-flight mouse grab
never gets pulled out from under a rebuilt tab component.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-18 12:49:26 +00:00
erikbrockoandClaude Sonnet 5 71084ea309 Log server activity, scrollable chat tabs, and move info panel to a chat tab
Native TS3 logs client joins/leaves/moves, group changes and channel edits
to the server tab; minor local-only notices (mic mute, tray) no longer
spam the log. Chat tabs scroll by mouse wheel like server tabs. The info
panel can now be moved into a persistent, generically-labelled chat tab
that tracks tree selection and collapses the panel's space entirely; a
tree rebuild no longer briefly fires a null selection that reset this.
Added "Find Client in Channel Tree" to the client context menu, and tree
selection now survives model rebuilds.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 21:47:12 +00:00
erikbrockoandClaude Sonnet 5 047c89404c Prefer RECORD over XInput2 on X11: raw button releases can go missing
On at least some driver stacks, XI_RawButtonRelease is never delivered
to a client that hasn't grabbed the pointer, even though the matching
XI_RawButtonPress arrives fine — a bound mouse button then looks stuck
down forever, both when recording a hotkey and when using one. Taking
an active XIGrabDevice grab does fix delivery, but even with
owner_events set it blocks clicks from reaching every other window, so
it's not usable. XRecordInputHook taps the same core events xev sees
and isn't affected, so it now goes first on X11; XInput2 stays as the
fallback for servers where RECORD is disabled or missing, and gets a
correctness cleanup (real per-device event selection instead of the
XIAllMasterDevices pseudo-device) along the way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 10:34:19 +00:00
erikbrocko 75ae6b89b2 Report mute/hardware status correctly, add Local Mic Mute, fix stale talking indicator
- Mute/deafen status now goes out through clientupdate instead of
  clientedit, which silently rejected client_input_muted/output_muted
  since they are runtime status, not editable client properties.
- Publish client_input_hardware so other clients see "Microphone
  Disabled" instead of silence while another tab holds the capture
  device; track input/output hardware flags for other clients too,
  and show a distinct grey "disabled" icon instead of reusing the red
  "muted" one for both the tree and the info panel.
- Implement TS3's Enable/Disable/Toggle Local Mic Mute hotkeys: they
  silence capture like a real mute, but never touch the published
  mute status or play a sound.
- A speaker's "talking" indicator only ever cleared when its
  zero-length end-of-burst voice packet arrived; if that one UDP
  packet was lost, the indicator stuck until their next burst. Add a
  watchdog that clears it after 200ms of silence from that speaker
  regardless.
2026-08-17 08:43:22 +00:00
erikbrocko e228dd4ad0 Replace RMS voice detection with TeamSpeak's own RNN VAD
Ports WebRTC's rnn_vad (as TS3 embeds it) to Java: LPC, pitch
estimation, spectral features and the RNN itself, feeding a
speech-probability detector that replaces the old SpeechDetector.
Also switches the volume-gate threshold from raw dBFS to
InputLevel's scale, matching TS3's own slider and range, with a
migration for settings saved under the old key.
2026-08-17 07:51:51 +00:00
erikbrockoandClaude Opus 5 752676e863 Capture global hotkeys on Windows through raw input
A message-only window registers the keyboard and mouse with
RIDEV_INPUTSINK, so every key and button arrives as WM_INPUT whether or
not the client is in front. Raw input only observes, where a
WH_KEYBOARD_LL hook sits in the path of the system input queue and can
swallow a keystroke; it also reports the side buttons and both edges of
every key, which push-to-talk needs.

Keyboard codes stay in each platform's own numbering — X keycodes on
X11, set-1 scan codes with the E0/E1 escape folded into the high byte on
Windows — since that is what the input API reports and the key-naming
call expects. Bindings are per-machine either way, as TeamSpeak's own
per-OS keydefs are. Mouse buttons are unified on the X numbering, so
"Mouse 4" means the same thing on both.

The RAWINPUT decoding lives in its own class so it can be tested off
Windows; the window and its pump have not been run on Windows yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 18:40:50 +00:00
erikbrockoandClaude Opus 5 edc8a0ca3a Capture hotkeys through XInput2, as TeamSpeak does
The bundled TS3 Linux binary dlopens libX11 and libXi and drives
XIQueryVersion/XISelectEvents/XGetEventData — XInput2 raw events, with no
trace of the RECORD extension anywhere in its tree. That is the better
choice for us too: XInput2 is core input, present on any remotely modern
server, where RECORD is a debugging extension that is sometimes disabled
or left out of the build. Both are passive, so the keystroke still
reaches the focused window either way.

XRecordInputHook stays as the fallback behind it. Raw events also explain
why TS3's hotkeys work under KWin's Wayland session despite it using no
Wayland API at all: it runs on Xwayland, and KWin's legacy X11 app
support forwards the keys.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 18:33:32 +00:00
erikbrockoandClaude Opus 5 7e4b9671fe Global hotkeys, in TeamSpeak's own shape
Bindings are captured system-wide rather than only while the window has
focus: X11's RECORD extension where the X server sees every key, and a
/dev/input reader as the Wayland fallback. Any key can act as a modifier,
mouse buttons included, as TS3 allows.

The action catalogue, its three categories and the "advanced actions"
split are reverse-engineered from the original client; actions this
client cannot perform are listed but greyed out. Push-to-talk becomes one
of these hotkeys, so the old focus-bound pushToTalkKey setting is gone and
the Voice Activation button edits that binding instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 17:08:28 +00:00
erikbrockoandClaude Opus 5 3e2c06248f Make the tray menu close, and its window come forward
Swing never grabs the pointer for a popup, so a click on the desktop or
another application is not seen and the menu stays up. The little window
the menu hangs off is focusable now and closes it when the focus goes
elsewhere, Escape closes it, and clicking the icon again toggles it.

Raising the window was ignored for the same reason it usually is: a
window manager refuses a raise from an application that does not have the
focus. The icon asks for _NET_ACTIVE_WINDOW instead — the request meant
for pagers and trays acting for the user — and falls back to Swing's
always-on-top shuffle when it cannot find the window. Windows are matched
by _NET_WM_PID and _NET_WM_NAME, since WM_NAME cannot carry the em dash
in our title.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 22:58:24 +00:00
erikbrockoandClaude Opus 5 32e5ffb576 Show the local client's state in the system tray
The icon carries the badge the tree draws next to our own nickname on the
active server — idle, talking, away, commander, microphone or speakers
muted — and clicking it brings the window back to the front. Right click
offers "Show TS3J" and "Quit".

AWT's tray icon cannot be transparent on X11: the toolkit embeds a window
of the screen's default, opaque visual and fills it with a background
colour before drawing the image, so every icon sits in a box. Panels that
can show transparent icons advertise an ARGB visual instead, so the icon
is docked by hand over the system tray protocol, in that visual, with the
image put on the window premultiplied. AWT's own icon stays as the
fallback for everything else.

Two details a panel will not forgive: an icon that publishes no size
hints is allocated a one-pixel sliver, and docking is a request, so an
icon that is never adopted has to hand over to the fallback rather than
sit invisible.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 22:45:32 +00:00
erikbrockoandClaude Opus 5 ef95b6305d Report a chosen client version and operating system
Other clients see the version and platform from clientinit in the info
panel, and until now that was whatever ts3j sends. The new Client Version
tab picks one instead.

Servers refuse a version they do not know with "client is modified", so
free text is not enough: the list holds genuine version/platform/signature
triples from released clients, newest first per platform. The fields stay
editable for a version whose signature is known from elsewhere, and a
refused connection now says where to change it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 20:06:09 +00:00
788 changed files with 72888 additions and 8483 deletions
+20
View File
@@ -0,0 +1,20 @@
name: test
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 25
cache: maven
# Builds ts3j from the submodule along with the client; no test needs a display or libopus.
- run: mvn -B -f ts3-client/pom.xml verify
+15 -1
View File
@@ -4,11 +4,15 @@ build/
out/ out/
*.class *.class
# The bundled proprietary TeamSpeak 3 client (reference binary, not our source) # Bundled proprietary TeamSpeak clients (reference binaries, not our source)
/TeamSpeak3-Client-linux_amd64/ /TeamSpeak3-Client-linux_amd64/
/ts6/
/ts6-server/
/re-android/
# Packages # Packages
*.jar *.jar
!android/gradle/wrapper/gradle-wrapper.jar
*.war *.war
*.zip *.zip
*.tar.gz *.tar.gz
@@ -34,3 +38,13 @@ release.properties
# OS # OS
.DS_Store .DS_Store
# Android / Gradle
android/.gradle/
android/.kotlin/
android/**/.cxx/
android/local.properties
# Release signing (keystore.properties points at the key)
android/keystore.properties
*.jks
+153
View File
@@ -0,0 +1,153 @@
import java.util.Properties
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
}
/**
* Puts the sound packs of an installed TeamSpeak 3 client into the app's assets, as the
* desktop client borrows them from the installation, with the sounds encoded as Opus
* (a fifteenth of the WAVs). They are TeamSpeak's and not in the repository; a build
* without the client ships no packs.
*/
abstract class BundleSoundPacks : DefaultTask() {
@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val packs: DirectoryProperty
/** The desktop code whose libopus does the encoding. */
@get:Classpath
abstract val encoder: ConfigurableFileCollection
@get:OutputDirectory
abstract val assets: DirectoryProperty
@get:Inject
abstract val exec: ExecOperations
@TaskAction
fun encode() {
val out = assets.get().asFile
out.deleteRecursively()
val source = packs.get().asFile
if (!source.isDirectory) {
logger.warn("No TeamSpeak 3 sound packs at $source; the app ships without sounds")
return
}
exec.javaexec {
classpath = encoder
mainClass.set("eu.lixko.ts3j.client.audio.desktop.EncodeSoundPacks")
jvmArgs("--enable-native-access=ALL-UNNAMED")
args(source.path, File(out, "sound").path)
}
}
}
val soundPackEncoder: Configuration by configurations.creating {
isCanBeConsumed = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR))
}
}
val ts3ClientDir: String = providers.gradleProperty("ts3.client.dir")
.orElse(providers.environmentVariable("TS3_CLIENT_DIR"))
.getOrElse(rootDir.resolve("../TeamSpeak3-Client-linux_amd64").path)
val bundleSoundPacks = tasks.register<BundleSoundPacks>("bundleSoundPacks") {
packs.set(File(ts3ClientDir, "sound"))
encoder.from(soundPackEncoder)
assets.set(layout.buildDirectory.dir("generated/soundPacks"))
}
androidComponents {
onVariants { variant ->
variant.sources.assets?.addGeneratedSourceDirectory(bundleSoundPacks, BundleSoundPacks::assets)
}
}
/**
* Release signing from keystore.properties (storeFile, storePassword, keyAlias, keyPassword),
* kept out of the repository; without it the release APK is left unsigned.
*/
val releaseKeystore = rootDir.resolve("keystore.properties").takeIf { it.isFile }?.let { file ->
Properties().apply { file.inputStream().use(::load) }
}
android {
namespace = "eu.lixko.ts3j.client.android"
compileSdk = 37
ndkVersion = "30.0.16248370"
defaultConfig {
applicationId = "eu.lixko.ts3j.client"
minSdk = 33
targetSdk = 36
versionCode = 1
versionName = "0.1.0"
ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
}
}
signingConfigs {
if (releaseKeystore != null) {
create("release") {
storeFile = file(releaseKeystore.getProperty("storeFile"))
storePassword = releaseKeystore.getProperty("storePassword")
keyAlias = releaseKeystore.getProperty("keyAlias")
keyPassword = releaseKeystore.getProperty("keyPassword")
}
}
}
// One APK per ABI for releases; debug builds stay a single APK for both.
buildTypes {
release {
signingConfig = signingConfigs.findByName("release")
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
androidResources {
// The app is English only; drops the libraries' translations.
localeFilters += "en"
}
buildFeatures {
compose = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
packaging {
// Compressed in the APK, which then is smaller to send; extracted on install.
dex.useLegacyPackaging = true
jniLibs.useLegacyPackaging = true
resources {
// BouncyCastle ships Java 9+ module metadata Android has no use for.
excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
}
}
}
dependencies {
implementation(project(":audio"))
soundPackEncoder(project(":desktop"))
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.service)
implementation(libs.androidsvg)
}
+14
View File
@@ -0,0 +1,14 @@
# ts3j looks up SRV records through JNDI only where it exists; Android lacks it.
-dontwarn javax.naming.**
# Reached from native code by name.
-keepclasseswithmembernames class eu.lixko.ts3j.client.android.audio.** {
native <methods>;
}
# ts3j builds protocol handlers and packet bodies reflectively.
-keep class com.github.manevolent.ts3j.** { *; }
# ini4j (identity .ini files) instantiates its parsers, builders, formatters
# and escape tools through ServiceFinder, by reflection.
-keepclassmembers class org.ini4j.spi.** { <init>(); }
+56
View File
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<!-- Speech sound packs talk through the phone's text-to-speech engine. -->
<queries>
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>
<application
android:name=".Ts3Application"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Material.NoActionBar">
<activity
android:name=".MainActivity"
android:label="@string/launcher_name"
android:exported="true"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- TeamSpeak server links from browsers and other apps connect. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="ts3server" />
</intent-filter>
</activity>
<service
android:name=".ConnectionService"
android:exported="false"
android:foregroundServiceType="mediaPlayback|microphone" />
<receiver
android:name=".ReplyReceiver"
android:exported="false" />
</application>
</manifest>
@@ -0,0 +1,36 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
/** What lives as long as the process, wired together once; each screen is handed only the parts it uses. */
class AppParts(context: Context) {
val settings: Settings = Settings.load()
val icons = IconTheme(context, settings)
val pictures = WebPictures(context.cacheDir, settings)
val swipe = SwipePrefs(context)
/** The reasons offered when adding a ban; shared by every server. */
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
private val bookmarkStore = Bookmarks.load()
private val identityStore = IdentityStore.load(settings)
private val contactStore = ContactStore.load()
val identities: IdentityManager = IdentityManager(context, identityStore, settings, bookmarkStore) { bookmarks.refresh() }
val bookmarks: BookmarkManager = BookmarkManager(context, icons, bookmarkStore, identities) { sessions.bookmarkEdited(it) }
val contacts: ContactManager = ContactManager(context, contactStore, settings)
val whisperLists: WhisperListManager = WhisperListManager()
val audio: AudioSetup = AudioSetup(context, settings)
val myTeamSpeak: MyTeamSpeakAccount = MyTeamSpeakAccount(context, pictures,
TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore), bookmarks, identities,
identityStore, bookmarkStore, settings) { sessions.myTeamSpeakChanged() }
private val serverParts = ServerParts(context, settings, identityStore, audio, contactStore, myTeamSpeak)
val sessions: SessionController = SessionController(context, settings, identities, bookmarks, serverParts,
LevelMonitor(settings, audio.audio))
}
@@ -0,0 +1,30 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.android.audio.AudioRoute
/** Where the Android-only audio choices are kept; the rest live in the shared settings. */
class AudioRoutePrefs(context: Context) {
private val prefs = context.getSharedPreferences("audio", Context.MODE_PRIVATE)
fun load(): AudioRoute = AudioRoute(
enumOr(prefs.getString(INPUT_PRESET, null), AudioRoute.DEFAULT.inputPreset()),
enumOr(prefs.getString(USAGE, null), AudioRoute.DEFAULT.usage()),
)
fun save(route: AudioRoute) {
prefs.edit()
.putString(INPUT_PRESET, route.inputPreset().name)
.putString(USAGE, route.usage().name)
.apply()
}
private inline fun <reified E : Enum<E>> enumOr(name: String?, default: E): E =
enumValues<E>().firstOrNull { it.name == name } ?: default
private companion object {
const val INPUT_PRESET = "inputPreset"
const val USAGE = "usage"
}
}
@@ -0,0 +1,76 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.sound.SoundNotifier
import eu.lixko.ts3j.client.sound.SoundPack
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The devices and routing audio goes through, the sound packs, and the floating push-to-talk button. */
class AudioSetup internal constructor(private val context: Context, private val settings: Settings) {
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
settings.outputDevice.addListener { soundPlayer.setOutputDevice(it) }
}
/** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) {
routePrefs.save(route)
_route.value = route
audio.setRoute(route)
}
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
private companion object {
const val OVERLAY_ENABLED = "enabled"
}
}
@@ -0,0 +1,99 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.os.Handler
import android.os.Looper
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The bookmarks, as the connect page lists them and home-screen shortcuts lead to them. */
class BookmarkManager internal constructor(
context: Context,
icons: IconTheme,
private val store: Bookmarks,
private val identities: IdentityManager,
/** A saved bookmark changed, for the servers connected with it. */
private val onEdited: (Bookmark) -> Unit,
) {
private val shortcuts = BookmarkShortcuts(context, icons)
private val main = Handler(Looper.getMainLooper())
private val _all = MutableStateFlow(store.all().toList())
val all: StateFlow<List<Bookmark>> = _all
/** Picks up bookmarks added or changed elsewhere, such as by an import. */
fun refresh() {
_all.value = store.all().toList()
}
fun find(id: String): Bookmark? = store.find(id)
internal fun startupBookmarks(): List<Bookmark> = store.startupBookmarks()
internal fun add(bookmark: Bookmark) {
store.add(bookmark)
save()
}
/** A bookmark to [address] as typed into the connect form, not yet saved. */
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark {
val (host, port) = SessionController.parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != identities.nicknameFor(identityId) }.orEmpty()
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
}
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */
fun save(index: Int, edited: Bookmark) {
val all = store.all()
if (index !in all.indices) {
store.add(edited)
} else {
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
all[index] = edited
}
save()
onEdited(edited)
}
fun remove(bookmark: Bookmark) {
val index = store.all().indexOf(bookmark)
if (index < 0) return
store.remove(index)
save()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
main.post {
val all = store.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) save()
}
}
private fun save() {
store.save()
refresh()
shortcuts.sync(_all.value)
}
val canPinShortcuts: Boolean get() = shortcuts.supported
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
fun pinShortcut(bookmark: Bookmark) {
// A bookmark not saved since ids came in has a new one on every load until it is.
store.save()
shortcuts.pin(bookmark)
}
}
@@ -0,0 +1,80 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Icon
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.net.IconRepository
/**
* Home-screen shortcuts that connect to a bookmark in one tap. A shortcut names its bookmark by
* [Bookmark.id], so editing the bookmark carries over and removing it disables the shortcut.
*/
internal class BookmarkShortcuts(private val context: Context, private val icons: IconTheme) {
private val manager = context.getSystemService(ShortcutManager::class.java)
val supported: Boolean get() = manager?.isRequestPinShortcutSupported == true
/** Asks the launcher to pin a shortcut; it confirms with the user itself. */
fun pin(bookmark: Bookmark) {
manager?.requestPinShortcut(info(bookmark), null)
}
/** Pinned shortcuts take on their bookmarks' current names and icons; those of removed ones stop working. */
fun sync(bookmarks: List<Bookmark>) {
val manager = manager ?: return
val byId = bookmarks.associateBy { shortcutId(it.id) }
val pinned = manager.pinnedShortcuts
val gone = pinned.map { it.id }.filter { it !in byId }
if (gone.isNotEmpty()) manager.disableShortcuts(gone, "Bookmark removed")
val kept = pinned.mapNotNull { byId[it.id] }
if (kept.isNotEmpty()) {
manager.enableShortcuts(kept.map { shortcutId(it.id) })
manager.updateShortcuts(kept.map(::info))
}
}
private fun info(bookmark: Bookmark): ShortcutInfo =
ShortcutInfo.Builder(context, shortcutId(bookmark.id))
.setShortLabel(bookmark.displayName())
.setLongLabel(listOfNotNull(bookmark.displayName(), bookmark.channel.ifBlank { null }).joinToString(" · "))
.setIcon(icon(bookmark.iconId))
.setIntent(Intent(context, MainActivity::class.java)
.setAction(ACTION_CONNECT)
.putExtra(EXTRA_BOOKMARK, bookmark.id))
.build()
/** The server's own icon as last seen there, else the pack's server icon, inside the adaptive icon's safe zone. */
private fun icon(iconId: Long): Icon {
val art = IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) }
?: icons.render(listOf("SERVER_GREEN", "BOOKMARK_MANAGER"), ART_PX, 0x202020)
val canvas = Bitmap.createBitmap(ADAPTIVE_PX, ADAPTIVE_PX, Bitmap.Config.ARGB_8888)
Canvas(canvas).apply {
drawColor(BACKGROUND)
if (art != null) {
val inset = (ADAPTIVE_PX - ART_PX) / 2
drawBitmap(art, null, Rect(inset, inset, inset + ART_PX, inset + ART_PX), null)
}
}
return Icon.createWithAdaptiveBitmap(canvas)
}
companion object {
const val ACTION_CONNECT = "eu.lixko.ts3j.client.android.CONNECT_BOOKMARK"
const val EXTRA_BOOKMARK = "bookmark"
/** 108 dp at xxxhdpi; the inner 72 dp always shows, the art sits well within. */
private const val ADAPTIVE_PX = 432
private const val ART_PX = 192
private const val BACKGROUND = 0xFFE8EEF4.toInt()
private fun shortcutId(bookmarkId: String) = "bookmark:$bookmarkId"
}
}
@@ -0,0 +1,83 @@
package eu.lixko.ts3j.client.android
import androidx.compose.runtime.Immutable
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.text.HtmlText
import eu.lixko.ts3j.client.text.TextQuery
/** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */
@Immutable
data class ChatLine(val id: Long, val html: String) {
/** The text to find in. */
val plain: String by lazy { HtmlText.plain(html) }
}
@Immutable
data class Conversation(
val key: ChatKey,
val title: String,
/** The peer's unique id in a private chat, once known. */
val uniqueId: String = "",
val lines: List<ChatLine> = emptyList(),
val unread: Boolean = false,
)
/** Every conversation of the session: the server's, the channel's, then the private ones. */
@Immutable
data class Chats(
val server: Conversation = Conversation(ChatKey.SERVER, "Server"),
val channel: Conversation = Conversation(ChatKey.CHANNEL, "Channel"),
val private: List<Conversation> = emptyList(),
) {
val all: List<Conversation> get() = listOf(server, channel) + private
val anyUnread: Boolean get() = all.any { it.unread }
operator fun get(key: ChatKey): Conversation? = when (key.scope()) {
ChatScope.SERVER -> server
ChatScope.CHANNEL -> channel
ChatScope.PRIVATE -> private.firstOrNull { it.key == key }
}
/** Applies [change] to a conversation, opening a private one titled [title] if needed. */
fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key.scope()) {
ChatScope.SERVER -> copy(server = change(server))
ChatScope.CHANNEL -> copy(channel = change(channel))
ChatScope.PRIVATE -> {
val existing = private.indexOfFirst { it.key == key }
if (existing < 0) {
copy(private = private + change(Conversation(key, title)))
} else {
copy(private = private.toMutableList().also { it[existing] = change(it[existing]) })
}
}
}
fun close(key: ChatKey): Chats = copy(private = private.filter { it.key != key })
companion object {
/** As many lines as a log history loads; older ones leave the conversation. */
const val MAX_LINES = 1000
}
}
fun Conversation.append(line: ChatLine, read: Boolean): Conversation =
copy(lines = (lines + line).takeLast(Chats.MAX_LINES), unread = unread || !read)
/** The [nth] match of the find bar's query in the line [line]. */
data class ChatMatch(val line: Long, val nth: Int)
/** Every match of [query] in [lines], oldest first; past [limit], only the newest. */
fun findIn(lines: List<ChatLine>, query: TextQuery, limit: Int): List<ChatMatch> {
if (query.isEmpty) return emptyList()
val out = ArrayList<ChatMatch>()
for (line in lines) {
val m = query.matcher(line.plain) ?: return emptyList()
var n = 0
while (m.find()) {
if (m.end() > m.start()) out += ChatMatch(line.id, n++)
}
}
return if (out.size > limit) out.subList(out.size - limit, out.size) else out
}
@@ -0,0 +1,243 @@
package eu.lixko.ts3j.client.android
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.graphics.Color
import android.graphics.drawable.Icon
import android.net.wifi.WifiManager
import android.os.PowerManager
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.net.ClientStatus
import eu.lixko.ts3j.client.session.SelfState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/**
* Keeps the process in the foreground while connected, so the connection and its audio
* survive the app leaving the screen, and offers the essentials in its notification.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ConnectionService : LifecycleService() {
private lateinit var sessions: SessionController
private lateinit var icons: IconTheme
private lateinit var audio: AudioSetup
private lateinit var wifiLock: WifiManager.WifiLock
private lateinit var wifiBackgroundLock: WifiManager.WifiLock
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var overlay: PttOverlay
private var foregroundTypes = 0
private var shown: ServerController? = null
override fun onCreate() {
super.onCreate()
val parts = (application as Ts3Application).parts
sessions = parts.sessions
icons = parts.icons
audio = parts.audio
getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
)
// Voice goes out every 20 ms; Wi-Fi power saving and a sleeping CPU would stretch that.
// Low-latency mode only holds while we are in the foreground with the screen on, so the
// high-performance lock keeps power saving off the rest of the time.
val wifi = getSystemService(WifiManager::class.java)
wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "ts3j:voice")
.apply { setReferenceCounted(false); acquire() }
@Suppress("DEPRECATION")
wifiBackgroundLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ts3j:voice-background")
.apply { setReferenceCounted(false); acquire() }
wakeLock = getSystemService(PowerManager::class.java)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ts3j:connection")
.apply { setReferenceCounted(false); acquire() }
show(sessions.current.value?.state?.value ?: SessionState(), capturing = false)
lifecycleScope.launch {
// The server count shows in the notification too.
combine(shownServer(), sessions.micOwner, sessions.servers) { shown, owner, _ -> shown to (owner != null) }
.conflate()
.collect { (shown, capturing) ->
if (shown != null) {
this@ConnectionService.shown = shown.first
show(shown.second, capturing)
// Talking flips the icon often, and Android drops updates that come too fast.
delay(MIN_UPDATE_MS)
}
}
}
lifecycleScope.launch {
sessions.current.flatMapLatest { it?.state ?: flowOf(null) }.collectLatest { state ->
if (state == null) {
// A reconnect leaves the server briefly; only stop once it stays gone.
delay(STOP_DELAY_MS)
stopSelf()
}
}
}
lifecycleScope.launch {
icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
}
overlay = PttOverlay(this, icons, sessions::setPushToTalk)
lifecycleScope.launch {
val owner = sessions.micOwner.flatMapLatest { server ->
server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null)
}
combine(owner, sessions.onScreen, audio.pttOverlay) { held, onScreen, enabled ->
val (state, tree) = held ?: return@combine null
val wanted = enabled && !onScreen && state.connected && state.micActive &&
state.inputMode == Settings.InputMode.PUSH_TO_TALK
val status = tree.client(state.selfClientId)?.status
when {
!wanted -> null
state.micMuted -> PttOverlay.Look.MUTED
status == ClientStatus.TALKING || status == ClientStatus.COMMANDER_TALKING -> PttOverlay.Look.TALKING
else -> PttOverlay.Look.IDLE
}
}.distinctUntilChanged().collect { look ->
if (look == null) overlay.hide() else overlay.show(look)
}
}
}
/**
* The server the notification speaks for, as the desktop tray icon does: the one
* holding the microphone, or the visible one when nobody is capturing.
*/
private fun shownServer(): Flow<Pair<ServerController, SessionState>?> =
combine(sessions.current, sessions.micOwner) { current, owner -> current to owner }
.flatMapLatest { (current, owner) ->
combine(current?.state ?: flowOf(null), owner?.state ?: flowOf(null)) { currentState, ownerState ->
when {
owner != null && ownerState?.connected == true -> owner to ownerState
current != null && currentState != null -> current to currentState
else -> null
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val server = shown ?: sessions.current.value ?: return START_NOT_STICKY
val state = server.state.value
when (intent?.action) {
ACTION_TOGGLE_MUTE -> server.setMicMuted(!state.micMuted)
ACTION_TOGGLE_DEAFEN -> server.setDeafened(!state.deafened)
ACTION_DISCONNECT -> server.disconnect()
}
return START_NOT_STICKY
}
/**
* The user swiped the app away: they are done with it, connection included. Leaving
* properly spares the server a ghost that would hold our identity until it times out.
*/
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
lifecycleScope.launch(Dispatchers.IO) {
sessions.leave()
stopSelf()
}
}
override fun onDestroy() {
overlay.hide()
wifiLock.release()
wifiBackgroundLock.release()
wakeLock.release()
super.onDestroy()
}
/** Posts the notification, re-declaring what the service uses when that changed. */
private fun show(state: SessionState, capturing: Boolean) {
val types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or
if (capturing && hasMicPermission()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0
val notification = notification(state)
if (types != foregroundTypes) {
startForeground(NOTIFICATION_ID, notification, types)
foregroundTypes = types
} else {
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification)
}
}
private fun hasMicPermission() =
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
private fun notification(state: SessionState): Notification {
val open = PendingIntent.getActivity(
this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE
)
val others = sessions.servers.value.size - 1
return Notification.Builder(this, CHANNEL)
.setSmallIcon(statusIcon(state.self))
.setLargeIcon(largeIcon(state.self))
.setContentTitle(if (others > 0) "${state.title} +$others" else state.title)
.setContentText(state.status)
.setContentIntent(open)
.setOngoing(true)
.addAction(action(ACTION_TOGGLE_MUTE, if (state.micMuted) "Unmute" else "Mute"))
.addAction(action(ACTION_TOGGLE_DEAFEN, if (state.deafened) "Undeafen" else "Deafen"))
.addAction(action(ACTION_DISCONNECT, "Disconnect"))
.build()
}
/**
* The status bar shows only the shape of an icon, which pack art loses, so it is
* drawn from the Material pack whatever pack is chosen.
*/
private fun statusIcon(self: SelfState): Icon {
val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt()
val bitmap = icons.renderMaterial(key, size, Color.WHITE)
?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
return Icon.createWithBitmap(bitmap)
}
/** The expanded notification has room for the chosen pack's own art, as the tree draws it. */
private fun largeIcon(self: SelfState): Icon? {
val key = self.iconKey() ?: return null
val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt()
return icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500))
?.let(Icon::createWithBitmap)
}
private fun action(action: String, label: String): Notification.Action {
val intent = PendingIntent.getService(
this, action.hashCode(), Intent(this, ConnectionService::class.java).setAction(action),
PendingIntent.FLAG_IMMUTABLE
)
return Notification.Action.Builder(null, label, intent).build()
}
private companion object {
const val CHANNEL = "connection"
const val NOTIFICATION_ID = 1
const val STOP_DELAY_MS = 3_000L
const val MIN_UPDATE_MS = 250L
const val STATUS_ICON_DP = 24
const val LARGE_ICON_DP = 48
const val ACTION_TOGGLE_MUTE = "eu.lixko.ts3j.client.android.TOGGLE_MUTE"
const val ACTION_TOGGLE_DEAFEN = "eu.lixko.ts3j.client.android.TOGGLE_DEAFEN"
const val ACTION_DISCONNECT = "eu.lixko.ts3j.client.android.DISCONNECT"
}
}
@@ -0,0 +1,53 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
/** The contacts: friends, blocked clients and how each is treated. */
class ContactManager internal constructor(
private val context: Context,
internal val store: ContactStore,
private val settings: Settings,
) {
/** Copies of the contacts, as the store's own entries change in place. */
private val _all = MutableStateFlow(copies())
val all: StateFlow<List<Contact>> = _all
init {
// Mutations report on whichever thread made them, a connection thread included.
store.addListener { _all.value = copies() }
}
private fun copies(): List<Contact> = store.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [save]. */
fun find(uniqueId: String): Contact? = store.find(uniqueId)?.copy()
fun save(contact: Contact) = store.put(contact)
fun remove(uniqueId: String) = store.remove(uniqueId)
/** What a new contact starts with; changed in place, then [saveDefaults]. */
val defaults: ContactDefaults get() = settings.contactDefaults
fun saveDefaults() = settings.save()
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun import(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else store.merge(found)
}
}
@@ -0,0 +1,132 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.net.ChannelFiles
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.util.concurrent.atomic.AtomicLong
/** One upload or download as the file browser shows it. */
data class TransferRow(
val id: Long,
val name: String,
val upload: Boolean,
val channelId: Int,
/** The directory an upload goes into, to list again once it is there. */
val directory: String,
val transferred: Long,
val total: Long,
val state: FileTransfer.State,
val error: String?,
) {
val done: Boolean get() = state != FileTransfer.State.PENDING && state != FileTransfer.State.ACTIVE
val progress: Float get() = if (total > 0) (transferred.toFloat() / total).coerceIn(0f, 1f) else 0f
}
/**
* The channel file transfers of one server. Transfers go through files of our own in the cache,
* as the core reads and writes plain files: a download is copied where the user picked once
* complete, an upload is copied out of the picked document first. They outlive the browser page.
*/
class FileTransfers internal constructor(private val context: Context, private val files: ChannelFiles) {
private val ids = AtomicLong()
private val handles = HashMap<Long, FileTransfer>()
private val _rows = MutableStateFlow(emptyList<TransferRow>())
val rows: StateFlow<List<TransferRow>> = _rows
/** Downloads [file] into the document at [target]. */
fun download(channelId: Int, password: String, file: RemoteFile, target: Uri) {
val temp = File.createTempFile("download", null, context.cacheDir)
val row = add(file.name, upload = false, channelId, file.parentPath, file.size)
start(row, temp, onComplete = {
context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } }
?: throw IOException("Could not write the file")
}) { listener -> files.download(channelId, password, file.fullPath, temp, listener) }
}
/** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */
suspend fun upload(channelId: Int, password: String, directory: String, source: Uri) {
val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) }
val row = add(name, upload = true, channelId, directory, temp.length())
start(row, temp, onComplete = {}) { listener ->
files.upload(channelId, password, directory + name, temp, true, listener)
}
}
fun cancel(id: Long) {
synchronized(handles) { handles[id] }?.cancel()
}
fun clearFinished() = _rows.update { rows -> rows.filterNot { it.done } }
private fun add(name: String, upload: Boolean, channelId: Int, directory: String, total: Long): TransferRow {
val row = TransferRow(ids.incrementAndGet(), name, upload, channelId, directory, 0, total,
FileTransfer.State.PENDING, null)
_rows.update { it + row }
return row
}
/** Runs a transfer through [temp], which goes once it is done with; [onComplete] finishes a successful one. */
private fun start(row: TransferRow, temp: File, onComplete: () -> Unit,
begin: (FileTransfer.Listener) -> FileTransfer) {
var lastUpdate = 0L
val listener = FileTransfer.Listener { t ->
val now = System.nanoTime()
// Progress comes per buffer; the list need not redraw that often.
if (!t.isDone && now - lastUpdate < UPDATE_NANOS) return@Listener
lastUpdate = now
var error = t.errorMessage
if (t.state == FileTransfer.State.COMPLETED) {
error = runCatching(onComplete).exceptionOrNull()?.let { it.message ?: "Could not save the file" }
}
if (t.isDone) {
temp.delete()
synchronized(handles) { handles.remove(row.id) }
}
val state = if (error != null) FileTransfer.State.FAILED else t.state
update(row.id) { it.copy(transferred = t.transferredBytes, total = maxOf(t.totalBytes, 0), state = state, error = error) }
}
try {
val handle = begin(listener)
synchronized(handles) { if (!handle.isDone) handles[row.id] = handle }
} catch (e: RuntimeException) {
temp.delete()
update(row.id) { it.copy(state = FileTransfer.State.FAILED, error = e.message ?: "Not connected") }
}
}
private fun update(id: Long, change: (TransferRow) -> TransferRow) =
_rows.update { rows -> rows.map { if (it.id == id) change(it) else it } }
private fun copyIn(uri: Uri): Pair<String, File> {
val resolver = context.contentResolver
val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
}?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "file"
val temp = File.createTempFile("upload", null, context.cacheDir)
try {
resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } }
?: throw IOException("Could not read the file")
} catch (e: IOException) {
temp.delete()
throw e
}
// A server path takes no slashes in a file name.
return name.replace('/', '_') to temp
}
private companion object {
const val UPDATE_NANOS = 200_000_000L
}
}
@@ -0,0 +1,143 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.net.Uri
import android.provider.OpenableColumns
import android.util.LruCache
import com.caverock.androidsvg.RenderOptions
import com.caverock.androidsvg.SVG
import eu.lixko.ts3j.client.config.AppDirs
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.gfx.IconPack
import eu.lixko.ts3j.client.gfx.IconPacks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File
/**
* The icon packs the app draws with: the Material pack it ships, and TeamSpeak packs
* imported into its `gfx` folder, which are the very zips a TeamSpeak 3 install keeps in
* its own. Whatever the chosen pack lacks comes from the Material one.
*/
class IconTheme(private val context: Context, private val settings: Settings) {
private val folder = File(AppDirs.profile(), "gfx")
private val material: IconPack = IconPacks.material()
@Volatile
private var lookupOrder = listOf(material)
private val cache = LruCache<String, Bitmap>(256)
private val _packs = MutableStateFlow(emptyList<IconPack>())
val packs: StateFlow<List<IconPack>> = _packs
private val _active = MutableStateFlow(material)
val active: StateFlow<IconPack> = _active
init {
reload()
}
fun select(pack: IconPack) {
settings.iconPack.set(pack.id())
settings.save()
reload()
}
/**
* Copies a pack's zip into the app and switches to it.
*
* @return the pack, or `null` when the file is no icon pack
*/
fun import(uri: Uri): IconPack? {
folder.mkdirs()
val target = File(folder, displayName(uri).substringAfterLast('/').let {
if (it.endsWith(".zip", ignoreCase = true)) it else "$it.zip"
})
val staged = File(folder, target.name + ".part")
context.contentResolver.openInputStream(uri)?.use { input ->
staged.outputStream().use { input.copyTo(it) }
} ?: return null
target.delete()
staged.renameTo(target)
val pack = IconPack.load(target)
if (pack == null) {
target.delete()
return null
}
select(pack)
return _active.value
}
/**
* Draws the first of [keys] the packs have.
*
* @param rgb the colour for art that paints in the text colour
*/
fun render(keys: List<String>, size: Int, rgb: Int): Bitmap? = render(lookupOrder, keys, size, rgb)
/** Draws from the Material pack whatever pack is chosen, for chrome that must stay legible on its own colours. */
fun renderMaterial(key: String, size: Int, rgb: Int): Bitmap? = render(listOf(material), listOf(key), size, rgb)
private fun render(order: List<IconPack>, keys: List<String>, size: Int, rgb: Int): Bitmap? {
val cacheKey = "${order.first().id()}/${keys.joinToString(",")}@$size#$rgb"
cache.get(cacheKey)?.let { return it }
for (key in keys) {
for (pack in order) {
val data = pack.icon(key, size) ?: continue
val bitmap = (if (pack.isVector(key, size)) rasterize(IconPack.withCurrentColor(data, rgb), size)
else decode(data, size)) ?: continue
cache.put(cacheKey, bitmap)
return bitmap
}
}
return null
}
private fun reload() {
val packs = IconPacks.findAll(folder, null)
val active = IconPacks.select(packs, settings.iconPack.get()) ?: material
lookupOrder = IconPacks.lookupOrder(active, packs, material)
cache.evictAll()
_packs.value = packs
_active.value = active
}
private fun displayName(uri: Uri): String =
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
if (it.moveToFirst()) it.getString(0) else null
} ?: uri.lastPathSegment ?: "iconpack.zip"
private fun rasterize(svg: ByteArray, size: Int): Bitmap? = try {
val document = SVG.getFromString(String(svg, Charsets.UTF_8))
if (document.documentViewBox == null && document.documentWidth > 0 && document.documentHeight > 0) {
document.setDocumentViewBox(0f, 0f, document.documentWidth, document.documentHeight)
}
// Otherwise the art keeps the size it was authored at inside the viewport.
document.setDocumentWidth("100%")
document.setDocumentHeight("100%")
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
document.renderToCanvas(Canvas(it), RenderOptions().viewPort(0f, 0f, size.toFloat(), size.toFloat()))
}
} catch (e: Exception) {
null
}
/** Scales a bitmap icon into the square, keeping the aspect ratio of art that is not. */
private fun decode(data: ByteArray, size: Int): Bitmap? {
val source = BitmapFactory.decodeByteArray(data, 0, data.size) ?: return null
if (source.width == size && source.height == size) return source
val factor = minOf(size.toFloat() / source.width, size.toFloat() / source.height)
val w = source.width * factor
val h = source.height * factor
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also {
val left = (size - w) / 2
val top = (size - h) / 2
Canvas(it).drawBitmap(source, null, RectF(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG))
}
}
}
@@ -0,0 +1,173 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityEntry
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
/** What the identity manager shows of one identity. */
data class IdentityInfo(
val id: String,
val name: String,
val uniqueId: String,
val securityLevel: Int,
val isDefault: Boolean,
val nickname: String,
val phoneticNickname: String,
)
/** A search for a better key offset under way. */
data class Improvement(val id: String, val target: Int, val reached: Int)
/**
* The identities, as TeamSpeak's Tools → Identities manages them: create, import, export,
* rename, remove, pick the default and raise the security level. Raising the level runs
* on until it is reached or stopped, whichever page is on screen.
*/
class IdentityManager(
private val context: Context,
private val store: IdentityStore,
private val settings: Settings,
private val bookmarks: Bookmarks,
private val onBookmarksChanged: () -> Unit,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val _all = MutableStateFlow(snapshot())
val all: StateFlow<List<IdentityInfo>> = _all
private val _improving = MutableStateFlow<Improvement?>(null)
val improving: StateFlow<Improvement?> = _improving
private var improvement: Job? = null
/** Picks up identities added elsewhere, such as by an import or a first connect. */
fun refresh() {
_all.value = snapshot()
}
private fun snapshot(): List<IdentityInfo> = store.all().map {
IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId.get(),
it.nickname, it.phoneticNickname)
}
/** Generates an identity at TeamSpeak's default security level; the first one becomes the default. */
suspend fun generate(name: String): IdentityInfo = added {
store.generate(name, IdentityStore.DEFAULT_SECURITY_LEVEL)
}
/** Imports a TeamSpeak identity file, under the name it carries. */
suspend fun importFile(uri: Uri): IdentityInfo = added {
context.contentResolver.openInputStream(uri)?.use { store.importStream(it, null) }
?: throw IOException("Cannot open the file")
}
/** Imports the identities of a TeamSpeak 3 `settings.db`. */
suspend fun importFromTeamSpeak(uri: Uri): TeamSpeakImporter.Result = withContext(Dispatchers.IO) {
withLocalCopy(context, uri) { TeamSpeakImporter(store, bookmarks, settings).importIdentities(it) }
}.also {
adoptDefault(null)
refresh()
}
private suspend fun added(create: () -> IdentityEntry): IdentityInfo {
val entry = withContext(Dispatchers.IO) { create() }
adoptDefault(entry)
refresh()
return _all.value.first { it.id == entry.id }
}
/** Makes [entry], or else the first identity, the default while there is none. */
private fun adoptDefault(entry: IdentityEntry?) {
if (store.byId(settings.defaultIdentityId.get()) != null) return
val fallback = entry ?: store.all().firstOrNull() ?: return
settings.defaultIdentityId.set(fallback.id)
settings.save()
}
/** Writes the identity out in TeamSpeak's format, for the official client or another device. */
suspend fun export(id: String, uri: Uri) = withContext(Dispatchers.IO) {
val entry = store.byId(id) ?: return@withContext
val out = context.contentResolver.openOutputStream(uri, "wt") ?: throw IOException("Cannot write the file")
store.exportTo(entry, out)
}
fun rename(id: String, name: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
store.rename(entry, name)
refresh()
}
}
fun setNicknames(id: String, nickname: String, phoneticNickname: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
store.setNicknames(entry, nickname, phoneticNickname)
refresh()
}
}
/** The nickname of the identity a connect with [id] uses; empty when it has none. */
fun nicknameOf(id: String): String =
(store.byId(id) ?: store.byId(settings.defaultIdentityId.get()))?.nickname.orEmpty()
/** The nickname a connect with [id] goes by: the identity's own, else the global one. */
fun nicknameFor(id: String): String = nicknameOf(id).ifBlank { settings.nickname.get() }
fun setDefault(id: String) {
settings.defaultIdentityId.set(id)
settings.save()
refresh()
}
/** Deletes the identity; bookmarks that connected with it fall back to the default. */
fun remove(id: String) {
val entry = store.byId(id) ?: return
scope.launch(Dispatchers.IO) {
// Else the search would write the file back once it ends.
if (_improving.value?.id == id) improvement?.cancelAndJoin()
store.remove(entry, settings, bookmarks)
onBookmarksChanged()
refresh()
}
}
/** Searches for a key offset reaching [target], keeping the best found when stopped. */
fun improve(id: String, target: Int) {
if (improvement?.isActive == true) return
val entry = store.byId(id) ?: return
_improving.value = Improvement(id, target, entry.securityLevel)
improvement = scope.launch {
try {
store.improveSecurity(entry, target) { reached, _ ->
_improving.value = Improvement(id, target, reached)
isActive
}
} catch (e: IOException) {
// The level reached stays in memory for this run.
} finally {
_improving.value = null
refresh()
}
}
}
fun stopImproving() {
improvement?.cancel()
}
}
@@ -0,0 +1,97 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.audio.AudioBackend
import eu.lixko.ts3j.client.audio.InputLevel
import eu.lixko.ts3j.client.audio.VoiceInput
import eu.lixko.ts3j.client.config.Settings
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The microphone's level on [InputLevel]'s scale, and whether that would be sent. */
data class MicLevel(
val db: Double = InputLevel.SILENCE_DB,
val transmitting: Boolean = false,
/** Whether a microphone is being listened to at all. */
val live: Boolean = false,
)
/**
* The level meter behind the voice-activation settings. While connected it listens to the
* connection's own microphone, so it shows exactly what gets sent; otherwise it runs a test
* microphone of its own for as long as someone watches.
*/
class LevelMonitor(private val settings: Settings, private val audio: AudioBackend) {
private val _level = MutableStateFlow(MicLevel())
val level: StateFlow<MicLevel> = _level
/** The connection's microphone, when that is the one listened to. */
private var borrowed: VoiceInput? = null
private var test: VoiceInput? = null
/**
* Starts or stops listening.
*
* @param source the connection's microphone while it captures, else null
* @param busy whether a connection is under way, which will bring its own microphone
*/
@Synchronized
fun update(watching: Boolean, source: VoiceInput?, busy: Boolean, mayCapture: Boolean) {
when {
!watching -> release()
source != null -> if (borrowed !== source) {
release()
source.setLevelListener(::onLevel)
borrowed = source
}
busy || !mayCapture -> release()
test == null -> startTest()
}
}
/** The own microphone's transmit state, which the connection reports. */
fun talking(transmitting: Boolean) {
if (borrowed != null) _level.value = _level.value.copy(transmitting = transmitting)
}
/** Puts changed voice settings into effect on the test microphone. */
@Synchronized
fun apply() {
test?.let {
it.apply(settings)
it.setMode(testMode())
}
}
private fun startTest() {
release()
val input = audio.createInput(settings)
input.setMode(testMode())
input.setLevelListener(::onLevel)
input.setTalkListener { _level.value = _level.value.copy(transmitting = it) }
try {
input.start()
} catch (e: RuntimeException) {
return // no microphone to be had; the meter stays idle
}
test = input
}
private fun release() {
borrowed?.setLevelListener(null)
borrowed = null
test?.stop()
test = null
_level.value = MicLevel()
}
private fun onLevel(db: Double) {
_level.value = _level.value.copy(db = db, live = true)
}
/** Push-to-talk would never open without the button, and the test is there to tune the gate. */
private fun testMode(): Settings.InputMode {
val mode = settings.inputMode.get()
return if (mode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else mode
}
}
@@ -0,0 +1,21 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import java.io.File
import java.io.IOException
/**
* Hands [read] a temporary copy of the document at [uri], for readers that need a file they
* can seek in, which a content URI is not.
*/
internal fun <T> withLocalCopy(context: Context, uri: Uri, read: (File) -> T): T {
val copy = File.createTempFile("import", null, context.cacheDir)
try {
val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open the file")
input.use { copy.outputStream().use { out -> it.copyTo(out) } }
return read(copy)
} finally {
copy.delete()
}
}
@@ -0,0 +1,56 @@
package eu.lixko.ts3j.client.android
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import eu.lixko.ts3j.client.android.ui.App
import eu.lixko.ts3j.client.android.ui.Ts3Theme
import eu.lixko.ts3j.client.session.ServerLink
class MainActivity : ComponentActivity() {
private val sessions get() = (application as Ts3Application).sessions
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent))
setContent {
Ts3Theme { App((application as Ts3Application).parts) }
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handle(intent)
}
override fun onStart() {
super.onStart()
sessions.foreground = true
}
override fun onStop() {
sessions.foreground = false
super.onStop()
}
/** A notification opens its conversation; a `ts3server://` link or a bookmark shortcut connects, returning where. */
private fun handle(intent: Intent): ServerLink? = when (intent.action) {
Intent.ACTION_VIEW -> ServerLink.parse(intent.dataString)?.also { sessions.open(it) }
BookmarkShortcuts.ACTION_CONNECT -> intent.getStringExtra(BookmarkShortcuts.EXTRA_BOOKMARK)
?.let(sessions::openBookmark)
else -> {
openRequestedChat(intent)
null
}
}
private fun openRequestedChat(intent: Intent) {
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
if (serverId >= 0 && clientId >= 0) sessions.requestChat(serverId, clientId)
}
}
@@ -0,0 +1,141 @@
package eu.lixko.ts3j.client.android
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Person
import android.app.RemoteInput
import android.content.Context
import android.content.Intent
/**
* Tells the user about pokes and private messages while the app is out of sight. The
* notifications themselves are silent: the sound pack already plays TeamSpeak's own sound
* for either, as it does in the app.
*/
class MessageNotifier(private val context: Context) {
private val manager = context.getSystemService(NotificationManager::class.java)
private val me = Person.Builder().setName("You").build()
/** What each private conversation's notification shows, by [id] of server and peer. */
private val conversations = HashMap<Int, Conversation>()
private class Conversation(val peer: Person, val messages: MutableList<Notification.MessagingStyle.Message>)
init {
manager.createNotificationChannels(listOf(
channel(MESSAGES, R.string.messages_channel),
channel(POKES, R.string.pokes_channel),
))
}
private fun channel(id: String, name: Int) =
NotificationChannel(id, context.getString(name), NotificationManager.IMPORTANCE_HIGH).apply {
setSound(null, null)
enableVibration(true)
}
fun poke(from: String, message: String) {
val notification = Notification.Builder(context, POKES)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setContentTitle("$from poked you")
.setContentText(message.ifBlank { null })
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentIntent(open(null, null))
.setAutoCancel(true)
.build()
manager.notify(POKE_TAG, from.hashCode(), notification)
}
fun clearPokes() {
for (active in manager.activeNotifications) {
if (active.tag == POKE_TAG) manager.cancel(POKE_TAG, active.id)
}
}
/** A message the peer sent, which starts the conversation's notification if it had none. */
@Synchronized
fun received(serverId: Int, clientId: Int, from: String, text: String) {
val id = id(serverId, clientId)
val conversation = conversations[id]?.takeIf { it.peer.name == from }
?: Conversation(Person.Builder().setName(from).setKey("client:$serverId:$clientId").build(), ArrayList())
conversations[id] = conversation
add(serverId, clientId, conversation, text, conversation.peer, alert = true)
}
/** Our own reply, shown in a conversation already notified of; answers the reply action too. */
@Synchronized
fun sent(serverId: Int, clientId: Int, text: String) {
val conversation = conversations[id(serverId, clientId)] ?: return
add(serverId, clientId, conversation, text, me, alert = false)
}
private fun add(serverId: Int, clientId: Int, conversation: Conversation, text: String, sender: Person, alert: Boolean) {
conversation.messages += Notification.MessagingStyle.Message(text, System.currentTimeMillis(), sender)
if (conversation.messages.size > MAX_MESSAGES) conversation.messages.removeAt(0)
val style = Notification.MessagingStyle(me)
conversation.messages.forEach(style::addMessage)
val notification = Notification.Builder(context, MESSAGES)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setStyle(style)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentIntent(open(serverId, clientId))
.setOnlyAlertOnce(!alert)
.setAutoCancel(true)
.addAction(replyAction(serverId, clientId))
.build()
manager.notify(MESSAGE_TAG, id(serverId, clientId), notification)
}
/** The conversation came on screen, or ended with the connection. */
@Synchronized
fun clear(serverId: Int, clientId: Int) {
val id = id(serverId, clientId)
conversations.remove(id)
manager.cancel(MESSAGE_TAG, id)
}
/** The server's conversations, as its connection ended. */
@Synchronized
fun clearServer(serverId: Int) {
conversations.keys.filter { it ushr 16 == serverId }.forEach { clear(serverId, it and 0xFFFF) }
}
private fun open(serverId: Int?, clientId: Int?): PendingIntent {
val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
if (serverId != null && clientId != null) {
intent.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId)
}
return PendingIntent.getActivity(context, if (serverId != null && clientId != null) id(serverId, clientId) else -1,
intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun replyAction(serverId: Int, clientId: Int): Notification.Action {
val intent = Intent(context, ReplyReceiver::class.java)
.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId)
// Mutable: the system fills the typed reply into it.
val pending = PendingIntent.getBroadcast(context, id(serverId, clientId), intent,
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return Notification.Action.Builder(null, "Reply", pending)
.addRemoteInput(RemoteInput.Builder(KEY_REPLY).setLabel("Message").build())
.setSemanticAction(Notification.Action.SEMANTIC_ACTION_REPLY)
.build()
}
/** Client ids are 16 bits, and only unique on their server. */
private fun id(serverId: Int, clientId: Int) = serverId shl 16 or clientId
companion object {
/** The server and the client id of the private chat a notification opens or replies to. */
const val EXTRA_SERVER = "eu.lixko.ts3j.client.android.SERVER"
const val EXTRA_CHAT = "eu.lixko.ts3j.client.android.CHAT"
const val KEY_REPLY = "reply"
private const val MESSAGES = "messages"
private const val POKES = "pokes"
private const val MESSAGE_TAG = "message"
private const val POKE_TAG = "poke"
private const val MAX_MESSAGES = 25
}
}
@@ -0,0 +1,143 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/**
* The myTeamSpeak account the app stays signed in to: what it syncs, and the files shared
* in chat, which are kept in its cloud storage. Its reads block, so they run on [Dispatchers.IO].
*/
class MyTeamSpeakAccount internal constructor(
private val context: Context,
private val pictures: WebPictures,
private val importer: TeamSpeakImporter,
private val bookmarks: BookmarkManager,
private val identities: IdentityManager,
identityStore: IdentityStore,
bookmarkStore: Bookmarks,
settings: Settings,
/** Signed in or out, for the servers to pass on. */
private val onSignInChanged: () -> Unit,
) {
val login: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val _signedIn = MutableStateFlow(login.isSignedIn)
val signedIn: StateFlow<Boolean> = _signedIn
private val sync = MyTeamSpeakSync(login, identityStore, bookmarkStore, settings)
/** Files shared in chat. */
internal val attachments = ChatAttachments(login).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signIn(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { login.signIn(email, password) }
.also {
_signedIn.value = true
onSignInChanged()
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetch(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { login.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_signedIn.value = login.isSignedIn
}
suspend fun signOut() {
login.signOut()
_signedIn.value = false
onSignInChanged()
withContext(Dispatchers.IO) { attachments.close() }
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use; contacts announce themselves. */
suspend fun import(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
bookmarks.refresh()
identities.refresh()
}
/**
* Reads what changed in the account and works out what goes which way. Call on the main
* thread, which owns the bookmarks and identities; the network part runs on [Dispatchers.IO].
*/
suspend fun planSync(): MyTeamSpeakSync.Plan =
try {
sync.plan(withContext(Dispatchers.IO) { sync.fetch() })
} finally {
_signedIn.value = login.isSignedIn
}
/** Sends this side's changes, then brings the account's here; [plan]'s conflicts settled. Main thread. */
suspend fun finishSync(plan: MyTeamSpeakSync.Plan): MyTeamSpeakSync.Result {
try {
withContext(Dispatchers.IO) { sync.upload(plan) }
} finally {
_signedIn.value = login.isSignedIn
}
return sync.apply(plan).also {
bookmarks.refresh()
identities.refresh()
}
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
}
@@ -0,0 +1,220 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import eu.lixko.ts3j.client.session.ServerSession
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.CopyOnWriteArrayList
/**
* Keeps the connections on the network Android routes over.
*
* A TS3 server knows its clients by address, so once the phone moves from Wi-Fi to mobile
* data (or back) an old connection is dead weight: it can only time out. This notices the
* move, says goodbye over the old network while that still works, and connects again over
* the new one, back into the channel we were in. A server that still holds our old
* connection may refuse the new one for a while as a clone, so a failed attempt is retried.
*
* The process's sockets are bound to the network a connection was made over. Otherwise the
* old connection would silently follow the new default network, and its goodbye would come
* from an address the server does not know. A socket keeps the network it was made on, so
* each connection remembers its own.
*/
class NetworkFollower(context: Context) {
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val follows = CopyOnWriteArrayList<Follow>()
/** The system's default network; null while there is none. */
@Volatile
private var network: Network? = null
init {
connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(available: Network) {
network = available
follows.forEach(Follow::reconsider)
}
override fun onLost(lost: Network) {
if (network == lost) network = null
follows.forEach(Follow::reconsider)
}
})
}
/** Follows [session] until [Follow.forget]. */
fun follow(session: ServerSession, onChange: () -> Unit, system: (String) -> Unit): Follow =
Follow(session, onChange, system).also(follows::add)
/** Binds new sockets to [to], or lets them go by the default network once no connection wants one. */
private fun bind(to: Network?) {
connectivity.bindProcessToNetwork(to ?: follows.firstNotNullOfOrNull { f -> f.bound.takeIf { f.wanted } })
}
inner class Follow internal constructor(
private val session: ServerSession,
private val onChange: () -> Unit,
private val system: (String) -> Unit,
) {
/** The network the connection was made over. */
@Volatile
internal var bound: Network? = null
/** The user wants to be on the server: from their connect until they, or the server, end it. */
@Volatile
internal var wanted = false
private var settle: Job? = null
@Volatile
private var recovery: Job? = null
@Volatile
private var attempt: CompletableDeferred<Boolean>? = null
/** What to show in place of the session's status while getting back on the server. */
@Volatile
var status: String? = null
private set
val isRecovering: Boolean get() = recovery?.isActive == true
/** Before a connect the user asked for, which goes over the network there is now. */
fun connecting() {
recovery?.cancel()
wanted = true
bindHere(connectivity.activeNetwork)
}
/** The user leaves the server. */
fun leaving() {
wanted = false
recovery?.cancel()
unbind()
}
/** The session is thrown away. */
fun forget() {
leaving()
follows.remove(this)
}
fun onConnected() {
attempt?.complete(true)
}
fun onDisconnected() {
val pending = attempt
when {
pending != null -> pending.complete(false)
isRecovering -> {}
// A socket on a network that went away fails at once, before we hear of the change.
wanted && networkGone() -> synchronized(this) {
if (!isRecovering) recovery = recover()
}
// The server let us go (a kick, a shutdown, a failed first connect): leave it at that.
else -> {
wanted = false
unbind()
}
}
}
/** Waits for the network to settle: a handover often shows several changes in a row. */
internal fun reconsider() {
synchronized(this) {
settle?.cancel()
settle = scope.launch {
delay(SETTLE_MS)
synchronized(this@Follow) {
if (wanted && bound != network && !isRecovering) recovery = recover()
}
}
}
}
private fun recover() = scope.launch {
try {
val back = withTimeoutOrNull(GIVE_UP_MS) {
system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…")
session.disconnectNow("Network changed")
var retry = RETRY_MS
while (true) {
val current = awaitNetwork()
bindHere(current)
show("Reconnecting…")
val done = CompletableDeferred<Boolean>()
attempt = done
session.reconnect()
val connected = done.await()
attempt = null
if (connected) break
if (session.connectErrorId() == ERROR_BANNED) break
show("Reconnecting, retrying soon…")
delay(retry)
retry = (retry * 2).coerceAtMost(MAX_RETRY_MS)
}
}
if (session.connectErrorId() == ERROR_BANNED) {
wanted = false
unbind()
} else if (back == null) {
system("Could not get back on the server.")
wanted = false
unbind()
}
} finally {
attempt = null
status = null
onChange()
// The network may have moved again while we were busy.
reconsider()
}
}
private fun networkGone(): Boolean {
val on = bound ?: return false
return connectivity.getNetworkCapabilities(on) == null || connectivity.activeNetwork != on
}
private suspend fun awaitNetwork(): Network {
while (true) {
connectivity.activeNetwork?.let { return it }
show("Waiting for network…")
delay(POLL_MS)
}
}
private fun show(text: String) {
status = text
onChange()
}
private fun bindHere(to: Network?) {
bound = to
bind(to)
}
private fun unbind() {
bound = null
bind(null)
}
}
private companion object {
const val SETTLE_MS = 1_500L
/** The server's refusal for a banned client; asking again will not help. */
const val ERROR_BANNED = 3329
const val RETRY_MS = 5_000L
const val MAX_RETRY_MS = 30_000L
const val POLL_MS = 500L
const val GIVE_UP_MS = 5 * 60_000L
}
}
@@ -0,0 +1,42 @@
package eu.lixko.ts3j.client.android
import android.graphics.ImageDecoder
import android.graphics.drawable.AnimatedImageDrawable
import android.graphics.drawable.BitmapDrawable
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import java.nio.ByteBuffer
/** An avatar or a picture from a description: still, or moving like an animated GIF. */
sealed interface Picture {
val width: Int
val height: Int
data class Still(val bitmap: ImageBitmap) : Picture {
override val width get() = bitmap.width
override val height get() = bitmap.height
}
/** Shared by whatever shows it: one animation, drawn wherever it is on screen. */
data class Moving(val drawable: AnimatedImageDrawable) : Picture {
override val width get() = drawable.intrinsicWidth
override val height get() = drawable.intrinsicHeight
}
}
/** Decodes any image Android knows, no larger than [maxPx] on its longer side; null if it is none. */
internal fun decodePicture(data: ByteArray, maxPx: Int): Picture? = try {
val drawable = ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ ->
val largest = maxOf(info.size.width, info.size.height)
if (largest > maxPx) {
decoder.setTargetSize(info.size.width * maxPx / largest, info.size.height * maxPx / largest)
}
}
when (drawable) {
is AnimatedImageDrawable -> Picture.Moving(drawable)
is BitmapDrawable -> Picture.Still(drawable.bitmap.asImageBitmap())
else -> null
}
} catch (e: Exception) {
null
}
@@ -0,0 +1,176 @@
package eu.lixko.ts3j.client.android
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.provider.Settings
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
/**
* A push-to-talk button floating over other apps. Holding it talks; a double tap whose
* second touch is held moves it instead, so moving never transmits more than the first tap.
*/
class PttOverlay(
private val context: Context,
private val icons: IconTheme,
private val onPressed: (Boolean) -> Unit,
) {
enum class Look { IDLE, TALKING, MUTED }
private val windows = context.getSystemService(WindowManager::class.java)
private val prefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val size = (SIZE_DP * context.resources.displayMetrics.density).toInt()
private var button: Button? = null
/** Shows the button, or updates it when it is up; nothing while the app may not draw over others. */
fun show(look: Look) {
button?.let {
it.look = look
return
}
if (!Settings.canDrawOverlays(context)) return
val params = WindowManager.LayoutParams(
size, size,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT,
).apply {
gravity = Gravity.TOP or Gravity.START
val screen = windows.currentWindowMetrics.bounds
x = prefs.getInt(POS_X, screen.width() - size - size / 4)
y = prefs.getInt(POS_Y, screen.height() / 2)
}
val view = Button(params).also { it.look = look }
try {
windows.addView(view, params)
} catch (e: WindowManager.BadTokenException) {
// The permission went away since the check.
return
}
button = view
}
fun hide() {
val view = button ?: return
button = null
view.release()
windows.removeView(view)
}
@SuppressLint("ViewConstructor")
private inner class Button(private val params: WindowManager.LayoutParams) : View(context) {
var look = Look.IDLE
set(value) {
field = value
restyle()
}
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout().toLong()
private var pressed = false
private var dragging = false
private var lastTapUp = 0L
private var grabX = 0f
private var grabY = 0f
init {
contentDescription = "Push to talk"
alpha = RESTING_ALPHA
}
/** Half see-through at rest, so it hides less of the app beneath; solid while it talks. */
private fun restyle() {
alpha = if (pressed || look == Look.TALKING) 1f else RESTING_ALPHA
invalidate()
}
override fun onDraw(canvas: Canvas) {
val radius = width / 2f
val lit = pressed || look == Look.TALKING
paint.color = when {
look == Look.MUTED -> MUTED
lit -> TALKING
else -> IDLE
}
canvas.drawCircle(radius, radius, radius, paint)
if (lit) {
paint.color = Color.WHITE
paint.style = Paint.Style.STROKE
paint.strokeWidth = radius / 12
canvas.drawCircle(radius, radius, radius - paint.strokeWidth, paint)
paint.style = Paint.Style.FILL
}
val iconSize = width / 2
icon(iconSize)?.let {
val offset = (width - iconSize) / 2f
canvas.drawBitmap(it, offset, offset, null)
}
}
private fun icon(size: Int): Bitmap? =
icons.renderMaterial(if (look == Look.MUTED) "INPUT_MUTED" else "CAPTURE", size, Color.WHITE)
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(e: MotionEvent): Boolean {
when (e.actionMasked) {
MotionEvent.ACTION_DOWN -> {
dragging = e.eventTime - lastTapUp < doubleTapTimeout
if (dragging) {
grabX = e.rawX - params.x
grabY = e.rawY - params.y
} else {
press(true)
}
}
MotionEvent.ACTION_MOVE -> if (dragging) moveTo(e.rawX - grabX, e.rawY - grabY)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
val tap = !dragging && e.eventTime - e.downTime < doubleTapTimeout
lastTapUp = if (tap) e.eventTime else 0L
if (dragging) {
dragging = false
prefs.edit().putInt(POS_X, params.x).putInt(POS_Y, params.y).apply()
} else {
press(false)
}
}
}
return true
}
private fun moveTo(x: Float, y: Float) {
val screen = windows.currentWindowMetrics.bounds
params.x = x.toInt().coerceIn(0, screen.width() - width)
params.y = y.toInt().coerceIn(0, screen.height() - height)
windows.updateViewLayout(this, params)
}
private fun press(down: Boolean) {
if (pressed == down) return
pressed = down
onPressed(down)
restyle()
}
/** Lets go of the microphone should the button vanish under the finger. */
fun release() = press(false)
}
private companion object {
const val SIZE_DP = 64
const val RESTING_ALPHA = 0.5f
const val POS_X = "x"
const val POS_Y = "y"
val IDLE = Color.rgb(0x1C, 0x6F, 0xB8)
val TALKING = Color.rgb(0x2E, 0x9B, 0xF0)
val MUTED = Color.rgb(0x42, 0x42, 0x42)
}
}
@@ -0,0 +1,17 @@
package eu.lixko.ts3j.client.android
import android.app.RemoteInput
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
/** Sends what the user typed into a private message notification. */
class ReplyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1)
val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1)
val text = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(MessageNotifier.KEY_REPLY)?.toString()
if (serverId < 0 || clientId < 0 || text.isNullOrBlank()) return
(context.applicationContext as Ts3Application).sessions.reply(serverId, clientId, text)
}
}
@@ -0,0 +1,19 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.net.RequestException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.future.await
import java.util.concurrent.CompletableFuture
/** A server request's outcome, failing with its [RequestException]. */
internal suspend fun <T> CompletableFuture<T>.result(): Result<T> =
try {
Result.success(await())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Result.failure(RequestException.of(e))
}
/** The same for a request with no result. */
internal suspend fun CompletableFuture<Void>.done(): Result<Unit> = result().map { }
@@ -0,0 +1,39 @@
package eu.lixko.ts3j.client.android
import android.content.ContentValues
import android.content.Context
import android.graphics.BitmapFactory
import android.os.Environment
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/** Puts pictures into the shared Pictures collection, in a TeamSpeak album, where galleries find them. */
object SavedPictures {
/** Saves [data] as [name], its extension following what the data is; false if it could not be. */
suspend fun save(context: Context, name: String, data: ByteArray): Boolean = withContext(Dispatchers.IO) {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
val mime = bounds.outMimeType ?: return@withContext false
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, if (extension == null) name else "$name.$extension")
put(MediaStore.Images.Media.MIME_TYPE, mime)
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/TeamSpeak")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), values)
?: return@withContext false
try {
resolver.openOutputStream(uri)!!.use { it.write(data) }
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
true
} catch (e: Exception) {
resolver.delete(uri, null, null)
false
}
}
}
@@ -0,0 +1,556 @@
package eu.lixko.ts3j.client.android
import android.net.Uri
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.net.ChannelNode
import eu.lixko.ts3j.client.net.ClientEntry
import eu.lixko.ts3j.client.net.ChannelSettings
import eu.lixko.ts3j.client.net.ConnectionStats
import eu.lixko.ts3j.client.net.Details
import eu.lixko.ts3j.client.net.GroupChoice
import eu.lixko.ts3j.client.net.Permissions
import eu.lixko.ts3j.client.net.RequestException
import eu.lixko.ts3j.client.net.Whisper
import eu.lixko.ts3j.client.net.ban.BanEntry
import eu.lixko.ts3j.client.net.ban.BanRule
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.text.ChatHtml
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* One server the app is on: its [ServerSession], and the snapshots the UI shows of it. Session
* callbacks arrive on connection threads and are turned into immutable snapshots.
*/
class ServerController internal constructor(
/** Unique among the servers of this process run. */
val id: Int,
private val parts: ServerParts,
/** The owner, told of what happens to this server. */
private val app: SessionController,
) {
internal val session = parts.session(Listener())
private val network = parts.network.follow(session, ::refresh, ::system)
/** Whether this server holds the microphone; set by [SessionController] as it moves. */
@Volatile
internal var micOwner = false
/** Set once connecting began, so a session that never started is not taken for one that ended. */
@Volatile
private var started = false
/** Set when the user left, so the end needs no telling. */
@Volatile
internal var left = false
private val _state = MutableStateFlow(SessionState())
val state: StateFlow<SessionState> = _state
private val _tree = MutableStateFlow(ServerTree())
val tree: StateFlow<ServerTree> = _tree
private val _chats = MutableStateFlow(Chats())
val chats: StateFlow<Chats> = _chats
/** Channels the user folded away in the tree. */
private val _collapsed = MutableStateFlow(emptySet<Int>())
val collapsed: StateFlow<Set<Int>> = _collapsed
/** The conversation on screen, whose new lines are read as they come. */
@Volatile
var viewing: ChatKey? = null
set(value) {
field = value
if (value != null) markRead(value)
if (value != null && value.isPrivate) parts.notifier.clear(id, value.clientId())
}
/** Counts the answers to info requests, for the details on screen to be read again. */
private val _infoUpdates = MutableStateFlow(0)
val infoUpdates: StateFlow<Int> = _infoUpdates
val images = ServerImages(session.icons(), session.avatars())
/** A private chat a notification asked to show, until the UI took it up. */
private val _chatRequest = MutableStateFlow<ChatKey?>(null)
val chatRequest: StateFlow<ChatKey?> = _chatRequest
private val lineIds = AtomicLong()
/** Tree snapshots are taken one at a time, at most once per [TREE_FRAME_MS]. */
private val treeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default.limitedParallelism(1))
private val treePending = AtomicBoolean()
private val structureChanged = AtomicBoolean(true)
private var roots: List<ChannelNode> = emptyList()
val isConnected: Boolean get() = session.isConnected
internal val isBusy: Boolean get() = session.isBusy || network.isRecovering
internal val microphone get() = if (session.isConnected) session.microphone() else null
internal val playback get() = if (session.isConnected) session.playback() else null
/** Not on the server and not trying to get back on it: done with. */
internal val ended: Boolean get() = started && !isBusy
// ---- connection ----
internal fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
channel: String, channelPassword: String) {
network.connecting()
started = true
session.connect(host, port, nickname, password, identityId, channel, channelPassword)
refresh()
}
internal fun open(link: ServerLink, identityId: String) {
network.connecting()
started = true
session.open(link, identityId)
refresh()
}
/** The bookmark this server was connected from, if any. */
@Volatile
private var bookmarkId: String? = null
@Volatile
private var whisperControls = false
internal fun applyBookmark(bookmark: Bookmark) {
bookmarkId = bookmark.id
whisperControls = bookmark.showWhisperControls
refresh()
}
/** Takes on an edit of the bookmark we connected from, without reconnecting. */
internal fun bookmarkEdited(bookmark: Bookmark) {
if (bookmark.id == bookmarkId) applyBookmark(bookmark)
}
/** A bookmark leading back to this server, joining [channelId]; not yet saved. */
fun bookmark(channelId: Int): Bookmark? = session.toBookmark(session.model().channelPath(channelId))
?.also { it.showWhisperControls = whisperControls }
fun disconnect() {
left = true
network.leaving()
session.disconnect()
}
/** Before the app goes away with the connection, which [SessionController.leave] then ends. */
internal fun leaving() {
left = true
network.leaving()
}
internal fun dispose() {
network.forget()
treeScope.cancel()
session.dispose()
}
// ---- the local client ----
fun setMicMuted(muted: Boolean) = session.setMicMuted(muted)
fun setDeafened(deafened: Boolean) = session.setDeafened(deafened)
fun setAway(away: Boolean) = session.setAway(away, null)
/** Asks for talk power giving [reason], or withdraws the request with null. */
fun setTalkRequest(reason: String?) =
if (reason == null) session.cancelTalkRequest() else session.requestTalkPower(reason)
// ---- channels and clients ----
fun joinChannel(channelId: Int, password: String? = null) {
if (session.isConnected) session.channels().join(channelId, password)
}
fun setSubscribed(channelId: Int, subscribed: Boolean) {
if (session.isConnected) session.channels().setSubscribed(listOf(channelId), subscribed)
}
fun toggleCollapsed(channelId: Int) =
_collapsed.update { if (channelId in it) it - channelId else it + channelId }
fun expand(channelIds: Collection<Int>) = _collapsed.update { it - channelIds.toSet() }
/** What we may do on this server; nothing while not connected. */
val permissions: Permissions get() = session.permissions()
/** The channel kicked clients go back to; 0 until the server named it. */
val defaultChannelId: Int get() = session.model().defaultChannelId()
fun moveClients(clientIds: Collection<Int>, channelId: Int) {
if (session.isConnected) session.clients().move(clientIds, channelId)
}
fun poke(clientId: Int, message: String) {
if (session.isConnected) session.clients().poke(clientId, message)
}
/** The client's playback volume change in dB; 0 when unchanged. */
fun clientVolume(clientId: Int): Double =
session.model().getClient(clientId)?.let { session.contacts().volumeModifier(it) } ?: 0.0
fun setClientVolume(clientId: Int, decibels: Double) {
session.model().getClient(clientId)?.let { session.contacts().setVolumeModifier(it, decibels) }
}
// ---- whisper ----
fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper)
fun whisperToChannel(channelId: Int) = session.model().getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) }
fun whisperToClient(clientId: Int) = session.model().getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) }
/** The client who whispered to us last, while on the server. */
fun lastWhisperer(): ClientEntry? = session.lastWhisperer()
/** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */
fun channelRef(channelId: Int): String? = session.model().getChannel(channelId)?.let { session.model().channelPath(it.id) }
fun clientRef(clientId: Int): WhisperList.Client? =
session.model().getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) }
/** The clients on the server, for adding to a whisper list; ourselves left out. */
fun clientRefs(): List<WhisperList.Client> = if (!session.isConnected) emptyList()
else session.model().allClients().filter { it.id != session.selfClientId() && !it.uniqueId.isNullOrEmpty() }
.sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) }
fun channelPaths(): List<String> = session.channelPaths()
// ---- channel administration ----
/** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */
fun sortChoices(channelId: Int, parentId: Int): List<ChannelNode> =
if (channelId > 0) session.model().siblingsOf(channelId) else session.model().childrenOf(parentId)
/** A channel's editable properties as the server has them. */
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = session.channels().settings(channelId).result()
suspend fun editChannel(channelId: Int, changes: Map<String, String>): Result<Unit> =
if (changes.isEmpty()) Result.success(Unit)
else session.channels().edit(channelId, changes, emptyMap(), emptyList()).done()
suspend fun createChannel(parentId: Int, settings: ChannelSettings): Result<Unit> =
session.channels().create(parentId, settings.creationParameters(), emptyMap()).result().map { }
/** Deletes a channel, with its sub-channels and the clients in it moved out. */
suspend fun deleteChannel(channelId: Int): Result<Unit> = session.channels().delete(channelId, true).done()
// ---- files ----
val files = parts.fileTransfers(session.files())
/** The files in a directory of a channel's repository; empty for an empty one. */
suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> =
withContext(Dispatchers.IO) { runCatching { session.files().list(channelId, password, path) } }
suspend fun createDirectory(channelId: Int, password: String, path: String): Result<Unit> =
fileCall { session.files().createDirectory(channelId, password, path) }
suspend fun deleteFile(channelId: Int, password: String, path: String): Result<Unit> =
fileCall { session.files().delete(channelId, password, path) }
suspend fun renameFile(channelId: Int, password: String, from: String, to: String): Result<Unit> =
fileCall { session.files().rename(channelId, password, from, to) }
private suspend fun fileCall(call: () -> Unit): Result<Unit> = withContext(Dispatchers.IO) { runCatching(call) }
// ---- moderation ----
val canRequestTalkPower: Boolean get() = session.canRequestTalkPower()
fun kickFromChannel(clientIds: Collection<Int>, reason: String) {
if (session.isConnected) session.clients().kickFromChannel(clientIds, reason)
}
fun kickFromServer(clientIds: Collection<Int>, reason: String) {
if (session.isConnected) session.clients().kickFromServer(clientIds, reason)
}
fun setTalker(clientIds: Collection<Int>, talker: Boolean) {
if (session.isConnected) session.clients().setTalker(clientIds, talker)
}
/** Bans a client for [seconds], or for good with 0. */
fun ban(clientId: Int, seconds: Long, reason: String) {
if (session.isConnected) session.clients().ban(clientId, seconds, reason)
}
fun serverGroupChoices(clientId: Int): List<GroupChoice> =
session.model().getClient(clientId)?.let(session.model()::serverGroupChoices).orEmpty()
fun channelGroupChoices(clientId: Int): List<GroupChoice> =
session.model().getClient(clientId)?.let(session.model()::channelGroupChoices).orEmpty()
fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) {
val client = session.model().getClient(clientId) ?: return
if (session.isConnected) session.clients().setServerGroup(client.databaseId, groupId, assign)
}
/** Gives a client [groupId] in the channel they are in. */
fun setChannelGroup(clientId: Int, groupId: Int) {
val client = session.model().getClient(clientId) ?: return
if (session.isConnected) session.clients().setChannelGroup(client.databaseId, client.channelId, groupId)
}
// ---- ban list ----
/** One reading of a client's connection figures, or null when not connected. */
suspend fun connectionStats(clientId: Int): ConnectionStats? =
if (!session.isConnected) null
else suspendCoroutine { done -> session.requestConnectionInfo(clientId) { done.resume(it) } }
/** The server's bans, or why they could not be read. */
suspend fun banList(): Result<List<BanEntry>> = session.bans().list().result()
suspend fun addBan(rule: BanRule): Result<Unit> = session.bans().add(rule).done()
suspend fun replaceBan(banId: Int, rule: BanRule): Result<Unit> = session.bans().replace(banId, rule).done()
suspend fun deleteBans(banIds: Collection<Int>): Result<Unit> = session.bans().delete(banIds).done()
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = permissions.canDeleteBans(bans, session.selfUniqueId())
fun canEditBan(ban: BanEntry): Boolean = permissions.canEditBan(ban, session.selfUniqueId())
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(session.selfUniqueId())
/** Uploads [data] as our avatar. */
suspend fun setAvatar(data: ByteArray): Result<Unit> {
if (!session.isConnected) return Result.failure(RequestException.notConnected())
val file = withContext(Dispatchers.IO) {
File.createTempFile("avatar", null, parts.cacheDir).apply { writeBytes(data) }
}
return try {
session.avatarAdmin().set(file).done()
} finally {
file.delete()
}
}
// ---- details ----
fun serverDetails(): Details? =
if (session.isConnected) Details.server(session.model(), "${session.address()}:${session.port()}") else null
fun channelDetails(channelId: Int): Details? = session.model().getChannel(channelId)?.let(Details::channel)
fun clientDetails(clientId: Int): Details? = session.model().getClient(clientId)?.let {
Details.client(it, session.model(), parts.contactStore.find(it.uniqueId))
}
/** Asks the server for what the channel's details lack; they change once it answers. */
fun requestChannelDetails(channelId: Int) {
val channel = session.model().getChannel(channelId) ?: return
if (session.isConnected && !channel.descriptionLoaded) session.channels().requestInfo(channelId)
}
fun requestClientDetails(clientId: Int) {
if (session.isConnected) session.clients().requestInfo(clientId)
}
/** Files a client on the server as a contact; a new entry takes the type's defaults. */
fun addContact(clientId: Int, type: ContactType) {
val client = session.model().getClient(clientId) ?: return
parts.contactStore.add(client.uniqueId, client.nickname, type, parts.settings.contactDefaults)
}
internal fun contactsChanged() {
treeScope.launch { session.contacts().applyAll() }
scheduleTree(structure = false)
}
// ---- chat ----
/** Opens the private chat with a client, loading what was said before. */
fun openPrivateChat(clientId: Int): ChatKey {
val key = ChatKey.privateWith(clientId)
val client = session.model().getClient(clientId)
if (client != null) {
_chats.update { chats ->
chats.update(key, session.contacts().displayName(client)) { it.copy(uniqueId = client.uniqueId) }
}
session.loadPrivateChatHistory(clientId, client.uniqueId)
}
return key
}
fun closePrivateChat(key: ChatKey) = _chats.update { it.close(key) }
fun send(key: ChatKey, text: String) = session.sendChat(key, text)
/** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */
suspend fun sendFile(key: ChatKey, uri: Uri) {
parts.openShared(uri)
.onSuccess { session.sendAttachment(key, parts.attachments, it.data, it.size, it.name) }
.onFailure { app.error(it.message ?: "Could not read the file") }
}
fun markRead(key: ChatKey) {
if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } }
}
internal fun requestChat(clientId: Int) {
_chatRequest.value = ChatKey.privateWith(clientId)
}
fun chatRequestHandled() {
_chatRequest.value = null
}
/** Answers a private message from its notification. */
internal fun reply(clientId: Int, text: String) {
if (session.isConnected) send(ChatKey.privateWith(clientId), text) else parts.notifier.clear(id, clientId)
}
private fun addLine(key: ChatKey, title: String, html: String) {
val line = ChatLine(lineIds.incrementAndGet(), html)
_chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } }
}
private fun replaceLines(key: ChatKey, title: String, html: List<String>) {
val lines = html.map { ChatLine(lineIds.incrementAndGet(), it) }
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
}
/** One of this app's own notices, in the server chat. */
private fun system(text: String) = addLine(ChatKey.SERVER, "", ChatHtml.system(text))
// ---- snapshots ----
private fun snapshotState(): SessionState {
val self = session.model().getClient(session.selfClientId())
return SessionState(
title = session.title(),
status = network.status ?: session.status(),
connected = session.isConnected,
busy = isBusy,
micActive = micOwner && app.hasMicPermission(),
micPermission = app.hasMicPermission(),
micMuted = session.isMicMuted,
deafened = session.isDeafened,
away = session.isAway,
selfClientId = if (session.isConnected) session.selfClientId() else 0,
channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
inputMode = parts.settings.inputMode.get(),
hostButton = if (session.isConnected) session.model().hostButton() else null,
self = session.selfState(),
whisper = session.whisper()?.label,
whisperNobody = session.isWhisperingToNobody,
whisperControls = whisperControls,
)
}
internal fun refresh() {
_state.value = snapshotState()
app.serverChanged(this)
}
/** Takes a new tree snapshot soon; [structure] when channels or clients came, went or moved. */
internal fun scheduleTree(structure: Boolean) {
if (structure) structureChanged.set(true)
if (!treePending.compareAndSet(false, true)) return
treeScope.launch {
delay(TREE_FRAME_MS)
treePending.set(false)
if (structureChanged.getAndSet(false)) roots = session.model().buildTree()
_tree.value = ServerTree.of(roots, session.model(), session.contacts().store(),
parts.settings.colorContacts.get(), parts.settings.countryFlags.get(), parts.settings.clientRowColors)
refresh()
}
}
private inner class Listener : ServerSession.Listener {
override fun onSessionChanged() = refresh()
override fun append(key: ChatKey, title: String, html: String) = addLine(key, title, html)
override fun setHistory(key: ChatKey, title: String, html: List<String>) = replaceLines(key, title, html)
override fun rename(key: ChatKey, name: String) = _chats.update {
when (key.scope()) {
ChatScope.SERVER -> it.copy(server = it.server.copy(title = name.ifBlank { "Server" }))
ChatScope.CHANNEL -> it.copy(channel = it.channel.copy(title = name.ifBlank { "Channel" }))
else -> it
}
}
override fun closePrivateChats() = _chats.update { it.copy(private = emptyList()) }
override fun onPrivateMessage(fromClientId: Int, fromName: String, message: String) {
if (!app.foreground) parts.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
}
override fun onPrivateMessageSent(toClientId: Int, message: String) =
parts.notifier.sent(id, toClientId, ChatHtml.plainMessage(message))
override fun onConnected() {
network.onConnected()
app.connected(this@ServerController)
refresh()
}
override fun onDisconnected(reason: String?) {
network.onDisconnected()
parts.notifier.clearServer(id)
app.disconnected(this@ServerController)
scheduleTree(structure = true)
refresh()
}
override fun onModelChanged() {
scheduleTree(structure = true)
// A server edit may have changed it.
if (session.isConnected && session.model().hostButton() != _state.value.hostButton) refresh()
}
override fun onServerIconChanged(iconId: Long) =
app.serverIconChanged(session.address(), session.port(), iconId)
override fun onInfoUpdated() {
_infoUpdates.update { it + 1 }
// Avatars announce their arrival as info updates.
images.loaded()
}
override fun onIconsUpdated() = images.loaded()
override fun onTalkStateChanged(clientId: Int, talking: Boolean) {
if (clientId == session.selfClientId() && micOwner) app.talking(talking)
scheduleTree(structure = false)
}
override fun onError(message: String) = app.error(message)
override fun onPoke(fromName: String, message: String) = app.poked(fromName, message)
}
private companion object {
const val TREE_FRAME_MS = 30L
}
}
@@ -0,0 +1,65 @@
package eu.lixko.ts3j.client.android
import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import eu.lixko.ts3j.client.net.IconRepository
import eu.lixko.ts3j.client.net.avatar.AvatarRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.util.concurrent.ConcurrentHashMap
/**
* One server's icons and its clients' avatars, decoded once. What is still
* downloading reads as null until [version] moves on.
*/
class ServerImages internal constructor(
private val iconStore: IconRepository,
private val avatarStore: AvatarRepository,
) {
private val icons = ConcurrentHashMap<Long, ImageBitmap>()
private val avatars = ConcurrentHashMap<String, Picture>()
private val _version = MutableStateFlow(0)
val version: StateFlow<Int> = _version
internal fun loaded() = _version.update { it + 1 }
fun icon(id: Long): ImageBitmap? {
if (id == 0L) return null
icons[id]?.let { return it }
val bitmap = iconStore.get(id)?.let { decode(it, ICON_PX) } ?: return null
icons[id] = bitmap
return bitmap
}
fun avatar(uniqueId: String, flag: String): Picture? {
if (flag.isEmpty()) return null
avatars[flag]?.let { return it }
val picture = avatarStore.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null
avatars[flag] = picture
return picture
}
/** The avatar's file as the server keeps it; null while it has none or it is still downloading. */
fun avatarData(uniqueId: String, flag: String): ByteArray? =
if (flag.isEmpty()) null else avatarStore.get(uniqueId, flag)?.data()
/** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */
private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2
val options = BitmapFactory.Options().apply { inSampleSize = sample }
return BitmapFactory.decodeByteArray(data, 0, data.size, options)?.asImageBitmap()
}
private companion object {
const val ICON_PX = 64
const val AVATAR_PX = 512
}
}
@@ -0,0 +1,34 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.net.ChannelFiles
import eu.lixko.ts3j.client.session.ServerSession
import java.io.File
/** What every server the app is on runs on and reports to, shared by all of them. */
class ServerParts internal constructor(
private val context: Context,
internal val settings: Settings,
private val identityStore: IdentityStore,
private val audio: AudioSetup,
internal val contactStore: ContactStore,
private val myTeamSpeak: MyTeamSpeakAccount,
) {
internal val notifier = MessageNotifier(context)
internal val network = NetworkFollower(context)
internal val cacheDir: File get() = context.cacheDir
internal val attachments get() = myTeamSpeak.attachments
internal fun session(listener: ServerSession.Listener) =
ServerSession(settings, identityStore, audio.audio, audio.sounds, contactStore, listener).also {
it.setMyTeamSpeakLogin(myTeamSpeak.login)
}
internal fun fileTransfers(files: ChannelFiles) = FileTransfers(context, files)
internal suspend fun openShared(uri: Uri) = myTeamSpeak.openShared(uri)
}
@@ -0,0 +1,201 @@
package eu.lixko.ts3j.client.android
import androidx.compose.runtime.Immutable
import eu.lixko.ts3j.client.config.ClientRowColors
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.net.ChannelNode
import eu.lixko.ts3j.client.net.ClientEntry
import eu.lixko.ts3j.client.net.ClientStatus
import eu.lixko.ts3j.client.net.ServerModel
import eu.lixko.ts3j.client.net.Spacers
import eu.lixko.ts3j.client.net.TreeMatch
import eu.lixko.ts3j.client.text.TextQuery
/**
* A copy of the channel tree taken at one moment. The model's own nodes change in place
* on connection threads, which Compose cannot observe; these never change.
*/
@Immutable
data class ServerTree(
val channels: List<ChannelItem> = emptyList(),
/** The server's own icon; 0 for none. */
val serverIconId: Long = 0,
/** Whether client rows show their country's flag. */
val countryFlags: Boolean = false,
) {
fun channel(id: Int): ChannelItem? = find(channels) { it.id == id }
fun client(id: Int): ClientItem? {
var found: ClientItem? = null
find(channels) { c -> found = c.clients.firstOrNull { it.id == id }; found != null }
return found
}
/** The channels from the root down to the one [clientId] is in; null when they are not in the tree. */
fun pathTo(clientId: Int): List<Int>? {
fun walk(items: List<ChannelItem>): List<Int>? {
for (c in items) {
if (c.clients.any { it.id == clientId }) return listOf(c.id)
walk(c.children)?.let { return listOf(c.id) + it }
}
return null
}
return walk(channels)
}
/** The channels from the root down to [channelId]'s parent; null when it is not in the tree. */
fun parentsOf(channelId: Int): List<Int>? {
fun walk(items: List<ChannelItem>, above: List<Int>): List<Int>? {
for (c in items) {
if (c.id == channelId) return above
walk(c.children, above + c.id)?.let { return it }
}
return null
}
return walk(channels, emptyList())
}
/** The ids of what [find] matches, in reading order. */
fun hits(find: TreeFind): List<Int> {
val out = ArrayList<Int>()
fun walk(items: List<ChannelItem>) {
for (c in items) {
if (find.matches(c)) out += c.id
c.clients.forEach { if (find.matches(it)) out += it.id }
walk(c.children)
}
}
if (!find.query.isEmpty) walk(channels)
return out
}
/** Only what [find] matches: a matching channel with its clients, a matching client, and the channels leading to either. */
fun only(find: TreeFind): ServerTree {
fun keep(c: ChannelItem): ChannelItem? {
val matches = find.matches(c)
val clients = if (matches) c.clients else c.clients.filter(find::matches)
val children = c.children.mapNotNull(::keep)
return if (matches || clients.isNotEmpty() || children.isNotEmpty()) c.copy(clients = clients, children = children) else null
}
return copy(channels = channels.mapNotNull(::keep))
}
private fun find(items: List<ChannelItem>, test: (ChannelItem) -> Boolean): ChannelItem? {
for (c in items) {
if (test(c)) return c
find(c.children, test)?.let { return it }
}
return null
}
companion object {
fun of(roots: List<ChannelNode>, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
countryFlags: Boolean, rowColors: ClientRowColors): ServerTree =
ServerTree(
roots.map { channel(it, model, contacts, colorContacts, rowColors) },
model.serverIconId(),
countryFlags,
)
private fun channel(c: ChannelNode, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
rowColors: ClientRowColors): ChannelItem {
val clients = c.clients
val spacer = Spacers.parse(c.name)
return ChannelItem(
id = c.id,
name = c.name ?: "",
spacer = spacer,
iconId = if (spacer == null) c.iconId else 0,
locked = c.hasPassword,
full = c.maxClients >= 0 && clients.size >= c.maxClients,
subscribed = c.subscribed,
clients = clients.map { client(it, model, contacts, colorContacts, rowColors) },
children = c.children.map { channel(it, model, contacts, colorContacts, rowColors) },
)
}
private fun client(c: ClientEntry, model: ServerModel, contacts: ContactStore, colorContacts: Boolean,
rowColors: ClientRowColors): ClientItem {
val contact = contacts.find(c.uniqueId)
val away = c.away && c.awayMessage.isNotEmpty() && contact?.ignoreAwayMessage != true
val status = ClientStatus.of(c)
return ClientItem(
id = c.id,
uniqueId = c.uniqueId,
nickname = c.nickname ?: "",
name = contact?.displayName(c.nickname) ?: c.nickname ?: "",
awayMessage = if (away) c.awayMessage else "",
status = status,
background = rowColors.of(status),
self = c.self,
contactType = contact?.type,
highlight = if (colorContacts) contact?.type ?: ContactType.NEUTRAL else ContactType.NEUTRAL,
groupIconIds = (model.serverGroupsOf(c.serverGroupIds) + listOfNotNull(model.channelGroup(c.channelGroupId)))
.map { it.iconId }.filter { it != 0L },
avatarFlag = c.avatarFlag.orEmpty(),
country = c.country.orEmpty(),
serverGroupIds = c.serverGroupIds.toList(),
channelGroupId = c.channelGroupId,
talker = c.talker,
lacksTalkPower = model.lacksTalkPower(c),
talkRequest = c.talkRequest,
)
}
}
}
/** What the find bar looks for in the tree: clients, or with [channels] channels. */
@Immutable
data class TreeFind(val query: TextQuery, val channels: Boolean) {
fun matches(c: ChannelItem) = channels && TreeMatch.channel(query, c.name)
fun matches(c: ClientItem) = !channels && TreeMatch.client(query, c.nickname, c.name)
}
@Immutable
data class ChannelItem(
val id: Int,
val name: String,
/** Set for a spacer: a cosmetic separator rather than a channel to join. */
val spacer: Spacers.Spacer?,
val locked: Boolean,
val full: Boolean,
val subscribed: Boolean,
/** 0 for none. */
val iconId: Long,
val clients: List<ClientItem>,
val children: List<ChannelItem>,
)
@Immutable
data class ClientItem(
val id: Int,
val uniqueId: String,
val nickname: String,
/** The name shown: the contact's own name for them where there is one. */
val name: String,
val awayMessage: String,
val status: ClientStatus,
/** The row's background colour, ARGB; 0 for none. */
val background: Int,
val self: Boolean,
/** How the client is filed in the contacts; null when it is not one. */
val contactType: ContactType?,
/** The contact colour the name is drawn in, NEUTRAL when contacts are not coloured. */
val highlight: ContactType,
/** The icons of the client's server groups, then of its channel group, as TeamSpeak lines them up. */
val groupIconIds: List<Long>,
/** The MD5 of the client's avatar; empty for none. */
val avatarFlag: String,
/** The code of the country the server places the client in; empty when it cannot tell. */
val country: String,
val serverGroupIds: List<Int>,
val channelGroupId: Int,
/** Granted talk power. */
val talker: Boolean,
/** Short of the channel's needed talk power, so kept from talking. */
val lacksTalkPower: Boolean,
/** Waiting for talk power. */
val talkRequest: Boolean,
)
@@ -0,0 +1,368 @@
package eu.lixko.ts3j.client.android
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Handler
import android.os.Looper
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.net.HostButton
import eu.lixko.ts3j.client.session.SelfState
import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.session.Sessions
import eu.lixko.ts3j.client.text.BBCode
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import java.util.concurrent.atomic.AtomicInteger
/** What the app shows of a connection and the local client on it. */
data class SessionState(
val title: String = "",
val status: String = "Not connected",
val connected: Boolean = false,
val busy: Boolean = false,
/** Whether this server holds the microphone, which only one server can at a time. */
val micActive: Boolean = false,
val micPermission: Boolean = false,
val micMuted: Boolean = false,
val deafened: Boolean = false,
val away: Boolean = false,
val selfClientId: Int = 0,
val channelId: Int = 0,
val inputMode: Settings.InputMode = Settings.InputMode.VOICE_ACTIVATION,
val hostButton: HostButton? = null,
/** What the tree shows for the local client, and the connection notification too. */
val self: SelfState = SelfState.DISCONNECTED,
/** Who the microphone whispers to instead of the channel; null when it talks in the channel. */
val whisper: String? = null,
/** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */
val whisperNobody: Boolean = false,
/** Whether the menus offer whispering, as the bookmark connected with says. */
val whisperControls: Boolean = false,
)
/** Something that happened once, for the UI to tell the user about. */
sealed interface SessionEvent {
data class Poke(val from: String, val message: String) : SessionEvent
data class Error(val message: String) : SessionEvent
/** A link or shortcut brought a server on screen, in front of whatever page was open. */
data object ServerOpened : SessionEvent
}
/**
* The servers the app is on and what they share, outliving any activity: [ConnectionService]
* keeps the process in the foreground while any is connected. Only one server captures with
* the microphone at a time; [Sessions] hands it over.
*/
class SessionController internal constructor(
private val context: Context,
private val settings: Settings,
private val identities: IdentityManager,
private val bookmarks: BookmarkManager,
private val parts: ServerParts,
private val levels: LevelMonitor,
) {
private val main = Handler(Looper.getMainLooper())
private val nextId = AtomicInteger()
/** Touched on the main thread only, as [Sessions] wants. */
private val sessions = Sessions { main.post(::microphoneMoved) }
private val _servers = MutableStateFlow(emptyList<ServerController>())
/** Every server the app is on or getting on, in the order they were connected. */
val servers: StateFlow<List<ServerController>> = _servers
private val _current = MutableStateFlow<ServerController?>(null)
/** The server on screen; null when there is none. */
val current: StateFlow<ServerController?> = _current
private val _micOwner = MutableStateFlow<ServerController?>(null)
/** The server capturing with the microphone; null when none is. */
val micOwner: StateFlow<ServerController?> = _micOwner
/** Why the last connection that ended did, for the connect form to show; null when it was left. */
private val _lastEnd = MutableStateFlow<String?>(null)
val lastEnd: StateFlow<String?> = _lastEnd
private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16)
val events: SharedFlow<SessionEvent> = _events
private val _onScreen = MutableStateFlow(false)
val onScreen: StateFlow<Boolean> = _onScreen
/** Whether the app is on screen; pokes and private messages are notified of while it is not. */
var foreground: Boolean
get() = _onScreen.value
set(value) {
_onScreen.value = value
if (value) parts.notifier.clearPokes()
// The process may be let go of any time once out of sight.
else parts.contactStore.flush()
}
val micLevel: StateFlow<MicLevel> = levels.level
@Volatile
private var watchingLevel = false
init {
// Mutations report on whichever thread made them, a connection thread included.
parts.contactStore.addListener { _servers.value.forEach(ServerController::contactsChanged) }
Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer)
settings.countryFlags.addListener { servers.value.forEach { it.scheduleTree(structure = false) } }
}
val lastAddress: String get() = settings.lastAddress.get()
// ---- connection ----
/** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */
fun connect(address: String, nickname: String, password: String = "", identityId: String = "") {
val (host, port) = parseAddress(address)
settings.lastAddress.set(address)
if (identities.nicknameOf(identityId).isBlank()) settings.nickname.set(nickname)
settings.save()
start(host, port, nickname, password, identityId, "", "")
}
fun connect(bookmark: Bookmark) {
start {
it.session.setMyTeamSpeakFeatures(bookmark.myTeamSpeakFeatures)
it.applyBookmark(bookmark)
it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password,
bookmark.identityId, bookmark.channel, bookmark.channelPassword)
}
}
private fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
channel: String, channelPassword: String) {
start { it.start(host, port, nickname, password, identityId, channel, channelPassword) }
}
private fun start(connect: (ServerController) -> Unit) {
val server = ServerController(nextId.incrementAndGet(), parts, this)
sessions.add(server.session)
_servers.update { it + server }
_current.value = server
_lastEnd.value = null
context.startForegroundService(Intent(context, ConnectionService::class.java))
connect(server)
}
/**
* Goes where a `ts3server://` link leads: on a server we are on already, to the channel it
* names; else connects there as another server.
*/
fun open(link: ServerLink, identityId: String = "") {
if (link.bookmarkLabel.isNotEmpty()) {
bookmarks.add(link.toBookmark())
}
val on = _servers.value.firstOrNull { it.session.isOn(link) }
if (on != null) {
_current.value = on
on.session.follow(link)
} else {
start { it.open(link, identityId) }
}
_events.tryEmit(SessionEvent.ServerOpened)
}
/** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */
fun openBookmark(id: String): ServerLink? {
val bookmark = bookmarks.find(id)
if (bookmark == null) {
error("That bookmark no longer exists")
return null
}
return ServerLink.of(bookmark).also { open(it, bookmark.identityId) }
}
private var startedUp = false
/** Connects the bookmarks flagged for startup, once per process; [opened] is a server the launch already went to. */
fun connectStartupBookmarks(opened: ServerLink?) {
if (startedUp) return
startedUp = true
for (b in bookmarks.startupBookmarks()) {
if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) }
}
}
fun select(server: ServerController) {
if (server in _servers.value) _current.value = server
}
/** Leaves every server before returning, for when the app goes away with the connections. */
fun leave() {
val servers = _servers.value
servers.forEach(ServerController::leaving)
ServerSession.shutdownAll(servers.map { it.session })
parts.contactStore.flush()
parts.attachments.close()
}
fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id }
/** A server's state changed; one that is done with goes from the list. */
internal fun serverChanged(server: ServerController) {
if (server.micOwner) updateLevels()
if (server.ended) main.post { remove(server) }
}
private fun remove(server: ServerController) {
if (server !in _servers.value || !server.ended) return
sessions.remove(server.session)
val rest = _servers.value - server
_servers.value = rest
if (_current.value == server) _current.value = rest.lastOrNull()
server.dispose()
val reason = server.state.value.status
_lastEnd.value = if (server.left) null else reason
if (!server.left && rest.isNotEmpty()) error("${server.state.value.title}: $reason")
}
internal fun connected(server: ServerController) {
// The first connect generates an identity when there was none.
identities.refresh()
main.post {
// Without the permission yet, the UI hands the microphone over once it is granted.
if (hasMicPermission()) sessions.connected(server.session)
}
}
internal fun disconnected(server: ServerController) {
main.post { sessions.disconnected(server.session) }
}
internal fun error(message: String) {
_events.tryEmit(SessionEvent.Error(message))
}
internal fun poked(from: String, message: String) {
_events.tryEmit(SessionEvent.Poke(from, message))
if (!foreground) parts.notifier.poke(from, BBCode.toPlain(message))
}
internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
// ---- what the servers share ----
/** A saved bookmark changed; the servers connected with it take on what applies at once. */
internal fun bookmarkEdited(bookmark: Bookmark) = _servers.value.forEach { it.bookmarkEdited(bookmark) }
internal fun serverIconChanged(address: String, port: Int, iconId: Long) = bookmarks.serverIconChanged(address, port, iconId)
/** The channels of a server we are on at [host]:[port], to pick one to join. */
fun channelPathsAt(host: String, port: Int): List<String> = sessions.connectedTo(host, port)?.channelPaths().orEmpty()
/** The channel we are in on the server at [host]:[port]; null when we are not on it. */
fun currentChannelAt(host: String, port: Int): String? = sessions.connectedTo(host, port)?.currentChannelPath()
/** Signed in or out of myTeamSpeak. */
internal fun myTeamSpeakChanged() = _servers.value.forEach { it.session.updateMyTeamSpeak() }
/** Puts new client row colours, already set in [settings], into effect. */
fun clientRowColorsChanged() {
settings.save()
servers.value.forEach { it.scheduleTree(structure = false) }
}
// ---- the local client ----
fun hasMicPermission() =
context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
/** Moves the microphone to [server]; needs RECORD_AUDIO granted. */
fun giveMicrophoneTo(server: ServerController) {
if (server.isConnected) sessions.giveMicrophoneTo(server.session)
}
/** Opens the microphone of the server holding it while push-to-talk is held. */
fun setPushToTalk(pressed: Boolean) = sessions.setPushToTalk(pressed)
/** Transmits on the server holding the microphone while held, past the voice-activation gate too. */
fun setForceTransmit(pressed: Boolean) = sessions.setForceTransmit(pressed)
private fun microphoneMoved() {
val owner = sessions.microphoneOwner()
for (server in _servers.value) {
server.micOwner = server.session == owner
server.refresh()
}
_micOwner.value = _servers.value.firstOrNull { it.micOwner }
updateLevels()
}
/** Switches between push to talk and voice activation; returns the new mode. */
fun toggleInputMode(): Settings.InputMode {
settings.inputMode.set(if (settings.inputMode.get() == Settings.InputMode.PUSH_TO_TALK)
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK)
applySettings()
return settings.inputMode.get()
}
/** Saves the settings and puts the voice ones into effect at once. */
fun applySettings() {
settings.save()
try {
for (server in _servers.value) {
server.microphone?.apply(settings)
server.refresh()
server.scheduleTree(structure = false)
}
levels.apply()
} catch (e: RuntimeException) {
error(e.message ?: "Microphone unavailable")
}
}
/** Output device, volume and receive buffer are global, so they go to every connection. */
private fun applyOutputSettings() {
for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume.get())
server.playback?.setOutputDevice(settings.outputDevice.get())
server.playback?.setReceiveBuffer(settings.receiveBuffer.get())
}
}
/** Listens to the microphone for the level meter while [on]. */
fun watchLevel(on: Boolean) {
watchingLevel = on
updateLevels()
}
private fun updateLevels() {
val owner = _micOwner.value
levels.update(watchingLevel, owner?.microphone, owner?.isBusy == true, hasMicPermission())
}
// ---- notifications ----
/** Shows a private chat a notification was tapped for. */
fun requestChat(serverId: Int, clientId: Int) {
val server = server(serverId) ?: return
_current.value = server
server.requestChat(clientId)
}
/** Answers a private message from its notification. */
fun reply(serverId: Int, clientId: Int, text: String) {
server(serverId)?.reply(clientId, text) ?: parts.notifier.clear(serverId, clientId)
}
companion object {
const val DEFAULT_PORT = 9987
/** `host[:port]` as typed, the port defaulting to TeamSpeak's. */
fun parseAddress(address: String): Pair<String, Int> {
val host = address.substringBefore(':').trim()
val port = address.substringAfter(':', "").trim().toIntOrNull() ?: DEFAULT_PORT
return host to port
}
}
}
@@ -0,0 +1,53 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.content.res.AssetManager
import eu.lixko.ts3j.client.config.AppDirs
import java.io.File
/**
* Unpacks the sound packs bundled in the APK into the profile's `sound` folder, where
* [eu.lixko.ts3j.client.sound.SoundNotifier] finds packs, as they are read as plain files.
* It happens once per installed version of the app; packs of other origins in the
* folder are left alone.
*/
class SoundPackInstaller(private val context: Context) {
private val root = File(AppDirs.profile(), ASSET_DIR)
private val marker = File(root, ".bundled")
/** Where a pack is unpacked first, outside [root] so it is never seen half written. */
private val staging = File(AppDirs.profile(), ".sound-staging")
/** @return whether the packs were (re)installed, so the list of them has to be read again */
fun install(): Boolean {
val version = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime.toString()
if (marker.isFile && marker.readText() == version) return false
val assets = context.assets
for (pack in assets.list(ASSET_DIR).orEmpty()) {
staging.deleteRecursively()
copy(assets, "$ASSET_DIR/$pack", staging)
val target = File(root, pack)
target.deleteRecursively()
root.mkdirs()
check(staging.renameTo(target)) { "Cannot install sound pack $pack" }
}
root.mkdirs()
marker.writeText(version)
return true
}
private fun copy(assets: AssetManager, path: String, to: File) {
val children = assets.list(path).orEmpty()
if (children.isEmpty()) {
to.parentFile?.mkdirs()
assets.open(path).use { input -> to.outputStream().use { input.copyTo(it) } }
return
}
to.mkdirs()
for (child in children) copy(assets, "$path/$child", File(to, child))
}
private companion object {
const val ASSET_DIR = "sound"
}
}
@@ -0,0 +1,31 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.os.Bundle
import android.speech.tts.TextToSpeech
import eu.lixko.ts3j.client.sound.SoundPlayer
/**
* Adds the phone's text-to-speech to a wave player, for packs that speak their
* notifications. Sentences asked for before the engine is up are dropped: they
* would come out late, past what they announce.
*/
class SpeakingSoundPlayer(context: Context, private val waves: SoundPlayer) : SoundPlayer by waves {
@Volatile
private var ready = false
private val tts = TextToSpeech(context.applicationContext) { status -> ready = status == TextToSpeech.SUCCESS }
override fun canSpeak() = true
override fun say(text: String, volume: Double) {
if (!ready) return
val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, volume.toFloat()) }
tts.speak(text, TextToSpeech.QUEUE_ADD, params, null)
}
override fun shutdown() {
tts.shutdown()
waves.shutdown()
}
}
@@ -0,0 +1,37 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** What a sideways swipe over the channel tree does. */
enum class TreeSwipe { OFF, CHAT, SERVERS }
/** The swipe gestures, an Android-only choice kept apart from the shared settings. */
class SwipePrefs(context: Context) {
private val prefs = context.getSharedPreferences("swipe", Context.MODE_PRIVATE)
private val _tree = MutableStateFlow(
TreeSwipe.entries.firstOrNull { it.name == prefs.getString(TREE, null) } ?: TreeSwipe.CHAT)
val tree: StateFlow<TreeSwipe> = _tree
private val _chatTabs = MutableStateFlow(prefs.getBoolean(CHAT_TABS, true))
/** Whether a sideways swipe over the chat goes to the neighbouring conversation. */
val chatTabs: StateFlow<Boolean> = _chatTabs
fun setTree(swipe: TreeSwipe) {
prefs.edit().putString(TREE, swipe.name).apply()
_tree.value = swipe
}
fun setChatTabs(enabled: Boolean) {
prefs.edit().putBoolean(CHAT_TABS, enabled).apply()
_chatTabs.value = enabled
}
private companion object {
const val TREE = "tree"
const val CHAT_TABS = "chatTabs"
}
}
@@ -0,0 +1,20 @@
package eu.lixko.ts3j.client.android
import android.app.Application
import eu.lixko.ts3j.client.config.AppDirs
class Ts3Application : Application() {
lateinit var parts: AppParts
private set
val sessions: SessionController get() = parts.sessions
override fun onCreate() {
super.onCreate()
// Before any store loads: there is no home directory to find them in.
AppDirs.init(filesDir, filesDir.toPath().resolve("chats"))
parts = AppParts(this)
Thread(parts.audio::installSoundPacks, "sound-packs").start()
}
}
@@ -0,0 +1,64 @@
package eu.lixko.ts3j.client.android
import android.util.LruCache
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.net.PictureDownloads
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.ConcurrentHashMap
/** The pictures descriptions show, fetched by core's downloads and decoded while there is room. */
class WebPictures(cacheDir: File, private val settings: Settings) {
sealed interface State {
data object Loading : State
data object Broken : State
data class Shown(val picture: Picture) : State
}
private val downloads = PictureDownloads(File(cacheDir, "pictures"), false)
private val decoded = LruCache<String, Picture>(CACHED)
private val undecodable = ConcurrentHashMap.newKeySet<String>()
private val _version = MutableStateFlow(0)
/** Moves on whenever a download has come or failed. */
val version: StateFlow<Int> = _version
init {
downloads.addListener { _version.update { it + 1 } }
}
/** Fetches pictures whose addresses start with [scheme] from [source] rather than the web. */
fun addSource(scheme: String, source: PictureDownloads.Source) = downloads.addSource(scheme, source)
/** Asks again for the pictures that could not be had. */
fun retryFailed() = downloads.retryFailed()
/** Whether pictures are shown at all, rather than links to them. */
val enabled: Boolean get() = settings.descriptionPictures.get()
suspend fun state(url: String): State {
decoded.get(url)?.let { return State.Shown(it) }
if (url in undecodable) return State.Broken
val file = downloads.get(url) ?: return if (downloads.failed(url)) State.Broken else State.Loading
val picture = withContext(Dispatchers.IO) { decodePicture(file.readBytes(), MAX_PX) }
if (picture == null) {
undecodable += url
return State.Broken
}
decoded.put(url, picture)
return State.Shown(picture)
}
/** The picture's file as downloaded; null while it is not there. */
suspend fun data(url: String): ByteArray? = withContext(Dispatchers.IO) { downloads.get(url)?.readBytes() }
private companion object {
const val CACHED = 32
const val MAX_PX = 1024
}
}
@@ -0,0 +1,41 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The saved whisper lists, shared by every server. */
class WhisperListManager internal constructor() {
private val store = WhisperLists.load()
private val _all = MutableStateFlow(copies())
val all: StateFlow<List<WhisperList>> = _all
private fun copies() = store.all().map { it.copy() }
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
fun save(index: Int, list: WhisperList) {
val all = store.all()
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
saved()
}
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
fun addTo(index: Int, newName: String, add: (WhisperList) -> Unit) {
val list = store.all().getOrNull(index)?.copy() ?: WhisperList(newName)
add(list)
save(index, list)
}
fun remove(index: Int) {
val all = store.all()
if (index !in all.indices) return
all.removeAt(index)
saved()
}
private fun saved() {
store.save()
_all.value = copies()
}
}
@@ -0,0 +1,136 @@
package eu.lixko.ts3j.client.android.ui
import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AppParts
import eu.lixko.ts3j.client.android.SessionEvent
import eu.lixko.ts3j.client.android.TreeSwipe
@Composable
fun App(parts: AppParts) {
val sessions = parts.sessions
val current by sessions.current.collectAsStateWithLifecycle()
// Each server keeps its own screen state (chat open, conversation) while another is shown.
val serverStates = rememberSaveableStateHolder()
var connectOpen by rememberSaveable { mutableStateOf(false) }
val snackbar = remember { SnackbarHostState() }
var settingsOpen by rememberSaveable { mutableStateOf(false) }
var contactsOpen by rememberSaveable { mutableStateOf(false) }
var myTeamSpeakOpen by rememberSaveable { mutableStateOf(false) }
var editingContact by rememberSaveable { mutableStateOf<String?>(null) }
// Set when a contact's page was opened from a client, so leaving it goes back there.
var contactDirect by rememberSaveable { mutableStateOf(false) }
var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) }
var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) }
LaunchedEffect(sessions) {
sessions.events.collect { event ->
when (event) {
is SessionEvent.Poke -> poke = event
is SessionEvent.Error -> snackbar.showSnackbar(event.message)
SessionEvent.ServerOpened -> {
connectOpen = false
settingsOpen = false
contactsOpen = false
myTeamSpeakOpen = false
editingBookmark = null
}
}
}
}
val context = LocalContext.current
val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
if (granted[Manifest.permission.RECORD_AUDIO] == true) sessions.current.value?.let(sessions::giveMicrophoneTo)
}
fun missing(vararg names: String) =
names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
// The connection runs without either permission, just silent or without its notification.
val connectAsking: (() -> Unit) -> Unit = { connect ->
connect()
connectOpen = false
val ask = missing(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS)
if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray())
}
val enableMicrophone: () -> Unit = {
if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) sessions.current.value?.let(sessions::giveMicrophoneTo)
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
}
val openContacts: (String?) -> Unit = { uniqueId ->
contactsOpen = true
editingContact = uniqueId
contactDirect = uniqueId != null
}
CompositionLocalProvider(LocalIconTheme provides parts.icons, LocalWebPictures provides parts.pictures) {
val server = current
val bookmark = editingBookmark
when {
bookmark != null -> BookmarkScreen(sessions, parts.bookmarks, parts.identities, bookmark, onDone = { editingBookmark = null })
contactsOpen -> ContactsScreen(parts.contacts, editingContact, onEdit = { uniqueId ->
if (uniqueId == null && contactDirect) contactsOpen = false
contactDirect = false
editingContact = uniqueId
}, onBack = { contactsOpen = false })
myTeamSpeakOpen -> MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { myTeamSpeakOpen = false })
settingsOpen -> SettingsScreen(parts, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
server != null && !connectOpen -> {
val servers by sessions.servers.collectAsStateWithLifecycle()
val treeSwipe by parts.swipe.tree.collectAsStateWithLifecycle()
val serverSwipe = rememberSwipeState()
SwipeHost(
serverSwipe, server,
neighbour = { at, dir ->
if (treeSwipe != TreeSwipe.SERVERS) null
else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) }
},
onSwipe = sessions::select,
modifier = Modifier.fillMaxSize(),
) { shown ->
serverStates.SaveableStateProvider(shown.id) {
CompositionLocalProvider(LocalServerImages provides shown.images) {
PictureViewerHost(shown) {
ServerScreen(sessions, parts.whisperLists, parts.myTeamSpeak, parts.swipe, parts.banReasons, shown, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it },
serverSwipe = serverSwipe, active = shown == server)
}
}
}
}
}
else -> ConnectScreen(sessions, parts.bookmarks, parts.identities, parts.myTeamSpeak, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking,
onEditBookmark = { editingBookmark = it },
onBack = if (current != null) ({ connectOpen = false }) else null)
}
}
poke?.let { p ->
AlertDialog(
onDismissRequest = { poke = null },
title = { Text("${p.from} poked you") },
text = if (p.message.isNotBlank()) ({ Text(p.message) }) else null,
confirmButton = { TextButton(onClick = { poke = null }) { Text("OK") } },
)
}
}
@@ -0,0 +1,103 @@
package eu.lixko.ts3j.client.android.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.MyTsException
import java.io.IOException
import kotlinx.coroutines.launch
/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */
class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
/**
* Shared files for [server]'s chat: a picture opens full size, anything else is saved where
* the user picks; sharing picks a file to send into the conversation [shown] gives.
*/
@Composable
fun rememberAttachmentActions(
account: MyTeamSpeakAccount,
server: ServerController,
snackbar: SnackbarHostState,
shown: ChatKey,
): AttachmentActions {
val scope = rememberCoroutineScope()
val signedIn by account.signedIn.collectAsStateWithLifecycle()
val key by rememberUpdatedState(shown)
val viewer = LocalPictureViewer.current
val pictures = LocalWebPictures.current
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
var saving by rememberSaveable { mutableStateOf<String?>(null) }
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
val ref = ChatAttachment.Ref.parse(saving)
saving = null
if (uri == null || ref == null) return@rememberLauncherForActivityResult
scope.launch {
val error = try {
account.saveAttachment(ref, uri)
null
} catch (e: MyTsException) {
e.message
} catch (e: IOException) {
e.message
}
snackbar.showSnackbar(if (error == null) "Saved ${ref.fileName}." else "Could not save ${ref.fileName}: $error")
}
}
val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) scope.launch { server.sendFile(key, uri) }
}
return AttachmentActions(
open = open@{ href ->
val ref = ChatAttachment.Ref.parse(href) ?: return@open
when {
!signedIn -> tell(SIGN_IN)
ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) {
pictures?.data(href) ?: runCatching { account.downloadAttachment(ref) }.getOrNull()
})
else -> {
saving = href
saver.launch(ref.fileName)
}
}
},
share = { if (signedIn) picker.launch("*/*") else tell(SIGN_IN) },
)
}
private const val SIGN_IN = "Sign in to myTeamSpeak to share files"
/** Asks where to save a file of the given name, typed by its extension. */
internal object SaveAs : ActivityResultContract<String, Uri?>() {
override fun createIntent(context: Context, input: String): Intent {
val extension = input.substringAfterLast('.', "").lowercase()
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream"
return Intent(Intent.ACTION_CREATE_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType(type)
.putExtra(Intent.EXTRA_TITLE, input)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri? =
intent?.data.takeIf { resultCode == Activity.RESULT_OK }
}
@@ -0,0 +1,312 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.net.ban.BanEntry
import eu.lixko.ts3j.client.net.ban.BanPattern
import eu.lixko.ts3j.client.net.ban.BanRule
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
/** What the ban list shows instead of itself: a ban's editor, a new or an existing ban's. */
private sealed interface BanEdit {
data object New : BanEdit
data class Existing(val ban: BanEntry) : BanEdit
}
/** The server's ban list, as TeamSpeak's Ban List window: searchable, own bans apart, add, edit and remove. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: () -> Unit) {
val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
var bans by remember { mutableStateOf<List<BanEntry>?>(null) }
var status by remember { mutableStateOf("Loading…") }
/** Bumped to read the list again. */
var generation by remember { mutableIntStateOf(0) }
var query by rememberSaveable { mutableStateOf("") }
var onlyOwn by rememberSaveable { mutableStateOf(false) }
var shown by remember { mutableStateOf<BanEntry?>(null) }
var edit by remember { mutableStateOf<BanEdit?>(null) }
LaunchedEffect(generation) {
status = "Loading…"
server.banList()
.onSuccess {
bans = it
status = if (it.size == 1) "1 ban" else "${it.size} bans"
}
.onFailure {
bans = emptyList()
status = "Failed to request ban list: ${it.message}"
}
}
/** Reports a failed change, or re-reads the list to show what the server now holds. */
val change = { action: suspend () -> Result<Unit>, failure: String ->
scope.launch {
action().onFailure { snackbar.showSnackbar("$failure: ${it.message}") }
generation++
}
Unit
}
edit?.let { e ->
val existing = (e as? BanEdit.Existing)?.ban
BanEditor(existing, presets, server.permissions.maxBanSeconds(), onBack = { edit = null }) { rule ->
edit = null
if (existing == null) change({ server.addBan(rule) }, "Error adding ban")
else change({ server.replaceBan(existing.id, rule) }, "Error editing ban")
}
return
}
SubScreen(
"Ban list", onBack,
actions = {
if (server.permissions.canCreateBans()) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") }
IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") }
},
snackbar = snackbar,
) { padding ->
val needle = query.trim().lowercase(Locale.ROOT)
val filtered = remember(bans, needle, onlyOwn) {
bans.orEmpty().filter { ban ->
(!onlyOwn || server.isOwnBan(ban)) && (needle.isEmpty() || searchText(ban).contains(needle))
}
}
Column(Modifier.padding(padding).imePadding().fillMaxSize()) {
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(query, { query = it }, Modifier.weight(1f), placeholder = { Text("Search") },
singleLine = true, leadingIcon = { PackIcon("SEARCH", null) })
FilterChip(onlyOwn, { onlyOwn = !onlyOwn }, label = { Text("Own") })
}
Text(status, Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
LazyColumn(Modifier.weight(1f)) {
items(filtered, key = { it.id }) { ban ->
ListItem(
headlineContent = { Text(ban.targets(), maxLines = 2, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Column {
if (ban.reason.isNotEmpty()) Text(ban.reason, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text("${ban.invokerName} · ${expiry(ban)}", style = MaterialTheme.typography.bodySmall)
}
},
modifier = Modifier.clickable { shown = ban },
)
HorizontalDivider()
}
}
}
}
shown?.let { ban ->
BanSheet(
ban,
onDismiss = { shown = null },
onEdit = if (server.canEditBan(ban)) ({ shown = null; edit = BanEdit.Existing(ban) }) else null,
onDelete = if (server.canDeleteBans(listOf(ban))) ({
shown = null
change({ server.deleteBans(listOf(ban.id)) }, "Error deleting ban")
}) else null,
)
}
}
private fun searchText(ban: BanEntry): String =
listOf(ban.targets(), ban.reason, ban.invokerName, date(ban.createdEpochSeconds), expiry(ban))
.joinToString("\n").lowercase(Locale.ROOT)
private val DATE: DateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
private fun date(epochSeconds: Long): String =
if (epochSeconds <= 0) "" else DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault()))
private fun expiry(ban: BanEntry): String = if (ban.isPermanent) "Never expires" else "Expires ${date(ban.expiresEpochSeconds())}"
/** Everything about one ban, and what may be done with it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun BanSheet(ban: BanEntry, onDismiss: () -> Unit, onEdit: (() -> Unit)?, onDelete: (() -> Unit)?) {
var confirmDelete by remember { mutableStateOf(false) }
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Fact("Name", ban.name)
Fact("IP", ban.ip)
Fact("Unique ID", ban.uid)
Fact("Last nickname", ban.lastNickname)
Fact("myTeamSpeak ID", ban.mytsid)
Fact("Reason", ban.reason)
Fact("Creator", ban.invokerName)
Fact("Created", date(ban.createdEpochSeconds))
Fact("Expires", if (ban.isPermanent) "Never" else date(ban.expiresEpochSeconds()))
Fact("Enforced", ban.enforcements.toString())
}
onEdit?.let { Action("EDIT", "Edit", onClick = it) }
onDelete?.let { Action("DELETE", "Delete") { confirmDelete = true } }
}
}
if (confirmDelete && onDelete != null) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete ban?") },
text = { Text(ban.targets()) },
confirmButton = { TextButton(onClick = { confirmDelete = false; onDelete() }) { Text("Delete") } },
dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } },
)
}
}
@Composable
private fun Fact(label: String, value: String) {
if (value.isEmpty()) return
Column {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(value, style = MaterialTheme.typography.bodyMedium)
}
}
/** Adds a ban, or rewrites [existing]: what it matches, why, and for how long. */
@Composable
private fun BanEditor(
existing: BanEntry?,
presets: BanReasonPresets,
maxSeconds: Long,
onBack: () -> Unit,
onSave: (BanRule) -> Unit,
) {
val decoded = remember { BanPattern.decode(existing?.ip, existing?.name) }
var ip by remember { mutableStateOf(decoded.ip) }
var name by remember { mutableStateOf(decoded.name) }
var pattern by remember { mutableStateOf(if (existing == null) BanPattern.WILDCARD_IPV4 else decoded.pattern) }
var uid by remember { mutableStateOf(existing?.uid.orEmpty()) }
var mytsid by remember { mutableStateOf(existing?.mytsid.orEmpty()) }
var reason by remember { mutableStateOf(existing?.reason.orEmpty()) }
val duration = remember { BanDurationState(existing?.durationSeconds ?: DEFAULT_BAN_SECONDS) }
val rule = BanRule(pattern.ipToRegex(ip), pattern.nameToRegex(name), uid, mytsid, duration.seconds, reason)
val ipValid = BanPattern.isValidRegex(rule.ipRegex)
val nameValid = BanPattern.isValidRegex(rule.nameRegex)
val valid = rule.hasTarget() && ipValid && nameValid && duration.valid
SubScreen(
if (existing == null) "Add ban" else "Edit ban", onBack,
actions = { TextButton(onClick = { onSave(rule) }, enabled = valid) { Text("Save") } },
) { padding ->
Column(
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(ip, { ip = it }, Modifier.fillMaxWidth(), label = { Text("IP") }, singleLine = true,
isError = !ipValid)
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true,
isError = !nameValid)
PatternField(pattern) { pattern = it }
OutlinedTextField(uid, { uid = it }, Modifier.fillMaxWidth(), label = { Text("Unique ID") }, singleLine = true)
OutlinedTextField(mytsid, { mytsid = it }, Modifier.fillMaxWidth(), label = { Text("myTeamSpeak ID") },
singleLine = true)
ReasonField(reason, { reason = it }, presets)
BanDurationField(duration, maxSeconds)
}
}
}
/** How the IP and name are written: wildcards, fixed strings or regular expressions. */
@Composable
private fun PatternField(pattern: BanPattern, onSelect: (BanPattern) -> Unit) {
var open by remember { mutableStateOf(false) }
Row(verticalAlignment = Alignment.CenterVertically) {
Text("Interpret as", Modifier.weight(1f))
Box {
OutlinedButton(onClick = { open = true }) { Text(pattern.label()) }
DropdownMenu(open, { open = false }) {
for (p in BanPattern.entries) DropdownMenuItem({ Text(p.label()) }, onClick = { open = false; onSelect(p) })
}
}
}
}
/** The reason, with the saved presets to pick from and the reason typed to save as one. */
@Composable
private fun ReasonField(reason: String, onChange: (String) -> Unit, presets: BanReasonPresets) {
var open by remember { mutableStateOf(false) }
var saved by remember { mutableStateOf(presets.all().toList()) }
Box {
Row(verticalAlignment = Alignment.Top) {
LimitedField(reason, onChange, "Reason", BanRule.REASON_LIMIT, Modifier.weight(1f))
IconButton(onClick = { open = true }, Modifier.padding(top = 8.dp)) { Icon(Icons.Filled.ArrowDropDown, "Presets") }
}
DropdownMenu(open, { open = false }, Modifier.align(Alignment.TopEnd)) {
for (preset in saved) {
DropdownMenuItem({ Text(preset, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; onChange(preset.take(BanRule.REASON_LIMIT)) },
trailingIcon = {
IconButton(onClick = {
presets.remove(preset)
presets.save()
saved = presets.all().toList()
}) { PackIcon("DELETE", "Remove preset") }
})
}
if (saved.isNotEmpty()) HorizontalDivider()
DropdownMenuItem({ Text("Save as preset") }, enabled = reason.isNotBlank(), onClick = {
open = false
presets.add(reason)
presets.save()
saved = presets.all().toList()
})
}
}
}
@@ -0,0 +1,185 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.BookmarkManager
import eu.lixko.ts3j.client.android.IdentityManager
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark
/** A bookmark on the edit page: [index] among the saved ones, -1 for a new one. */
class BookmarkEdit(val index: Int, val bookmark: Bookmark)
val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
save = { edit ->
val b = edit?.bookmark ?: return@listSaver emptyList()
listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password,
b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id,
b.myTeamSpeakFeatures, b.showWhisperControls)
},
restore = { saved ->
if (saved.isEmpty()) null
else BookmarkEdit(saved[0] as Int, Bookmark(saved[1] as String, saved[2] as String, saved[3] as Int,
saved[4] as String, saved[5] as String).apply {
identityId = saved[6] as String
channel = saved[7] as String
channelPassword = saved[8] as String
connectOnStartup = saved[9] as Boolean
iconId = saved[10] as Long
id = saved[11] as String
myTeamSpeakFeatures = saved[12] as Boolean
showWhisperControls = saved[13] as Boolean
})
},
)
/** Every setting of one bookmark, saved only on Save. */
@Composable
fun BookmarkScreen(sessions: SessionController, bookmarks: BookmarkManager, identityManager: IdentityManager, edit: BookmarkEdit, onDone: () -> Unit) {
val b = edit.bookmark
val identities by identityManager.all.collectAsStateWithLifecycle()
var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) }
var address by rememberSaveable {
mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}")
}
var nickname by rememberSaveable { mutableStateOf(b.nickname.orEmpty()) }
var password by rememberSaveable { mutableStateOf(b.password.orEmpty()) }
var identityId by rememberSaveable { mutableStateOf(b.identityId.orEmpty()) }
var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) }
var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) }
var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) }
var myTeamSpeakFeatures by rememberSaveable { mutableStateOf(b.myTeamSpeakFeatures) }
var showWhisperControls by rememberSaveable { mutableStateOf(b.showWhisperControls) }
val save = {
val (host, port) = SessionController.parseAddress(address)
bookmarks.save(edit.index, b.copy().also {
it.label = label.trim().ifEmpty { host }
it.address = host
it.port = port
it.nickname = nickname.trim()
it.password = password
it.identityId = identityId
it.channel = channel.trim()
it.channelPassword = channelPassword
it.connectOnStartup = connectOnStartup
it.myTeamSpeakFeatures = myTeamSpeakFeatures
it.showWhisperControls = showWhisperControls
})
onDone()
}
SubScreen(if (edit.index < 0) "New bookmark" else "Edit bookmark", onBack = onDone, actions = {
TextButton(onClick = save, enabled = address.isNotBlank()) { Text("Save") }
}) { padding ->
Column(
Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedTextField(label, { label = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true)
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
label = { Text("Server password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) { identityId = it }
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
placeholder = { Text(identityManager.nicknameFor(identityId)) }, singleLine = true)
val paths = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> sessions.channelPathsAt(host, port) }
}
val current = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> sessions.currentChannelAt(host, port) }
}
ChannelField(channel, paths, current) { channel = it }
OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(),
label = { Text("Channel password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
Row(Modifier.fillMaxWidth().clickable { connectOnStartup = !connectOnStartup },
verticalAlignment = Alignment.CenterVertically) {
Text("Connect on startup", Modifier.weight(1f))
Switch(connectOnStartup, { connectOnStartup = it })
}
Row(Modifier.fillMaxWidth().clickable { myTeamSpeakFeatures = !myTeamSpeakFeatures },
verticalAlignment = Alignment.CenterVertically) {
Text("Enable myTeamSpeak features", Modifier.weight(1f))
Switch(myTeamSpeakFeatures, { myTeamSpeakFeatures = it })
}
Row(Modifier.fillMaxWidth().clickable { showWhisperControls = !showWhisperControls },
verticalAlignment = Alignment.CenterVertically) {
Text("Show whisper controls", Modifier.weight(1f))
Switch(showWhisperControls, { showWhisperControls = it })
}
}
}
}
/**
* The channel to join, typed or picked among [paths] of the server when we are on it,
* or taken from [current], the one we are in there.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ChannelField(channel: String, paths: List<String>, current: String?, onChange: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
// A channel already picked lists them all, for picking another.
val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) }
val expanded = open && matches.isNotEmpty()
ExposedDropdownMenuBox(expanded, { open = it }) {
OutlinedTextField(
channel, { onChange(it); open = true }, singleLine = true,
label = { Text("Channel") },
placeholder = { Text("Default") },
trailingIcon = {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { current?.let(onChange) }, enabled = current != null) {
PackIcon(listOf("MAKE_CURRENT_CHANNEL_DEFAULT", "CHANNEL_SWITCH"), "This channel")
}
if (paths.isNotEmpty()) ExposedDropdownMenuDefaults.TrailingIcon(expanded)
}
},
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
)
ExposedDropdownMenu(expanded, { open = false }) {
for (path in matches) {
DropdownMenuItem({ Text(path) }, onClick = {
open = false
onChange(path)
})
}
}
}
}
@@ -0,0 +1,212 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.ChannelCodec
import eu.lixko.ts3j.client.net.ChannelSettings
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/** The channel being edited ([channelId] > 0), or one to create below [parentId] (0: the top level). */
data class ChannelEdit(val channelId: Int, val parentId: Int = 0)
/**
* TeamSpeak's channel editor on one page: name, password, topic and description, then the
* channel's type, sorting, audio and limits. Only what changed is sent, as the server refuses
* an edit carrying one property we may not change.
*/
@Composable
fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> Unit) {
val creating = edit.channelId <= 0
val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
/** The channel as the server described it, which changes are measured against. */
var original by remember { mutableStateOf<ChannelSettings?>(null) }
var edited by remember { mutableStateOf<ChannelSettings?>(null) }
var passwordText by remember { mutableStateOf("") }
var saving by remember { mutableStateOf(false) }
LaunchedEffect(edit) {
if (creating) {
// Made from a channel's sheet, a channel is usually a throwaway one, as in TeamSpeak;
// the server puts a new channel after its siblings.
val fresh = ChannelSettings().apply {
type = ChannelSettings.Type.TEMPORARY
parentId = edit.parentId
order = server.sortChoices(0, edit.parentId).lastOrNull()?.id ?: 0
}
original = fresh
edited = fresh.copy()
} else {
server.channelSettings(edit.channelId)
.onSuccess { original = it; edited = it.copy() }
.onFailure { snackbar.showSnackbar("Could not read the channel: ${it.message}"); onDone() }
}
}
val change = { f: ChannelSettings.() -> Unit -> edited = edited?.copy()?.apply(f) }
val save = save@{
val e = edited ?: return@save
val o = original ?: return@save
if (e.name.isBlank()) {
scope.launch { snackbar.showSnackbar("The channel needs a name.") }
return@save
}
saving = true
scope.launch {
val trimmed = e.copy().apply { name = name.trim() }
val saved = if (creating) server.createChannel(edit.parentId, trimmed)
else server.editChannel(edit.channelId, trimmed.changesFrom(o))
saving = false
saved.onSuccess { onDone() }.onFailure {
snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + it.message)
}
}
}
val title = when {
!creating -> "Edit channel"
edit.parentId > 0 -> "New sub-channel"
else -> "New channel"
}
SubScreen(title, onBack = onDone, snackbar = snackbar, actions = {
TextButton(onClick = save, enabled = edited != null && !saving) { Text(if (creating) "Create" else "Save") }
}) { padding ->
val e = edited
if (e == null) {
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
return@SubScreen
}
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(e.name, { change { name = it } }, Modifier.fillMaxWidth(), label = { Text("Name") },
singleLine = true)
OutlinedTextField(passwordText, {
passwordText = it
change { password = it }
}, Modifier.fillMaxWidth(), label = { Text("Password") }, singleLine = true,
placeholder = if (e.hasPassword && e.password == null) ({ Text("Unchanged") }) else null,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
if (e.hasPassword && e.password == null) {
TextButton(onClick = { change { password = "" } }) { Text("Remove password") }
}
OutlinedTextField(e.topic, { change { topic = it } }, Modifier.fillMaxWidth(), label = { Text("Topic") },
singleLine = true)
OutlinedTextField(e.description, { change { description = it } }, Modifier.fillMaxWidth(),
label = { Text("Description") }, minLines = 3, maxLines = 10)
}
Section("Channel type")
Segments(listOf(
ChannelSettings.Type.TEMPORARY to "Temporary",
ChannelSettings.Type.SEMI_PERMANENT to "Semi-permanent",
ChannelSettings.Type.PERMANENT to "Permanent",
), e.type) { change { type = it } }
// The default channel cannot stop being one; another has to take over.
if (original?.defaultChannel != true) {
Toggle("Default channel", e.defaultChannel) { change { defaultChannel = it } }
}
val siblings = remember(edit) {
server.sortChoices(edit.channelId, edit.parentId).filter { it.id != edit.channelId }
}
Picker("Sort after", listOf(0 to "(first)") + siblings.map { it.id to it.name },
e.order.takeIf { o -> o == 0 || siblings.any { it.id == o } } ?: 0) { change { order = it } }
NumberField("Needed talk power", e.neededTalkPower, 0..9999) { change { neededTalkPower = it } }
Section("Audio")
val preset = ChannelCodec.Preset.of(e.codec, e.codecQuality)
var custom by remember { mutableStateOf(preset == null) }
val presets: List<Pair<ChannelCodec.Preset?, String>> =
ChannelCodec.Preset.entries.map { it to it.label } + (null to "Custom")
Segments(presets, if (custom) null else preset) { picked ->
custom = picked == null
if (picked != null) change { codec = picked.codec; codecQuality = picked.quality }
}
if (custom) {
Picker("Codec", ChannelCodec.NAMES.indices.map { it to ChannelCodec.NAMES[it] },
ChannelCodec.clampCodec(e.codec)) { change { codec = it } }
Level("Quality", e.codecQuality.toFloat(), 0f..ChannelCodec.MAX_QUALITY.toFloat(),
{ it.roundToInt().toString() }, steps = ChannelCodec.MAX_QUALITY - 1) {
change { codecQuality = it.roundToInt() }
}
}
Hint("Bandwidth: ${ChannelCodec.bandwidthText(e.codec, e.codecQuality)} per talking client")
Section("Advanced")
Column(Modifier.padding(horizontal = 16.dp)) {
OutlinedTextField(e.phoneticName, { change { phoneticName = it } }, Modifier.fillMaxWidth(),
label = { Text("Phonetic name") }, singleLine = true)
}
if (e.type == ChannelSettings.Type.TEMPORARY) {
NumberField("Delete delay (seconds)", e.deleteDelay, 0..ChannelSettings.MAX_DELETE_DELAY) {
change { deleteDelay = it }
}
}
Toggle("Voice encrypted", e.encrypted) { change { encrypted = it } }
Text("Max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
Segments(listOf(true to "Unlimited", false to "Limited"), e.maxClientsUnlimited) {
change { maxClientsUnlimited = it }
}
if (!e.maxClientsUnlimited) NumberField("Users", e.maxClients, 0..65535) { change { maxClients = it } }
Text("Family max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
val family = when {
e.familyInherited -> FamilyLimit.INHERITED
e.familyUnlimited -> FamilyLimit.UNLIMITED
else -> FamilyLimit.LIMITED
}
Segments(FamilyLimit.entries.map { it to it.label }, family) {
change {
familyInherited = it == FamilyLimit.INHERITED
familyUnlimited = it == FamilyLimit.UNLIMITED
}
}
if (family == FamilyLimit.LIMITED) {
NumberField("Users", e.maxFamilyClients, 0..65535) { change { maxFamilyClients = it } }
}
}
}
}
private enum class FamilyLimit(val label: String) { INHERITED("Inherited"), UNLIMITED("Unlimited"), LIMITED("Limited") }
/** A whole number within [range]; what does not parse leaves the value alone. */
@Composable
private fun NumberField(label: String, value: Int, range: IntRange, onChange: (Int) -> Unit) {
var text by remember(value) { mutableStateOf(value.toString()) }
Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(text, {
text = it.filter(Char::isDigit).take(7)
text.toIntOrNull()?.let { n -> onChange(n.coerceIn(range)) }
}, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
}
@@ -0,0 +1,366 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Surface
import androidx.compose.runtime.derivedStateOf
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.gfx.IconKeys
import eu.lixko.ts3j.client.net.ClientStatus
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
/** A channel's or a client's row. */
data class TreeRef(val channel: Boolean, val id: Int)
/** One line of the tree as the list shows it. */
private sealed interface TreeRow {
val ref: TreeRef
val key: String get() = (if (ref.channel) "c" else "u") + ref.id
data class Channel(val channel: ChannelItem, val depth: Int, val expanded: Boolean, val current: Boolean) : TreeRow {
override val ref get() = TreeRef(true, channel.id)
val expandable get() = channel.clients.isNotEmpty() || channel.children.isNotEmpty()
}
data class Client(val client: ClientItem, val depth: Int) : TreeRow {
override val ref get() = TreeRef(false, client.id)
}
}
/** The tree's channels and clients in reading order, leaving out what sits in folded channels. */
private fun flatten(tree: ServerTree, collapsed: Set<Int>, currentChannel: Int): List<TreeRow> {
val rows = ArrayList<TreeRow>()
fun add(channel: ChannelItem, depth: Int) {
val expanded = channel.id !in collapsed
rows += TreeRow.Channel(channel, depth, expanded, channel.id == currentChannel)
if (!expanded) return
channel.clients.forEach { rows += TreeRow.Client(it, depth + 1) }
channel.children.forEach { add(it, depth + 1) }
}
tree.channels.forEach { add(it, 0) }
return rows
}
private fun ChannelItem.holdsSelf(): Boolean = clients.any { it.self } || children.any { it.holdsSelf() }
/** Where the list shows our own client: its row, or the folded channel hiding it; -1 when it shows nowhere. */
private fun selfAnchor(rows: List<TreeRow>): Int = rows.indexOfFirst { row ->
when (row) {
is TreeRow.Client -> row.client.self
is TreeRow.Channel -> !row.expanded && row.channel.holdsSelf()
}
}
/** Which way our own row lies off screen. */
private enum class Offscreen { ABOVE, BELOW }
/** Floats over the tree's edge on the side our own row went off. */
@Composable
private fun BoxScope.ScrollToSelf(where: Offscreen?, onClick: () -> Unit) {
AnimatedVisibility(where == Offscreen.ABOVE, Modifier.align(Alignment.TopCenter).padding(top = 8.dp),
enter = slideInVertically { -it * 2 } + fadeIn(), exit = slideOutVertically { -it * 2 } + fadeOut()) {
ScrollToSelfChip(up = true, onClick)
}
AnimatedVisibility(where == Offscreen.BELOW, Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp),
enter = slideInVertically { it * 2 } + fadeIn(), exit = slideOutVertically { it * 2 } + fadeOut()) {
ScrollToSelfChip(up = false, onClick)
}
}
@Composable
private fun ScrollToSelfChip(up: Boolean, onClick: () -> Unit) {
Surface(onClick = onClick, shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer,
shadowElevation = 4.dp) {
Row(Modifier.padding(start = 10.dp, end = 14.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(18.dp).rotate(if (up) 180f else 0f))
Text("Me", style = MaterialTheme.typography.labelLarge)
}
}
}
@Composable
fun ChannelTree(
serverName: String,
tree: ServerTree,
collapsed: Set<Int>,
currentChannel: Int,
onToggle: (ChannelItem) -> Unit,
onChannel: (ChannelItem) -> Unit,
onChannelDoubleTap: (ChannelItem) -> Unit,
onClient: (ClientItem) -> Unit,
onServer: () -> Unit,
modifier: Modifier = Modifier,
/** A row to scroll to and flash, once the channels above it are expanded. */
reveal: TreeRef? = null,
onRevealed: () -> Unit = {},
/** The rows the find bar matched, and the one it is on, which a reveal does not flash. */
found: Set<TreeRef> = emptySet(),
foundCurrent: TreeRef? = null,
listState: LazyListState = rememberLazyListState(),
/** Brings our own client into view; its row may sit in folded channels. */
onShowSelf: () -> Unit = {},
/** Clients picked to be moved or kicked together. */
selected: Set<Int> = emptySet(),
/** Picks a client into [selected]; null when there is nothing to do with several. */
onClientLongPress: ((ClientItem) -> Unit)? = null,
) {
val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) }
var flashing by remember { mutableStateOf<TreeRef?>(null) }
LaunchedEffect(reveal, rows) {
val ref = reveal ?: return@LaunchedEffect
val index = rows.indexOfFirst { it.ref == ref }
if (index < 0) return@LaunchedEffect
// Index 0 is the server's row. The row ends up in the middle of the list.
val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2
listState.animateScrollToItem(index + 1, -middle)
if (ref != foundCurrent) flashing = ref
onRevealed()
}
LaunchedEffect(flashing) {
if (flashing != null) {
delay(1500)
flashing = null
}
}
val anchor = remember(rows) { selfAnchor(rows) }
val offscreen by remember(anchor) {
derivedStateOf {
if (anchor < 0) return@derivedStateOf null
val info = listState.layoutInfo
val index = anchor + 1 // past the server's row
val item = info.visibleItemsInfo.firstOrNull { it.index == index }
when {
item != null && item.offset >= info.viewportStartOffset &&
item.offset + item.size <= info.viewportEndOffset -> null
item != null -> if (item.offset < info.viewportStartOffset) Offscreen.ABOVE else Offscreen.BELOW
info.visibleItemsInfo.isEmpty() -> null
index < info.visibleItemsInfo.first().index -> Offscreen.ABOVE
else -> Offscreen.BELOW
}
}
}
Box(modifier.fillMaxSize()) {
LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 4.dp)) {
item(key = "server") {
RowLayout(depth = 0, onClick = onServer) {
PackIcon("SERVER_GREEN", null, size = ICON)
Text(serverName, Modifier.weight(1f), fontWeight = FontWeight.Bold, maxLines = 1,
overflow = TextOverflow.Ellipsis)
ServerIcon(tree.serverIconId, size = ICON)
}
}
items(rows, key = { it.key }) { row ->
val background = rowBackground(
when {
row.ref == flashing -> FLASH
!row.ref.channel && row.ref.id in selected -> MaterialTheme.colorScheme.secondaryContainer
row.ref == foundCurrent -> findCurrentColor()
row.ref in found -> findMatchColor()
else -> Color.Transparent
},
)
when (row) {
is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap)
is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient, onClientLongPress)
}
}
}
ScrollToSelf(offscreen, onShowSelf)
}
}
private val ICON = 16.dp
private val INDENT = 14.dp
private val ROW = 26.dp
/** Amber, see-through so the row's text keeps its own colour and contrast. */
private val FLASH = Color(0x80FFB300)
/** Fades in fast and out slowly, so a flash is seen. */
@Composable
private fun rowBackground(target: Color): Color {
val color by animateColorAsState(target, tween(if (target == FLASH) 150 else 600), label = "row")
return color
}
@Composable
private fun RowLayout(
depth: Int,
onClick: (() -> Unit)?,
background: Color = Color.Transparent,
/** The colour under [background], which a flash or find match goes over. */
tint: Color = Color.Transparent,
onDoubleClick: (() -> Unit)? = null,
onLongClick: (() -> Unit)? = null,
content: @Composable RowScope.() -> Unit,
) {
Row(
Modifier
.fillMaxWidth()
.background(tint)
.background(background)
.height(ROW)
.then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onLongClick = onLongClick, onClick = onClick) else Modifier)
.padding(start = 4.dp + INDENT * depth, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
ProvideTextStyle(MaterialTheme.typography.bodyMedium, content = { content() })
}
}
@Composable
private fun ChannelRow(
row: TreeRow.Channel,
background: Color,
onToggle: (ChannelItem) -> Unit,
onChannel: (ChannelItem) -> Unit,
onDoubleTap: (ChannelItem) -> Unit,
) {
val channel = row.channel
val spacer = channel.spacer
RowLayout(row.depth, onClick = { onChannel(channel) }, background = background,
onDoubleClick = if (spacer == null) ({ onDoubleTap(channel) }) else null) {
Box(
Modifier.fillMaxHeight().width(ICON + 4.dp)
.then(if (row.expandable) Modifier.clickable { onToggle(channel) } else Modifier),
contentAlignment = Alignment.Center,
) {
if (row.expandable) {
Icon(Icons.Filled.KeyboardArrowDown, if (row.expanded) "Collapse" else "Expand",
Modifier.size(ICON + 2.dp).rotate(if (row.expanded) 0f else -90f))
}
}
if (spacer != null) {
SpacerLabel(spacer.align(), spacer.caption().orEmpty(), Modifier.weight(1f))
} else {
PackIcon(IconKeys.channel(channel.locked, channel.full, channel.subscribed).asList(), null, size = ICON)
Text(
channel.name,
Modifier.weight(1f),
color = if (row.current) MaterialTheme.colorScheme.primary else Color.Unspecified,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
ServerIcon(channel.iconId, size = ICON)
}
}
}
/** A spacer's caption, placed as its tag asks; a repeated one of dashes or the like becomes a rule. */
@Composable
private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) {
if (align == '*') {
if (caption.isNotEmpty() && caption.all { it in "-_=.~" }) {
HorizontalDivider(modifier)
} else {
Text(caption.repeat(200 / caption.length.coerceAtLeast(1)), modifier, maxLines = 1, overflow = TextOverflow.Clip)
}
return
}
val textAlign = when (align) {
'c' -> TextAlign.Center
'r' -> TextAlign.End
else -> TextAlign.Start
}
Text(caption, modifier, textAlign = textAlign, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@Composable
private fun ClientRow(
row: TreeRow.Client,
countryFlags: Boolean,
background: Color,
onClient: (ClientItem) -> Unit,
onLongPress: ((ClientItem) -> Unit)?,
) {
val client = row.client
RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background),
onLongClick = onLongPress?.let { { it(client) } }) {
Spacer(Modifier.width(ICON + 4.dp))
StatusIcon(client.status)
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
client.name,
fontWeight = if (client.self) FontWeight.Bold else FontWeight.Normal,
color = when (client.highlight) {
ContactType.FRIEND -> StatusColors.friend
ContactType.BLOCKED -> StatusColors.blocked
else -> Color.Unspecified
},
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (client.awayMessage.isNotEmpty()) {
Text("[${client.awayMessage}]", Modifier.weight(1f, fill = false),
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
// TeamSpeak's order: talk power ahead of the groups, a talk request after them.
if (client.talker) PackIcon("IS_TALKER", "Talk power granted", size = ICON)
else if (client.lacksTalkPower) PackIcon("INPUT_MUTED", "Insufficient talk power", size = ICON)
for (id in client.groupIconIds) ServerIcon(id, size = ICON)
if (client.talkRequest) PackIcon("TALK_POWER_REQUEST", "Talk power requested", size = ICON)
// The country's flag comes last, at the row's edge.
if (countryFlags) CountryFlag(client.country)
}
}
@Composable
fun StatusIcon(status: ClientStatus, modifier: Modifier = Modifier) {
PackIcon(IconKeys.client(status), status.name, modifier, size = ICON)
}
@@ -0,0 +1,221 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Badge
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ChatLine
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.Chats
import eu.lixko.ts3j.client.android.Conversation
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.text.TextQuery
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
@Composable
fun ChatPane(
chats: Chats,
selected: Conversation,
canSend: Boolean,
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey) -> Unit,
onSend: (String) -> Unit,
/** Picks a file to share in [selected]. */
onAttach: () -> Unit,
onLink: (String) -> Unit,
modifier: Modifier = Modifier,
/** The lines to show, when not all of [selected]'s. */
lines: List<ChatLine> = selected.lines,
find: TextQuery = TextQuery.EMPTY,
/** The match the find bar is on. */
current: ChatMatch? = null,
/** A line to scroll to. */
reveal: Long? = null,
onRevealed: () -> Unit = {},
/** Whether a swipe over the lines goes to the neighbouring conversation. */
swipeTabs: Boolean = false,
/** For the lines, such as a swipe out of the chat. */
linesModifier: Modifier = Modifier,
) {
Column(modifier) {
val tabs = rememberLazyListState()
// A conversation picked by other means than its chip, such as a swipe, comes into view.
LaunchedEffect(selected.key) {
val index = chats.all.indexOfFirst { it.key == selected.key }
val info = tabs.layoutInfo
if (index >= 0 && info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
tabs.animateScrollToItem(index)
}
}
LazyRow(
state = tabs,
contentPadding = PaddingValues(horizontal = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(chats.all, key = { it.key.toString() }) { conversation ->
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
}
}
val swipe = rememberSwipeState()
SwipeHost(
swipe, selected.key,
neighbour = { key, dir ->
if (!swipeTabs) null
else chats.all.indexOfFirst { it.key == key }.takeIf { it >= 0 }?.let { chats.all.getOrNull(it + dir)?.key }
},
onSwipe = onSelect,
modifier = Modifier.weight(1f).then(linesModifier).swipeSource(swipe),
) { key ->
// Each conversation opens at its newest line; the one beside it while swiping shows all of its own.
if (key == selected.key) Lines(lines, onLink, Modifier.fillMaxSize(), find, current, reveal, onRevealed)
else chats[key]?.let { Lines(it.lines, onLink, Modifier.fillMaxSize(), TextQuery.EMPTY, null, null) {} }
}
// One unsent message per conversation, kept while another one is on screen.
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
val draftKey = selected.key.toString()
val draft = drafts[draftKey].orEmpty()
val send = {
if (draft.isNotBlank()) {
onSend(draft.trim())
drafts.remove(draftKey)
}
}
Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onAttach, enabled = canSend) {
Icon(Icons.Filled.AttachFile, "Share file")
}
OutlinedTextField(
draft, { drafts[draftKey] = it },
Modifier.weight(1f).onPreviewKeyEvent { e ->
// A hardware keyboard's Enter sends, as on the desktop; Shift+Enter starts a new line.
val enter = e.key == Key.Enter && !e.isShiftPressed
if (enter && e.type == KeyEventType.KeyDown) send()
enter
},
placeholder = { Text("Message ${selected.title}", maxLines = 1, overflow = TextOverflow.Ellipsis) },
enabled = canSend,
maxLines = 4,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
)
IconButton(onClick = send, enabled = canSend && draft.isNotBlank()) {
Icon(Icons.AutoMirrored.Filled.Send, "Send")
}
}
}
}
private val DraftsSaver = Saver<SnapshotStateMap<String, String>, HashMap<String, String>>(
save = { HashMap(it) },
restore = { mutableStateMapOf<String, String>().apply { putAll(it) } },
)
@Composable
private fun ConversationChip(
conversation: Conversation,
selected: Boolean,
onSelect: (ChatKey) -> Unit,
onClose: (ChatKey) -> Unit,
) {
val key = conversation.key
FilterChip(
selected = selected,
onClick = { onSelect(key) },
label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingIcon = if (conversation.unread) ({ Badge() }) else null,
trailingIcon = if (key.isPrivate) ({
Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) })
}) else null,
)
}
/** The conversation's lines, following new ones while the newest is in view. */
@Composable
private fun Lines(
lines: List<ChatLine>,
onLink: (String) -> Unit,
modifier: Modifier,
find: TextQuery,
current: ChatMatch?,
reveal: Long?,
onRevealed: () -> Unit,
) {
val listState = rememberLazyListState(initialFirstVisibleItemIndex = (lines.size - 1).coerceAtLeast(0))
val link by rememberUpdatedState(onLink)
// Following the end until the user scrolls away from it, so a restored log, new lines
// and pictures that load late all keep the newest line in view.
var follow by remember { mutableStateOf(true) }
LaunchedEffect(listState) {
snapshotFlow { listState.isScrollInProgress }.drop(1).filter { !it }
.collect { follow = !listState.canScrollForward }
}
LaunchedEffect(listState) {
snapshotFlow { follow && listState.canScrollForward && !listState.isScrollInProgress }.filter { it }
.collect { listState.scrollToItem(listState.layoutInfo.totalItemsCount - 1, Int.MAX_VALUE) }
}
LaunchedEffect(reveal, lines) {
val id = reveal ?: return@LaunchedEffect
val index = lines.indexOfFirst { it.id == id }
if (index < 0) return@LaunchedEffect
val info = listState.layoutInfo
if (info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
// The line's top ends up in the middle of the list.
val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2
listState.animateScrollToItem(index, -middle)
}
onRevealed()
}
LazyColumn(modifier.fillMaxWidth(), state = listState, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) {
items(lines, key = { it.id }) { line ->
RichText(line.html, { link(it) }, Modifier.padding(vertical = 2.dp), MaterialTheme.typography.bodyMedium,
find, if (current?.line == line.id) current.nth else -1)
}
}
}
@@ -0,0 +1,318 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.fromHtml
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.WebPictures
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.text.BBCode
import eu.lixko.ts3j.client.text.ChatHtml
import eu.lixko.ts3j.client.text.TextQuery
/**
* HTML as [BBCode][eu.lixko.ts3j.client.text.BBCode] and [ChatHtml] write it, with its rules as dividers
* and its pictures fetched from the web: Android's HTML parser shows neither, so the text is
* split at them.
*/
@Composable
fun RichText(
html: String,
onLink: (String) -> Unit,
modifier: Modifier = Modifier,
style: TextStyle = LocalTextStyle.current,
/** Matches to highlight: [current] is the index of the one the find bar is on, if it is here. */
find: TextQuery = TextQuery.EMPTY,
current: Int = -1,
) {
val link by rememberUpdatedState(onLink)
val color = linkColor()
val parsed = remember(html, color) { split(html) { chatText(it, color) { href -> link(href) } } }
val match = findMatchColor()
val currentMatch = findCurrentColor()
val pieces = remember(parsed, find, current, match, currentMatch) {
if (find.isEmpty) parsed else highlight(parsed, find, current, match, currentMatch)
}
Column(modifier) {
for (piece in pieces) {
when (piece) {
Piece.Rule -> HorizontalDivider(Modifier.padding(vertical = 6.dp))
is Piece.Image -> WebPicture(piece, style) { link(it) }
// As wide as there is room, for aligned paragraphs to have somewhere to go.
is Piece.Text -> if (piece.text.isNotEmpty()) Text(piece.text, Modifier.fillMaxWidth(), style = style)
}
}
}
}
/** [pieces] with [find]'s matches behind [match], and the [current]th of them, counting across pieces, behind [currentMatch]. */
private fun highlight(pieces: List<Piece>, find: TextQuery, current: Int, match: Color, currentMatch: Color): List<Piece> {
var n = 0
return pieces.map { piece ->
if (piece !is Piece.Text) return@map piece
val m = find.matcher(piece.text.text) ?: return@map piece
val text = AnnotatedString.Builder(piece.text)
while (m.find()) {
if (m.end() == m.start()) continue
text.addStyle(SpanStyle(background = if (n == current) currentMatch else match), m.start(), m.end())
n++
}
Piece.Text(text.toAnnotatedString())
}
}
/** The web pictures descriptions show. */
val LocalWebPictures = staticCompositionLocalOf<WebPictures?> { null }
private sealed interface Piece {
data class Text(val text: AnnotatedString) : Piece
data object Rule : Piece
/** @param href where the picture links to, if it sits in a link */
data class Image(val url: String, val href: String?, val align: Alignment.Horizontal) : Piece
}
/**
* [html] cut at its rules and pictures. Each piece of text is closed where it is cut and the
* next reopens what it was in, so an aligned block or a link carries on past a picture.
*/
private fun split(html: String, text: (String) -> AnnotatedString): List<Piece> {
val pieces = ArrayList<Piece>()
val divs = ArrayList<String>()
var anchor: String? = null
var href: String? = null
val current = StringBuilder()
fun cut() {
if (anchor != null) current.append("</a>")
repeat(divs.size) { current.append("</div>") }
pieces += Piece.Text(text(current.toString()))
current.setLength(0)
divs.forEach { current.append(it) }
anchor?.let { current.append(it) }
}
var last = 0
for (m in CUT_TAG.findAll(html)) {
current.append(html, last, m.range.first)
last = m.range.last + 1
val tag = m.value
when {
tag.startsWith("<hr", ignoreCase = true) -> {
cut()
pieces += Piece.Rule
}
tag.startsWith("<img", ignoreCase = true) -> {
cut()
pieces += Piece.Image(unescape(m.groupValues[1]), href?.let(::unescape), alignment(divs))
}
tag.startsWith("<div", ignoreCase = true) -> {
divs += tag
current.append(tag)
}
tag.equals("</div>", ignoreCase = true) -> {
divs.removeLastOrNull()
current.append(tag)
}
tag.startsWith("<a", ignoreCase = true) -> {
anchor = tag
href = m.groupValues[2]
current.append(tag)
}
else -> {
anchor = null
href = null
current.append(tag)
}
}
}
current.append(html, last, html.length)
pieces += Piece.Text(text(current.toString()))
return pieces
}
/** Where the innermost aligned block puts what is in it. */
private fun alignment(divs: List<String>): Alignment.Horizontal {
val align = divs.asReversed().firstNotNullOfOrNull { ALIGN.find(it)?.groupValues?.get(1) }
return when (align) {
"center" -> Alignment.CenterHorizontally
"right" -> Alignment.End
else -> Alignment.Start
}
}
private fun unescape(s: String) =
s.replace("&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,246 @@
package eu.lixko.ts3j.client.android.ui
import android.graphics.BitmapFactory
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.BookmarkManager
import eu.lixko.ts3j.client.android.IdentityInfo
import eu.lixko.ts3j.client.android.IdentityManager
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.net.IconRepository
/** Where to connect to: an address typed in, or a bookmark. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConnectScreen(
sessions: SessionController,
bookmarkManager: BookmarkManager,
identityManager: IdentityManager,
account: MyTeamSpeakAccount,
snackbar: SnackbarHostState,
onSettings: () -> Unit,
onMyTeamSpeak: () -> Unit,
onConnect: (() -> Unit) -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
/** Back to the servers already connected; null when there are none. */
onBack: (() -> Unit)?,
) {
val lastEnd by sessions.lastEnd.collectAsStateWithLifecycle()
val bookmarks by bookmarkManager.all.collectAsStateWithLifecycle()
val identities by identityManager.all.collectAsStateWithLifecycle()
val myTeamSpeakSignedIn by account.signedIn.collectAsStateWithLifecycle()
var address by rememberSaveable { mutableStateOf(sessions.lastAddress) }
var identityId by rememberSaveable { mutableStateOf("") }
var nickname by rememberSaveable { mutableStateOf(identityManager.nicknameFor("")) }
var password by rememberSaveable { mutableStateOf("") }
if (onBack != null) BackHandler(onBack = onBack)
Scaffold(
topBar = {
TopAppBar(
title = { Text("TeamSpook TS3j") },
navigationIcon = {
if (onBack != null) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
},
actions = {
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
},
)
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
LazyColumn(
Modifier.padding(padding).imePadding(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
item {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") },
singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri))
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
singleLine = true)
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(),
label = { Text("Server password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) {
identityId = it
nickname = identityManager.nicknameFor(it)
}
lastEnd?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(
onClick = { onConnect { sessions.connect(address.trim(), nickname.trim(), password, identityId) } },
enabled = address.isNotBlank() && nickname.isNotBlank(),
) { Text("Connect") }
TextButton(onClick = {
onEditBookmark(BookmarkEdit(-1, bookmarkManager.newBookmark(address.trim(), nickname.trim(), password, identityId)))
}, enabled = address.isNotBlank()) { Text("Add bookmark") }
}
}
}
if (bookmarks.isNotEmpty()) {
item {
Text("Bookmarks", Modifier.padding(top = 16.dp), style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary)
}
} else {
item {
OutlinedButton(onClick = onMyTeamSpeak, Modifier.padding(top = 16.dp)) {
Text(if (myTeamSpeakSignedIn) "Import from myTeamSpeak" else "Sign in to myTeamSpeak")
}
}
}
itemsIndexed(bookmarks) { index, bookmark ->
BookmarkRow(bookmark, identities, { onConnect { sessions.connect(bookmark) } },
onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) },
onPin = if (bookmarkManager.canPinShortcuts) ({ bookmarkManager.pinShortcut(bookmark) }) else null,
onRemove = { bookmarkManager.remove(bookmark) })
}
}
}
}
/** The identities to connect with, the default one first as an empty id. */
private fun identityChoices(identities: List<IdentityInfo>): List<Pair<String, String>> {
val default = identities.firstOrNull { it.isDefault }?.name
return listOf("" to (default?.let { "Default ($it)" } ?: "Default")) + identities.map { it.id to it.name }
}
/** An id no longer among the identities connects with the default, and shows as such. */
private fun shownId(identities: List<IdentityInfo>, id: String) = id.takeIf { i -> identities.any { it.id == i } } ?: ""
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun IdentityField(identities: List<IdentityInfo>, selected: String, onSelect: (String) -> Unit) {
val choices = identityChoices(identities)
val shown = shownId(identities, selected)
var open by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(open, { open = it }) {
OutlinedTextField(
choices.first { it.first == shown }.second, {}, readOnly = true, singleLine = true,
label = { Text("Identity") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) },
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
)
ExposedDropdownMenu(open, { open = false }) {
for ((id, name) in choices) {
DropdownMenuItem({ Text(name) }, onClick = {
open = false
onSelect(id)
})
}
}
}
}
/** The server's icon as last seen there, else the pack's bookmark icon. */
@Composable
private fun BookmarkIcon(iconId: Long) {
val cached = remember(iconId) {
IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }
}
if (cached != null) Image(cached, null, Modifier.size(24.dp))
else PackIcon("BOOKMARK_MANAGER", null)
}
private val AUTOCONNECT = Color(0xFF3A9D4A)
@Composable
private fun BookmarkRow(
bookmark: Bookmark,
identities: List<IdentityInfo>,
onConnect: () -> Unit,
onEdit: () -> Unit,
/** Null when the launcher takes no shortcuts. */
onPin: (() -> Unit)?,
onRemove: () -> Unit,
) {
val identity = identities.firstOrNull { it.id == bookmark.identityId }
var menu by remember { mutableStateOf(false) }
ListItem(
headlineContent = {
Text(buildAnnotatedString {
if (bookmark.connectOnStartup) {
withStyle(SpanStyle(color = AUTOCONNECT, fontWeight = FontWeight.Bold)) { append("AC") }
append(' ')
}
append(bookmark.displayName())
})
},
supportingContent = {
Text(listOfNotNull(bookmark.hostPort(), bookmark.channel.ifBlank { null }, identity?.name)
.joinToString(" · "))
},
leadingContent = { BookmarkIcon(bookmark.iconId) },
trailingContent = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Bookmark options") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Edit") }, onClick = { menu = false; onEdit() })
onPin?.let { DropdownMenuItem({ Text("Add to home screen") }, onClick = { menu = false; it() }) }
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; onRemove() })
}
}
},
modifier = Modifier.clickable(onClick = onConnect),
)
}
@@ -0,0 +1,150 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.ConnectionStats
import eu.lixko.ts3j.client.net.ConnectionStatsFormat
import kotlinx.coroutines.delay
private const val REFRESH_MS = 1000L
private val TABS = ConnectionStatsFormat.TRAFFIC_TABS.map { it.title() } +
listOf(ConnectionStatsFormat.QUOTA_TAB, ConnectionStatsFormat.VOICE_TAB)
/**
* A client's connection figures, read again every second while shown, laid out as TeamSpeak's
* Connection Info window: name, times, ping and address beside the avatar, then a tab per
* traffic category with Total / In / Out columns, Quota, and what our playback made of their voice.
*/
@Composable
fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) {
var stats by remember { mutableStateOf<ConnectionStats?>(null) }
LaunchedEffect(clientId) {
while (true) {
stats = server.connectionStats(clientId) ?: break
delay(REFRESH_MS)
}
}
var tab by rememberSaveable { mutableIntStateOf(0) }
val s = stats
SubScreen("Connection info", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Summary(s, client?.nickname ?: "", Modifier.weight(1f))
if (client != null && client.avatarFlag.isNotEmpty()) {
Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp)
}
}
PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) {
TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) }
}
val traffic = ConnectionStatsFormat.TRAFFIC_TABS
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
when {
tab < traffic.size -> TrafficTable(ConnectionStatsFormat.trafficRows(s, traffic[tab].kind()))
tab == traffic.size -> Figures(ConnectionStatsFormat.quotaGroups(s))
else -> Figures(listOf(ConnectionStatsFormat.voiceRows(s?.voiceReceived)))
}
}
}
}
}
@Composable
private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) {
val context = LocalContext.current
val address = ConnectionStatsFormat.copyableAddress(s)
val rows = ConnectionStatsFormat.summaryRows(s, nickname)
Column(modifier) {
rows.forEachIndexed { i, row ->
Row(Modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(row.value, textAlign = TextAlign.End)
if (i == rows.lastIndex) {
IconButton(
onClick = {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Client address", address))
},
enabled = address != null,
modifier = Modifier.size(32.dp),
) { PackIcon("COPY", "Copy client address", size = 18.dp) }
}
}
}
}
}
/** Labelled figures in groups set apart by a rule. */
@Composable
private fun Figures(groups: List<List<ConnectionStatsFormat.Row>>) {
groups.forEachIndexed { g, rows ->
if (g > 0) HorizontalDivider(Modifier.padding(vertical = 8.dp))
for (row in rows) {
Row(Modifier.padding(vertical = 4.dp)) {
Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(row.value, textAlign = TextAlign.End)
}
}
}
}
@Composable
private fun TrafficTable(rows: List<ConnectionStatsFormat.TrafficRow>) {
Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
LabelCell("")
ConnectionStatsFormat.COLUMNS.forEachIndexed { i, column -> ValueCell(column, i == 0, FontStyle.Italic) }
}
for (row in rows) {
Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
LabelCell(row.label)
ValueCell(row.total, narrow = true)
ValueCell(row.`in`)
ValueCell(row.out)
}
}
}
@Composable
private fun RowScope.LabelCell(text: String) =
Text(text, Modifier.weight(1.5f), color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall)
/** The Total column only ever holds the loss percentage. */
@Composable
private fun RowScope.ValueCell(text: String, narrow: Boolean = false, fontStyle: FontStyle? = null) =
Text(text, Modifier.weight(if (narrow) 0.7f else 1f), style = MaterialTheme.typography.bodySmall, fontStyle = fontStyle,
textAlign = TextAlign.End)
@@ -0,0 +1,274 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ContactManager
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.contacts.NicknameDisplay
import java.time.format.DateTimeFormatter
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
private val DISPLAYS = listOf(
NicknameDisplay.ONLY_NICKNAME to "Nickname",
NicknameDisplay.ONLY_CUSTOM to "Custom name",
NicknameDisplay.BOTH to "Both",
)
private val GROUPS = listOf(
ContactType.FRIEND to "Friends",
ContactType.BLOCKED to "Blocked",
ContactType.NEUTRAL to "Neutral",
)
/**
* The contact list, grouped as TeamSpeak's Contacts window groups it, with each
* contact's own page and the defaults new contacts start out with.
*
* @param editing the unique id of the contact whose page is open, if any
*/
@Composable
fun ContactsScreen(contacts: ContactManager, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) {
var defaults by rememberSaveable { mutableStateOf(false) }
when {
editing != null -> return ContactScreen(contacts, editing, onBack = { onEdit(null) })
defaults -> return ContactDefaultsScreen(contacts, onBack = { defaults = false })
}
val all by contacts.all.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
var imported by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
imported = runCatching { contacts.import(uri) }.fold(
{ (found, added) ->
if (found == 0) "That file holds no contacts."
else "Imported $found contacts, $added of them new."
},
{ "That file is not a TeamSpeak 3 settings.db." },
)
}
}
SubScreen("Contacts", onBack, actions = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Defaults for new contacts") }, onClick = { menu = false; defaults = true })
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
menu = false
importer.launch(arrayOf("*/*"))
})
}
}
}) { padding ->
LazyColumn(Modifier.padding(padding)) {
imported?.let { item { Hint(it) } }
if (all.isEmpty()) {
item {
Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " +
"or import the contacts of TeamSpeak 3 from its settings.db.")
}
}
for ((type, title) in GROUPS) {
val group = all.filter { it.type == type }.sortedBy { label(it).lowercase() }
if (group.isEmpty()) continue
item(key = type) { Section(title) }
items(group, key = { it.key() }) { contact ->
ListItem(
headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
supportingContent = { Text(lastSeen(contact)) },
modifier = Modifier.clickable { onEdit(contact.key()) },
)
}
}
}
}
}
/** One contact's settings; each is stored as it is changed, the names once the page is left. */
@Composable
private fun ContactScreen(contacts: ContactManager, uniqueId: String, onBack: () -> Unit) {
val all by contacts.all.collectAsStateWithLifecycle()
// A client's unique id may stand for a contact filed under its myTeamSpeak ID.
val key = remember(uniqueId) { contacts.find(uniqueId)?.key() ?: uniqueId }
val contact = all.firstOrNull { it.key() == key }
if (contact == null) {
LaunchedEffect(Unit) { onBack() }
return
}
// Starts from the stored entry, which may have been seen again since this page opened.
fun edit(change: Contact.() -> Unit) {
contacts.find(key)?.let { contacts.save(it.apply(change)) }
}
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
var removing by remember { mutableStateOf(false) }
val leave = {
if (customName.trim() != contact.nickname || phoneticName.trim() != contact.phoneticNickname) {
edit {
nickname = customName.trim()
phoneticNickname = phoneticName.trim()
}
}
onBack()
}
SubScreen(label(contact), leave, actions = {
IconButton(onClick = { removing = true }) { PackIcon(if (contact.type == ContactType.BLOCKED) "REMOVE_FOE" else "REMOVE_FRIEND", "Remove from contacts") }
}) { padding ->
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
OutlinedTextField(customName, { customName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
label = { Text("Custom nickname") }, singleLine = true)
OutlinedTextField(phoneticName, { phoneticName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
label = { Text("Phonetic nickname") }, singleLine = true)
Section("Contact")
Segments(GROUPS.map { (type, _) -> type to type.label() }, contact.type) { edit { type = it } }
Section("Show as")
Segments(DISPLAYS, contact.nicknameDisplay) { edit { nicknameDisplay = it } }
Section("Ignore")
Toggle("Mute", contact.automute) { edit { automute = it } }
Toggle("Ignore server and channel chat", contact.ignorePublicMessages) { edit { ignorePublicMessages = it } }
Toggle("Ignore private chat", contact.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
Toggle("Ignore pokes", contact.ignorePokes) { edit { ignorePokes = it } }
Toggle("Hide avatar", contact.ignoreAvatar) { edit { ignoreAvatar = it } }
Toggle("Hide away message", contact.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
Toggle("Deny whisper", !contact.whisperAllowed) { edit { whisperAllowed = !it } }
Section("Playback")
val volume = if (contact.hasVolumeModifier) contact.volumeModifier.toFloat() else 0f
Level("Volume", volume, -30f..20f, ::formatVolume) { db ->
val rounded = db.roundToInt().toDouble()
edit {
hasVolumeModifier = rounded != 0.0
volumeModifier = rounded
}
}
Section("Details")
val context = LocalContext.current
val idLabel = if (contact.uniqueId.isEmpty()) "myTeamSpeak ID" else "Unique ID"
LinkRow(idLabel, contact.shownId()) {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText(idLabel, contact.shownId()))
}
ListItem(headlineContent = { Text(lastSeen(contact)) })
}
}
if (removing) {
AlertDialog(
onDismissRequest = { removing = false },
title = { Text("Remove ${label(contact)}?") },
text = { Text("Their settings here are forgotten; they show as anyone else again.") },
confirmButton = {
TextButton(onClick = {
removing = false
contacts.remove(key)
onBack()
}) { Text("Remove") }
},
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
)
}
}
/** What a client starts out with when added as a friend, blocked or neutral. */
@Composable
private fun ContactDefaultsScreen(contacts: ContactManager, onBack: () -> Unit) {
val defaults = contacts.defaults
var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) }
var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) }
fun edit(change: ContactDefaults.Entry.() -> Unit) {
val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() }
defaults.of(tab).copyFrom(changed)
contacts.saveDefaults()
entry = changed
}
SubScreen("Defaults for new contacts", onBack) { padding ->
Column(Modifier.padding(padding)) {
PrimaryTabRow(selectedTabIndex = GROUPS.indexOfFirst { it.first == tab }) {
for ((type, title) in GROUPS) Tab(tab == type, onClick = { tab = type }, text = { Text(title) })
}
Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Show as")
Segments(DISPLAYS, entry.nicknameDisplay) { edit { nicknameDisplay = it } }
Section("Ignore")
Toggle("Mute", entry.automute) { edit { automute = it } }
Toggle("Ignore server and channel chat", entry.ignorePublicMessages) { edit { ignorePublicMessages = it } }
Toggle("Ignore private chat", entry.ignorePrivateMessages) { edit { ignorePrivateMessages = it } }
Toggle("Ignore pokes", entry.ignorePokes) { edit { ignorePokes = it } }
Toggle("Hide avatar", entry.ignoreAvatar) { edit { ignoreAvatar = it } }
Toggle("Hide away message", entry.ignoreAwayMessage) { edit { ignoreAwayMessage = it } }
Toggle("Deny whisper", entry.ignoreWhisper) { edit { ignoreWhisper = it } }
}
}
}
}
private fun label(contact: Contact) = contact.label()
private fun lastSeen(contact: Contact): String {
val seen = contact.lastSeen ?: return "Never seen"
val where = contact.lastSeenServerName.ifBlank { contact.lastSeenServerAddress }
return "Last seen ${SEEN.format(seen)}" + if (where.isNotBlank()) " on $where" else ""
}
private fun formatVolume(db: Float): String {
val rounded = db.roundToInt()
return if (rounded == 0) "Unchanged" else "${if (rounded > 0) "+" else ""}$rounded dB"
}
private fun typeColor(type: ContactType): Color = when (type) {
ContactType.FRIEND -> StatusColors.friend
ContactType.BLOCKED -> StatusColors.blocked
ContactType.NEUTRAL -> Color.Unspecified
}
@@ -0,0 +1,137 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.net.Details
import eu.lixko.ts3j.client.text.BBCode
/**
* The facts of the server, a channel or a client, then its description, for the top of its sheet.
* The minor facts wait behind "more…".
*/
@Composable
fun DetailsSection(details: Details, onLink: (String) -> Unit, modifier: Modifier = Modifier) {
var all by rememberSaveable(details.title()) { mutableStateOf(false) }
val shown = if (all) details.fields() else details.fields().filterNot { it.minor() }
val more = !all && shown.size < details.fields().size
Column(modifier.padding(horizontal = 24.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (shown.isNotEmpty() || more) {
Column(Modifier.animateContentSize(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
for (field in shown) Fact(field)
if (more) {
Text("more…", Modifier.clickable { all = true }.padding(vertical = 2.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
}
}
}
when {
details.description().isNotBlank() -> Description(details.description(), onLink)
details.pending() -> Text("Loading description…", style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun Fact(field: Details.Field) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(field.label(), Modifier.width(96.dp), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (field.groups().isEmpty()) {
Text(field.value(), style = MaterialTheme.typography.bodySmall)
} else {
// Each group with its icon, as TeamSpeak's info frame lists them.
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
// A nameless group shows only its icon, and takes no comma.
val lastNamed = field.groups().indexOfLast { it.name.isNotBlank() }
field.groups().forEachIndexed { i, group ->
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
ServerIcon(group.iconId, size = 14.dp)
if (group.name.isNotBlank()) {
Text(group.name.trim() + if (i < lastNamed) "," else "", style = MaterialTheme.typography.bodySmall)
}
}
}
}
}
}
}
/** The description in a box that opens up, when there is more of it than fits folded. */
@Composable
private fun Description(bbcode: String, onLink: (String) -> Unit) {
val html = remember(bbcode) { BBCode.toHtml(bbcode, true) }
var expanded by rememberSaveable(bbcode) { mutableStateOf(false) }
var overflows by remember(bbcode) { mutableStateOf(false) }
val expandable = overflows || expanded
val background = MaterialTheme.colorScheme.surfaceContainerHigh
Surface(
Modifier.fillMaxWidth().then(if (expandable) Modifier.clickable { expanded = !expanded } else Modifier),
shape = RoundedCornerShape(12.dp),
color = background,
) {
Column(Modifier.animateContentSize().padding(12.dp)) {
Box {
Folded(FOLDED_HEIGHT, expanded, onOverflow = { overflows = it }) {
RichText(html, onLink, style = MaterialTheme.typography.bodyMedium)
}
if (overflows && !expanded) {
Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(24.dp)
.background(Brush.verticalGradient(listOf(Color.Transparent, background))))
}
}
if (expandable) {
Text(if (expanded) "Less" else "More", Modifier.padding(top = 4.dp),
style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
}
}
}
}
/** Its content cut to [height] unless [open], telling whether there is more of it than that. */
@Composable
private fun Folded(height: Dp, open: Boolean, onOverflow: (Boolean) -> Unit, content: @Composable () -> Unit) {
val report by rememberUpdatedState(onOverflow)
Layout(content, Modifier.clipToBounds()) { measurables, constraints ->
val placeable = measurables.first().measure(constraints.copy(maxHeight = Constraints.Infinity))
val limit = height.roundToPx()
report(placeable.height > limit)
val shown = if (open) placeable.height else minOf(placeable.height, limit)
layout(placeable.width, shown) { placeable.place(0, 0) }
}
}
private val FOLDED_HEIGHT = 128.dp
@@ -0,0 +1,238 @@
package eu.lixko.ts3j.client.android.ui
import android.text.format.DateUtils
import android.text.format.Formatter
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.TransferRow
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import kotlinx.coroutines.launch
/** A channel's file repository: folders to walk, files to download, upload, rename and delete. */
@Composable
fun FilesScreen(server: ServerController, channelId: Int, channelName: String, password: String, onBack: () -> Unit) {
val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
var path by rememberSaveable { mutableStateOf("/") }
var files by remember { mutableStateOf<List<RemoteFile>?>(null) }
var failure by remember { mutableStateOf<String?>(null) }
var reloads by remember { mutableIntStateOf(0) }
val transfers by server.files.rows.collectAsStateWithLifecycle()
var downloading by remember { mutableStateOf<RemoteFile?>(null) }
var creatingFolder by remember { mutableStateOf(false) }
var renaming by remember { mutableStateOf<RemoteFile?>(null) }
var deleting by remember { mutableStateOf<RemoteFile?>(null) }
LaunchedEffect(path, reloads) {
failure = null
server.listFiles(channelId, password, path)
.onSuccess { list -> files = list.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) }
.onFailure { files = emptyList(); failure = it.message ?: "Could not list the files" }
}
// An upload into the folder on screen shows up once it is there.
val uploadedHere = transfers.count { it.upload && it.channelId == channelId && it.directory == path && it.state == FileTransfer.State.COMPLETED }
LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ }
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
val act = { call: suspend () -> Result<Unit> ->
scope.launch {
call().onSuccess { reloads++ }.onFailure { snackbar.showSnackbar(it.message ?: it.javaClass.simpleName) }
}
Unit
}
val saver = rememberLauncherForActivityResult(SaveAs) { uri ->
val file = downloading
downloading = null
if (uri != null && file != null) server.files.download(channelId, password, file, uri)
}
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
runCatching { server.files.upload(channelId, password, path, uri) }
.onFailure { tell("Could not read the file: ${it.message}") }
}
}
SubScreen(channelName, onBack = { if (path == "/") onBack() else path = parentOf(path) }, snackbar = snackbar, actions = {
IconButton(onClick = { creatingFolder = true }) { PackIcon("ADD_FOLDER", "New folder") }
IconButton(onClick = { picker.launch(arrayOf("*/*")) }) { PackIcon("UPLOAD", "Upload") }
IconButton(onClick = { reloads++ }) { PackIcon(listOf("FILE_REFRESH", "REFRESH"), "Refresh") }
}) { padding ->
Column(Modifier.padding(padding).fillMaxSize()) {
Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { path = parentOf(path) }, enabled = path != "/") { PackIcon("FILE_UP", "Up") }
Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium)
}
HorizontalDivider()
Box(Modifier.weight(1f).fillMaxWidth()) {
val list = files
when {
list == null -> CircularProgressIndicator(Modifier.align(Alignment.Center))
list.isEmpty() -> Text(failure ?: "No files", Modifier.align(Alignment.Center).padding(24.dp),
color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
else -> LazyColumn {
items(list, key = { it.fullPath }) { file ->
FileRow(file,
onOpen = {
if (file.isDirectory) path = file.fullPath + "/"
else { downloading = file; saver.launch(file.name) }
},
onRename = { renaming = file },
onDelete = { deleting = file })
}
}
}
}
if (transfers.isNotEmpty()) Transfers(transfers, server.files::cancel, server.files::clearFinished)
}
}
if (creatingFolder) {
TextPrompt("New folder", "Name", "Create", onDismiss = { creatingFolder = false }, onConfirm = { name ->
creatingFolder = false
if (name.isNotBlank()) act { server.createDirectory(channelId, password, path + name.trim()) }
})
}
renaming?.let { file ->
TextPrompt("Rename", "Name", "Rename", initial = file.name, onDismiss = { renaming = null }, onConfirm = { name ->
renaming = null
if (name.isNotBlank() && name != file.name) {
act { server.renameFile(channelId, password, file.fullPath, file.parentPath + name.trim()) }
}
})
}
deleting?.let { file ->
AlertDialog(
onDismissRequest = { deleting = null },
title = { Text("Delete ${file.name}?") },
text = if (file.isDirectory) ({ Text("Everything in the folder goes with it.") }) else null,
confirmButton = {
TextButton(onClick = {
deleting = null
act { server.deleteFile(channelId, password, file.fullPath) }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } },
)
}
}
private fun parentOf(path: String): String {
val trimmed = path.removeSuffix("/")
val slash = trimmed.lastIndexOf('/')
return if (slash <= 0) "/" else trimmed.substring(0, slash + 1)
}
@Composable
private fun FileRow(file: RemoteFile, onOpen: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) {
val context = LocalContext.current
var menu by remember { mutableStateOf(false) }
val modified = if (file.lastModifiedEpochSec > 0) {
DateUtils.formatDateTime(context, file.lastModifiedEpochSec * 1000,
DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH)
} else null
ListItem(
headlineContent = { Text(file.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Text(listOfNotNull(if (file.isDirectory) null else Formatter.formatShortFileSize(context, file.size), modified)
.joinToString(" · "))
},
leadingContent = { PackIcon(if (file.isDirectory) listOf("FOLDER") else listOf("FILE", "FILETRANSFER"), null) },
trailingContent = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "File options") }
DropdownMenu(menu, { menu = false }) {
if (!file.isDirectory) DropdownMenuItem({ Text("Download") }, onClick = { menu = false; onOpen() })
DropdownMenuItem({ Text("Rename") }, onClick = { menu = false; onRename() })
DropdownMenuItem({ Text("Delete") }, onClick = { menu = false; onDelete() })
}
}
},
modifier = Modifier.clickable(onClick = onOpen),
)
}
/** The transfers under way and done, newest last. */
@Composable
private fun Transfers(rows: List<TransferRow>, onCancel: (Long) -> Unit, onClear: () -> Unit) {
val context = LocalContext.current
Surface(tonalElevation = 3.dp) {
Column(Modifier.fillMaxWidth().heightIn(max = 220.dp)) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text("Transfers", Modifier.weight(1f), style = MaterialTheme.typography.titleSmall)
if (rows.any { it.done }) TextButton(onClick = onClear) { Text("Clear finished") }
}
LazyColumn {
items(rows, key = { it.id }) { row ->
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically) {
PackIcon(if (row.upload) "UPLOAD" else "DOWNLOAD", null)
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
Text(row.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
when (row.state) {
FileTransfer.State.PENDING, FileTransfer.State.ACTIVE ->
LinearProgressIndicator({ row.progress }, Modifier.fillMaxWidth().padding(vertical = 4.dp))
else -> Text(status(row, context), style = MaterialTheme.typography.bodySmall,
color = if (row.state == FileTransfer.State.FAILED) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant)
}
}
if (!row.done) IconButton(onClick = { onCancel(row.id) }) { Icon(Icons.Default.Close, "Cancel") }
}
}
}
}
}
}
private fun status(row: TransferRow, context: android.content.Context): String = when (row.state) {
FileTransfer.State.COMPLETED -> (if (row.upload) "Uploaded" else "Downloaded") + " · " +
Formatter.formatShortFileSize(context, row.total)
FileTransfer.State.CANCELLED -> "Cancelled"
else -> row.error ?: "Failed"
}
@@ -0,0 +1,190 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.gfx.IconKeys
import eu.lixko.ts3j.client.net.ClientStatus
import eu.lixko.ts3j.client.text.TextQuery
/** What the find bar holds: the text, how to match it, and whether it is [open]. */
@Stable
class FindState(text: String = "", flags: Int = 0) {
var open by mutableStateOf(false)
var input by mutableStateOf(TextFieldValue(text))
var matchCase by mutableStateOf(flags and 1 != 0)
var wholeWord by mutableStateOf(flags and 2 != 0)
var regex by mutableStateOf(flags and 4 != 0)
/** Counts the times it was asked to show, for the field to take the focus each time. */
var shown by mutableStateOf(0)
private set
/** Show only what matches. */
var filter by mutableStateOf(flags and 8 != 0)
/** In the tree, find channels rather than clients. */
var channels by mutableStateOf(flags and 16 != 0)
/** What is typed, as it is to be matched; empty while the bar is closed. */
val query: TextQuery
get() = if (open) TextQuery(input.text, matchCase, wholeWord, regex) else TextQuery.EMPTY
/** [query], but nothing when it is not a valid regular expression. */
val usable: TextQuery
get() = query.let { if (it.isInvalid) TextQuery.EMPTY else it }
/** Opens the bar with what it holds selected, to be typed over. */
fun show() {
input = input.copy(selection = TextRange(0, input.text.length))
open = true
shown++
}
companion object {
val Saver = listSaver<FindState, Any>(
save = {
val flags = (if (it.matchCase) 1 else 0) or (if (it.wholeWord) 2 else 0) or (if (it.regex) 4 else 0) or
(if (it.filter) 8 else 0) or (if (it.channels) 16 else 0)
listOf(it.input.text, flags, it.open)
},
restore = { FindState(it[0] as String, it[1] as Int).apply { open = it[2] as Boolean } },
)
}
}
/**
* The find bar, in the place of the top bar: the field, where the view is among the matches,
* previous/next, and the options. Enter goes to the next match, Shift+Enter to the previous.
*
* @param inTree whether it finds in the tree, which offers finding channels instead of clients
* @param position the 1-based match the view is on, or 0 for none
* @param more whether there are more matches than [total]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FindBar(state: FindState, inTree: Boolean, position: Int, total: Int, more: Boolean, onStep: (Int) -> Unit) {
val focus = remember { FocusRequester() }
LaunchedEffect(state.shown) { focus.requestFocus() }
val query = state.query
TopAppBar(
expandedHeight = 48.dp,
navigationIcon = { IconButton(onClick = { state.open = false }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Close") } },
title = {
TextField(
state.input, { state.input = it },
Modifier.focusRequester(focus).onPreviewKeyEvent { e ->
when {
e.key == Key.Enter -> {
if (e.type == KeyEventType.KeyDown) onStep(if (e.isShiftPressed) -1 else 1)
true
}
e.key == Key.Escape && e.type == KeyEventType.KeyDown -> {
state.open = false
true
}
else -> false
}
},
placeholder = {
Text(if (!inTree) "Find" else if (state.channels) "Find channels" else "Find clients", maxLines = 1)
},
leadingIcon = if (inTree) ({
IconButton(onClick = { state.channels = !state.channels }) {
if (state.channels) PackIcon(IconKeys.channel(false, false, true).asList(), "Finding channels", size = 18.dp)
else PackIcon(IconKeys.client(ClientStatus.IDLE), "Finding clients", size = 18.dp)
}
}) else null,
trailingIcon = if (state.input.text.isNotEmpty()) ({
IconButton(onClick = { state.input = TextFieldValue() }) { Icon(Icons.Filled.Close, "Clear", Modifier.size(18.dp)) }
}) else null,
isError = query.isInvalid,
singleLine = true,
textStyle = MaterialTheme.typography.bodyLarge,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { onStep(1) }),
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
errorContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
)
},
actions = {
Row(verticalAlignment = Alignment.CenterVertically) {
if (!query.isEmpty) {
Text(
if (query.isInvalid) "!" else "${if (position > 0) "$position/" else ""}$total${if (more) "+" else ""}",
Modifier.padding(horizontal = 4.dp),
color = if (query.isInvalid || total == 0) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelMedium,
)
}
val navigable = total > 1 || (total == 1 && position == 0)
IconButton(onClick = { onStep(-1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowUp, "Previous") }
IconButton(onClick = { onStep(1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowDown, "Next") }
FindOptions(state)
}
},
)
}
@Composable
private fun FindOptions(state: FindState) {
var open by remember { mutableStateOf(false) }
IconButton(onClick = { open = true }) { Icon(Icons.Filled.MoreVert, "Options") }
DropdownMenu(open, onDismissRequest = { open = false }) {
@Composable
fun option(label: String, checked: Boolean, set: (Boolean) -> Unit) = DropdownMenuItem(
text = { Text(label) },
onClick = { set(!checked) },
leadingIcon = { Checkbox(checked, set) },
)
option("Only matches", state.filter) { state.filter = it }
option("Match case", state.matchCase) { state.matchCase = it }
option("Whole words", state.wholeWord) { state.wholeWord = it }
option("Regular expression", state.regex) { state.regex = it }
}
}
@@ -0,0 +1,64 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.Picture
import eu.lixko.ts3j.client.android.WebPictures
import eu.lixko.ts3j.client.net.HostButton
/**
* The server's host button in the top bar: its own picture fitted to the bar's icons, or
* the pack's host button icon while there is none (yet).
*/
@Composable
fun HostButtonAction(button: HostButton, onOpen: (String) -> Unit) {
val label = button.tooltip.ifEmpty { button.url }.ifEmpty { null }
val picture = hostPicture(button.gfxUrl)
Box(
Modifier
.fillMaxHeight()
.clickable(enabled = button.url.isNotEmpty()) { onOpen(button.url) }
.padding(horizontal = 12.dp),
contentAlignment = Alignment.Center,
) {
if (picture == null) {
PackIcon("HOSTER_BUTTON", label)
} else {
Image(
rememberPicturePainter(picture),
label,
Modifier
.widthIn(max = 24.dp * MAX_ASPECT)
.height(24.dp)
.aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)),
)
}
}
}
@Composable
private fun hostPicture(url: String): Picture? {
val pictures = LocalWebPictures.current
if (pictures == null || url.isEmpty()) return null
val version by pictures.version.collectAsStateWithLifecycle()
val state by produceState<WebPictures.State>(WebPictures.State.Loading, url, version) {
value = pictures.state(url)
}
return (state as? WebPictures.State.Shown)?.picture
}
/** Keeps a banner-shaped picture from crowding out the server's name. */
private const val MAX_ASPECT = 6
@@ -0,0 +1,282 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.IdentityInfo
import eu.lixko.ts3j.client.android.IdentityManager
import kotlinx.coroutines.launch
/** Beyond this a search takes years; TeamSpeak's own dialog stops there too. */
private const val MAX_SECURITY_LEVEL = 40
/**
* The identities a server knows this client by, as TeamSpeak's Tools → Identities
* manages them, with each identity's own page.
*/
@Composable
fun IdentitiesScreen(manager: IdentityManager, onBack: () -> Unit) {
var editing by rememberSaveable { mutableStateOf<String?>(null) }
editing?.let { id -> return IdentityScreen(manager, id, onBack = { editing = null }) }
val identities by manager.all.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
var creating by remember { mutableStateOf(false) }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
fun work(failure: String, block: suspend () -> String?) {
busy = true
scope.launch {
message = try {
block()
} catch (e: Exception) {
"$failure: ${e.message ?: e}"
}
busy = false
}
}
val fileImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) work("That file is not a TeamSpeak identity") {
editing = manager.importFile(uri).id
null
}
}
val dbImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) work("That file is not a TeamSpeak 3 settings.db") {
val r = manager.importFromTeamSpeak(uri)
if (r.identities() == 0) "That file holds no identities."
else "Imported ${r.identitiesAdded()} of ${r.identities()} identities."
}
}
SubScreen("Identities", onBack, actions = {
IconButton(onClick = { creating = true }, enabled = !busy) { PackIcon("IDENTITY_ADD", "New identity") }
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Import identity file") }, onClick = {
menu = false
fileImporter.launch(arrayOf("*/*"))
})
DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = {
menu = false
dbImporter.launch(arrayOf("*/*"))
})
}
}
}) { padding ->
LazyColumn(Modifier.padding(padding)) {
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
message?.let { item { Hint(it) } }
if (identities.isEmpty()) {
item {
Hint("No identities. One is created on the first connect.")
}
}
items(identities, key = { it.id }) { identity ->
ListItem(
headlineContent = { Text(identity.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Text("Security level ${identity.securityLevel}", maxLines = 1)
},
trailingContent = if (identity.isDefault) ({ PackIcon("IDENTITY_DEFAULT", "Default") }) else null,
modifier = Modifier.clickable { editing = identity.id },
)
}
}
}
if (creating) {
NewIdentityDialog(onDismiss = { creating = false }) { name ->
creating = false
work("Could not create the identity") {
editing = manager.generate(name).id
null
}
}
}
}
/** One identity: its name, whether it is the default, its security level and unique ID. */
@Composable
private fun IdentityScreen(manager: IdentityManager, id: String, onBack: () -> Unit) {
val identities by manager.all.collectAsStateWithLifecycle()
val improving by manager.improving.collectAsStateWithLifecycle()
val identity = identities.firstOrNull { it.id == id }
if (identity == null) {
LaunchedEffect(Unit) { onBack() }
return
}
val scope = rememberCoroutineScope()
var name by rememberSaveable(id) { mutableStateOf(identity.name) }
var nickname by rememberSaveable(id) { mutableStateOf(identity.nickname) }
var phonetic by rememberSaveable(id) { mutableStateOf(identity.phoneticNickname) }
var removing by remember { mutableStateOf(false) }
var raising by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
val leave = {
val trimmed = name.trim()
if (trimmed.isNotEmpty() && trimmed != identity.name) manager.rename(id, trimmed)
if (nickname.trim() != identity.nickname || phonetic.trim() != identity.phoneticNickname) {
manager.setNicknames(id, nickname.trim(), phonetic.trim())
}
onBack()
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
if (uri != null) scope.launch {
message = runCatching { manager.export(id, uri) }.fold(
{ "Exported." },
{ "Could not export: ${it.message ?: it}" },
)
}
}
val mine = improving?.takeIf { it.id == id }
SubScreen(identity.name, leave, actions = {
IconButton(onClick = { exporter.launch(fileName(name.ifBlank { identity.name })) }) {
PackIcon("IDENTITY_EXPORT", "Export")
}
IconButton(onClick = { removing = true }) { PackIcon("DELETE", "Remove") }
}) { padding ->
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) {
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp),
label = { Text("Name") }, singleLine = true, isError = name.isBlank())
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp),
label = { Text("Nickname") }, placeholder = { Text("Global nickname") }, singleLine = true)
OutlinedTextField(phonetic, { phonetic = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
label = { Text("Phonetic nickname") }, singleLine = true)
message?.let { Hint(it) }
Section("Use")
if (identity.isDefault) {
Hint("Default identity")
} else {
LinkRow("Make default", null, "IDENTITY_DEFAULT") {
manager.setDefault(id)
}
}
Section("Security level")
if (mine != null) {
ListItem(
headlineContent = { Text("Improving to ${mine.target}: reached ${mine.reached}") },
supportingContent = { LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) },
trailingContent = { TextButton(onClick = manager::stopImproving) { Text("Stop") } },
)
} else {
LinkRow("Level ${identity.securityLevel}",
if (improving != null) "Another identity is being improved" else "Improve",
"SECURITY") { if (improving == null) raising = true }
}
Section("Details")
val context = LocalContext.current
LinkRow("Unique ID", identity.uniqueId) {
// The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Unique ID", identity.uniqueId))
}
}
}
if (raising) {
LevelDialog(identity, onDismiss = { raising = false }) { target ->
raising = false
manager.improve(id, target)
}
}
if (removing) {
AlertDialog(
onDismissRequest = { removing = false },
title = { Text("Remove ${identity.name}?") },
text = {
Text("Server groups and permissions tied to it are lost. Export it first to keep it.")
},
confirmButton = {
TextButton(onClick = {
removing = false
manager.remove(id)
}) { Text("Remove") }
},
dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } },
)
}
}
@Composable
private fun NewIdentityDialog(onDismiss: () -> Unit, onConfirm: (String) -> Unit) {
var name by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("New identity") },
text = {
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true)
},
confirmButton = { TextButton(onClick = { onConfirm(name.trim()) }, enabled = name.isNotBlank()) { Text("Create") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@Composable
private fun LevelDialog(identity: IdentityInfo, onDismiss: () -> Unit, onConfirm: (Int) -> Unit) {
var text by remember { mutableStateOf((identity.securityLevel + 1).toString()) }
val level = text.trim().toIntOrNull()?.takeIf { it in identity.securityLevel + 1..MAX_SECURITY_LEVEL }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Improve security level") },
text = {
Column {
Text("Current level: ${identity.securityLevel}", style = MaterialTheme.typography.bodyMedium)
OutlinedTextField(text, { text = it }, Modifier.fillMaxWidth().padding(top = 8.dp),
label = { Text("Target level") }, singleLine = true, isError = level == null,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
},
confirmButton = { TextButton(onClick = { level?.let(onConfirm) }, enabled = level != null) { Text("Start") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
private fun fileName(name: String) = name.replace(Regex("[^\\w.-]+"), "_") + ".ini"
@@ -0,0 +1,261 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.LocalMinimumInteractiveComponentSize
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.GroupChoice
import eu.lixko.ts3j.client.net.ClientAdmin
import eu.lixko.ts3j.client.net.ban.BanRule
import eu.lixko.ts3j.client.net.ban.BanUnit
/** Asks to confirm a kick, with an optional reason. */
@Composable
fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) {
var reason by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = { LimitedField(reason, { reason = it }, "Reason", ClientAdmin.KICK_REASON_LIMIT) },
confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** Asks for a ban's reason and length. */
@Composable
fun BanPrompt(name: String, maxSeconds: Long, onDismiss: () -> Unit, onBan: (seconds: Long, reason: String) -> Unit) {
var reason by remember { mutableStateOf("") }
val duration = remember { BanDurationState(DEFAULT_BAN_SECONDS) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Ban $name") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
LimitedField(reason, { reason = it }, "Reason", BanRule.REASON_LIMIT)
BanDurationField(duration, maxSeconds)
}
},
confirmButton = {
TextButton(onClick = { onBan(duration.seconds, reason.trim()) }, enabled = duration.valid) { Text("Ban") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** Thirty minutes, as the official client starts its ban dialog. */
internal const val DEFAULT_BAN_SECONDS = 30 * 60L
/** A one-line field that takes no more than [limit] characters, counting them as they come. */
@Composable
internal fun LimitedField(value: String, onChange: (String) -> Unit, label: String, limit: Int, modifier: Modifier = Modifier) {
OutlinedTextField(
value, { onChange(it.take(limit)) },
modifier.fillMaxWidth(),
label = { Text(label) },
singleLine = true,
supportingText = { Text("${value.length}/$limit", Modifier.fillMaxWidth(), textAlign = TextAlign.End) },
)
}
/** A ban's length as typed: an amount of a [BanUnit]. */
internal class BanDurationState(seconds: Long) {
var unit by mutableStateOf(BanUnit.largestFor(seconds))
var amount by mutableStateOf(BanUnit.largestFor(seconds).amountOf(seconds).takeIf { it > 0 }?.toString() ?: "30")
val valid: Boolean get() = unit == BanUnit.PERMANENT || (amount.toLongOrNull() ?: 0) > 0
/** The length in seconds; 0 for permanent. */
val seconds: Long get() = unit.toSeconds(amount.toLongOrNull() ?: 0)
fun set(seconds: Long) {
unit = BanUnit.largestFor(seconds)
if (unit != BanUnit.PERMANENT) amount = unit.amountOf(seconds).toString()
}
}
/** The amount, its unit, and a jump to the longest ban the server lets us hand out. */
@Composable
internal fun BanDurationField(state: BanDurationState, maxSeconds: Long, modifier: Modifier = Modifier) {
var units by remember { mutableStateOf(false) }
Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
if (state.unit == BanUnit.PERMANENT) "" else state.amount,
{ text -> state.amount = text.filter(Char::isDigit).take(9) },
Modifier.width(120.dp),
enabled = state.unit != BanUnit.PERMANENT,
label = { Text("Duration") },
singleLine = true,
isError = !state.valid,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
Box(Modifier.weight(1f)) {
OutlinedButton(onClick = { units = true }, Modifier.fillMaxWidth()) { Text(state.unit.label()) }
DropdownMenu(units, { units = false }) {
for (unit in BanUnit.entries) {
DropdownMenuItem({ Text(unit.label()) }, onClick = { units = false; state.unit = unit })
}
}
}
if (maxSeconds != 0L) TextButton(onClick = { state.set(maxSeconds) }) { Text("Max") }
}
}
/**
* A client's groups to tick: several server groups, or with [single] the one channel group.
* Groups we may not assign are listed only when the client is in them, greyed out; a change shows once the server
* made it.
*/
@Composable
fun GroupsDialog(
title: String,
choices: List<GroupChoice>,
single: Boolean,
onDismiss: () -> Unit,
onChange: (groupId: Int, assign: Boolean) -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides Dp.Unspecified) {
LazyColumn {
items(choices.filter { it.allowed() || it.assigned() }, key = { it.group().id }) { choice ->
val group = choice.group()
// A client always has one channel group: picking another is the only change.
val changeable = choice.allowed() && !(single && choice.assigned())
val toggle = { if (changeable) onChange(group.id, !choice.assigned()) }
Row(
Modifier.fillMaxWidth()
.clickable(enabled = changeable, onClick = toggle)
.alpha(if (choice.allowed()) 1f else 0.38f)
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (single) {
RadioButton(choice.assigned(), onClick = toggle, enabled = choice.allowed())
} else {
Checkbox(choice.assigned(), onCheckedChange = { toggle() }, enabled = choice.allowed())
}
Box(Modifier.width(24.dp), contentAlignment = Alignment.Center) {
if (group.iconId != 0L) ServerIcon(group.iconId)
}
Text(group.name, Modifier.padding(start = 8.dp))
}
}
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } },
)
}
/**
* Talk power, the kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out.
* Null when there is none of them.
*/
@Composable
fun clientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit): (@Composable () -> Unit)? {
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
val kickChannel = !client.self && server.permissions.canKickFromChannel()
val kickServer = !client.self && server.permissions.canKickFromServer()
val ban = !client.self && server.permissions.canBanClients()
val talker = server.permissions.canGrantTalkPower() && (client.talker || client.lacksTalkPower)
val showServerGroups = serverGroups.any { it.allowed() }
val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() }
if (!(talker || kickChannel || kickServer || ban || showServerGroups || showChannelGroups)) return null
return {
ClientModeration(server, client, serverGroups, channelGroups, talker, kickChannel, kickServer, ban,
showServerGroups, showChannelGroups, onDone)
}
}
@Composable
private fun ClientModeration(
server: ServerController,
client: ClientItem,
serverGroups: List<GroupChoice>,
channelGroups: List<GroupChoice>,
talker: Boolean,
kickChannel: Boolean,
kickServer: Boolean,
ban: Boolean,
showServerGroups: Boolean,
showChannelGroups: Boolean,
onDone: () -> Unit,
) {
var kick by remember { mutableStateOf<Boolean?>(null) }
var banning by remember { mutableStateOf(false) }
var groups by remember { mutableStateOf<Boolean?>(null) }
if (talker) {
if (client.talker) Action("TALK_POWER_REVOKE", "Revoke talk power") { server.setTalker(listOf(client.id), false); onDone() }
else Action("TALK_POWER_GRANT", "Grant talk power") { server.setTalker(listOf(client.id), true); onDone() }
}
if (kickChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false }
if (kickServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true }
if (ban) Action("BAN_CLIENT", "Ban") { banning = true }
if (showServerGroups) Action("PERMISSIONS_SERVER_GROUPS", "Server groups") { groups = true }
if (showChannelGroups) Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group") { groups = false }
kick?.let { fromServer ->
KickPrompt(
if (fromServer) "Kick ${client.name} from the server?" else "Kick ${client.name} from the channel?",
onDismiss = { kick = null },
) { reason ->
kick = null
if (fromServer) server.kickFromServer(listOf(client.id), reason) else server.kickFromChannel(listOf(client.id), reason)
onDone()
}
}
if (banning) {
BanPrompt(client.name, server.permissions.maxBanSeconds(), onDismiss = { banning = false }) { seconds, reason ->
banning = false
server.ban(client.id, seconds, reason)
onDone()
}
}
groups?.let { ofServer ->
GroupsDialog(
if (ofServer) "Server groups" else "Channel group",
if (ofServer) serverGroups else channelGroups,
single = !ofServer,
onDismiss = { groups = null },
) { groupId, assign ->
if (ofServer) server.setServerGroup(client.id, groupId, assign) else server.setChannelGroup(client.id, groupId)
}
}
}
@@ -0,0 +1,297 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.myts.AccountInfo
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
import eu.lixko.ts3j.client.myts.MyTsException
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import java.io.IOException
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import kotlinx.coroutines.launch
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
/**
* The myTeamSpeak account: sign in and out, pick what the account synchronises to import,
* or synchronise both ways. Signing in lasts until signing out; the password itself is not kept.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
val login = account.login
val scope = rememberCoroutineScope()
var signedIn by remember { mutableStateOf(login.isSignedIn) }
var busy by remember { mutableStateOf(false) }
var message by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf(false) }
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var info by remember { mutableStateOf<AccountInfo?>(null) }
var all by remember { mutableStateOf(emptyList<SyncItem>()) }
var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
var conflicted by remember { mutableStateOf<MyTeamSpeakSync.Plan?>(null) }
fun show(fetched: MyTeamSpeak.Account) {
info = fetched.info()
all = fetched.items()
rows = all.filter { it !is SyncItem.Folder && (it !is SyncItem.Contact || TeamSpeakImporter.isImportable(it)) }.map {
val imported = account.isImported(it)
ItemRow(it, imported, !imported)
}
message = if (rows.isEmpty()) "The account holds no bookmarks, identities or contacts." else null
error = false
}
fun work(block: suspend () -> Unit) {
busy = true
message = null
scope.launch {
try {
block()
} catch (e: MyTsException) {
message = e.message
error = true
} catch (e: IOException) {
message = "Could not reach myTeamSpeak: ${e.message}"
error = true
}
// A sign-in the server no longer takes has signed out.
signedIn = login.isSignedIn
busy = false
}
}
suspend fun finishSync(plan: MyTeamSpeakSync.Plan) {
val r = account.finishSync(plan)
rows = rows.map { it.copy(imported = account.isImported(it.item)) }
message = if (r.sent() == 0 && r.received() == 0) "In sync."
else "Synchronized: ${r.sent()} sent, ${r.received()} received."
}
LaunchedEffect(Unit) {
if (signedIn) work { show(account.fetch()) }
}
conflicted?.let { plan ->
SyncConflictsScreen(plan.conflicts()) { accepted ->
conflicted = null
if (accepted) work { finishSync(plan) } else message = "Synchronization cancelled."
}
return
}
BackHandler(onBack = onBack)
Scaffold(
topBar = {
TopAppBar(
title = { Text("myTeamSpeak") },
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = {
if (signedIn) {
IconButton(onClick = { work { show(account.fetch()) } }, enabled = !busy) {
PackIcon("REFRESH", "Refresh")
}
}
},
)
},
) { padding ->
LazyColumn(
Modifier.padding(padding).imePadding(),
contentPadding = PaddingValues(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) }
if (!signedIn) {
item {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Sign in to bring over the bookmarks, identities and contacts your account synchronises. " +
"The app stays signed in; your password itself is not kept.")
OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") },
singleLine = true, enabled = !busy,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email))
OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), label = { Text("Password") },
singleLine = true, enabled = !busy, visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
Button(
onClick = {
work {
show(account.signIn(email.trim(), password))
password = ""
}
},
enabled = !busy && email.isNotBlank() && password.isNotEmpty(),
) { Text("Sign in") }
}
}
} else {
item {
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Signed in as ${login.username()}", style = MaterialTheme.typography.titleMedium)
Text(login.email(), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
OutlinedButton(onClick = {
scope.launch { account.signOut() }
signedIn = false
rows = emptyList()
all = emptyList()
info = null
message = null
}) { Text("Sign out") }
}
}
info?.let { details ->
item {
Column(Modifier.padding(horizontal = 16.dp)) {
if (details.userId().isNotEmpty()) Detail("ID", details.userId())
if (details.uuid().isNotEmpty()) Detail("UUID", details.uuid())
details.created()?.let { Detail("Created", dateFormat.format(it)) }
}
}
}
if (rows.isNotEmpty()) {
item {
Text("Synchronised by the account", Modifier.padding(start = 16.dp, top = 16.dp),
style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
}
}
for ((title, section) in listOf(
"Identities" to rows.filter { it.item is SyncItem.Identity },
"Bookmarks" to rows.filter { it.item is SyncItem.Bookmark },
"Contacts" to rows.filter { it.item is SyncItem.Contact },
)) {
if (section.isEmpty()) continue
item {
val select = section.any { !it.selected }
Row(Modifier.padding(start = 16.dp, top = 8.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(title, Modifier.weight(1f),
style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
TextButton(onClick = {
rows = rows.map { if (it in section) it.copy(selected = select) else it }
}) { Text(if (select) "Select all" else "Deselect all") }
}
}
items(section, key = { it.item.uuid() }) { row ->
val toggle = { rows = rows.map { if (it === row) it.copy(selected = !it.selected) else it } }
ListItem(
headlineContent = { Text(name(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = { Text(details(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingContent = { Checkbox(row.selected, { toggle() }) },
trailingContent = if (row.imported) ({ Text("Imported", style = MaterialTheme.typography.labelMedium) }) else null,
modifier = Modifier.clickable(onClick = toggle),
)
}
}
item {
Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (rows.isNotEmpty()) {
Button(
onClick = {
work {
val r = account.import(all, rows.filter { it.selected }.map { it.item })
rows = rows.map { it.copy(imported = account.isImported(it.item), selected = false) }
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " +
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " +
"${count(r.contactsAdded(), "contact", "contacts")}."
}
},
enabled = !busy && rows.any { it.selected },
) { Text("Import selected") }
}
OutlinedButton(
onClick = {
work {
val plan = account.planSync()
if (plan.conflicts().isEmpty()) finishSync(plan) else conflicted = plan
}
},
enabled = !busy,
) { Text("Synchronize") }
}
}
}
message?.let { text ->
item {
Text(text, Modifier.padding(horizontal = 16.dp),
color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface)
}
}
}
}
}
private val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault())
/** A labelled value that can be selected and copied. */
@Composable
private fun Detail(label: String, value: String) {
Column(Modifier.padding(top = 8.dp)) {
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
SelectionContainer { Text(value, style = MaterialTheme.typography.bodyMedium) }
}
}
private fun name(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> item.name().ifBlank { item.address() }
is SyncItem.Identity -> item.name()
is SyncItem.Contact -> item.customName().ifBlank { item.myTeamSpeakId() }
else -> ""
}
private fun details(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port())
is SyncItem.Identity -> item.nickname()
is SyncItem.Contact -> item.myTeamSpeakId()
else -> ""
}
private fun count(n: Int, one: String, many: String) = "$n ${if (n == 1) one else many}"
@@ -0,0 +1,88 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings
import kotlin.math.abs
import kotlin.math.roundToInt
private const val MIN_BITRATE_KBITS = 8f
private const val MAX_BITRATE_KBITS = 160f
/** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */
@Composable
fun NetworkSettingsScreen(settings: Settings, sessions: SessionController, onBack: () -> Unit) {
fun <T> change(setting: Setting<T>, value: T) {
setting.set(value)
sessions.applySettings()
}
var vbr by remember { mutableStateOf(settings.vbr.get()) }
var fec by remember { mutableStateOf(settings.fec.get()) }
var music by remember { mutableStateOf(settings.music.get()) }
var redundancy by remember { mutableStateOf(settings.redundancyDelay.get()) }
var copies by remember { mutableStateOf(settings.redundancyCopies.get()) }
var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer.get()) }
SubScreen("Network", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Encoder")
Level("Bitrate", settings.bitrate.get() / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) {
change(settings.bitrate, it.roundToInt() * 1000)
}
Toggle("Variable bitrate (VBR)", vbr) {
vbr = it
change(settings.vbr, it)
}
Toggle("Forward error correction (FEC)", fec) {
fec = it
change(settings.fec, it)
}
Level("Complexity", settings.complexity.get().toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) {
change(settings.complexity, it.roundToInt())
}
Toggle("Music codec (stereo, higher fidelity)", music) {
music = it
change(settings.music, it)
}
Section("Redundancy")
ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) {
redundancy = it
change(settings.redundancyDelay, it)
}
if (redundancy > 0) {
Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" },
steps = Settings.MAX_REDUNDANCY_COPIES - 2) {
copies = it.roundToInt()
change(settings.redundancyCopies, copies)
}
}
Section("Receive")
ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) {
receiveBuffer = it
change(settings.receiveBuffer, it)
}
}
}
}
/** A slider stepping through the millisecond [choices], starting at the one nearest [ms]. */
@Composable
private fun ChoiceLevel(label: String, choices: IntArray, ms: Int, onDone: (Int) -> Unit) {
val index = choices.indices.minBy { abs(choices[it] - ms) }
fun at(position: Float) = choices[position.roundToInt()]
Level(label, index.toFloat(), 0f..(choices.size - 1).toFloat(), { at(it).let { v -> if (v == 0) "Off" else "$v ms" } },
steps = choices.size - 2) { onDone(at(it)) }
}
@@ -0,0 +1,42 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.IconTheme
val LocalIconTheme = staticCompositionLocalOf<IconTheme> { error("No icon theme provided") }
/** An icon of the active pack, named by its TeamSpeak key; art in the text colour takes [LocalContentColor]. */
@Composable
fun PackIcon(key: String, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) =
PackIcon(listOf(key), contentDescription, modifier, size)
/** The first of [keys] the pack has, for icons packs need not ship in every variant. */
@Composable
fun PackIcon(keys: List<String>, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) {
val theme = LocalIconTheme.current
val active by theme.active.collectAsStateWithLifecycle()
val pixels = with(LocalDensity.current) { size.roundToPx() }
val color = LocalContentColor.current
val rgb = color.copy(alpha = 1f).toArgb()
val bitmap = remember(keys, pixels, rgb, active) { theme.render(keys, pixels, rgb)?.asImageBitmap() }
if (bitmap == null) {
Spacer(modifier.size(size))
} else {
// Disabled controls fade their content colour; the pack's own colours fade with it.
Image(bitmap, contentDescription, modifier.size(size), alpha = color.alpha)
}
}
@@ -0,0 +1,220 @@
package eu.lixko.ts3j.client.android.ui
import android.content.ClipData
import android.content.ClipboardManager
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import eu.lixko.ts3j.client.android.Picture
import eu.lixko.ts3j.client.android.SavedPictures
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.decodePicture
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** A picture to open full size. */
class ViewedPicture(
/** What to call it when saved, without an extension. */
val name: String,
/** Where it is on the web; null for an avatar. */
val url: String? = null,
/** Follows the link it sits in; null when it sits in none. */
val openLink: (() -> Unit)? = null,
/** Our own avatar, which there is no taking. */
val ownAvatar: Boolean = false,
/** Its file; null when it is not there. */
val read: suspend () -> ByteArray?,
)
/** Opens a picture full size; null where nothing can. */
val LocalPictureViewer = staticCompositionLocalOf<((ViewedPicture) -> Unit)?> { null }
/** Lets [content] open pictures full size, over everything, with [server] to take one as our avatar on. */
@Composable
fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) {
var viewed by remember { mutableStateOf<ViewedPicture?>(null) }
CompositionLocalProvider(LocalPictureViewer provides { viewed = it }, content = content)
val context = LocalContext.current
viewed?.let { picture ->
PictureViewer(
picture,
onSteal = if (picture.ownAvatar) null else { data ->
val message = server.setAvatar(data).fold({ "Avatar set." }, { it.message })
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
},
onDismiss = { viewed = null },
)
}
}
/** A name to save the picture at [url] under: its file's, or "picture" when it has none. */
fun pictureName(url: String): String =
url.substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/')
.substringBeforeLast('.').ifBlank { "picture" }
/** The picture on black, filling the screen; pinch or double-tap to zoom, tap to hide the bar. */
@Composable
private fun PictureViewer(
picture: ViewedPicture,
/** Takes the picture as our avatar; null when it cannot be. */
onSteal: (suspend (ByteArray) -> Unit)?,
onDismiss: () -> Unit,
) {
val state by produceState<Shown?>(null, picture) {
val data = picture.read()
value = Shown(data, data?.let { withContext(Dispatchers.Default) { decodePicture(it, MAX_PX) } })
}
val data = state?.data
var bar by remember { mutableStateOf(true) }
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
var size by remember { mutableStateOf(IntSize.Zero) }
fun panTo(target: Offset) {
val maxX = size.width * (scale - 1) / 2
val maxY = size.height * (scale - 1) / 2
offset = Offset(target.x.coerceIn(-maxX, maxX), target.y.coerceIn(-maxY, maxY))
}
Dialog(onDismiss, DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
Box(
Modifier.fillMaxSize().background(Color.Black).onSizeChanged { size = it }
.pointerInput(Unit) {
detectTapGestures(
onTap = { bar = !bar },
onDoubleTap = { scale = if (scale > 1f) 1f else DOUBLE_TAP_SCALE; panTo(Offset.Zero) },
)
}
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(1f, MAX_SCALE)
panTo(offset + pan)
}
},
contentAlignment = Alignment.Center,
) {
val shown = state?.picture
when {
state == null -> PackIcon("LOADING_IMAGE", "Loading picture")
shown == null -> PackIcon("BROKEN_IMAGE", "Broken picture")
else -> Image(
rememberPicturePainter(shown), null,
Modifier.fillMaxSize().graphicsLayer {
scaleX = scale
scaleY = scale
translationX = offset.x
translationY = offset.y
},
contentScale = ContentScale.Fit,
)
}
if (bar) {
CompositionLocalProvider(LocalContentColor provides Color.White) {
Bar(picture, data, onSteal, onDismiss, Modifier.align(Alignment.TopCenter))
}
}
}
}
}
@Composable
private fun Bar(
picture: ViewedPicture,
data: ByteArray?,
onSteal: (suspend (ByteArray) -> Unit)?,
onDismiss: () -> Unit,
modifier: Modifier,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) }
Row(
modifier.fillMaxWidth()
.background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.6f), Color.Transparent)))
.statusBarsPadding(),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") }
Box(Modifier.weight(1f))
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Picture options") }
DropdownMenu(menu, onDismissRequest = { menu = false }) {
DropdownMenuItem({ Text("Save") }, enabled = data != null, onClick = {
menu = false
val bytes = data ?: return@DropdownMenuItem
scope.launch {
val saved = SavedPictures.save(context, picture.name, bytes)
Toast.makeText(context, if (saved) "Saved." else "Could not save.", Toast.LENGTH_SHORT).show()
}
})
if (onSteal != null) {
DropdownMenuItem({ Text("Steal for avatar") }, enabled = data != null, onClick = {
menu = false
val bytes = data ?: return@DropdownMenuItem
scope.launch { onSteal(bytes) }
})
}
picture.url?.let { url ->
DropdownMenuItem({ Text("Copy URL") }, onClick = {
menu = false
context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("URL", url))
})
}
picture.openLink?.let { open ->
DropdownMenuItem({ Text("Open link") }, onClick = {
menu = false
onDismiss()
open()
})
}
}
}
}
}
/** The picture's file, and the picture when the file is one; both null when it is not there. */
private class Shown(val data: ByteArray?, val picture: Picture?)
private const val MAX_PX = 4096
private const val MAX_SCALE = 8f
private const val DOUBLE_TAP_SCALE = 2.5f
@@ -0,0 +1,95 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.net.ClientStatus
import kotlinx.coroutines.flow.MutableStateFlow
/** What push-to-talk would talk on: the server holding the microphone, which need not be the one on screen. */
internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean)
@Composable
internal fun rememberPttTarget(sessions: SessionController): PttTarget {
val owner by sessions.micOwner.collectAsStateWithLifecycle()
val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle()
val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle()
val self = tree.client(state.selfClientId)
val talking = self?.status == ClientStatus.TALKING || self?.status == ClientStatus.COMMANDER_TALKING
return PttTarget(owner, state, talking)
}
/** Talks while held. */
@Composable
internal fun PushToTalk(
talking: Boolean,
onPressed: (Boolean) -> Unit,
modifier: Modifier,
shape: Shape = RoundedCornerShape(24.dp),
textStyle: TextStyle = MaterialTheme.typography.titleMedium,
) {
val colors = MaterialTheme.colorScheme
Surface(
modifier.pointerInput(Unit) {
// Held until the finger lifts, wherever it wanders; a tap gesture would end once it left the button.
awaitEachGesture {
awaitFirstDown()
onPressed(true)
try {
do {
val event = awaitPointerEvent()
event.changes.forEach { it.consume() }
} while (event.changes.any { it.pressed })
} finally {
onPressed(false)
}
}
},
shape = shape,
color = if (talking) StatusColors.talking else colors.primaryContainer,
contentColor = if (talking) Color.White else colors.onPrimaryContainer,
) {
Box(contentAlignment = Alignment.Center) {
Text(if (talking) "Talking…" else "Hold to talk", style = textStyle)
}
}
}
/** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */
@Composable
fun GiantPttScreen(sessions: SessionController, onBack: () -> Unit) {
val target = rememberPttTarget(sessions)
SubScreen("Giant PTT", onBack) { padding ->
val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp)
if (target.owner != null && target.state.connected) {
PushToTalk(target.talking, sessions::setForceTransmit, fill, RoundedCornerShape(32.dp),
MaterialTheme.typography.displaySmall)
} else {
Box(fill, contentAlignment = Alignment.Center) {
Text("Not connected",
style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
}
@@ -0,0 +1,120 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.config.ClientRowColors
/** A row background: none, a preset, or a custom colour. [argb] is 0 for none. */
@Composable
internal fun RowColorPicker(label: String, argb: Int, onChange: (Int) -> Unit) {
var open by remember { mutableStateOf(false) }
var custom by remember { mutableStateOf(false) }
Box {
Row(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(label)
Text(nameOf(argb), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Swatch(argb, 28.dp)
}
DropdownMenu(open, { open = false }) {
DropdownMenuItem({ Text("None") }, leadingIcon = { Swatch(0) }, onClick = {
open = false
onChange(0)
})
for (p in ClientRowColors.PRESETS) {
DropdownMenuItem({ Text(p.name()) }, leadingIcon = { Swatch(p.argb()) }, onClick = {
open = false
onChange(p.argb())
})
}
DropdownMenuItem({ Text("Custom…") }, onClick = {
open = false
custom = true
})
}
}
if (custom) {
CustomColorDialog(if (argb != 0) argb else 0x59808080, onDismiss = { custom = false }) {
custom = false
onChange(it)
}
}
}
private fun nameOf(argb: Int): String =
if (argb == 0) "None" else ClientRowColors.presetOf(argb)?.name() ?: "Custom"
@Composable
private fun CustomColorDialog(initial: Int, onDismiss: () -> Unit, onPick: (Int) -> Unit) {
var alpha by remember { mutableIntStateOf(initial ushr 24) }
var red by remember { mutableIntStateOf(initial shr 16 and 0xFF) }
var green by remember { mutableIntStateOf(initial shr 8 and 0xFF) }
var blue by remember { mutableIntStateOf(initial and 0xFF) }
val argb = (alpha shl 24) or (red shl 16) or (green shl 8) or blue
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Custom colour") },
text = {
Column {
Box(Modifier.fillMaxWidth().height(40.dp).clip(RoundedCornerShape(6.dp))
.background(MaterialTheme.colorScheme.surface)) {
Box(Modifier.fillMaxWidth().height(40.dp).background(Color(argb)))
}
Channel("Red", red) { red = it }
Channel("Green", green) { green = it }
Channel("Blue", blue) { blue = it }
Channel("Opacity", alpha) { alpha = it }
}
},
confirmButton = { TextButton({ onPick(argb) }, enabled = argb != 0) { Text("OK") } },
dismissButton = { TextButton(onDismiss) { Text("Cancel") } },
)
}
@Composable
private fun Channel(label: String, value: Int, onChange: (Int) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, Modifier.width(64.dp), style = MaterialTheme.typography.bodySmall)
Slider(value.toFloat(), { onChange(it.toInt()) }, Modifier.weight(1f), valueRange = 0f..255f)
}
}
/** The colour over the screen's background, as a row would show it; outlined so "none" shows too. */
@Composable
private fun Swatch(argb: Int, size: Dp = 20.dp) {
val shape = RoundedCornerShape(4.dp)
Box(Modifier.size(size).clip(shape).background(MaterialTheme.colorScheme.surface).background(Color(argb))
.border(1.dp, MaterialTheme.colorScheme.outline, shape))
}
@@ -0,0 +1,126 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.Conversation
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.TreeFind
import eu.lixko.ts3j.client.android.findIn
/** The channel tree as it shows under the find bar: what of it, which rows are folded, and the match it is on. */
@Stable
internal class TreeView(
private val server: ServerController,
private val source: State<ServerTree>,
private val collapsedSource: State<Set<Int>>,
private val find: FindState,
) {
val treeFind by derivedStateOf { TreeFind(find.usable, find.channels) }
val filtering by derivedStateOf { find.filter && !treeFind.query.isEmpty }
val tree by derivedStateOf { if (filtering) source.value.only(treeFind) else source.value }
val hits by derivedStateOf { source.value.hits(treeFind) }
val found by derivedStateOf { hits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }
/** The match the tree is on. */
private var at by mutableStateOf<Int?>(null)
val current: TreeRef? get() = at?.takeIf { it in hits }?.let { TreeRef(treeFind.channels, it) }
val position: Int get() = hits.indexOf(at) + 1
/** A row to bring into view. */
var reveal by mutableStateOf<TreeRef?>(null)
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
private var folded by mutableStateOf(Folded(null, emptySet()))
private val filterFolded: Set<Int> get() = folded.ids.takeIf { folded.find == treeFind }.orEmpty()
val collapsed: Set<Int> get() = if (filtering) filterFolded else collapsedSource.value
private data class Folded(val find: TreeFind?, val ids: Set<Int>)
fun toggle(channelId: Int) {
if (!filtering) server.toggleCollapsed(channelId)
else if (channelId in filterFolded) folded = Folded(treeFind, filterFolded - channelId)
else folded = Folded(treeFind, filterFolded + channelId)
}
/** Opens the channels down to [ref] and brings it into view. */
fun show(ref: TreeRef) {
val tree = source.value
val path = (if (ref.channel) tree.parentsOf(ref.id) else tree.pathTo(ref.id)).orEmpty()
if (filtering) folded = Folded(treeFind, filterFolded - path.toSet()) else server.expand(path)
reveal = ref
}
private fun showHit(id: Int) {
at = id
show(TreeRef(treeFind.channels, id))
}
/** For a new search: on the first match while the tree is on screen, else on none. */
fun restart(onScreen: Boolean) {
at = null
if (onScreen) hits.firstOrNull()?.let(::showHit)
}
fun step(delta: Int) {
if (hits.isNotEmpty()) showHit(hits[next(hits.indexOf(at), delta, hits.size)])
}
}
@Composable
internal fun rememberTreeView(
server: ServerController,
tree: State<ServerTree>,
collapsed: State<Set<Int>>,
find: FindState,
): TreeView = remember(server, tree, collapsed, find) { TreeView(server, tree, collapsed, find) }
/** A conversation as it shows under the find bar: its lines, and the match it is on. */
@Stable
internal class ChatSearch(private val conversation: State<Conversation>, private val find: FindState) {
val query get() = find.usable
val lines by derivedStateOf {
val all = conversation.value.lines
if (find.filter && !query.isEmpty) all.filter { query.matches(it.plain) } else all
}
val hits by derivedStateOf { findIn(lines, query, MAX_CHAT_MATCHES) }
val capped: Boolean get() = hits.size == MAX_CHAT_MATCHES
/** The match the chat is on. */
var at by mutableStateOf<ChatMatch?>(null)
private set
val position: Int get() = hits.indexOf(at) + 1
/** A line to bring into view. */
var reveal by mutableStateOf<Long?>(null)
/** For a new search: on the newest match while the chat is on screen, else on none. */
fun restart(onScreen: Boolean) {
at = if (onScreen) hits.lastOrNull() else null
reveal = at?.line
}
fun step(delta: Int) {
if (hits.isEmpty()) return
at = hits[next(hits.indexOf(at), delta, hits.size)]
reveal = at?.line
}
}
@Composable
internal fun rememberChatSearch(conversation: State<Conversation>, find: FindState): ChatSearch =
remember(conversation, find) { ChatSearch(conversation, find) }
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
@@ -0,0 +1,140 @@
package eu.lixko.ts3j.client.android.ui
import android.graphics.BitmapFactory
import android.graphics.drawable.AnimatedImageDrawable
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.Picture
import eu.lixko.ts3j.client.android.ServerImages
import eu.lixko.ts3j.client.gfx.CountryFlags
import eu.lixko.ts3j.client.net.IconRepository
import java.util.Optional
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.roundToInt
/** The images of the server on screen. */
val LocalServerImages = staticCompositionLocalOf<ServerImages?> { null }
/**
* A group, channel or server icon; nothing while it has none or it is still downloading.
* TeamSpeak's default group icons are the pack's, drawn in its style, as on the desktop.
*/
@Composable
fun ServerIcon(id: Long, modifier: Modifier = Modifier, size: Dp = 16.dp) {
if (id == 0L) return
if (id in 1..IconRepository.MAX_BUNDLED_ID) {
val theme = LocalIconTheme.current
val active by theme.active.collectAsStateWithLifecycle()
val pixels = with(LocalDensity.current) { size.roundToPx() }
val rgb = LocalContentColor.current.copy(alpha = 1f).toArgb()
val themed = remember(id, pixels, rgb, active) { theme.render(listOf("GROUP_$id"), pixels, rgb)?.asImageBitmap() }
if (themed != null) {
Image(themed, null, modifier.size(size))
return
}
}
val images = LocalServerImages.current ?: return
val version by images.version.collectAsStateWithLifecycle()
val bitmap = remember(id, version) { images.icon(id) } ?: return
Image(bitmap, null, modifier.size(size))
}
/** A client's avatar, moving if it is an animated GIF; nothing while they have none or it is still downloading. */
@Composable
fun Avatar(uniqueId: String, flag: String, modifier: Modifier = Modifier, size: Dp = 64.dp) {
val images = LocalServerImages.current ?: return
val version by images.version.collectAsStateWithLifecycle()
val picture = remember(flag, version) { images.avatar(uniqueId, flag) } ?: return
Image(rememberPicturePainter(picture), "Avatar", modifier.size(size).clip(RoundedCornerShape(8.dp)))
}
/** Draws [picture], playing it while on screen if it moves. */
@Composable
fun rememberPicturePainter(picture: Picture): Painter = when (picture) {
is Picture.Still -> remember(picture) { BitmapPainter(picture.bitmap) }
is Picture.Moving -> rememberMovingPainter(picture.drawable)
}
@Composable
private fun rememberMovingPainter(drawable: AnimatedImageDrawable): Painter {
val painter = remember(drawable) { MovingPainter(drawable) }
DisposableEffect(drawable) {
drawable.callback = painter
drawable.start()
onDispose {
drawable.stop()
if (drawable.callback === painter) drawable.callback = null
}
}
return painter
}
private class MovingPainter(private val drawable: AnimatedImageDrawable) : Painter(), Drawable.Callback {
/** Read while drawing, so that each new frame draws again. */
private var frame by mutableIntStateOf(0)
private val main = Handler(Looper.getMainLooper())
override val intrinsicSize = Size(drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat())
override fun DrawScope.onDraw() {
frame
drawIntoCanvas { canvas ->
drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt())
drawable.draw(canvas.nativeCanvas)
}
}
override fun invalidateDrawable(who: Drawable) {
frame++
}
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
main.postAtTime(what, `when`)
}
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
main.removeCallbacks(what)
}
}
private val flags = ConcurrentHashMap<String, Optional<ImageBitmap>>()
/** The flag of a country, at TeamSpeak's 16×11; nothing for no country or one without a flag. */
@Composable
fun CountryFlag(code: String, modifier: Modifier = Modifier) {
if (code.isEmpty()) return
val bitmap = remember(code) {
flags.getOrPut(code) {
Optional.ofNullable(CountryFlags.png(code)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() })
}.orElse(null)
} ?: return
Image(bitmap, CountryFlags.name(code), modifier.size(16.dp, 11.dp))
}
@@ -0,0 +1,105 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.config.WhisperList
/** What fills a server's screen: its tree and chat, or a page of its own. */
internal sealed interface ServerPage {
data object Main : ServerPage
data object BanList : ServerPage
data object WhisperLists : ServerPage
data class EditChannel(val edit: ChannelEdit) : ServerPage
/** A channel's files, with the password the channel takes. */
data class Files(val channelId: Int, val name: String, val password: String) : ServerPage
data class ConnectionInfo(val clientId: Int) : ServerPage
}
/** A sheet or dialog over the tree and chat; one at a time. */
internal sealed interface Overlay {
data object None : Overlay
data object Server : Overlay
/** [fromTree] when it was opened from the tree rather than a link. */
data class Client(val id: Int, val fromTree: Boolean) : Overlay
data class Channel(val id: Int) : Overlay
/** A locked channel being joined, while its password is asked for. */
data class JoinLocked(val channelId: Int) : Overlay
/** A locked channel whose files are wanted, while its password is asked for. */
data class FilesLocked(val channelId: Int) : Overlay
data class DeleteChannel(val id: Int) : Overlay
/** Kicking the clients picked in the tree: from the server, or from their channels. */
data class Kick(val fromServer: Boolean) : Overlay
/** Something being added to a whisper list, while the list is picked: its name and how to add it. */
class AddToWhisperList(val name: String, val add: (WhisperList) -> Unit) : Overlay
}
/** Where a server's screen is: on which page, the tree or the chat, and what is over it. */
@Stable
internal class ServerNav(page: ServerPage = ServerPage.Main, showChat: Boolean = false, chatKey: ChatKey = ChatKey.CHANNEL) {
var page by mutableStateOf(page)
var showChat by mutableStateOf(showChat)
/** The conversation the chat shows. */
var chatKey by mutableStateOf(chatKey)
var overlay by mutableStateOf<Overlay>(Overlay.None)
fun openChat(key: ChatKey) {
chatKey = key
showChat = true
}
fun back() {
page = ServerPage.Main
}
fun dismiss() {
overlay = Overlay.None
}
companion object {
// Sheets and dialogs are not kept: they would come back over a tree that has moved on.
val Saver = listSaver<ServerNav, Any>(
save = { listOf(it.showChat, saveKey(it.chatKey)) + savePage(it.page) },
restore = { ServerNav(restorePage(it.drop(2)), it[0] as Boolean, restoreKey(it[1] as String)) },
)
private fun saveKey(key: ChatKey) = when (key.scope()) {
ChatScope.SERVER -> "server"
ChatScope.CHANNEL -> "channel"
ChatScope.PRIVATE -> "private:${key.clientId()}"
}
private fun restoreKey(saved: String) = when {
saved == "server" -> ChatKey.SERVER
saved.startsWith("private:") -> ChatKey.privateWith(saved.substringAfter(':').toInt())
else -> ChatKey.CHANNEL
}
private fun savePage(page: ServerPage): List<Any> = when (page) {
ServerPage.Main -> listOf("main")
ServerPage.BanList -> listOf("bans")
ServerPage.WhisperLists -> listOf("whisper")
is ServerPage.EditChannel -> listOf("edit", page.edit.channelId, page.edit.parentId)
is ServerPage.Files -> listOf("files", page.channelId, page.name, page.password)
is ServerPage.ConnectionInfo -> listOf("info", page.clientId)
}
private fun restorePage(saved: List<Any>): ServerPage = when (saved[0]) {
"bans" -> ServerPage.BanList
"whisper" -> ServerPage.WhisperLists
"edit" -> ServerPage.EditChannel(ChannelEdit(saved[1] as Int, saved[2] as Int))
"files" -> ServerPage.Files(saved[1] as Int, saved[2] as String, saved[3] as String)
"info" -> ServerPage.ConnectionInfo(saved[1] as Int)
else -> ServerPage.Main
}
}
}
@Composable
internal fun rememberServerNav(): ServerNav = rememberSaveable(saver = ServerNav.Saver) { ServerNav() }
@@ -0,0 +1,167 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.WhisperListManager
import kotlinx.coroutines.launch
/** Joins [channel], asking for its password first when it is locked. */
internal fun ServerNav.join(server: ServerController, channel: ChannelItem) {
if (channel.locked) overlay = Overlay.JoinLocked(channel.id) else server.joinChannel(channel.id)
}
/** The sheet or dialog [ServerNav.overlay] names; a sheet goes with its client or channel when that leaves the tree. */
@Composable
internal fun ServerOverlay(
nav: ServerNav,
whisperLists: WhisperListManager,
server: ServerController,
state: SessionState,
tree: ServerTree,
treeView: TreeView,
picking: TreePicking,
snackbar: SnackbarHostState,
onLink: (String) -> Unit,
onEditContact: (String) -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
) {
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val can = server.permissions
// Out here: the dialog leaves the composition, and would take its scope along, before the deletion fails.
val scope = rememberCoroutineScope()
val dismiss = nav::dismiss
/** Closes the overlay, then does [action]. */
fun then(action: () -> Unit): () -> Unit = { dismiss(); action() }
when (val o = nav.overlay) {
Overlay.None -> {}
Overlay.Server -> remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = dismiss,
onBookmark = then { server.bookmark(state.channelId)?.let { b -> onEditBookmark(BookmarkEdit(-1, b)) } },
onBanList = if (can.canViewBanList()) then { nav.page = ServerPage.BanList } else null,
onCreateChannel = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, 0)) } else null)
}
is Overlay.Client -> {
val id = o.id
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = dismiss,
onMessage = then { nav.openChat(server.openPrivateChat(id)) },
onPoke = { server.poke(id, it); dismiss() },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); dismiss() },
onTalkRequest = if (client.self && (client.talkRequest || server.canRequestTalkPower)) {
{ server.setTalkRequest(it); dismiss() }
} else null,
onAddContact = { server.addContact(id, it) },
onEditContact = then { onEditContact(client.uniqueId) },
onConnectionInfo = then { nav.page = ServerPage.ConnectionInfo(id) },
onWhisper = if (state.whisperControls) then { server.whisperToClient(id) } else null,
onAddToWhisperList = if (state.whisperControls) then {
server.clientRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(client.name) { it.clients.add(ref) } }
} else null,
onMove = if (can.canMoveClients()) then { picking.moving = setOf(id) } else null,
onMoveToOwnChannel = if (can.canMoveClients() && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
then { server.moveClients(listOf(id), state.channelId) }
} else null,
onFindInTree = if (o.fromTree) null else then {
nav.showChat = false
treeView.show(TreeRef(false, id))
},
moderation = clientModeration(server, client, dismiss),
)
}
}
is Overlay.Channel -> {
val id = o.id
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = dismiss,
onJoin = then { nav.join(server, channel) },
onSubscribe = { server.setSubscribed(id, it); dismiss() },
onWhisper = if (state.whisperControls) then { server.whisperToChannel(id) } else null,
onAddToWhisperList = if (state.whisperControls) then {
server.channelRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(channel.name) { it.channels.add(ref) } }
} else null,
onFiles = if (can.canBrowseFiles()) then {
if (channel.locked) nav.overlay = Overlay.FilesLocked(id)
else nav.page = ServerPage.Files(id, channel.name, "")
} else null,
onCreateSub = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, id)) } else null,
onEdit = if (can.canEditChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(id)) } else null,
onDelete = if (can.canDeleteChannels()) then { nav.overlay = Overlay.DeleteChannel(id) } else null,
)
}
}
is Overlay.Kick -> {
val others = picking.kickable(o.fromServer)
val whom = others.singleOrNull()?.let { tree.client(it)?.name } ?: "${others.size} clients"
KickPrompt(
if (o.fromServer) "Kick $whom from the server?" else "Kick $whom from the channel?",
onDismiss = dismiss,
) { reason ->
dismiss()
picking.kick(o.fromServer, reason)
}
}
is Overlay.JoinLocked -> TextPrompt(
title = "Join ${tree.channel(o.channelId)?.name.orEmpty()}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = dismiss,
onConfirm = { dismiss(); server.joinChannel(o.channelId, it) },
)
is Overlay.FilesLocked -> TextPrompt(
title = "Files of ${tree.channel(o.channelId)?.name.orEmpty()}",
label = "Channel password",
confirm = "Open",
password = true,
onDismiss = dismiss,
onConfirm = { dismiss(); nav.page = ServerPage.Files(o.channelId, tree.channel(o.channelId)?.name.orEmpty(), it) },
)
is Overlay.DeleteChannel -> {
val channel = tree.channel(o.id)
AlertDialog(
onDismissRequest = dismiss,
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = then {
scope.launch { server.deleteChannel(o.id).onFailure { snackbar.showSnackbar("Could not delete the channel: ${it.message}") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } },
)
}
is Overlay.AddToWhisperList -> AddToWhisperListDialog(whisperLists, o.name, onDismiss = dismiss) { index, newName ->
dismiss()
whisperLists.addTo(index, newName, o.add)
}
}
}
@@ -0,0 +1,249 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SwipePrefs
import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.android.WhisperListManager
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.text.TsLink
/** A connection: the channel tree and the chat, with the voice controls underneath. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ServerScreen(
sessions: SessionController,
whisperLists: WhisperListManager,
account: MyTeamSpeakAccount,
swipe: SwipePrefs,
banReasons: BanReasonPresets,
server: ServerController,
snackbar: SnackbarHostState,
onSettings: () -> Unit,
/** Opens the given client's contact page. */
onEditContact: (String) -> Unit,
onEnableMicrophone: () -> Unit,
onConnectOther: () -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
/** Turns to another server, for a swipe over the tree. */
serverSwipe: SwipeState? = null,
/** False for a server beside the one on show while swiping to it. */
active: Boolean = true,
) {
val sessionState = server.state.collectAsStateWithLifecycle()
val state by sessionState
val treeState = server.tree.collectAsStateWithLifecycle()
val tree by treeState
val chatsState = server.chats.collectAsStateWithLifecycle()
val chats by chatsState
val nav = rememberServerNav()
// Out here, so the tree keeps its place while the chat or another page replaces it.
val treeList = rememberLazyListState()
val conversationState = remember(chatsState, nav) { derivedStateOf { chatsState.value[nav.chatKey] ?: chatsState.value.channel } }
val conversation by conversationState
val picking = rememberTreePicking(server, treeState, sessionState)
val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
// The chat lies to the right of the tree.
val chatBesideTree = treeSwipe == TreeSwipe.CHAT
val pageSwipe = rememberSwipeState()
val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
LaunchedEffect(chatRequest) {
val key = chatRequest ?: return@LaunchedEffect
nav.openChat(if (chats[key] != null) key else server.openPrivateChat(key.clientId))
server.chatRequestHandled()
}
val viewing = if (nav.showChat) conversation.key else null
LifecycleResumeEffect(viewing, active) {
if (active) server.viewing = viewing
onPauseOrDispose { server.viewing = null }
}
val uriHandler = LocalUriHandler.current
val attachments = rememberAttachmentActions(account, server, snackbar, conversation.key)
val onLink: (String) -> Unit = { href ->
val ref = TsLink.parse(href)
when {
ChatAttachment.isHref(href) -> attachments.open(href)
ServerLink.isLink(href) -> ServerLink.parse(href)?.let { sessions.open(it) }
ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false)
else -> nav.overlay = Overlay.Channel(ref.id)
}
}
// Find: in the tree, clients or channels; in the chat, the conversation on screen.
val find = rememberSaveable(saver = FindState.Saver) { FindState() }
val treeView = rememberTreeView(server, treeState, server.collapsed.collectAsStateWithLifecycle(), find)
val chatSearch = rememberChatSearch(conversationState, find)
LaunchedEffect(treeView.treeFind, nav.showChat) { treeView.restart(onScreen = !nav.showChat) }
LaunchedEffect(chatSearch.query, conversation.key, find.filter, nav.showChat) { chatSearch.restart(onScreen = nav.showChat) }
when (val page = nav.page) {
ServerPage.Main -> {}
ServerPage.BanList -> return BanListScreen(server, banReasons, onBack = nav::back)
ServerPage.WhisperLists -> return WhisperListsScreen(whisperLists, server, onBack = nav::back)
is ServerPage.EditChannel -> return ChannelEditScreen(server, page.edit, onDone = nav::back)
is ServerPage.Files -> return FilesScreen(server, page.channelId, page.name, page.password, onBack = nav::back)
is ServerPage.ConnectionInfo -> return ConnectionInfoScreen(server, page.clientId, tree.client(page.clientId), onBack = nav::back)
}
val onTree = !nav.showChat
BackHandler(active && nav.showChat) { nav.showChat = false }
BackHandler(active && onTree && picking.moving != null) { picking.moving = null }
BackHandler(active && onTree && picking.moving == null && picking.selection.isNotEmpty()) { picking.clear() }
BackHandler(active && find.open) { find.open = false }
Scaffold(
// A hardware keyboard's Ctrl+F, as on the desktop.
modifier = Modifier.onPreviewKeyEvent { e ->
val ctrlF = e.isCtrlPressed && e.key == Key.F
if (ctrlF && e.type == KeyEventType.KeyDown) find.show()
ctrlF
},
topBar = {
if (find.open) {
if (nav.showChat) {
FindBar(find, inTree = false, chatSearch.position, chatSearch.hits.size, chatSearch.capped, chatSearch::step)
} else {
FindBar(find, inTree = true, treeView.position, treeView.hits.size, false, treeView::step)
}
} else {
TopAppBar(
title = { ServerSwitcher(sessions, server, state, onConnectOther) },
expandedHeight = 48.dp,
actions = {
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
if (state.connected && state.whisperControls) WhisperMenu(whisperLists, server, state) { nav.page = ServerPage.WhisperLists }
IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
},
)
}
},
bottomBar = {
Column {
val ptt = rememberPttTarget(sessions)
WhisperBanner(state) { server.setWhisper(null) }
VoiceBar(state, ptt.owner != null, ptt.talking, sessions, server, onEnableMicrophone, nav.showChat, chats.anyUnread) {
nav.showChat = !nav.showChat
}
}
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
SwipeHost(
pageSwipe, nav.showChat,
neighbour = { chat, dir -> if (chatBesideTree && (dir > 0) != chat) !chat else null },
onSwipe = { nav.showChat = it },
modifier = Modifier.padding(padding).consumeWindowInsets(padding).imePadding(),
) { chat ->
if (!chat) Column(Modifier.fillMaxSize()) {
PickingBar(picking, server, tree, state.channelId) { nav.overlay = Overlay.Kick(it) }
ChannelTree(
serverName = state.title,
tree = treeView.tree,
collapsed = treeView.collapsed,
currentChannel = state.channelId,
onToggle = { treeView.toggle(it.id) },
onChannel = { channel ->
val clients = picking.moving
when {
channel.spacer != null -> {}
clients != null -> picking.moveTo(channel.id, clients)
else -> nav.overlay = Overlay.Channel(channel.id)
}
},
onChannelDoubleTap = { channel ->
val clients = picking.moving
when {
clients != null -> picking.moveTo(channel.id, clients)
channel.id == state.channelId -> {}
else -> nav.join(server, channel)
}
},
onClient = {
if (picking.selection.isEmpty()) nav.overlay = Overlay.Client(it.id, fromTree = true)
else picking.toggle(it.id)
},
onServer = { nav.overlay = Overlay.Server },
modifier = Modifier.weight(1f).swipeSource(when (treeSwipe) {
TreeSwipe.CHAT -> pageSwipe
TreeSwipe.SERVERS -> serverSwipe
TreeSwipe.OFF -> null
}),
reveal = treeView.reveal,
onRevealed = { treeView.reveal = null },
found = treeView.found,
foundCurrent = treeView.current,
listState = treeList,
selected = picking.selection,
onClientLongPress = if (picking.canPick) ({ picking.pick(it.id) }) else null,
onShowSelf = { treeView.show(TreeRef(false, state.selfClientId)) },
)
} else {
ChatPane(
chats = chats,
selected = conversation,
canSend = state.connected,
onSelect = { nav.chatKey = it },
onClose = { key ->
if (nav.chatKey == key) nav.chatKey = ChatKey.CHANNEL
server.closePrivateChat(key)
},
onSend = { server.send(conversation.key, it) },
onAttach = attachments.share,
onLink = onLink,
modifier = Modifier.fillMaxSize(),
lines = chatSearch.lines,
find = chatSearch.query,
current = chatSearch.at,
reveal = chatSearch.reveal,
onRevealed = { chatSearch.reveal = null },
swipeTabs = chatTabSwipe,
linesModifier = Modifier.swipeSource(if (chatBesideTree) pageSwipe else null),
)
}
}
}
ServerOverlay(nav, whisperLists, server, state, tree, treeView, picking, snackbar, onLink, onEditContact, onEditBookmark)
}
@@ -0,0 +1,94 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
internal fun ServerSwitcher(sessions: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by sessions.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; sessions.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -0,0 +1,141 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AppParts
import eu.lixko.ts3j.client.android.IconTheme
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SwipePrefs
import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.config.Settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES, MY_TEAMSPEAK }
/**
* The settings, by category. Every change is saved and put into effect at once,
* as there is no dialog to confirm.
*/
@Composable
fun SettingsScreen(parts: AppParts, onContacts: () -> Unit, onBack: () -> Unit) {
var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
when (page) {
SettingsPage.SOUND -> return SoundSettingsScreen(parts.settings, parts.sessions, parts.audio, onBack = { page = null })
SettingsPage.NETWORK -> return NetworkSettingsScreen(parts.settings, parts.sessions, onBack = { page = null })
SettingsPage.GIANT_PTT -> return GiantPttScreen(parts.sessions, onBack = { page = null })
SettingsPage.DESIGN -> return DesignScreen(parts.settings, parts.icons, parts.swipe, parts.sessions, onBack = { page = null })
SettingsPage.IDENTITIES -> return IdentitiesScreen(parts.identities, onBack = { page = null })
SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { page = null })
null -> {}
}
SubScreen("Settings", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
LinkRow("Contacts", "Friends and blocked users", "CONTACT", onContacts)
LinkRow("Sound Settings", "Devices, transmission, voice activation, processing, volume", "PLAYBACK") {
page = SettingsPage.SOUND
}
LinkRow("Network", "Bitrate, error correction, redundancy, buffering", "PING_4") {
page = SettingsPage.NETWORK
}
LinkRow("Giant PTT", "A push-to-talk button filling the screen", "CAPTURE") {
page = SettingsPage.GIANT_PTT
}
LinkRow("Design", "Icon pack, country flags, client colours, description pictures", "GUISETUP") {
page = SettingsPage.DESIGN
}
LinkRow("Identities", "Create, import, export, security level",
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
LinkRow("myTeamSpeak",
if (parts.myTeamSpeak.login.isSignedIn) "Signed in as ${parts.myTeamSpeak.login.username()}"
else "Sign in to bring over your synchronised bookmarks, identities and contacts",
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
}
}
}
@Composable
private fun DesignScreen(settings: Settings, icons: IconTheme, swipe: SwipePrefs, sessions: SessionController, onBack: () -> Unit) {
SubScreen("Design", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
IconPackPicker(icons)
var pictures by remember { mutableStateOf(settings.descriptionPictures.get()) }
Toggle("Show pictures in descriptions", pictures) {
pictures = it
settings.descriptionPictures.set(it)
settings.save()
}
Section("Channel tree")
var flags by remember { mutableStateOf(settings.countryFlags.get()) }
Toggle("Show country flags in the channel tree", flags) {
flags = it
settings.countryFlags.set(it)
settings.save()
}
val colors = settings.clientRowColors
var any by remember { mutableIntStateOf(colors.any) }
var talking by remember { mutableIntStateOf(colors.talking) }
var mutedAway by remember { mutableIntStateOf(colors.mutedAway) }
RowColorPicker("Client background", any) {
any = it
colors.any = it
sessions.clientRowColorsChanged()
}
RowColorPicker("While talking", talking) {
talking = it
colors.talking = it
sessions.clientRowColorsChanged()
}
RowColorPicker("Muted / away", mutedAway) {
mutedAway = it
colors.mutedAway = it
sessions.clientRowColorsChanged()
}
val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
Picker("Swipe sideways", listOf(
TreeSwipe.OFF to "Off",
TreeSwipe.CHAT to "Channel tree and chat",
TreeSwipe.SERVERS to "Connected servers",
), treeSwipe, swipe::setTree)
Section("Chat")
val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
Toggle("Swipe between chat tabs", chatTabSwipe, swipe::setChatTabs)
}
}
}
/** Chooses the icon pack, and brings in TeamSpeak packs from a file. */
@Composable
private fun IconPackPicker(theme: IconTheme) {
val packs by theme.packs.collectAsStateWithLifecycle()
val active by theme.active.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
var failed by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch {
val pack = withContext(Dispatchers.IO) { runCatching { theme.import(uri) }.getOrNull() }
failed = if (pack == null) "That file is not an icon pack." else null
}
}
Picker("Icon pack", packs.map { it to it.name() }, active) { theme.select(it) }
LinkRow("Import icon pack", "A TeamSpeak 3 pack (.zip), such as those in the gfx folder of a TeamSpeak 3 install") {
importer.launch(arrayOf("application/zip", "application/octet-stream"))
}
failed?.let { Hint(it) }
}
@@ -0,0 +1,175 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Slider
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
/** The width a segment needs for a label of a word or two; narrower screens get a list instead. */
private val SEGMENT_WIDTH = 110.dp
/** A full-screen page with a back arrow; the system back gesture leaves it the same way. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SubScreen(
title: String,
onBack: () -> Unit,
actions: @Composable RowScope.() -> Unit = {},
snackbar: SnackbarHostState? = null,
content: @Composable (PaddingValues) -> Unit,
) {
BackHandler(onBack = onBack)
Scaffold(
snackbarHost = { snackbar?.let { SnackbarHost(it) } },
topBar = {
TopAppBar(
title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = actions,
)
},
content = content,
)
}
/** A row that opens another page, or does one thing when tapped. */
@Composable
internal fun LinkRow(title: String, summary: String?, iconKey: String? = null, onClick: () -> Unit) {
ListItem(
headlineContent = { Text(title) },
supportingContent = summary?.let { { Text(it) } },
leadingContent = iconKey?.let { { PackIcon(it, null) } },
modifier = Modifier.clickable(onClick = onClick),
)
}
@Composable
internal fun Section(title: String) {
Text(title, Modifier.padding(start = 16.dp, top = 24.dp, bottom = 4.dp),
style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
}
@Composable
internal fun Choice(label: String, selected: Boolean, onSelect: () -> Unit) {
Row(Modifier.fillMaxWidth().clickable(onClick = onSelect).padding(horizontal = 16.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically) {
RadioButton(selected, onClick = onSelect)
Text(label, Modifier.padding(start = 8.dp))
}
}
/** One of [options] as a row of segments, or as radio buttons where the segments would not fit. */
@Composable
internal fun <T> Segments(options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth - 32.dp < SEGMENT_WIDTH * options.size) {
Column { for ((value, label) in options) Choice(label, value == selected) { onSelect(value) } }
return@BoxWithConstraints
}
SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) {
options.forEachIndexed { index, (value, label) ->
SegmentedButton(
selected = value == selected,
onClick = { onSelect(value) },
shape = SegmentedButtonDefaults.itemShape(index, options.size),
) { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }
}
}
}
}
@Composable
internal fun Toggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
Row(Modifier.fillMaxWidth().clickable { onChange(!checked) }.padding(horizontal = 16.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically) {
Text(label, Modifier.weight(1f))
Switch(checked, onChange)
}
}
@Composable
internal fun Hint(text: String) {
Text(text, Modifier.padding(horizontal = 16.dp, vertical = 2.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
/** One of [options], shown as its label and picked from a menu. */
@Composable
internal fun <T> Picker(label: String, options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {
var open by remember { mutableStateOf(false) }
Box {
Column(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(label)
Text(options.firstOrNull { it.first == selected }?.second ?: "", style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(open, { open = false }) {
for ((value, text) in options) {
DropdownMenuItem({ Text(text) }, onClick = {
open = false
onSelect(value)
})
}
}
}
}
/** A slider that applies its value once let go of. */
@Composable
internal fun Level(
label: String,
value: Float,
range: ClosedFloatingPointRange<Float>,
format: (Float) -> String,
steps: Int = 0,
onChange: (Float) -> Unit = {},
onDone: (Float) -> Unit,
) {
var current by remember(value) { mutableFloatStateOf(value) }
Column(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) {
Row {
Text(label, Modifier.weight(1f))
Text(format(current), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Slider(current, {
current = it
onChange(it)
}, valueRange = range, steps = steps, onValueChangeFinished = { onDone(current) })
}
}
@@ -0,0 +1,309 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.Icon
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.layout.onSizeChanged
import kotlinx.coroutines.launch
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.net.Details
import kotlin.math.roundToInt
/** What can be done with a client: the private chat, a poke, a move, their volume, filing them as a contact. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ClientSheet(
client: ClientItem,
details: Details?,
onLink: (String) -> Unit,
away: Boolean,
initialVolume: Double,
onDismiss: () -> Unit,
onMessage: () -> Unit,
onPoke: (String) -> Unit,
onVolume: (Double) -> Unit,
onAway: (Boolean) -> Unit,
/** Asks for talk power with a reason, or withdraws the request with null; null when we may not ask. */
onTalkRequest: ((String?) -> Unit)?,
onAddContact: (ContactType) -> Unit,
onEditContact: () -> Unit,
onConnectionInfo: () -> Unit,
/** Both null when whisper controls are hidden. */
onWhisper: (() -> Unit)?,
onAddToWhisperList: (() -> Unit)?,
/** Null when the client cannot be moved. */
onMove: (() -> Unit)?,
/** Null when the client cannot be moved, or is in our channel already. */
onMoveToOwnChannel: (() -> Unit)?,
/** Null when the sheet was opened from the tree. */
onFindInTree: (() -> Unit)?,
/** Kicks, bans and groups, as far as we may use them; null when there are none. */
moderation: (@Composable () -> Unit)? = null,
) {
var poking by remember { mutableStateOf(false) }
var requesting by remember { mutableStateOf(false) }
val sheetState = rememberModalBottomSheetState()
val scope = rememberCoroutineScope()
// A half-open sheet would fold the admin actions out below the screen's edge.
val adminActions = @Composable { content: @Composable ColumnScope.() -> Unit ->
ExpandableAction("PERMISSIONS_CLIENTS", "Admin actions…", onExpand = { scope.launch { sheetState.expand() } }, content)
}
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
StatusIcon(client.status)
Column(Modifier.weight(1f)) {
// The country's flag goes before the name, as in TeamSpeak's info frame.
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CountryFlag(client.country)
Text(client.name, style = MaterialTheme.typography.titleLarge)
}
if (client.name != client.nickname) Text(client.nickname, style = MaterialTheme.typography.bodyMedium)
if (client.awayMessage.isNotEmpty()) Text(client.awayMessage, style = MaterialTheme.typography.bodyMedium)
}
val viewer = LocalPictureViewer.current
val images = LocalServerImages.current
Avatar(client.uniqueId, client.avatarFlag, Modifier.clickable(enabled = viewer != null && images != null) {
viewer?.invoke(ViewedPicture("avatar_${client.nickname}", ownAvatar = client.self) {
images?.avatarData(client.uniqueId, client.avatarFlag)
})
})
}
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) }
if (client.self) {
Action("AWAY", if (away) "Back" else "Away") { onAway(!away) }
onTalkRequest?.let { request ->
if (client.talkRequest) Action("TALK_POWER_CANCEL_REQUEST", "Cancel talk power request") { request(null) }
else Action("TALK_POWER_REQUEST", "Request talk power") { requesting = true }
}
moderation?.let { adminActions { it() } }
} else {
Action("PLAYER_CHAT", "Send message", onClick = onMessage)
Action("POKE", "Poke") { poking = true }
onWhisper?.let { Action("PLAYER_WHISPER", "Whisper", onClick = it) }
// "Add to whisper list…" (onAddToWhisperList) is left out for now.
onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) }
if (onMove != null || moderation != null) {
adminActions {
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
moderation?.invoke()
}
}
if (client.contactType == null) {
Row {
Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) }
Action("ADD_FOE", "Block", Modifier.weight(1f)) { onAddContact(ContactType.BLOCKED) }
}
} else {
Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact)
}
}
Action("INFO", "Connection info", onClick = onConnectionInfo)
if (!client.self) {
var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) }
Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB",
Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium)
Slider(
volume, { volume = it.roundToInt().toFloat() },
Modifier.padding(horizontal = 24.dp),
valueRange = -30f..20f,
onValueChangeFinished = { onVolume(volume.toDouble()) },
)
}
}
}
if (poking) {
TextPrompt(
title = "Poke ${client.name}",
label = "Message",
confirm = "Poke",
onDismiss = { poking = false },
onConfirm = { poking = false; onPoke(it) },
)
}
if (requesting) {
TextPrompt(
title = "Request talk power",
label = "Reason",
confirm = "Request",
onDismiss = { requesting = false },
onConfirm = { requesting = false; onTalkRequest?.invoke(it.trim()) },
)
}
}
/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChannelSheet(
channel: ChannelItem,
details: Details?,
onLink: (String) -> Unit,
current: Boolean,
onDismiss: () -> Unit,
onJoin: () -> Unit,
onSubscribe: (Boolean) -> Unit,
/** Both null when whisper controls are hidden. */
onWhisper: (() -> Unit)?,
onAddToWhisperList: (() -> Unit)?,
/** Each null when we may not. */
onFiles: (() -> Unit)?,
onCreateSub: (() -> Unit)?,
onEdit: (() -> Unit)?,
onDelete: (() -> Unit)?,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Text(channel.name, Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
style = MaterialTheme.typography.titleLarge)
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
if (!current) {
Action("CHANNEL_SWITCH", "Join", onClick = onJoin)
}
if (channel.subscribed) {
Action("UNSUBSCRIBE_FROM_CHANNEL", "Unsubscribe") { onSubscribe(false) }
} else {
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
}
onWhisper?.let { Action("WHISPER", "Whisper", onClick = it) }
onAddToWhisperList?.let { Action("ON_WHISPERLIST", "Add to whisper list…", onClick = it) }
onFiles?.let { Action("FILETRANSFER", "Browse files", onClick = it) }
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) }
}
}
}
/** The server's details: its version, who is on it, its welcome message. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ServerSheet(
details: Details,
onLink: (String) -> Unit,
onDismiss: () -> Unit,
onBookmark: () -> Unit,
onBanList: (() -> Unit)?,
onCreateChannel: (() -> Unit)?,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) {
PackIcon("SERVER_GREEN", null)
Text(details.title(), style = MaterialTheme.typography.titleLarge)
}
DetailsSection(details, onLink)
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
onCreateChannel?.let { Action("CHANNEL_CREATE", "Create channel", onClick = it) }
onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) }
}
}
}
@Composable
internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifier.fillMaxWidth(), onClick: () -> Unit) {
ListItem(
headlineContent = { Text(label) },
leadingContent = { PackIcon(iconKey, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = modifier.clickable(onClick = onClick).padding(horizontal = 8.dp),
)
}
/** A row that, once tapped, gives its place to the [content] it stands for, scrolled into view. */
@Composable
internal fun ExpandableAction(
iconKey: String,
label: String,
onExpand: () -> Unit = {},
content: @Composable ColumnScope.() -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val inView = remember { BringIntoViewRequester() }
if (!expanded) {
ListItem(
headlineContent = { Text(label) },
leadingContent = { PackIcon(iconKey, null) },
trailingContent = { Icon(Icons.Filled.KeyboardArrowDown, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = Modifier.fillMaxWidth().clickable { expanded = true; onExpand() }.padding(horizontal = 8.dp),
)
}
AnimatedVisibility(expanded, enter = expandVertically() + fadeIn()) {
Column(
Modifier.bringIntoViewRequester(inView)
// Follows the items as they unfold.
.onSizeChanged { scope.launch { inView.bringIntoView() } },
content = content,
)
}
}
/** Asks for one line of text. */
@Composable
fun TextPrompt(
title: String,
label: String,
confirm: String,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
initial: String = "",
password: Boolean = false,
) {
var text by remember { mutableStateOf(initial) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
OutlinedTextField(text, { text = it }, label = { Text(label) }, singleLine = true,
visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None)
},
confirmButton = { TextButton(onClick = { onConfirm(text) }) { Text(confirm) } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@@ -0,0 +1,260 @@
package eu.lixko.ts3j.client.android.ui
import android.content.Intent
import android.net.Uri
import android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION
import android.provider.Settings.canDrawOverlays
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AudioSetup
import eu.lixko.ts3j.client.android.MicLevel
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.audio.InputLevel
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings
import kotlin.math.roundToInt
private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB")
/** Audio devices, transmission, voice activation, processing and playback. */
@Composable
fun SoundSettingsScreen(settings: Settings, sessions: SessionController, audio: AudioSetup, onBack: () -> Unit) {
fun <T> change(setting: Setting<T>, value: T) {
setting.set(value)
sessions.applySettings()
}
var inputMode by remember { mutableStateOf(settings.inputMode.get()) }
var vadMode by remember { mutableStateOf(settings.vadMode.get()) }
var agc by remember { mutableStateOf(settings.agc.get()) }
var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning.get()) }
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) }
var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) }
var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) }
val inputs by audio.inputDevices.collectAsStateWithLifecycle()
val outputs by audio.outputDevices.collectAsStateWithLifecycle()
val route by audio.route.collectAsStateWithLifecycle()
val level by sessions.micLevel.collectAsStateWithLifecycle()
val packs by audio.soundPacks.collectAsStateWithLifecycle()
var pack by remember { mutableStateOf(audio.soundPack?.id()) }
LifecycleStartEffect(Unit) {
sessions.watchLevel(true)
onStopOrDispose { sessions.watchLevel(false) }
}
SubScreen("Sound Settings", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Devices")
DevicePicker("Microphone", inputs, inputDevice) {
inputDevice = it
change(settings.inputDevice, it)
}
DevicePicker("Speaker", outputs, outputDevice) {
outputDevice = it
change(settings.outputDevice, it)
}
Picker(
"Microphone preset",
INPUT_PRESETS.map { (preset, label) ->
val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !audio.unprocessedSupported
preset to if (unsupported) "$label (not supported here)" else label
},
route.inputPreset(),
) { audio.setRoute(AudioRoute(it, route.usage())) }
Hint(PRESET_HINTS.getValue(route.inputPreset()))
Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp))
for ((usage, label) in USAGES) {
Choice(label, route.usage() == usage) { audio.setRoute(AudioRoute(route.inputPreset(), usage)) }
}
Section("Transmission")
for ((mode, label) in INPUT_MODES) {
Choice(label, inputMode == mode) {
inputMode = mode
change(settings.inputMode, mode)
}
}
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(audio)
val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC
LevelMeter(level, threshold.takeIf { gated })
if (!level.live) {
Hint(if (sessions.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.")
}
if (inputMode == Settings.InputMode.VOICE_ACTIVATION) {
Section("Voice activation")
for ((mode, label) in VAD_MODES) {
Choice(label, vadMode == mode) {
vadMode = mode
change(settings.vadMode, mode)
}
}
if (vadMode != Settings.VadMode.AUTOMATIC) {
Level("Volume threshold", settings.vadThresholdDb.get().toFloat(), -50f..50f, { "${it.roundToInt()}" },
onChange = { threshold = it }) {
change(settings.vadThresholdDb, it.roundToInt().toDouble())
}
}
if (vadMode != Settings.VadMode.VOLUME_GATE) {
Level("Speech likelihood", settings.speechThreshold.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change(settings.speechThreshold, it.toDouble())
}
}
}
Section("Processing")
val suppression = if (settings.denoise.get()) settings.denoiserLevel.get() + 1 else 0
Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(),
{ DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) {
val step = it.roundToInt()
settings.denoise.set(step > 0)
if (step > 0) settings.denoiserLevel.set(step - 1)
sessions.applySettings()
}
Toggle("Automatic gain control", agc) {
agc = it
change(settings.agc, it)
}
if (agc) {
Level("Boost quiet speech", settings.agcBoostDb.get().toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(),
{ "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) {
change(settings.agcBoostDb, it.roundToInt())
}
}
Section("Playback")
Level("Volume", settings.outputVolume.get().toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) {
change(settings.outputVolume, it.toDouble())
}
Section("Notification sounds")
if (packs.isEmpty()) {
Hint("This build of the app came without sound packs.")
} else {
Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id ->
packs.firstOrNull { it.id() == id }?.let(audio::setSoundPack)
pack = id
}
}
Level("Volume", settings.soundVolume.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change(settings.soundVolume, it.toDouble())
}
Toggle("Beep when talking while muted", mutedTalkWarning) {
mutedTalkWarning = it
change(settings.mutedTalkWarning, it)
}
}
}
}
private val INPUT_MODES = listOf(
Settings.InputMode.VOICE_ACTIVATION to "Voice activation",
Settings.InputMode.PUSH_TO_TALK to "Push to talk",
Settings.InputMode.CONTINUOUS to "Continuous",
)
private val INPUT_PRESETS = listOf(
AudioRoute.InputPreset.VOICE_RECOGNITION to "Voice recognition",
AudioRoute.InputPreset.VOICE_COMMUNICATION to "Voice communication",
AudioRoute.InputPreset.UNPROCESSED to "Unprocessed",
AudioRoute.InputPreset.VOICE_PERFORMANCE to "Voice performance",
AudioRoute.InputPreset.GENERIC to "Generic",
AudioRoute.InputPreset.CAMCORDER to "Camcorder",
)
private val PRESET_HINTS = mapOf(
AudioRoute.InputPreset.VOICE_RECOGNITION to "Little or no processing by the phone; the client's own does the rest.",
AudioRoute.InputPreset.VOICE_COMMUNICATION to
"The phone's call processing: echo cancellation, noise suppression and gain. Works best with voices played as a call.",
AudioRoute.InputPreset.UNPROCESSED to "The raw microphone signal.",
AudioRoute.InputPreset.VOICE_PERFORMANCE to "Low latency and no processing, meant for live performance.",
AudioRoute.InputPreset.GENERIC to "The phone's default microphone source, with whatever it applies to it.",
AudioRoute.InputPreset.CAMCORDER to "Tuned for recording video, often with the rear microphone.",
)
private val USAGES = listOf(
AudioRoute.Usage.MEDIA to "As media (Bluetooth stays in high quality)",
AudioRoute.Usage.VOICE_COMMUNICATION to "As a call (lets the phone cancel echo)",
)
private val VAD_MODES = listOf(
Settings.VadMode.AUTOMATIC to "Automatic",
Settings.VadMode.VOLUME_GATE to "Volume gate",
Settings.VadMode.HYBRID to "Hybrid",
)
/** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */
@Composable
private fun FloatingButtonToggle(audio: AudioSetup) {
val context = LocalContext.current
val enabled by audio.pttOverlay.collectAsStateWithLifecycle()
val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (canDrawOverlays(context)) audio.setPttOverlay(true)
}
Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on ->
if (!on || canDrawOverlays(context)) audio.setPttOverlay(on)
else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")))
}
Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.")
}
/** Picks a device by its settings id; one that is not plugged in now still shows as chosen. */
@Composable
private fun DevicePicker(label: String, devices: List<AudioDevice>, selected: String, onSelect: (String) -> Unit) {
val options = devices.map { it.id() to it.label() }.let { list ->
if (list.any { it.first == selected }) list else list + (selected to "Not connected")
}
Picker(label, options, selected, onSelect)
}
/** The microphone level, lit while it would be sent, with the volume gate's threshold marked. */
@Composable
private fun LevelMeter(level: MicLevel, thresholdDb: Float?) {
val track = MaterialTheme.colorScheme.surfaceVariant
val fill = if (level.transmitting) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline
val marker = MaterialTheme.colorScheme.onSurface
fun fraction(db: Double) =
((db - InputLevel.MIN_DB) / (InputLevel.MAX_DB - InputLevel.MIN_DB)).toFloat().coerceIn(0f, 1f)
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Row {
Text("Microphone level", Modifier.weight(1f))
if (level.live) Text("${level.db.roundToInt()}", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Canvas(Modifier.fillMaxWidth().padding(top = 6.dp).height(12.dp)) {
val radius = CornerRadius(size.height / 2)
drawRoundRect(track, cornerRadius = radius)
if (level.live) {
drawRoundRect(fill, size = Size(size.width * fraction(level.db), size.height), cornerRadius = radius)
}
if (thresholdDb != null) {
val x = size.width * fraction(thresholdDb.toDouble())
drawLine(marker, Offset(x, -2.dp.toPx()), Offset(x, size.height + 2.dp.toPx()), strokeWidth = 2.dp.toPx())
}
}
}
}
@@ -0,0 +1,152 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.core.animate
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.awaitHorizontalTouchSlopOrCancellation
import androidx.compose.foundation.gestures.horizontalDrag
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.positionChangeIgnoreConsumed
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.input.pointer.util.addPointerInputChange
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.sign
/** How fast a short swipe must be to turn the page. */
private val FLING_VELOCITY = 600.dp
/** Where a sideways swipe between a [SwipeHost]'s pages is at. */
@Stable
class SwipeState {
/** How far the page on show has moved, in pixels; negative to the left. */
internal var shift by mutableFloatStateOf(0f)
/** Whether a swipe is under way, so the pages either side are on show too. */
internal var active by mutableStateOf(false)
/** The pointer that went down over one of the [swipeSource]s. */
internal var armed: PointerId? = null
}
@Composable
internal fun rememberSwipeState() = remember { SwipeState() }
/** Lets a swipe that starts over this element turn [state]'s pages. */
internal fun Modifier.swipeSource(state: SwipeState?): Modifier =
if (state == null) this else pointerInput(state) {
awaitEachGesture {
// Seen before the host looks at the same press.
state.armed = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial).id
}
}
/**
* Pages side by side, [current] on show and those either side ([neighbour] gives them, -1 to the left,
* 1 to the right) following the finger. A swipe has to start over a [swipeSource] of [state];
* one that has no page to go to is left to a host further out. [onSwipe] is told of the page swiped to.
* Pages are told apart by equality, so [T] should be a key rather than a snapshot of what it shows.
*/
@Composable
internal fun <T : Any> SwipeHost(
state: SwipeState,
current: T,
neighbour: (T, Int) -> T?,
onSwipe: (T) -> Unit,
modifier: Modifier = Modifier,
page: @Composable (T) -> Unit,
) {
var shown by remember { mutableStateOf(current) }
/** A page swiped to that [current] has not caught up with yet. */
var awaited by remember { mutableStateOf<T?>(null) }
val latest by rememberUpdatedState(current)
val pageNear by rememberUpdatedState(neighbour)
val swiped by rememberUpdatedState(onSwipe)
val scope = rememberCoroutineScope()
var settling by remember { mutableStateOf<Job?>(null) }
LaunchedEffect(current) {
awaited = null
if (!state.active) shown = current
}
Box(modifier.clipToBounds().pointerInput(state) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
if (state.armed != down.id) return@awaitEachGesture
val start = awaitHorizontalTouchSlopOrCancellation(down.id) { change, over ->
if (pageNear(shown, direction(over)) != null) change.consume()
} ?: return@awaitEachGesture
settling?.cancel()
state.active = true
val width = size.width.toFloat()
val left = pageNear(shown, -1)
val right = pageNear(shown, 1)
val drag = { dx: Float ->
state.shift = (state.shift + dx).coerceIn(if (right != null) -width else 0f, if (left != null) width else 0f)
}
val velocity = VelocityTracker()
velocity.addPointerInputChange(start)
drag(start.positionChangeIgnoreConsumed().x)
val lifted = horizontalDrag(start.id) { change ->
drag(change.positionChange().x)
change.consume()
velocity.addPointerInputChange(change)
}
val fling = if (lifted) velocity.calculateVelocity().x else 0f
val from = state.shift
val dir = when {
abs(fling) > FLING_VELOCITY.toPx() -> direction(fling)
abs(from) > width / 3 -> direction(from)
else -> 0
}
// A fling back against the swipe turns no page.
val target = if (dir != 0 && dir == direction(from)) pageNear(shown, dir) else null
settling = scope.launch {
animate(from, if (target != null) -dir * width else 0f, fling) { value, _ -> state.shift = value }
if (target != null) {
shown = target
awaited = target
swiped(target)
} else if (awaited == null) {
shown = latest
}
state.shift = 0f
state.active = false
}
}
}) {
val at = shown
val pages = if (!state.active) listOf(at to 0)
else listOfNotNull(neighbour(at, -1)?.to(-1), at to 0, neighbour(at, 1)?.to(1))
for ((item, slot) in pages) {
// Keyed, so the page swiped to keeps its state when it becomes the one on show.
key(item) {
Box(Modifier.fillMaxSize().graphicsLayer { translationX = state.shift + slot * size.width }) {
page(item)
}
}
}
}
}
/** A drag or fling to the left heads for what lies to the right. */
private fun direction(dx: Float): Int = -sign(dx).toInt()
@@ -0,0 +1,151 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync.Conflict
/**
* Which copy to keep of each item changed both here and in myTeamSpeak since the last
* synchronisation: the item's fields side by side, the ones that differ in bold.
* [onDone] gets whether the user went on; the choices are recorded on the conflicts.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SyncConflictsScreen(conflicts: List<Conflict>, onDone: (Boolean) -> Unit) {
// Mirrors the choices recorded on the conflicts, for recomposition.
val choices = remember(conflicts) {
mutableStateMapOf<Int, Conflict.Choice>().apply {
conflicts.forEachIndexed { i, c -> c.choice()?.let { put(i, it) } }
}
}
fun choose(index: Int, choice: Conflict.Choice) {
conflicts[index].choose(choice)
choices[index] = choice
}
BackHandler { onDone(false) }
Scaffold(
topBar = {
TopAppBar(
title = { Text("Synchronization conflicts") },
navigationIcon = { IconButton(onClick = { onDone(false) }) { Icon(Icons.Filled.Close, "Cancel") } },
)
},
bottomBar = {
Surface(tonalElevation = 3.dp) {
Row(
Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.HERE) } }) {
Text("Keep all of this device's")
}
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.CLOUD) } }) {
Text("Keep all of myTeamSpeak's")
}
}
Button(onClick = { onDone(true) }, enabled = choices.size == conflicts.size) { Text("Synchronize") }
}
}
},
) { padding ->
LazyColumn(
Modifier.padding(padding),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item { Text("Changed here and in myTeamSpeak since the last synchronization:") }
itemsIndexed(conflicts) { index, conflict ->
ConflictCard(conflict, choices[index]) { choose(index, it) }
}
}
}
}
@Composable
private fun ConflictCard(conflict: Conflict, choice: Conflict.Choice?, onChoose: (Conflict.Choice) -> Unit) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text((if (conflict.isIdentity) "Identity: " else "Bookmark: ") + conflict.title(),
style = MaterialTheme.typography.titleMedium)
Row {
Spacer(0.3f)
Header(if (conflict.deletedHere()) "This device (deleted)" else "This device")
Header(if (conflict.deletedInCloud()) "myTeamSpeak (deleted)" else "myTeamSpeak")
}
for (d in conflict.differences()) {
Row {
Text(d.label(), Modifier.weight(0.3f), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
Value(if (conflict.deletedHere()) "—" else d.here(), d.differs())
Value(if (conflict.deletedInCloud()) "—" else d.cloud(), d.differs())
}
}
Option(if (conflict.deletedHere()) "Delete" else "Keep this device's", choice == Conflict.Choice.HERE) {
onChoose(Conflict.Choice.HERE)
}
Option(if (conflict.deletedInCloud()) "Delete" else "Keep myTeamSpeak's", choice == Conflict.Choice.CLOUD) {
onChoose(Conflict.Choice.CLOUD)
}
}
}
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Spacer(weight: Float) {
androidx.compose.foundation.layout.Spacer(Modifier.weight(weight))
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Header(text: String) {
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.labelMedium)
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Value(text: String, differs: Boolean) {
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.bodySmall,
fontWeight = if (differs) FontWeight.Bold else FontWeight.Normal)
}
@Composable
private fun Option(text: String, selected: Boolean, onClick: () -> Unit) {
Row(
Modifier.fillMaxWidth().selectable(selected, onClick = onClick, role = Role.RadioButton),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected, onClick = null)
Text(text, Modifier.padding(start = 8.dp))
}
}
@@ -0,0 +1,38 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
/** Colours that mean the same in either theme, as TeamSpeak uses them. */
object StatusColors {
val talking = Color(0xFF2E9BF0)
val muted = Color(0xFFD9443A)
val away = Color(0xFF9E8A2E)
val friend = Color(0xFF3A9D4A)
val blocked = Color(0xFFD9443A)
}
/** Links in chat and descriptions: blue, as links are, whatever the wallpaper's colours. */
@Composable
fun linkColor(): Color = if (isSystemInDarkTheme()) Color(0xFF7AB4FF) else Color(0xFF1A62D0)
/** Behind every match of the find bar's query, as on the desktop. */
@Composable
fun findMatchColor(): Color = if (isSystemInDarkTheme()) Color(0xFF5C4E1A) else Color(0xFFFFEBA3)
/** Behind the match the find bar is on. */
@Composable
fun findCurrentColor(): Color = if (isSystemInDarkTheme()) Color(0xFF9C6A12) else Color(0xFFFFB84D)
/** The system's own (wallpaper) colours, which every supported Android version offers. */
@Composable
fun Ts3Theme(content: @Composable () -> Unit) {
val context = LocalContext.current
val colors = if (isSystemInDarkTheme()) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
MaterialTheme(colorScheme = colors, content = content)
}
@@ -0,0 +1,145 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionState
/** Clients picked in the tree by a long press, to act on together, and clients being moved while a channel is picked. */
@Stable
internal class TreePicking(
private val server: ServerController,
private val tree: State<ServerTree>,
private val state: State<SessionState>,
) {
/** The clients to move, while a channel for them is being picked. */
var moving by mutableStateOf<Set<Int>?>(null)
private var picked by mutableStateOf(emptySet<Int>())
/** The picked clients still on the server. */
val selection by derivedStateOf { picked.filterTo(LinkedHashSet()) { tree.value.client(it) != null } }
val canPick: Boolean get() = with(server.permissions) { canMoveClients() || canKickFromChannel() || canKickFromServer() }
fun pick(clientId: Int) {
picked = selection + clientId
}
fun toggle(clientId: Int) {
picked = if (clientId in selection) selection - clientId else selection + clientId
}
fun clear() {
picked = emptySet()
}
/** Those of the selection not in our channel. */
val outsideOwnChannel: Set<Int>
get() = selection - tree.value.channel(state.value.channelId)?.clients.orEmpty().map { it.id }.toSet()
/** Whom of the selection a kick goes to: never us, and from a channel, nobody already in the default one. */
fun kickable(fromServer: Boolean): Set<Int> {
val inDefault = if (fromServer) emptySet() else tree.value.channel(server.defaultChannelId)?.clients.orEmpty().map { it.id }.toSet()
return selection - state.value.selfClientId - inDefault
}
fun kick(fromServer: Boolean, reason: String) {
val whom = kickable(fromServer)
if (fromServer) server.kickFromServer(whom, reason) else server.kickFromChannel(whom, reason)
clear()
}
fun moveTo(channelId: Int, clients: Set<Int>) {
server.moveClients(clients, channelId)
moving = null
clear()
}
}
@Composable
internal fun rememberTreePicking(server: ServerController, tree: State<ServerTree>, state: State<SessionState>): TreePicking =
remember(server, tree, state) { TreePicking(server, tree, state) }
/** Above the tree: the clients being moved, or what may be done with those picked. */
@Composable
internal fun PickingBar(picking: TreePicking, server: ServerController, tree: ServerTree, ownChannel: Int, onKick: (fromServer: Boolean) -> Unit) {
val moving = picking.moving
val selection = picking.selection
if (moving != null) {
val clients = moving.mapNotNull { tree.client(it) }
if (clients.isEmpty()) {
LaunchedEffect(moving) { picking.moving = null }
} else {
MovePrompt(clients.singleOrNull()?.name ?: "${clients.size} clients") { picking.moving = null }
}
} else if (selection.isNotEmpty()) {
val can = server.permissions
val outside = picking.outsideOwnChannel
SelectionBar(
count = selection.size,
onMove = if (can.canMoveClients()) ({ picking.moving = selection }) else null,
onMoveHere = if (can.canMoveClients() && outside.isNotEmpty()) ({ picking.moveTo(ownChannel, outside) }) else null,
onKickChannel = if (can.canKickFromChannel() && picking.kickable(false).isNotEmpty()) ({ onKick(false) }) else null,
onKickServer = if (can.canKickFromServer() && picking.kickable(true).isNotEmpty()) ({ onKick(true) }) else null,
onClear = picking::clear,
)
}
}
/** How many clients are picked in the tree, and what may be done with them at once. */
@Composable
private fun SelectionBar(
count: Int,
onMove: (() -> Unit)?,
onMoveHere: (() -> Unit)?,
onKickChannel: (() -> Unit)?,
onKickServer: (() -> Unit)?,
onClear: () -> Unit,
) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Clear selection") }
Text("$count selected", Modifier.weight(1f), maxLines = 1, style = MaterialTheme.typography.bodyMedium)
onMove?.let { IconButton(onClick = it) { PackIcon("CHANNEL_SWITCH", "Move to…") } }
onMoveHere?.let { IconButton(onClick = it) { PackIcon("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to my channel") } }
onKickChannel?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_CHANNEL", "Kick from channel") } }
onKickServer?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_SERVER", "Kick from server") } }
}
}
}
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
@@ -0,0 +1,141 @@
package eu.lixko.ts3j.client.android.ui
import android.widget.Toast
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.config.Settings
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
internal fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
sessions: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = sessions.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, sessions::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
}
}
}
val away = @Composable {
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
}
}
val chat = @Composable {
IconToggleButton(showChat, { onChat() }) {
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
Modifier.alpha(if (showChat) 1f else 0.7f))
}
}
}
Surface(tonalElevation = 3.dp) {
// The same places whatever shows: sides of three buttons each keep the talk button centred.
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
Slot { mic() }; Slot { deafen() }; Slot { activate() }
}
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
Slot { away() }; Slot { chat() }
}
}
}
}
private val SLOT = 48.dp
private val SIDE = SLOT * 3
/** One button's place in the bar, kept whether or not the button shows. */
@Composable
private fun Slot(content: @Composable () -> Unit) {
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
}
/** An icon button that also answers a long press. */
@Composable
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
Box(
Modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(CircleShape)
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.alpha(if (enabled) 1f else 0.38f),
contentAlignment = Alignment.Center,
) { content() }
}
@@ -0,0 +1,254 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.WhisperListManager
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.net.Whisper
/** Says the microphone whispers instead of talking in the channel, until stopped. */
@Composable
fun WhisperBanner(state: SessionState, onStop: () -> Unit) {
val target = state.whisper ?: return
Surface(color = MaterialTheme.colorScheme.tertiaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("WHISPER", null)
Column(Modifier.weight(1f).padding(horizontal = 12.dp)) {
Text("Whispering to $target", maxLines = 1, overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium)
if (state.whisperNobody) {
Text("Nobody there", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
}
}
TextButton(onClick = onStop) { Text("Stop") }
}
}
}
/** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */
@Composable
fun WhisperMenu(whisperLists: WhisperListManager, server: ServerController, state: SessionState, onManage: () -> Unit) {
val lists by whisperLists.all.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box {
IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") }
DropdownMenu(open, { open = false }) {
val replyTo = remember(open) { server.lastWhisperer() }
replyTo?.let { client ->
DropdownMenuItem({ Text("Reply to ${client.nickname}") }, leadingIcon = { PackIcon("PLAYER_WHISPER", null) },
onClick = { open = false; server.whisperToClient(client.id) })
}
for (list in lists) {
DropdownMenuItem({ Text(list.name.ifBlank { "Unnamed" }) },
leadingIcon = { PackIcon("ON_WHISPERLIST", null) },
enabled = !list.isEmpty,
onClick = { open = false; server.setWhisper(Whisper.of(list)) })
}
if (state.whisper != null) {
DropdownMenuItem({ Text("Stop whispering") }, leadingIcon = { PackIcon("WHISPER", null) },
onClick = { open = false; server.setWhisper(null) })
}
if (replyTo != null || lists.isNotEmpty() || state.whisper != null) HorizontalDivider()
DropdownMenuItem({ Text("Whisper lists…") }, leadingIcon = { PackIcon("WHISPERLISTS", null) },
onClick = { open = false; onManage() })
}
}
}
/** Picks the whisper list to add something to, or names a new one. */
@Composable
fun AddToWhisperListDialog(whisperLists: WhisperListManager, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) {
val lists by whisperLists.all.collectAsStateWithLifecycle()
var naming by remember { mutableStateOf(false) }
if (naming) {
TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = {
if (it.isNotBlank()) onPick(-1, it.trim()) else onDismiss()
})
return
}
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Add $what to") },
text = {
Column(Modifier.verticalScroll(rememberScrollState())) {
lists.forEachIndexed { index, list ->
ListItem(headlineContent = { Text(list.name.ifBlank { "Unnamed" }) },
modifier = Modifier.clickable { onPick(index, "") })
}
ListItem(headlineContent = { Text("New list…") }, modifier = Modifier.clickable { naming = true })
}
},
confirmButton = {},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** The saved whisper lists, each opening onto its channels and clients. */
@Composable
fun WhisperListsScreen(whisperLists: WhisperListManager, server: ServerController, onBack: () -> Unit) {
val lists by whisperLists.all.collectAsStateWithLifecycle()
/** The list being edited: its index, -1 for a new one; null on the overview. */
var editing by rememberSaveable { mutableStateOf<Int?>(null) }
editing?.let { index ->
WhisperListScreen(whisperLists, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null })
return
}
SubScreen("Whisper lists", onBack = onBack, actions = {
TextButton(onClick = { editing = -1 }) { Text("New") }
}) { padding ->
if (lists.isEmpty()) {
Box(Modifier.padding(padding).fillMaxWidth().padding(24.dp)) {
Text("No whisper lists", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
return@SubScreen
}
LazyColumn(Modifier.padding(padding)) {
itemsIndexed(lists) { index, list ->
var menu by remember { mutableStateOf(false) }
ListItem(
headlineContent = { Text(list.name.ifBlank { "Unnamed" }) },
supportingContent = { Text(summary(list)) },
leadingContent = { PackIcon("ON_WHISPERLIST", null) },
trailingContent = {
Box {
IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "List options") }
DropdownMenu(menu, { menu = false }) {
DropdownMenuItem({ Text("Whisper") }, enabled = !list.isEmpty, onClick = {
menu = false
server.setWhisper(Whisper.of(list))
onBack()
})
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; whisperLists.remove(index) })
}
}
},
modifier = Modifier.clickable { editing = index },
)
}
}
}
}
private fun summary(list: WhisperList): String {
val parts = listOfNotNull(
list.channels.size.takeIf { it > 0 }?.let { if (it == 1) "1 channel" else "$it channels" },
list.clients.size.takeIf { it > 0 }?.let { if (it == 1) "1 client" else "$it clients" },
)
return parts.joinToString(", ").ifEmpty { "Empty" }
}
/** One whisper list: its name, channels and clients, saved on Save. */
@Composable
private fun WhisperListScreen(whisperLists: WhisperListManager, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) {
var name by rememberSaveable { mutableStateOf(saved.name) }
var list by remember { mutableStateOf(saved.copy()) }
val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) }
var addingChannel by remember { mutableStateOf(false) }
var addingClient by remember { mutableStateOf(false) }
SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = {
TextButton(onClick = {
whisperLists.save(index, list.copy().apply { this.name = name.trim() })
onBack()
}, enabled = name.isNotBlank()) { Text("Save") }
}) { padding ->
LazyColumn(Modifier.padding(padding)) {
item {
OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(16.dp), label = { Text("Name") },
singleLine = true)
}
item { Section("Channels") }
items(list.channels) { channel ->
RemovableRow("CHANNEL_GREEN", channel) { change { channels.remove(channel) } }
}
item { LinkRow("Add channel…", null, "CHANNEL_CREATE") { addingChannel = true } }
item { Section("Clients") }
items(list.clients) { client ->
RemovableRow("PLAYER_WHISPER", client.nickname.ifBlank { client.uniqueId }) { change { clients.remove(client) } }
}
item { LinkRow("Add client…", null, "ADD_FRIEND") { addingClient = true } }
}
}
if (addingChannel) {
val paths = remember { server.channelPaths().filter { it !in list.channels } }
ChoiceDialog("Add channel", paths, { it }, onDismiss = { addingChannel = false }) {
addingChannel = false
change { channels.add(it) }
}
}
if (addingClient) {
val online = remember { server.clientRefs().filter { c -> list.clients.none { it.uniqueId == c.uniqueId } } }
ChoiceDialog("Add client", online, { it.nickname }, onDismiss = { addingClient = false }) {
addingClient = false
change { clients.add(it) }
}
}
}
@Composable
private fun RemovableRow(iconKey: String, label: String, onRemove: () -> Unit) {
ListItem(
headlineContent = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingContent = { PackIcon(iconKey, null) },
trailingContent = { IconButton(onClick = onRemove) { Icon(Icons.Default.Close, "Remove") } },
)
}
/** Picks one of [choices], of the server on screen; says so when it has none. */
@Composable
private fun <T> ChoiceDialog(title: String, choices: List<T>, label: (T) -> String, onDismiss: () -> Unit, onPick: (T) -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = {
if (choices.isEmpty()) Text("Nothing to add on this server")
else LazyColumn(Modifier.heightIn(max = 400.dp)) {
items(choices) { choice ->
ListItem(headlineContent = { Text(label(choice), maxLines = 1, overflow = TextOverflow.Ellipsis) },
modifier = Modifier.clickable { onPick(choice) })
}
}
},
confirmButton = {},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by ts3-client/tools/AppIcon.java; the art sits in the adaptive icon's safe zone. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="256"
android:viewportHeight="256">
<group
android:scaleX="0.62"
android:scaleY="0.62"
android:pivotX="128"
android:pivotY="128">
<path android:pathData="M128,6.9C68.5,6.9 18.3,48.4 16.1,102.2L16.1,102.2C10.2,104.5 6,110.3 6,117L6,139.5C6,148.4 13.2,155.5 22,155.5L25.4,155.5C30.2,172.1 37.8,178.4 50.3,178.4C53.9,178.4 57.9,177.9 62.3,176.9L62.3,176.9C66.7,176.1 71.5,174.8 76.8,173.4L76.8,173.4C78.5,174.8 80.6,175.7 83,175.7C88.2,175.7 92.5,171.4 92.5,166.2C92.5,161 88.2,156.7 83,156.7C78.8,156.7 75.3,159.4 74,163.1L74,163.1C68.7,164.5 64.2,165.7 60.2,166.5L60.2,166.5C56.2,167.3 52.9,167.9 50.1,167.9C42.8,167.9 38.7,164.2 35.4,152.1L35.4,152.1C39.1,149.2 41.5,144.7 41.5,139.5L41.5,117C41.5,110.3 37.4,104.6 31.6,102.2L31.6,102.2C33.7,58.6 75.1,22.3 128,22.3C180.9,22.3 222.3,58.6 224.4,102.2L224.4,102.2C218.6,104.6 214.5,110.3 214.5,117L214.5,139.5C214.5,148.4 221.6,155.5 230.5,155.5L234,155.5C242.8,155.5 250,148.4 250,139.5L250,117C250,110.3 245.8,104.5 239.9,102.2L239.9,102.2C237.7,48.4 187.5,6.9 128,6.9ZM77,43C74.1,44.7 71.4,46.6 68.8,48.6L68.8,48.6C73.3,53.8 79.5,61 83,66.7C88.1,75 92.5,86.6 94.8,92.8C97.2,98.9 97.2,100.5 97.2,103.4C97.2,106.4 93.5,107.4 94.8,110.5C96.2,113.7 101.9,118.4 105.5,122.4C109,126.3 115,131.1 116.2,134.2C117.3,137.4 115,139.7 112.6,141.3C110.2,142.9 103.3,141.5 101.9,143.7C100.6,145.9 104.9,151.4 104.3,154.4C103.8,157 99.7,158.4 98.6,160.7L98.6,160.7C99.1,162 99.4,163.5 99.5,164.9L99.5,164.9C100.7,167 102.3,169.1 101.9,170.9C101.3,173.9 95.2,176.1 94.8,179.2C94.4,182.4 98.2,186.5 99.6,189.9C101,193.2 103.9,196.4 103.1,199.4C102.3,202.3 97.8,205.1 94.8,207.7C91.9,210.2 87.5,211.4 85.4,214.8C83.2,218.1 83,224 81.8,227.8C80.6,231.5 81.2,234.1 78.3,237.3C75.3,240.4 67.6,244.8 64,246.7C60.5,248.7 58.1,248.7 56.9,249.1L199.1,249.1C197.9,248.7 195.5,248.7 192,246.7C188.4,244.8 180.7,240.4 177.7,237.3C174.8,234.1 175.4,231.5 174.2,227.8C173,224 172.8,218.1 170.6,214.8C168.5,211.4 164.1,210.2 161.2,207.7C158.2,205.1 153.7,202.3 152.9,199.4C152.1,196.4 155,193.2 156.4,189.9C157.8,186.5 161.6,182.4 161.2,179.2C160.8,176.1 154.7,173.9 154.1,170.9C153.5,168 158,164.2 157.6,161.5C157.2,158.7 152.3,157.3 151.7,154.4C151.1,151.4 155.4,145.9 154.1,143.7C152.7,141.5 145.8,142.9 143.4,141.3C141,139.7 138.7,137.4 139.8,134.2C141,131.1 147,126.3 150.5,122.4C154.1,118.4 159.8,113.7 161.2,110.5C162.5,107.4 158.8,106.4 158.8,103.4C158.8,100.5 158.8,98.9 161.2,92.8C163.5,86.6 167.9,75 173,66.7C176.5,61 182.7,53.8 187.2,48.6L187.2,48.6C184.6,46.6 181.9,44.7 179,43Z">
<aapt:attr name="android:fillColor">
<gradient
android:type="linear"
android:startX="0"
android:startY="0"
android:endX="154"
android:endY="256"
android:startColor="#FF4FA3FF"
android:endColor="#FF2442B8" />
</aapt:attr>
</path>
</group>
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/white" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TeamSpook TS3j</string>
<string name="launcher_name">TS3J</string>
<string name="connection_channel">Connection</string>
<string name="messages_channel">Private messages</string>
<string name="pokes_channel">Pokes</string>
</resources>
+37
View File
@@ -0,0 +1,37 @@
plugins {
alias(libs.plugins.android.library)
}
android {
namespace = "eu.lixko.ts3j.client.android.audio"
compileSdk = 37
ndkVersion = "30.0.16248370"
defaultConfig {
minSdk = 33
ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
}
externalNativeBuild {
cmake {
arguments += "-DANDROID_STL=c++_static"
}
}
}
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
version = "4.1.2"
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
api(project(":core"))
}
+31
View File
@@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 3.22)
project(ts3audio LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
# Oboe and libopus from source, built static into our one library together with a static
# libc++, so the app ships a single small .so per ABI.
include(FetchContent)
FetchContent_Declare(oboe
URL https://github.com/google/oboe/archive/refs/tags/1.11.0.tar.gz
URL_HASH SHA256=0ccf2110640a2b4489f1c93a404f2978656b434d8c5dc9cb6258f9cc95c79b15)
FetchContent_Declare(opus
URL https://github.com/xiph/opus/releases/download/v1.5.2/opus-1.5.2.tar.gz
URL_HASH SHA256=65c1d2f78b9f2fb20082c38cbe47c951ad5839345876e46941612ee87f9a7ce1)
set(OPUS_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)
set(OPUS_BUILD_TESTING OFF CACHE BOOL "" FORCE)
set(OPUS_BUILD_SHARED_LIBRARY OFF CACHE BOOL "" FORCE)
set(OPUS_INSTALL_PKG_CONFIG_MODULE OFF CACHE BOOL "" FORCE)
set(OPUS_INSTALL_CMAKE_CONFIG_MODULE OFF CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(oboe opus)
add_library(ts3audio SHARED audio_line.cpp opus_jni.cpp)
target_link_libraries(ts3audio PRIVATE oboe opus log)
target_compile_options(ts3audio PRIVATE -Wall -Wextra)
# Only the JNI entry points are exported; everything else may be dropped.
set_target_properties(ts3audio PROPERTIES CXX_VISIBILITY_PRESET hidden C_VISIBILITY_PRESET hidden)
foreach(lib oboe opus)
target_compile_options(${lib} PRIVATE -ffunction-sections -fdata-sections)
endforeach()
target_link_options(ts3audio PRIVATE -Wl,--gc-sections -Wl,--exclude-libs,ALL)
+274
View File
@@ -0,0 +1,274 @@
// An Oboe stream behind the blocking read/write interface of AudioCapture and AudioPlayback.
//
// The real-time callback never waits and never calls into Java: it only moves samples
// between the device and a lock-free ring, which the Java side fills or drains at its own
// pace, blocking while the ring is full (playback) or short (capture).
#include <jni.h>
#include <oboe/Oboe.h>
#include <android/log.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstring>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
namespace {
constexpr int32_t kSampleRate = 48000;
constexpr int32_t kFrameSize = 960; // 20 ms
// Capture keeps some slack for a Java thread that is briefly late; playback keeps little,
// since everything queued is latency.
constexpr int32_t kCaptureFrames = 8;
constexpr int32_t kPlaybackFrames = 3;
constexpr auto kPollInterval = std::chrono::milliseconds(1);
const char *kTag = "ts3audio";
/** Single-producer, single-consumer ring of 16-bit samples. */
class SampleRing {
public:
explicit SampleRing(size_t capacity) : buffer_(capacity) {}
size_t available() const {
return head_.load(std::memory_order_acquire) - tail_.load(std::memory_order_acquire);
}
size_t space() const { return buffer_.size() - available(); }
/** Producer side: stores as much of {@code data} as fits. */
size_t write(const int16_t *data, size_t count) {
size_t head = head_.load(std::memory_order_relaxed);
size_t tail = tail_.load(std::memory_order_acquire);
size_t n = std::min(count, buffer_.size() - (head - tail));
for (size_t i = 0; i < n; i++) buffer_[(head + i) % buffer_.size()] = data[i];
head_.store(head + n, std::memory_order_release);
return n;
}
/** Consumer side: takes up to {@code count} samples. */
size_t read(int16_t *data, size_t count) {
size_t tail = tail_.load(std::memory_order_relaxed);
size_t head = head_.load(std::memory_order_acquire);
size_t n = std::min(count, head - tail);
for (size_t i = 0; i < n; i++) data[i] = buffer_[(tail + i) % buffer_.size()];
tail_.store(tail + n, std::memory_order_release);
return n;
}
private:
std::vector<int16_t> buffer_;
std::atomic<size_t> head_{0};
std::atomic<size_t> tail_{0};
};
class AudioLine : public oboe::AudioStreamDataCallback, public oboe::AudioStreamErrorCallback {
public:
/** {@code preset} is the input preset of a capture line, {@code usage} a playback line's usage. */
AudioLine(bool input, int32_t deviceId, int32_t channels, int32_t preset, int32_t usage)
: input_(input), deviceId_(deviceId), channels_(channels), preset_(preset), usage_(usage),
ring_(static_cast<size_t>(kFrameSize) * channels * (input ? kCaptureFrames : kPlaybackFrames)) {}
int32_t channels() const { return channels_; }
oboe::Result open() {
oboe::AudioStreamBuilder builder;
builder.setDirection(input_ ? oboe::Direction::Input : oboe::Direction::Output)
->setSharingMode(oboe::SharingMode::Shared)
->setPerformanceMode(oboe::PerformanceMode::LowLatency)
->setFormat(oboe::AudioFormat::I16)
->setFormatConversionAllowed(true)
->setChannelCount(channels_)
->setChannelConversionAllowed(true)
->setSampleRate(kSampleRate)
->setSampleRateConversionQuality(oboe::SampleRateConversionQuality::Medium)
->setDataCallback(this)
->setErrorCallback(this);
int32_t deviceId = deviceId_.load();
if (deviceId > 0) builder.setDeviceId(deviceId);
if (input_) {
builder.setInputPreset(static_cast<oboe::InputPreset>(preset_.load()));
} else {
builder.setUsage(static_cast<oboe::Usage>(usage_.load()))->setContentType(oboe::ContentType::Speech);
}
std::shared_ptr<oboe::AudioStream> stream;
oboe::Result result = builder.openStream(stream);
if (result != oboe::Result::OK) return result;
std::lock_guard<std::mutex> lock(mutex_);
if (closing_.load()) { // closed while a reopen was under way
stream->close();
return oboe::Result::ErrorClosed;
}
if (stream_) stream_->close(); // a concurrent reopen got there first
stream_ = stream;
if (started_) result = stream_->requestStart();
return result;
}
oboe::Result start() {
std::lock_guard<std::mutex> lock(mutex_);
started_ = true;
return stream_ ? stream_->requestStart() : oboe::Result::ErrorClosed;
}
/** Moves the line to another device or configuration; the ring and whoever blocks on it stay. */
oboe::Result reopen(int32_t deviceId, int32_t preset, int32_t usage) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (closing_.load()) return oboe::Result::ErrorClosed;
if (stream_) {
stream_->stop();
stream_->close();
stream_.reset();
}
}
deviceId_.store(deviceId);
preset_.store(preset);
usage_.store(usage);
return open();
}
/** Blocks until {@code count} samples are captured; fewer only once closing. */
size_t read(int16_t *data, size_t count) {
size_t done = 0;
while (done < count && !closing_.load()) {
done += ring_.read(data + done, count - done);
if (done < count) std::this_thread::sleep_for(kPollInterval);
}
return done;
}
/** Blocks until all samples are queued for playback, or the line closes. */
void write(const int16_t *data, size_t count) {
size_t done = 0;
while (done < count && !closing_.load()) {
done += ring_.write(data + done, count - done);
if (done < count) std::this_thread::sleep_for(kPollInterval);
}
}
void close() {
closing_.store(true);
std::lock_guard<std::mutex> lock(mutex_);
if (stream_) {
stream_->stop();
stream_->close();
stream_.reset();
}
}
oboe::DataCallbackResult onAudioReady(oboe::AudioStream *, void *audioData, int32_t numFrames) override {
auto *samples = static_cast<int16_t *>(audioData);
size_t count = static_cast<size_t>(numFrames) * channels_;
if (input_) {
ring_.write(samples, count); // a reader that fell behind loses the newest audio
} else {
size_t played = ring_.read(samples, count);
if (played < count) std::memset(samples + played, 0, (count - played) * sizeof(int16_t));
}
return oboe::DataCallbackResult::Continue;
}
/** The device went away (headset unplugged, route changed): follow onto the new one. */
void onErrorAfterClose(oboe::AudioStream *, oboe::Result error) override {
if (closing_.load()) return;
__android_log_print(ANDROID_LOG_INFO, kTag, "stream closed (%s), reopening",
oboe::convertToText(error));
deviceId_.store(0);
open();
}
private:
const bool input_;
std::atomic<int32_t> deviceId_;
const int32_t channels_;
std::atomic<int32_t> preset_;
std::atomic<int32_t> usage_;
SampleRing ring_;
std::atomic<bool> closing_{false};
std::mutex mutex_;
std::shared_ptr<oboe::AudioStream> stream_;
bool started_ = false; // guarded by mutex_
};
AudioLine *line(jlong handle) {
return reinterpret_cast<AudioLine *>(handle);
}
thread_local std::vector<int16_t> scratch;
} // namespace
extern "C" {
JNIEXPORT jlong JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeOpen(JNIEnv *env, jclass, jboolean input, jint deviceId,
jint channels, jint preset, jint usage) {
auto *created = new AudioLine(input, deviceId, channels, preset, usage);
oboe::Result result = created->open();
if (result != oboe::Result::OK) {
delete created;
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result));
return 0;
}
return reinterpret_cast<jlong>(created);
}
JNIEXPORT jint JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeChannels(JNIEnv *, jclass, jlong handle) {
return line(handle)->channels();
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeStart(JNIEnv *env, jclass, jlong handle) {
oboe::Result result = line(handle)->start();
if (result != oboe::Result::OK) {
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result));
}
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeReopen(JNIEnv *env, jclass, jlong handle, jint deviceId,
jint preset, jint usage) {
oboe::Result result = line(handle)->reopen(deviceId, preset, usage);
if (result != oboe::Result::OK && result != oboe::Result::ErrorClosed) {
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result));
}
}
JNIEXPORT jint JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeRead(JNIEnv *env, jclass, jlong handle, jbyteArray buffer,
jint offset, jint length) {
size_t samples = static_cast<size_t>(length) / sizeof(int16_t);
scratch.resize(samples);
size_t read = line(handle)->read(scratch.data(), samples);
env->SetByteArrayRegion(buffer, offset, static_cast<jsize>(read * sizeof(int16_t)),
reinterpret_cast<const jbyte *>(scratch.data()));
return static_cast<jint>(read * sizeof(int16_t));
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeWrite(JNIEnv *env, jclass, jlong handle, jbyteArray buffer,
jint offset, jint length) {
size_t samples = static_cast<size_t>(length) / sizeof(int16_t);
scratch.resize(samples);
env->GetByteArrayRegion(buffer, offset, static_cast<jsize>(samples * sizeof(int16_t)),
reinterpret_cast<jbyte *>(scratch.data()));
line(handle)->write(scratch.data(), samples);
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeClose(JNIEnv *, jclass, jlong handle) {
line(handle)->close();
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeDelete(JNIEnv *, jclass, jlong handle) {
delete line(handle);
}
} // extern "C"
+112
View File
@@ -0,0 +1,112 @@
// libopus for NativeOpus: handles are the raw encoder/decoder pointers.
#include <jni.h>
#include <opus.h>
#include <string>
#include <vector>
namespace {
constexpr int kMaxPacketBytes = 4096;
void throwOpus(JNIEnv *env, const char *call, int error) {
std::string message = std::string(call) + " failed: " + opus_strerror(error);
env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), message.c_str());
}
OpusEncoder *encoder(jlong handle) { return reinterpret_cast<OpusEncoder *>(handle); }
OpusDecoder *decoder(jlong handle) { return reinterpret_cast<OpusDecoder *>(handle); }
} // namespace
extern "C" {
JNIEXPORT jlong JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels,
jint application) {
int error = OPUS_OK;
OpusEncoder *created = opus_encoder_create(sampleRate, channels, application, &error);
if (error != OPUS_OK) {
throwOpus(env, "opus_encoder_create", error);
return 0;
}
return reinterpret_cast<jlong>(created);
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderCtl(JNIEnv *env, jclass, jlong handle, jint request,
jint value) {
int result = opus_encoder_ctl(encoder(handle), request, value);
if (result < 0) throwOpus(env, "opus_encoder_ctl", result);
}
JNIEXPORT jbyteArray JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encode(JNIEnv *env, jclass, jlong handle, jfloatArray pcm,
jint frameSize) {
unsigned char packet[kMaxPacketBytes];
jfloat *samples = env->GetFloatArrayElements(pcm, nullptr);
int length = opus_encode_float(encoder(handle), samples, frameSize, packet, kMaxPacketBytes);
env->ReleaseFloatArrayElements(pcm, samples, JNI_ABORT);
if (length < 0) {
throwOpus(env, "opus_encode_float", length);
return nullptr;
}
jbyteArray out = env->NewByteArray(length);
env->SetByteArrayRegion(out, 0, length, reinterpret_cast<const jbyte *>(packet));
return out;
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderDestroy(JNIEnv *, jclass, jlong handle) {
opus_encoder_destroy(encoder(handle));
}
JNIEXPORT jlong JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels) {
int error = OPUS_OK;
OpusDecoder *created = opus_decoder_create(sampleRate, channels, &error);
if (error != OPUS_OK) {
throwOpus(env, "opus_decoder_create", error);
return 0;
}
return reinterpret_cast<jlong>(created);
}
/**
* Decodes {@code packet}, or conceals {@code frameSize} samples when it is null; with {@code fec},
* rebuilds the packet before {@code packet} from its error correction copy.
*/
JNIEXPORT jint JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decode(JNIEnv *env, jclass, jlong handle, jbyteArray packet,
jfloatArray out, jint frameSize, jboolean fec) {
std::vector<unsigned char> data;
if (packet != nullptr) {
data.resize(static_cast<size_t>(env->GetArrayLength(packet)));
env->GetByteArrayRegion(packet, 0, static_cast<jsize>(data.size()), reinterpret_cast<jbyte *>(data.data()));
}
jfloat *samples = env->GetFloatArrayElements(out, nullptr);
int decoded = opus_decode_float(decoder(handle), packet != nullptr ? data.data() : nullptr,
static_cast<opus_int32>(data.size()), samples, frameSize, fec ? 1 : 0);
env->ReleaseFloatArrayElements(out, samples, decoded < 0 ? JNI_ABORT : 0);
if (decoded < 0) throwOpus(env, "opus_decode_float", decoded);
return decoded;
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderReset(JNIEnv *, jclass, jlong handle) {
opus_decoder_ctl(decoder(handle), OPUS_RESET_STATE);
}
JNIEXPORT void JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderDestroy(JNIEnv *, jclass, jlong handle) {
opus_decoder_destroy(decoder(handle));
}
JNIEXPORT jstring JNICALL
Java_eu_lixko_ts3j_client_android_audio_NativeOpus_version0(JNIEnv *env, jclass) {
return env->NewStringUTF(opus_get_version_string());
}
} // extern "C"
@@ -0,0 +1,60 @@
package eu.lixko.ts3j.client.android.audio;
import android.content.Context;
import eu.lixko.ts3j.client.audio.AudioBackend;
import eu.lixko.ts3j.client.audio.AudioIo;
import eu.lixko.ts3j.client.audio.StreamingVoiceOutput;
import eu.lixko.ts3j.client.audio.opus.OpusCodec;
/** Android's audio stack: Oboe for the devices, libopus built with the NDK. */
public final class AndroidAudioBackend implements AudioBackend {
private final AndroidAudioIo io;
private final OpusCodec opus = new NativeOpus();
public AndroidAudioBackend(Context context) {
this.io = new AndroidAudioIo(context.getApplicationContext());
}
@Override
public AudioIo io() {
return io;
}
/** How the lines meet Android's audio: microphone preset, and media or call playback. */
public AudioRoute route() {
return io.route();
}
/** Applies at once to the lines that are open. */
public void setRoute(AudioRoute route) {
io.setRoute(route);
}
/** Whether the device offers {@link AudioRoute.InputPreset#UNPROCESSED} truly unprocessed. */
public boolean unprocessedSupported() {
return io.unprocessedSupported();
}
/** Runs on the main thread whenever an audio device comes or goes. */
public void addDeviceListener(Runnable listener) {
io.addDeviceListener(listener);
}
@Override
public OpusCodec opus() {
return opus;
}
/** One low-latency stream for everyone, as mobile audio wants. */
@Override
public StreamingVoiceOutput.Lines outputLines() {
return StreamingVoiceOutput.Lines.SHARED;
}
@Override
public String description() {
return "Opus " + opus.version() + ", Oboe";
}
}
@@ -0,0 +1,332 @@
package eu.lixko.ts3j.client.android.audio;
import android.content.Context;
import android.media.AudioDeviceCallback;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Looper;
import eu.lixko.ts3j.client.audio.AudioCapture;
import eu.lixko.ts3j.client.audio.AudioDevice;
import eu.lixko.ts3j.client.audio.AudioIo;
import eu.lixko.ts3j.client.audio.AudioPlayback;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The device's microphones and speakers, opened through Oboe.
*
* <p>Android's device ids are handed out anew whenever a device appears, so a Bluetooth
* headset has another one each time it reconnects. What the settings keep is the device's
* type and address instead, which stay the same, and each open looks the id up.
*
* <p>Also owns the phone's call state: communication mode and the communication device are
* only set while a line needs them, i.e. playback as a call or a headset microphone.
*/
final class AndroidAudioIo implements AudioIo {
/** AudioDeviceInfo.TYPE_ECHO_REFERENCE, which the SDK keeps as a system API. */
private static final int TYPE_ECHO_REFERENCE = 28;
private final AudioManager audioManager;
private final Set<OboeLine> open = ConcurrentHashMap.newKeySet();
/** Reopening streams takes a moment; it happens off the caller's thread, one at a time. */
private final ExecutorService reopener = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r, "audio-reopen");
t.setDaemon(true);
return t;
});
private final List<Runnable> deviceListeners = new ArrayList<>();
private volatile AudioRoute route = AudioRoute.DEFAULT;
/** Whether this class put the phone into communication mode, and so must take it out. */
private boolean inCall;
/** The line being opened, which counts towards the call before it exists; null when none is. */
private String openingDevice;
private boolean openingInput;
AndroidAudioIo(Context context) {
this.audioManager = context.getSystemService(AudioManager.class);
audioManager.registerAudioDeviceCallback(new AudioDeviceCallback() {
@Override
public void onAudioDevicesAdded(AudioDeviceInfo[] added) {
returnToDevices(added);
notifyDevices();
}
@Override
public void onAudioDevicesRemoved(AudioDeviceInfo[] removed) {
notifyDevices();
}
}, new Handler(Looper.getMainLooper()));
}
// ---- devices ----
@Override
public List<AudioDevice> inputDevices() {
return devices(AudioManager.GET_DEVICES_INPUTS, true);
}
@Override
public List<AudioDevice> outputDevices() {
return devices(AudioManager.GET_DEVICES_OUTPUTS, false);
}
/** Runs on the main thread whenever a device comes or goes. */
void addDeviceListener(Runnable listener) {
synchronized (deviceListeners) {
deviceListeners.add(listener);
}
}
private void notifyDevices() {
synchronized (deviceListeners) {
for (Runnable listener : deviceListeners) listener.run();
}
}
private List<AudioDevice> devices(int flags, boolean input) {
Map<String, AudioDevice> out = new LinkedHashMap<>();
out.put(AudioDevice.DEFAULT.id(), AudioDevice.DEFAULT);
for (AudioDeviceInfo info : audioManager.getDevices(flags)) {
String label = label(info, input);
if (label != null) out.putIfAbsent(key(info), new AudioDevice(key(info), label));
}
return new ArrayList<>(out.values());
}
/** What the settings store for a device. */
private static String key(AudioDeviceInfo info) {
return info.getType() + ":" + info.getAddress();
}
/** The device's current id, or 0 to let the system choose when it is not there. */
private int resolve(String device, int flags) {
if (device == null || device.isEmpty()) return 0;
for (AudioDeviceInfo info : audioManager.getDevices(flags)) {
if (key(info).equals(device)) return info.getId();
}
return 0;
}
private static int flags(OboeLine line) {
return line.isInput() ? AudioManager.GET_DEVICES_INPUTS : AudioManager.GET_DEVICES_OUTPUTS;
}
/** A picked device that dropped out took its lines to the default; bring them back. */
private void returnToDevices(AudioDeviceInfo[] added) {
for (AudioDeviceInfo info : added) {
for (OboeLine line : open) {
if (key(info).equals(line.device) && info.isSource() == line.isInput()) {
reopen(line, info.getId());
}
}
}
}
// ---- lines ----
AudioRoute route() {
return route;
}
/** Takes on a new route, moving the lines it concerns over at once. */
void setRoute(AudioRoute newRoute) {
AudioRoute old = route;
route = newRoute;
synchronized (this) {
updateCall();
}
for (OboeLine line : open) {
boolean affected = line.isInput()
? old.inputPreset() != newRoute.inputPreset()
: old.usage() != newRoute.usage();
if (affected) reopen(line, resolve(line.device, flags(line)));
}
}
private void reopen(OboeLine line, int deviceId) {
reopener.execute(() -> {
try {
line.reopen(deviceId, route);
} catch (IllegalStateException ignored) {
// The stream could not come back on those terms; the line reads silence until closed.
}
});
}
@Override
public AudioCapture openCapture(String deviceId, int preferredChannels) {
opening(true, deviceId);
try {
return register(OboeLine.capture(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_INPUTS),
preferredChannels, route, this::closed));
} finally {
opened();
}
}
@Override
public AudioPlayback openPlayback(String deviceId, int preferredChannels) {
opening(false, deviceId);
try {
return register(OboeLine.playback(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_OUTPUTS),
preferredChannels, route, this::closed));
} finally {
opened();
}
}
/** A stream opens on the call as it will be, so the call is set up for it first. */
private synchronized void opening(boolean input, String device) {
openingInput = input;
openingDevice = device == null ? "" : device;
updateCall();
}
private synchronized void opened() {
openingDevice = null;
updateCall();
}
private synchronized OboeLine register(OboeLine line) {
open.add(line);
return line;
}
private synchronized void closed() {
open.removeIf(line -> !line.isOpen());
updateCall();
}
/**
* Puts the phone into communication mode while a line needs it, pointing the call at
* the picked device, and leaves it again once none does.
*/
private void updateCall() {
AudioDeviceInfo headsetMic = null;
String output = null;
List<String> inputs = new ArrayList<>();
for (OboeLine line : open) {
if (line.isInput()) inputs.add(line.device);
else if (output == null) output = line.device;
}
if (openingDevice != null) {
if (openingInput) inputs.add(openingDevice);
else if (output == null) output = openingDevice;
}
for (String input : inputs) {
AudioDeviceInfo mic = find(input, AudioManager.GET_DEVICES_INPUTS);
if (mic != null && isHeadsetMic(mic)) headsetMic = mic;
}
// Held while anything is open, the microphone included: a notification sound coming
// and going must not take the phone in and out of a call.
boolean call = route.usage() == AudioRoute.Usage.VOICE_COMMUNICATION && (!open.isEmpty() || openingDevice != null);
boolean needed = headsetMic != null || call;
if (needed && !inCall) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
inCall = true;
} else if (!needed && inCall) {
audioManager.clearCommunicationDevice();
audioManager.setMode(AudioManager.MODE_NORMAL);
inCall = false;
}
if (!needed) return;
// A headset microphone only works over the headset's call link, so it decides.
AudioDeviceInfo target = headsetMic != null
? communicationDevice(headsetMic.getAddress(), headsetMic.getType())
: communicationDevice(find(output, AudioManager.GET_DEVICES_OUTPUTS));
if (target != null) audioManager.setCommunicationDevice(target);
else audioManager.clearCommunicationDevice();
}
private AudioDeviceInfo find(String device, int flags) {
if (device == null || device.isEmpty()) return null;
for (AudioDeviceInfo info : audioManager.getDevices(flags)) {
if (key(info).equals(device)) return info;
}
return null;
}
private static boolean isHeadsetMic(AudioDeviceInfo info) {
return info.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || info.getType() == AudioDeviceInfo.TYPE_BLE_HEADSET;
}
/** The communication device that is {@code output}, if calls can go there. */
private AudioDeviceInfo communicationDevice(AudioDeviceInfo output) {
if (output == null) return null;
// Calls cannot go over A2DP; the same headset's call profile can.
int type = output.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ? AudioDeviceInfo.TYPE_BLUETOOTH_SCO : output.getType();
return communicationDevice(output.getAddress(), type);
}
private AudioDeviceInfo communicationDevice(String address, int inputType) {
for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) {
if (info.getType() == inputType && info.getAddress().equals(address)) return info;
}
// Wired and USB headsets, and the built-in microphone, have no address in common with an output.
for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) {
if (info.getType() == inputType) return info;
}
return null;
}
boolean unprocessedSupported() {
return "true".equals(audioManager.getProperty(AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED));
}
/** How a device is offered in the settings, or null for one no user would pick. */
private static String label(AudioDeviceInfo info, boolean input) {
String product = info.getProductName() == null ? "" : info.getProductName().toString();
String address = info.getAddress();
switch (info.getType()) {
case AudioDeviceInfo.TYPE_BUILTIN_MIC:
return "Phone microphone" + (address.isEmpty() ? "" : " (" + address + ")");
case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER:
return "Phone speaker";
case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE:
return "Earpiece";
case AudioDeviceInfo.TYPE_WIRED_HEADSET:
return input ? "Wired headset microphone" : "Wired headset";
case AudioDeviceInfo.TYPE_WIRED_HEADPHONES:
return "Wired headphones";
case AudioDeviceInfo.TYPE_USB_HEADSET:
case AudioDeviceInfo.TYPE_USB_DEVICE:
case AudioDeviceInfo.TYPE_USB_ACCESSORY:
return product + " (USB)";
case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP:
return product + " (Bluetooth, media quality)";
case AudioDeviceInfo.TYPE_BLUETOOTH_SCO:
return product + " (Bluetooth, call quality)";
case AudioDeviceInfo.TYPE_BLE_HEADSET:
case AudioDeviceInfo.TYPE_BLE_SPEAKER:
return product + " (Bluetooth LE)";
case AudioDeviceInfo.TYPE_HEARING_AID:
return product + " (hearing aid)";
case AudioDeviceInfo.TYPE_HDMI:
case AudioDeviceInfo.TYPE_HDMI_ARC:
case AudioDeviceInfo.TYPE_HDMI_EARC:
return "HDMI";
case AudioDeviceInfo.TYPE_TELEPHONY:
case AudioDeviceInfo.TYPE_REMOTE_SUBMIX:
case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE:
case TYPE_ECHO_REFERENCE:
case AudioDeviceInfo.TYPE_FM_TUNER:
case AudioDeviceInfo.TYPE_TV_TUNER:
case AudioDeviceInfo.TYPE_BUS:
case AudioDeviceInfo.TYPE_BLE_BROADCAST:
return null;
default:
return product.isEmpty() ? "Device " + info.getId() : product;
}
}
}
@@ -0,0 +1,49 @@
package eu.lixko.ts3j.client.android.audio;
/**
* How the app's audio meets Android's: which processing the platform applies to the
* microphone, and whether playback is media or a call.
*/
public record AudioRoute(InputPreset inputPreset, Usage usage) {
/** The client runs TS3's own processing, so by default the platform adds as little as it can. */
public static final AudioRoute DEFAULT = new AudioRoute(InputPreset.VOICE_RECOGNITION, Usage.MEDIA);
/** Oboe's input presets, which are Android's audio sources. */
public enum InputPreset {
/** Tuned for speech with light or no processing; what the client expects. */
VOICE_RECOGNITION(6),
/** The platform's call processing: echo cancellation, noise suppression, gain control. */
VOICE_COMMUNICATION(7),
/** No processing at all, where the device supports it. */
UNPROCESSED(9),
/** Low latency and no processing, meant for live performance. */
VOICE_PERFORMANCE(10),
/** The plain microphone source, with whatever the vendor applies to it. */
GENERIC(1),
CAMCORDER(5);
final int oboeValue;
InputPreset(int oboeValue) {
this.oboeValue = oboeValue;
}
}
/** Oboe's playback usages. */
public enum Usage {
/** Plays like music: stays on A2DP headphones and leaves the phone out of call mode. */
MEDIA(1),
/**
* Plays as a call: Android goes into communication mode, which is what its echo
* canceller works against, and Bluetooth headsets switch to their headset profile.
*/
VOICE_COMMUNICATION(2);
final int oboeValue;
Usage(int oboeValue) {
this.oboeValue = oboeValue;
}
}
}
@@ -0,0 +1,119 @@
package eu.lixko.ts3j.client.android.audio;
import eu.lixko.ts3j.client.audio.opus.AbstractCtlOpusEncoder;
import eu.lixko.ts3j.client.audio.opus.LibOpus;
import eu.lixko.ts3j.client.audio.opus.OpusCodec;
import eu.lixko.ts3j.client.audio.opus.OpusDecoder;
import eu.lixko.ts3j.client.audio.opus.OpusEncoder;
/** libopus, built into the app with the NDK. */
public final class NativeOpus implements OpusCodec {
static {
System.loadLibrary("ts3audio");
}
@Override
public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) {
return new Encoder(encoderCreate(sampleRate, channels, LibOpus.application(application)), frameSize);
}
@Override
public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) {
return new Decoder(decoderCreate(sampleRate, channels), maxFrameSize);
}
@Override
public String version() {
return version0();
}
/** Methods may come from different threads, one at a time, so they only share the handle. */
private static final class Encoder extends AbstractCtlOpusEncoder {
private final int frameSize;
private long handle;
Encoder(long handle, int frameSize) {
this.handle = handle;
this.frameSize = frameSize;
}
@Override
protected synchronized void ctl(int request, int value) {
if (handle != 0) encoderCtl(handle, request, value);
}
@Override
public synchronized byte[] encode(float[] pcm) {
if (handle == 0) throw new IllegalStateException("encoder closed");
return NativeOpus.encode(handle, pcm, frameSize);
}
@Override
public synchronized void close() {
if (handle == 0) return;
encoderDestroy(handle);
handle = 0;
}
}
private static final class Decoder implements OpusDecoder {
private final int maxFrameSize;
private long handle;
Decoder(long handle, int maxFrameSize) {
this.handle = handle;
this.maxFrameSize = maxFrameSize;
}
@Override
public int decode(byte[] packet, float[] out) {
return NativeOpus.decode(live(), packet, out, maxFrameSize, false);
}
@Override
public int conceal(float[] out, int frameSize) {
return NativeOpus.decode(live(), null, out, Math.min(frameSize, maxFrameSize), false);
}
@Override
public int recover(byte[] next, float[] out, int frameSize) {
return NativeOpus.decode(live(), next, out, Math.min(frameSize, maxFrameSize), true);
}
@Override
public void reset() {
if (handle != 0) decoderReset(handle);
}
@Override
public void close() {
if (handle == 0) return;
decoderDestroy(handle);
handle = 0;
}
private long live() {
if (handle == 0) throw new IllegalStateException("decoder closed");
return handle;
}
}
private static native long encoderCreate(int sampleRate, int channels, int application);
private static native void encoderCtl(long handle, int request, int value);
private static native byte[] encode(long handle, float[] pcm, int frameSize);
private static native void encoderDestroy(long handle);
private static native long decoderCreate(int sampleRate, int channels);
private static native int decode(long handle, byte[] packet, float[] out, int frameSize, boolean fec);
private static native void decoderReset(long handle);
private static native void decoderDestroy(long handle);
private static native String version0();
}
@@ -0,0 +1,115 @@
package eu.lixko.ts3j.client.android.audio;
import eu.lixko.ts3j.client.audio.AudioCapture;
import eu.lixko.ts3j.client.audio.AudioPlayback;
/**
* An Oboe stream, as either an {@link AudioCapture} or an {@link AudioPlayback}. The native
* side keeps a ring between the real-time callback and these blocking calls.
*/
final class OboeLine implements AudioCapture, AudioPlayback {
static {
System.loadLibrary("ts3audio");
}
/** Held across native reads and writes, so {@link #close} never frees a line in use. */
private final Object io = new Object();
private final int channels;
private final boolean input;
/** The device as the settings name it, to find it again when the line is reopened. */
final String device;
private final Runnable onClose;
private volatile long handle;
private OboeLine(boolean input, String device, int deviceId, int channels, AudioRoute route, Runnable onClose) {
this.input = input;
this.device = device;
this.onClose = onClose;
this.handle = nativeOpen(input, deviceId, channels, route.inputPreset().oboeValue, route.usage().oboeValue);
this.channels = nativeChannels(handle);
}
static OboeLine capture(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) {
return new OboeLine(true, device, deviceId, channels, route, onClose);
}
static OboeLine playback(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) {
return new OboeLine(false, device, deviceId, channels, route, onClose);
}
boolean isInput() {
return input;
}
boolean isOpen() {
return handle != 0;
}
/** Moves the open stream onto {@code deviceId} with {@code route}; readers and writers carry on. */
void reopen(int deviceId, AudioRoute route) {
long h = handle;
if (h != 0) nativeReopen(h, deviceId, route.inputPreset().oboeValue, route.usage().oboeValue);
}
@Override
public int channels() {
return channels;
}
@Override
public void start() {
long h = handle;
if (h != 0) nativeStart(h);
}
@Override
public int read(byte[] buffer, int offset, int length) {
synchronized (io) {
long h = handle;
return h == 0 ? 0 : nativeRead(h, buffer, offset, length);
}
}
@Override
public void write(byte[] buffer, int offset, int length) {
synchronized (io) {
long h = handle;
if (h != 0) nativeWrite(h, buffer, offset, length);
}
}
/** Oboe has no drain; what is queued is at most a few frames and simply plays out. */
@Override
public void drain() {
}
@Override
public void close() {
long h = handle;
if (h == 0) return;
nativeClose(h); // wakes a blocked read or write
synchronized (io) {
if (handle == 0) return;
handle = 0;
nativeDelete(h);
}
onClose.run();
}
private static native long nativeOpen(boolean input, int deviceId, int channels, int preset, int usage);
private static native void nativeReopen(long handle, int deviceId, int preset, int usage);
private static native int nativeChannels(long handle);
private static native void nativeStart(long handle);
private static native int nativeRead(long handle, byte[] buffer, int offset, int length);
private static native void nativeWrite(long handle, byte[] buffer, int offset, int length);
private static native void nativeClose(long handle);
private static native void nativeDelete(long handle);
}
+5
View File
@@ -0,0 +1,5 @@
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.android.library) apply false
alias(libs.plugins.kotlin.compose) apply false
}
+31
View File
@@ -0,0 +1,31 @@
plugins {
`java-library`
}
val ts3ClientDir: String = providers.gradleProperty("ts3.client.dir")
.orElse(providers.environmentVariable("TS3_CLIENT_DIR"))
.getOrElse(rootDir.resolve("../TeamSpeak3-Client-linux_amd64").path)
/** TeamSpeak's own icon packs and country flags, proprietary and so taken from an install, as the desktop's build does. */
val teamspeakIconPacks = tasks.register<Sync>("teamspeakIconPacks") {
into(layout.buildDirectory.dir("generated/iconPacks"))
from(File(ts3ClientDir, "gfx")) {
include("default.zip", "default_colored_2014.zip", "default_mono_2014.zip", "countries.zip")
into("gfx/teamspeak")
}
}
java {
sourceSets["main"].java.setSrcDirs(listOf(rootDir.resolve("../ts3-client/core/src/main/java")))
sourceSets["main"].resources.setSrcDirs(listOf(rootDir.resolve("../ts3-client/core/src/main/resources")))
sourceSets["main"].resources.srcDir(teamspeakIconPacks)
}
tasks.withType<JavaCompile>().configureEach {
options.release = 17
options.encoding = "UTF-8"
}
dependencies {
api(project(":ts3j"))
}
+20
View File
@@ -0,0 +1,20 @@
plugins {
`java-library`
}
// The desktop client's platform code, run on the build machine only: its libopus
// encodes the sound packs the app ships (see :app's bundleSoundPacks).
java {
sourceSets["main"].java.setSrcDirs(listOf(rootDir.resolve("../ts3-client/desktop/src/main/java")))
sourceSets["main"].resources.setSrcDirs(listOf(rootDir.resolve("../ts3-client/desktop/src/main/resources")))
}
tasks.withType<JavaCompile>().configureEach {
// The FFM API it reaches libopus through; the build has to run on JDK 25 or newer.
options.release = 25
options.encoding = "UTF-8"
}
dependencies {
implementation(project(":core"))
}
+4
View File
@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configuration-cache=true
android.useAndroidX=true
+26
View File
@@ -0,0 +1,26 @@
[versions]
agp = "9.4.1"
kotlin = "2.4.20"
composeBom = "2026.09.00"
activityCompose = "1.13.0"
lifecycle = "2.11.0"
bouncycastle = "1.86"
ini4j = "0.5.1"
androidsvg = "1.4"
[libraries]
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" }
androidx-compose-material3 = { module = "androidx.compose.material3:material3" }
androidx-compose-material-icons = { module = "androidx.compose.material:material-icons-extended" }
androidx-compose-ui = { module = "androidx.compose.ui:ui" }
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-lifecycle-service = { module = "androidx.lifecycle:lifecycle-service", version.ref = "lifecycle" }
androidsvg = { module = "com.caverock:androidsvg-aar", version.ref = "androidsvg" }
bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
ini4j = { module = "org.ini4j:ini4j", version.ref = "ini4j" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
android-library = { id = "com.android.library", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+112
View File
@@ -0,0 +1,112 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
@rem Catch executions from older scripts and ensure they exit cleanly.
@rem This can be removed once we can be reasonably confident that few people
@rem will be migrating directly to this new wrapper.
goto afterSafetyNet
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto exitWithErrorLevel
:afterSafetyNet
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
1>&2 echo.
1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
1>&2 echo.
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
1>&2 echo location of your Java installation.
"%COMSPEC%" /c exit 1
goto exitWithErrorLevel
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
1>&2 echo.
1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
1>&2 echo.
1>&2 echo Please set the JAVA_HOME variable in your environment to match the
1>&2 echo location of your Java installation.
"%COMSPEC%" /c exit 1
goto exitWithErrorLevel
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+20
View File
@@ -0,0 +1,20 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "ts3-android"
// core, ts3j and desktop compile the very sources the desktop's Maven build does.
include(":ts3j", ":core", ":desktop", ":audio", ":app")
+18
View File
@@ -0,0 +1,18 @@
plugins {
`java-library`
}
java {
sourceSets["main"].java.setSrcDirs(listOf(rootDir.resolve("../ts3j/src/main/java")))
}
tasks.withType<JavaCompile>().configureEach {
options.release = 17
options.encoding = "UTF-8"
}
dependencies {
// Android ships a BouncyCastle of its own, but under a different package, so they never meet.
api(libs.bouncycastle)
api(libs.ini4j)
}

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