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>
This commit is contained in:
2026-10-06 20:59:44 +00:00
co-authored by Claude Opus 5.5
parent 70aac6f5ce
commit 33317df2eb
11 changed files with 713 additions and 467 deletions
@@ -1,32 +1,54 @@
package com.ts3client.android.ui package com.ts3client.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.Column
import androidx.compose.foundation.layout.Row 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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier 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.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.ts3client.android.ClientItem
import com.ts3client.android.ServerController import com.ts3client.android.ServerController
import com.ts3client.net.ConnectionStats import com.ts3client.net.ConnectionStats
import com.ts3client.net.ConnectionStatsFormat import com.ts3client.net.ConnectionStatsFormat
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
private const val REFRESH_MS = 1000L private const val REFRESH_MS = 1000L
private const val SELF_ADDRESS = "This device"
/** A client's connection figures, read again every second while shown, and what our playback made of their voice. */ 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 @Composable
fun ConnectionInfoScreen(server: ServerController, clientId: Int, nickname: String, onBack: () -> Unit) { fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) {
var stats by remember { mutableStateOf<ConnectionStats?>(null) } var stats by remember { mutableStateOf<ConnectionStats?>(null) }
LaunchedEffect(clientId) { LaunchedEffect(clientId) {
while (true) { while (true) {
@@ -34,35 +56,95 @@ fun ConnectionInfoScreen(server: ServerController, clientId: Int, nickname: Stri
delay(REFRESH_MS) delay(REFRESH_MS)
} }
} }
var tab by rememberSaveable { mutableIntStateOf(0) }
val s = stats val s = stats
SubScreen("Connection info", onBack) { padding -> SubScreen("Connection info", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
Text(nickname, Modifier.padding(horizontal = 16.dp, vertical = 8.dp), style = MaterialTheme.typography.titleLarge) Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Figures(ConnectionStatsFormat.summaryRows(s, SELF_ADDRESS)) Summary(s, client?.nickname ?: "", Modifier.weight(1f))
Section("Voice received") if (client != null && client.avatarFlag.isNotEmpty()) {
Figures(ConnectionStatsFormat.voiceRows(s?.voiceReceived)) Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp)
Section("Total") }
Figures(ConnectionStatsFormat.trafficRows(s, null)) }
for ((kind, title) in KINDS) { PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) {
Section(title) TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) }
Figures(ConnectionStatsFormat.trafficRows(s, kind)) }
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)))
}
} }
} }
} }
} }
private val KINDS = listOf(
ConnectionStats.Kind.SPEECH to "Speech",
ConnectionStats.Kind.KEEPALIVE to "Keep alive",
ConnectionStats.Kind.CONTROL to "Control",
)
@Composable @Composable
private fun Figures(rows: List<ConnectionStatsFormat.Row>) { private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) {
for (row in rows) { val context = LocalContext.current
Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { 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.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(row.value, Modifier.weight(1f), textAlign = TextAlign.End) 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)
@@ -209,7 +209,7 @@ fun ServerScreen(
return return
} }
connectionInfo?.let { id -> connectionInfo?.let { id ->
ConnectionInfoScreen(server, id, tree.client(id)?.name ?: "", onBack = { connectionInfo = null }) ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
return return
} }
@@ -29,6 +29,9 @@ public final class ClientEntry {
public volatile String avatarFlag = ""; public volatile String avatarFlag = "";
/** Where the server places the client ({@code client_country}), as an ISO code; empty when it cannot tell. */ /** Where the server places the client ({@code client_country}), as an ISO code; empty when it cannot tell. */
public volatile String country = ""; public volatile String country = "";
/** File transfer traffic this month ({@code client_month_bytes_*}), -1 until asked for. */
public volatile long monthBytesDownloaded = -1;
public volatile long monthBytesUploaded = -1;
public volatile boolean talking; public volatile boolean talking;
public volatile boolean inputMuted; // microphone muted (client_input_muted) public volatile boolean inputMuted; // microphone muted (client_input_muted)
@@ -342,6 +342,10 @@ final class ConnectionEventHandler implements TS3Listener {
if (has(e, "client_platform")) c.platform = e.get("client_platform"); if (has(e, "client_platform")) c.platform = e.get("client_platform");
conn.ui.onInfoUpdated(); conn.ui.onInfoUpdated();
} }
if (has(e, "client_month_bytes_downloaded"))
c.monthBytesDownloaded = TeamspeakConnection.safeLong(e, "client_month_bytes_downloaded");
if (has(e, "client_month_bytes_uploaded"))
c.monthBytesUploaded = TeamspeakConnection.safeLong(e, "client_month_bytes_uploaded");
if (has(e, "client_is_channel_commander")) if (has(e, "client_is_channel_commander"))
c.channelCommander = e.getBoolean("client_is_channel_commander"); c.channelCommander = e.getBoolean("client_is_channel_commander");
if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar"));
@@ -2,55 +2,51 @@ package com.ts3client.net;
import com.ts3client.audio.VoiceReceiveStats; import com.ts3client.audio.VoiceReceiveStats;
import java.util.ArrayList; import java.util.EnumMap;
import java.util.List; import java.util.Map;
/** /**
* A snapshot of a client's connection statistics, as shown in the Connection * A snapshot of a client's connection statistics, as shown in the Connection
* Info window. Values default to {@code -1} meaning "unknown / not reported", * Info window. Values default to {@code -1} meaning "unknown / not reported",
* which callers should render as a dash. * which callers should render as a dash.
* *
* <p>For the local client the figures are read live from the socket's own * <p>Traffic is seen from the client's side, as TeamSpeak shows it: <em>in</em> is what
* packet counters and are fully populated, including the per-{@link Kind} * the client received, <em>out</em> what it sent. For a remote client the figures come
* breakdown. For a remote client the figures come from the server's * from {@code notifyconnectioninfo} (the server relays the client's own counters, plus
* {@code notifyconnectioninfo} report and only the aggregate totals are * the loss it measured itself); for the local client they are read from our own socket.
* available; {@link #perKind} is then empty.
*/ */
public final class ConnectionStats { public final class ConnectionStats {
/** The three traffic categories TeamSpeak accounts separately. */ /** The three traffic categories TeamSpeak accounts separately. */
public enum Kind {KEEPALIVE, CONTROL, SPEECH} public enum Kind {SPEECH, KEEPALIVE, CONTROL}
/** A quota permission's value for "no limit". */
public static final long UNLIMITED = -1;
public int clientId; public int clientId;
public String nickname = ""; public String nickname = "";
public boolean self; public boolean self;
/** True when derived from local live counters (self); false for a server snapshot. */ /** Empty when the server withholds it. */
public boolean live;
public String ip = ""; public String ip = "";
public String version = ""; public int port = -1;
public String platform = "";
public double pingMs = -1; public double pingMs = -1;
public double pingDeviationMs = -1; public double pingDeviationMs = -1;
/** Total packet loss as a fraction 0..1, or -1 if unknown. */
public double packetLoss = -1;
public long connectedTimeMs = -1; public long connectedTimeMs = -1;
public long idleTimeMs = -1; public long idleTimeMs = -1;
public long filetransferBandwidthSent = -1; public long filetransferBandwidthSent = -1;
public long filetransferBandwidthReceived = -1; public long filetransferBandwidthReceived = -1;
// Aggregate totals across all traffic kinds. public final Traffic total = new Traffic();
public long packetsSentTotal = -1; private final Map<Kind, Traffic> perKind = new EnumMap<>(Kind.class);
public long packetsReceivedTotal = -1;
public long bytesSentTotal = -1; public long monthBytesDownloaded = -1;
public long bytesReceivedTotal = -1; public long monthBytesUploaded = -1;
public long bandwidthSentLastSecond = -1; /** Our own transfer quota in MiB, or {@link #UNLIMITED}; only known for ourselves. */
public long bandwidthReceivedLastSecond = -1; public long downloadQuotaMb = UNLIMITED;
public long bandwidthSentLastMinute = -1; public long uploadQuotaMb = UNLIMITED;
public long bandwidthReceivedLastMinute = -1;
/** /**
* How voice has been coming in here, measured by this client's own playback: from this * How voice has been coming in here, measured by this client's own playback: from this
@@ -58,45 +54,30 @@ public final class ConnectionStats {
*/ */
public VoiceReceiveStats voiceReceived; public VoiceReceiveStats voiceReceived;
/** Per-category breakdown (one row per {@link Kind}); empty when unavailable. */ /** One category's figures, or {@link #total} for a null {@code kind}. */
public final List<KindStats> perKind = new ArrayList<>(); public Traffic traffic(Kind kind) {
return kind == null ? total : perKind.computeIfAbsent(kind, k -> new Traffic());
public boolean hasBreakdown() {
return !perKind.isEmpty();
} }
/** Returns the stats for {@code kind}, or {@code null} if not present. */ /** One direction pair of counters. Values default to {@code -1} meaning "unknown". */
public KindStats kind(Kind kind) { public static final class Traffic {
for (KindStats k : perKind) { /** Fractions 0..1: server to client, and client to server. */
if (k.kind == kind) return k; public double lossIn = -1;
} public double lossOut = -1;
return null; public long packetsIn = -1;
} public long packetsOut = -1;
public long bytesIn = -1;
public long bytesOut = -1;
public long bandwidthInLastSecond = -1;
public long bandwidthOutLastSecond = -1;
public long bandwidthInLastMinute = -1;
public long bandwidthOutLastMinute = -1;
/** Returns the stats for {@code kind}, creating and registering the row if needed. */ /** The chance a packet is lost either way, or whichever direction is known. */
public KindStats getOrCreateKind(Kind kind) { public double lossTotal() {
KindStats existing = kind(kind); if (lossIn < 0) return lossOut;
if (existing != null) return existing; if (lossOut < 0) return lossIn;
KindStats created = new KindStats(kind); return 1 - (1 - lossIn) * (1 - lossOut);
perKind.add(created);
return created;
}
/** One category's counters. Values default to {@code -1} meaning "unknown". */
public static final class KindStats {
public final Kind kind;
public double packetLoss = -1; // fraction 0..1
public long packetsSent = -1;
public long packetsReceived = -1;
public long bytesSent = -1;
public long bytesReceived = -1;
public long bandwidthSentLastSecond = -1;
public long bandwidthReceivedLastSecond = -1;
public long bandwidthSentLastMinute = -1;
public long bandwidthReceivedLastMinute = -1;
public KindStats(Kind kind) {
this.kind = kind;
} }
} }
} }
@@ -9,23 +9,36 @@ import com.github.manevolent.ts3j.protocol.packet.statistics.PacketStatistics;
import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket;
import com.github.manevolent.ts3j.util.Pair; import com.github.manevolent.ts3j.util.Pair;
import com.ts3client.audio.VoiceOutput; import com.ts3client.audio.VoiceOutput;
import com.ts3client.net.filetransfer.FileTransferManager;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
* Builds {@link ConnectionStats} snapshots for the info dialog. The local client's own * Builds {@link ConnectionStats} snapshots for the info window from {@code getconnectioninfo}.
* figures are read straight from its live packet counters; a remote client's come from *
* {@code getconnectioninfo}, whose {@code notifyconnectioninfo} report arrives * <p>For another client the server answers twice: at once with the figures it last
* asynchronously via {@link #onReport} and is matched back up by client id. * heard, then again once the client has sent fresh ones ({@code setconnectioninfo}).
* For ourselves it answers once, with only what it measures itself (address, idle time,
* the loss on the way in); the traffic comes from our own socket's counters.
*/ */
final class ConnectionStatsCollector { final class ConnectionStatsCollector {
private static final long REPORT_WAIT_MS = 1000;
/** {@code clientgetvariables} for the month's transfer figures, which change slowly. */
private static final long VARIABLES_REFRESH_MS = 10_000;
private final TeamspeakConnection conn; private final TeamspeakConnection conn;
/** Outstanding {@code getconnectioninfo} requests awaiting a server report, keyed by client id. */ /** Requests awaiting their reports, keyed by client id. */
private final Map<Integer, PendingConnInfo> pending = new ConcurrentHashMap<>(); private final Map<Integer, Pending> pending = new ConcurrentHashMap<>();
private final Map<Integer, Long> variablesAskedAt = new ConcurrentHashMap<>();
/** The file transfer byte counts at the previous poll: time, sent, received. */
private long[] lastTransferSample;
ConnectionStatsCollector(TeamspeakConnection conn) { ConnectionStatsCollector(TeamspeakConnection conn) {
this.conn = conn; this.conn = conn;
@@ -34,61 +47,94 @@ final class ConnectionStatsCollector {
/** Drops any requests left over from a connection that just went away. */ /** Drops any requests left over from a connection that just went away. */
void clear() { void clear() {
pending.clear(); pending.clear();
variablesAskedAt.clear();
lastTransferSample = null;
} }
/** /**
* Fetches connection statistics for a client and delivers them to * Fetches a client's statistics and delivers them to {@code callback} exactly once,
* {@code callback} (invoked off the Swing EDT — the callback is responsible * on a background thread. May be called repeatedly to poll.
* for marshalling). May be called repeatedly to poll.
*/ */
void request(int clientId, Consumer<ConnectionStats> callback) { void request(int clientId, Consumer<ConnectionStats> callback) {
if (clientId == conn.getSelfClientId()) { new Thread(() -> callback.accept(collect(clientId)), "ts3j-conninfo").start();
new Thread(() -> callback.accept(withVoice(buildLocalStats(), clientId)), "ts3j-conninfo-self").start();
} else {
new Thread(() -> requestRemote(clientId, s -> callback.accept(withVoice(s, clientId))),
"ts3j-conninfo").start();
}
} }
/** Adds what our playback saw of the client's voice, or everyone's for ourselves. */ /** Folds an arriving {@code notifyconnectioninfo} report into its request. */
private ConnectionStats withVoice(ConnectionStats s, int clientId) { void onReport(UnknownTeamspeakEvent e) {
Pending p = pending.get(safeInt(e.get("clid")));
if (p == null) return;
synchronized (p.stats) {
applyReport(p.stats, e.getMap());
}
p.reports.countDown();
}
private ConnectionStats collect(int clientId) {
ConnectionStats s = new ConnectionStats();
s.clientId = clientId;
s.self = clientId == conn.getSelfClientId();
refreshVariables(clientId);
awaitReports(s, s.self ? 1 : 2);
synchronized (s) {
if (s.self) {
applyLocal(s);
applyTransferRate(s);
}
sumKinds(s);
ClientEntry entry = conn.getModel().getClient(clientId);
if (entry != null) {
s.nickname = entry.nickname;
s.monthBytesDownloaded = entry.monthBytesDownloaded;
s.monthBytesUploaded = entry.monthBytesUploaded;
}
if (s.self) {
ServerModel model = conn.getModel();
s.downloadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_download_per_client", -1);
s.uploadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_upload_per_client", -1);
}
VoiceOutput playback = conn.getPlayback(); VoiceOutput playback = conn.getPlayback();
if (playback != null) { if (playback != null) {
s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId); s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId);
} }
}
return s; return s;
} }
/** Matches an asynchronously arriving {@code notifyconnectioninfo} report to its request. */ private void awaitReports(ConnectionStats s, int expected) {
void onReport(UnknownTeamspeakEvent e) { LocalTeamspeakClientSocket client = conn.client;
int clid = safeInt(e.get("clid")); if (client == null) return;
PendingConnInfo p = pending.remove(clid); Pending p = new Pending(s, expected);
if (p == null) return; pending.put(s.clientId, p);
applyConnectionFields(p.stats, e.getMap()); try {
p.callback.accept(p.stats); client.executeCommand(new SingleCommand("getconnectioninfo", ProtocolRole.CLIENT,
new CommandSingleParameter("clid", Integer.toString(s.clientId)))).complete();
p.reports.await(REPORT_WAIT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception ignored) {
// refused (e.g. no permission to view it); what is known locally still shows
} finally {
pending.remove(s.clientId, p);
}
} }
/** Builds a live snapshot of the local client's connection from its own counters. */ /** Asks for the month's transfer figures now and then; they land in the model. */
private ConnectionStats buildLocalStats() { private void refreshVariables(int clientId) {
ConnectionStats s = new ConnectionStats(); long now = System.currentTimeMillis();
s.clientId = conn.getSelfClientId(); Long last = variablesAskedAt.get(clientId);
s.self = true; if (last != null && now - last < VARIABLES_REFRESH_MS) return;
s.live = true; variablesAskedAt.put(clientId, now);
s.packetLoss = 0; // the local client has no server->client loss figure conn.requestClientInfo(clientId);
ClientEntry self = conn.getModel().getClient(conn.getSelfClientId());
if (self != null) {
s.nickname = self.nickname;
s.version = self.version;
s.platform = self.platform;
s.idleTimeMs = self.idleTimeMs;
} }
/** Our own traffic, straight from the socket. */
private void applyLocal(ConnectionStats s) {
long connectedAt = conn.connectedAtMs; long connectedAt = conn.connectedAtMs;
if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt; if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt;
LocalTeamspeakClientSocket c = conn.client; LocalTeamspeakClientSocket c = conn.client;
if (c == null) return s; if (c == null) return;
try { try {
Pair<Double, Double> ping = c.getPing(); Pair<Double, Double> ping = c.getPing();
s.pingMs = ping.getKey() * 1000.0; s.pingMs = ping.getKey() * 1000.0;
@@ -96,158 +142,87 @@ final class ConnectionStatsCollector {
} catch (Exception ignored) { } catch (Exception ignored) {
// ping unavailable; leave as unknown // ping unavailable; leave as unknown
} }
long pSent = 0, pRecv = 0, bSent = 0, bRecv = 0;
long bwSs = 0, bwRs = 0, bwSm = 0, bwRm = 0;
for (PacketKind kind : PacketKind.values()) { for (PacketKind kind : PacketKind.values()) {
PacketStatistics st = c.getStatistics(kind); PacketStatistics st = c.getStatistics(kind);
ConnectionStats.KindStats ks = new ConnectionStats.KindStats(mapKind(kind)); ConnectionStats.Traffic t = s.traffic(mapKind(kind));
ks.packetLoss = 0; // the local client cannot measure its own server->client loss t.packetsIn = add(t.packetsIn, st.getReceivedPackets());
ks.packetsSent = st.getSentPackets(); t.packetsOut = add(t.packetsOut, st.getSentPackets());
ks.packetsReceived = st.getReceivedPackets(); t.bytesIn = add(t.bytesIn, st.getReceivedBytes());
ks.bytesSent = st.getSentBytes(); t.bytesOut = add(t.bytesOut, st.getSentBytes());
ks.bytesReceived = st.getReceivedBytes(); t.bandwidthInLastSecond = add(t.bandwidthInLastSecond, st.getReceivedBytesLastSecond());
ks.bandwidthSentLastSecond = st.getSentBytesLastSecond(); t.bandwidthOutLastSecond = add(t.bandwidthOutLastSecond, st.getSentBytesLastSecond());
ks.bandwidthReceivedLastSecond = st.getReceivedBytesLastSecond(); t.bandwidthInLastMinute = add(t.bandwidthInLastMinute, st.getReceivedBandwidthLastMinute());
ks.bandwidthSentLastMinute = st.getSentBandwidthLastMinute(); t.bandwidthOutLastMinute = add(t.bandwidthOutLastMinute, st.getSentBandwidthLastMinute());
ks.bandwidthReceivedLastMinute = st.getReceivedBandwidthLastMinute();
s.perKind.add(ks);
pSent += ks.packetsSent;
pRecv += ks.packetsReceived;
bSent += ks.bytesSent;
bRecv += ks.bytesReceived;
bwSs += ks.bandwidthSentLastSecond;
bwRs += ks.bandwidthReceivedLastSecond;
bwSm += ks.bandwidthSentLastMinute;
bwRm += ks.bandwidthReceivedLastMinute;
}
s.packetsSentTotal = pSent;
s.packetsReceivedTotal = pRecv;
s.bytesSentTotal = bSent;
s.bytesReceivedTotal = bRecv;
s.bandwidthSentLastSecond = bwSs;
s.bandwidthReceivedLastSecond = bwRs;
s.bandwidthSentLastMinute = bwSm;
s.bandwidthReceivedLastMinute = bwRm;
return s;
}
/**
* Requests a remote client's connection info: {@code getconnectioninfo}, whose
* {@code notifyconnectioninfo} report arrives asynchronously via {@link #onReport}.
* Version and platform come from the model; {@code clientinfo} would have them too,
* but it counts heavily against the server's flood protection, and this is polled.
* If the report does not arrive shortly (e.g. the server withholds it), the
* model-only snapshot is delivered instead.
*/
private void requestRemote(int clientId, Consumer<ConnectionStats> callback) {
ConnectionStats s = new ConnectionStats();
s.clientId = clientId;
ClientEntry entry = conn.getModel().getClient(clientId);
if (entry != null) {
s.nickname = entry.nickname;
s.version = entry.version;
s.platform = entry.platform;
}
LocalTeamspeakClientSocket client = conn.client;
PendingConnInfo p = new PendingConnInfo(callback, s);
pending.put(clientId, p);
boolean sent = false;
try {
SingleCommand cmd = new SingleCommand("getconnectioninfo", ProtocolRole.CLIENT,
new CommandSingleParameter("clid", Integer.toString(clientId)));
client.executeCommand(cmd).complete();
sent = true;
} catch (Exception ignored) {
// command failed; fall back to the model snapshot below
}
if (sent) {
try {
Thread.sleep(700); // give notifyconnectioninfo a chance to arrive
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
// If the report already arrived, onReport removed and delivered it.
if (pending.remove(clientId, p)) {
callback.accept(s);
} }
} }
/** Parses TeamSpeak {@code connection_*} fields from a command map into {@code s}. */ /** Our file transfer rate since the previous poll; the server reports it only for others. */
private static void applyConnectionFields(ConnectionStats s, Map<String, String> m) { private synchronized void applyTransferRate(ConnectionStats s) {
double ping = parseDouble(m.get("connection_ping")); FileTransferManager ft = conn.fileTransfers();
if (ping >= 0) s.pingMs = ping; if (ft == null) return;
double dev = parseDouble(m.get("connection_ping_deviation")); long[] now = {System.currentTimeMillis(), ft.bytesSent(), ft.bytesReceived()};
if (dev >= 0) s.pingDeviationMs = dev; long[] last = lastTransferSample;
double loss = parseDouble(m.get("connection_packetloss_total")); lastTransferSample = now;
if (loss < 0) loss = parseDouble(m.get("connection_server2client_packetloss_total")); long elapsed = last == null ? 0 : now[0] - last[0];
if (loss >= 0) s.packetLoss = loss; s.filetransferBandwidthSent = elapsed <= 0 ? 0 : (now[1] - last[1]) * 1000 / elapsed;
s.filetransferBandwidthReceived = elapsed <= 0 ? 0 : (now[2] - last[2]) * 1000 / elapsed;
}
long connected = parseLong(m.get("connection_connected_time")); /** Several of ts3j's packet kinds (commands and their acks) make up one TeamSpeak category. */
if (connected >= 0) s.connectedTimeMs = connected; private static long add(long current, long value) {
long idle = parseLong(m.get("connection_idle_time")); return Math.max(current, 0) + value;
if (idle >= 0) s.idleTimeMs = idle; }
/** Fills the totals from the categories: clients report only those. */
private static void sumKinds(ConnectionStats s) {
ConnectionStats.Traffic total = s.total;
if (total.packetsIn >= 0) return;
total.packetsIn = total.packetsOut = total.bytesIn = total.bytesOut = 0;
total.bandwidthInLastSecond = total.bandwidthOutLastSecond = 0;
total.bandwidthInLastMinute = total.bandwidthOutLastMinute = 0;
for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) {
ConnectionStats.Traffic t = s.traffic(kind);
total.packetsIn += Math.max(t.packetsIn, 0);
total.packetsOut += Math.max(t.packetsOut, 0);
total.bytesIn += Math.max(t.bytesIn, 0);
total.bytesOut += Math.max(t.bytesOut, 0);
total.bandwidthInLastSecond += Math.max(t.bandwidthInLastSecond, 0);
total.bandwidthOutLastSecond += Math.max(t.bandwidthOutLastSecond, 0);
total.bandwidthInLastMinute += Math.max(t.bandwidthInLastMinute, 0);
total.bandwidthOutLastMinute += Math.max(t.bandwidthOutLastMinute, 0);
}
}
/** Parses TeamSpeak's {@code connection_*} fields; ones the report leaves out stay as they are. */
private static void applyReport(ConnectionStats s, Map<String, String> m) {
s.pingMs = pickDouble(s.pingMs, m.get("connection_ping"));
s.pingDeviationMs = pickDouble(s.pingDeviationMs, m.get("connection_ping_deviation"));
s.connectedTimeMs = pick(s.connectedTimeMs, m.get("connection_connected_time"));
s.idleTimeMs = pick(s.idleTimeMs, m.get("connection_idle_time"));
String ip = m.get("connection_client_ip"); String ip = m.get("connection_client_ip");
if (ip != null && !ip.isEmpty()) s.ip = ip; if (ip != null && !ip.isEmpty()) s.ip = ip;
s.port = (int) pick(s.port, m.get("connection_client_port"));
s.packetsSentTotal = pick(s.packetsSentTotal, m.get("connection_packets_sent_total")); s.filetransferBandwidthSent = pick(s.filetransferBandwidthSent, m.get("connection_filetransfer_bandwidth_sent"));
s.packetsReceivedTotal = pick(s.packetsReceivedTotal, m.get("connection_packets_received_total"));
s.bytesSentTotal = pick(s.bytesSentTotal, m.get("connection_bytes_sent_total"));
s.bytesReceivedTotal = pick(s.bytesReceivedTotal, m.get("connection_bytes_received_total"));
s.bandwidthSentLastSecond =
pick(s.bandwidthSentLastSecond, m.get("connection_bandwidth_sent_last_second_total"));
s.bandwidthReceivedLastSecond =
pick(s.bandwidthReceivedLastSecond, m.get("connection_bandwidth_received_last_second_total"));
s.bandwidthSentLastMinute =
pick(s.bandwidthSentLastMinute, m.get("connection_bandwidth_sent_last_minute_total"));
s.bandwidthReceivedLastMinute =
pick(s.bandwidthReceivedLastMinute, m.get("connection_bandwidth_received_last_minute_total"));
s.filetransferBandwidthSent =
pick(s.filetransferBandwidthSent, m.get("connection_filetransfer_bandwidth_sent"));
s.filetransferBandwidthReceived = s.filetransferBandwidthReceived =
pick(s.filetransferBandwidthReceived, m.get("connection_filetransfer_bandwidth_received")); pick(s.filetransferBandwidthReceived, m.get("connection_filetransfer_bandwidth_received"));
applyPerKindFields(s, m); applyTraffic(s.total, m, "total");
}
/**
* Parses the per-category {@code connection_*_<kind>} fields (as sent in a
* {@code notifyconnectioninfo} report) into {@code s}, merging into any
* existing rows. Categories absent from the map are left untouched.
*/
private static void applyPerKindFields(ConnectionStats s, Map<String, String> m) {
for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) {
String suffix = kind.name().toLowerCase(java.util.Locale.ROOT); // keepalive/control/speech applyTraffic(s.traffic(kind), m, kind.name().toLowerCase(Locale.ROOT));
String probe = m.get("connection_packets_sent_" + suffix);
String probe2 = m.get("connection_server2client_packetloss_" + suffix);
if (probe == null && probe2 == null) continue; // this category not reported
ConnectionStats.KindStats ks = s.getOrCreateKind(kind);
ks.packetsSent = pick(ks.packetsSent, m.get("connection_packets_sent_" + suffix));
ks.packetsReceived = pick(ks.packetsReceived, m.get("connection_packets_received_" + suffix));
ks.bytesSent = pick(ks.bytesSent, m.get("connection_bytes_sent_" + suffix));
ks.bytesReceived = pick(ks.bytesReceived, m.get("connection_bytes_received_" + suffix));
ks.bandwidthSentLastSecond =
pick(ks.bandwidthSentLastSecond, m.get("connection_bandwidth_sent_last_second_" + suffix));
ks.bandwidthReceivedLastSecond =
pick(ks.bandwidthReceivedLastSecond, m.get("connection_bandwidth_received_last_second_" + suffix));
ks.bandwidthSentLastMinute =
pick(ks.bandwidthSentLastMinute, m.get("connection_bandwidth_sent_last_minute_" + suffix));
ks.bandwidthReceivedLastMinute =
pick(ks.bandwidthReceivedLastMinute, m.get("connection_bandwidth_received_last_minute_" + suffix));
double kloss = parseDouble(m.get("connection_server2client_packetloss_" + suffix));
if (kloss >= 0) ks.packetLoss = kloss;
} }
} }
private static long pick(long current, String value) { private static void applyTraffic(ConnectionStats.Traffic t, Map<String, String> m, String suffix) {
long v = parseLong(value); t.lossIn = pickDouble(t.lossIn, m.get("connection_server2client_packetloss_" + suffix));
return v >= 0 ? v : current; t.lossOut = pickDouble(t.lossOut, m.get("connection_client2server_packetloss_" + suffix));
t.packetsIn = pick(t.packetsIn, m.get("connection_packets_received_" + suffix));
t.packetsOut = pick(t.packetsOut, m.get("connection_packets_sent_" + suffix));
t.bytesIn = pick(t.bytesIn, m.get("connection_bytes_received_" + suffix));
t.bytesOut = pick(t.bytesOut, m.get("connection_bytes_sent_" + suffix));
t.bandwidthInLastSecond = pick(t.bandwidthInLastSecond, m.get("connection_bandwidth_received_last_second_" + suffix));
t.bandwidthOutLastSecond = pick(t.bandwidthOutLastSecond, m.get("connection_bandwidth_sent_last_second_" + suffix));
t.bandwidthInLastMinute = pick(t.bandwidthInLastMinute, m.get("connection_bandwidth_received_last_minute_" + suffix));
t.bandwidthOutLastMinute = pick(t.bandwidthOutLastMinute, m.get("connection_bandwidth_sent_last_minute_" + suffix));
} }
private static ConnectionStats.Kind mapKind(PacketKind kind) { private static ConnectionStats.Kind mapKind(PacketKind kind) {
@@ -261,6 +236,16 @@ final class ConnectionStatsCollector {
} }
} }
private static long pick(long current, String value) {
long v = parseLong(value);
return v >= 0 ? v : current;
}
private static double pickDouble(double current, String value) {
double v = parseDouble(value);
return v >= 0 ? v : current;
}
/** Parses a long, returning -1 for null/blank/non-numeric input. */ /** Parses a long, returning -1 for null/blank/non-numeric input. */
private static long parseLong(String s) { private static long parseLong(String s) {
if (s == null || s.isEmpty()) return -1; if (s == null || s.isEmpty()) return -1;
@@ -290,14 +275,14 @@ final class ConnectionStatsCollector {
} }
} }
/** Callback + accumulating snapshot for an in-flight {@code getconnectioninfo}. */ /** A request's snapshot, filled in by its reports as they arrive. */
private static final class PendingConnInfo { private static final class Pending {
final Consumer<ConnectionStats> callback;
final ConnectionStats stats; final ConnectionStats stats;
final CountDownLatch reports;
PendingConnInfo(Consumer<ConnectionStats> callback, ConnectionStats stats) { Pending(ConnectionStats stats, int expected) {
this.callback = callback;
this.stats = stats; this.stats = stats;
this.reports = new CountDownLatch(expected);
} }
} }
} }
@@ -3,114 +3,112 @@ package com.ts3client.net;
import com.ts3client.audio.VoiceReceiveStats; import com.ts3client.audio.VoiceReceiveStats;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** Renders {@link ConnectionStats} figures for display; an unknown value (negative) shows as a dash. */ /**
* Renders {@link ConnectionStats} the way the official Connection Info window does: a
* summary, one traffic table per tab with Total / In / Out columns, and a quota tab.
* An unknown value (negative) shows as a dash.
*/
public final class ConnectionStatsFormat { public final class ConnectionStatsFormat {
public static final String UNKNOWN = "—"; public static final String UNKNOWN = "—";
public static final String HIDDEN = "Hidden";
public static final String UNLIMITED = "Unlimited";
public static final String EXCEEDED = "Exceeded";
/** The traffic table's column headings, after the row labels. */
public static final List<String> COLUMNS = List.of("Total", "In", "Out");
private ConnectionStatsFormat() { private ConnectionStatsFormat() {
} }
public static String orDash(String s) {
return (s == null || s.isEmpty()) ? UNKNOWN : s;
}
public static String ping(double ms, double deviationMs) {
if (ms < 0) return UNKNOWN;
String base = Math.round(ms) + " ms";
if (deviationMs > 0) base += " (± " + Math.round(deviationMs) + " ms)";
return base;
}
/** A fraction 0..1 as a percentage. */
public static String loss(double fraction) {
if (fraction < 0) return UNKNOWN;
return new DecimalFormat("0.00").format(fraction * 100.0) + " %";
}
public static String count(long n) {
return n < 0 ? UNKNOWN : new DecimalFormat("#,##0").format(n);
}
/** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */
public static String countOf(long n, long of) {
if (n < 0) return UNKNOWN;
if (of <= 0) return count(n);
return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)";
}
public static String bytes(long bytes) {
if (bytes < 0) return UNKNOWN;
if (bytes < 1024) return bytes + " B";
double kib = bytes / 1024.0;
if (kib < 1024) return new DecimalFormat("0.0").format(kib) + " KiB";
double mib = kib / 1024.0;
if (mib < 1024) return new DecimalFormat("0.00").format(mib) + " MiB";
return new DecimalFormat("0.00").format(mib / 1024.0) + " GiB";
}
public static String rate(long bytesPerSecond) {
return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s";
}
/** Sent and received side by side. */
public static String upDown(String up, String down) {
return up + " / " + down;
}
/** A labelled figure. */ /** A labelled figure. */
public record Row(String label, String value) { public record Row(String label, String value) {
} }
/** Who the client is and how the link to them is doing; {@code s} may be null while loading. */ /** A traffic table row; {@code total} is empty where the official client leaves it blank. */
public static List<Row> summaryRows(ConnectionStats s, String selfAddress) { public record TrafficRow(String label, String total, String in, String out) {
ConnectionStats k = s == null ? new ConnectionStats() : s;
return List.of(
new Row("Address", k.self ? selfAddress : orDash(k.ip)),
new Row("Client version", orDash(k.version)),
new Row("Platform", orDash(k.platform)),
new Row("Ping", ping(k.pingMs, k.pingDeviationMs)),
new Row("Idle time", duration(k.idleTimeMs)),
new Row("Connected", duration(k.connectedTimeMs)),
new Row("Filetransfer (↑/↓)",
upDown(rate(k.filetransferBandwidthSent), rate(k.filetransferBandwidthReceived))));
} }
/** One traffic category's figures, or the totals for a null {@code kind}. */ /** A traffic tab: the totals for a null {@code kind}, else one category. */
public static List<Row> trafficRows(ConnectionStats s, ConnectionStats.Kind kind) { public record Tab(String title, ConnectionStats.Kind kind) {
double loss = -1;
long packetsSent = -1, packetsReceived = -1, bytesSent = -1, bytesReceived = -1;
long secondSent = -1, secondReceived = -1, minuteSent = -1, minuteReceived = -1;
if (s != null && kind == null) {
loss = s.packetLoss;
packetsSent = s.packetsSentTotal;
packetsReceived = s.packetsReceivedTotal;
bytesSent = s.bytesSentTotal;
bytesReceived = s.bytesReceivedTotal;
secondSent = s.bandwidthSentLastSecond;
secondReceived = s.bandwidthReceivedLastSecond;
minuteSent = s.bandwidthSentLastMinute;
minuteReceived = s.bandwidthReceivedLastMinute;
} else if (s != null && s.kind(kind) != null) {
ConnectionStats.KindStats k = s.kind(kind);
loss = k.packetLoss;
packetsSent = k.packetsSent;
packetsReceived = k.packetsReceived;
bytesSent = k.bytesSent;
bytesReceived = k.bytesReceived;
secondSent = k.bandwidthSentLastSecond;
secondReceived = k.bandwidthReceivedLastSecond;
minuteSent = k.bandwidthSentLastMinute;
minuteReceived = k.bandwidthReceivedLastMinute;
} }
public static final List<Tab> TRAFFIC_TABS = List.of(
new Tab("Total", null),
new Tab("Speech", ConnectionStats.Kind.SPEECH),
new Tab("Keep Alive", ConnectionStats.Kind.KEEPALIVE),
new Tab("Control", ConnectionStats.Kind.CONTROL));
public static final String QUOTA_TAB = "Quota";
public static final String VOICE_TAB = "Voice received";
/** Who the client is and how the link to them is doing; {@code s} may be null while loading. */
public static List<Row> summaryRows(ConnectionStats s, String nickname) {
ConnectionStats k = s == null ? new ConnectionStats() : s;
return List.of( return List.of(
new Row("Packet loss", loss(loss)), new Row("Client name", nickname),
new Row("Packets (↑/↓)", upDown(count(packetsSent), count(packetsReceived))), new Row("Connection time", duration(k.connectedTimeMs)),
new Row("Transferred (↑/↓)", upDown(bytes(bytesSent), bytes(bytesReceived))), new Row("Idle time", duration(k.idleTimeMs)),
new Row("Bandwidth · last second (↑/↓)", upDown(rate(secondSent), rate(secondReceived))), new Row("Ping", ping(k.pingMs, k.pingDeviationMs)),
new Row("Bandwidth · last minute (↑/↓)", upDown(rate(minuteSent), rate(minuteReceived)))); new Row("Client address", s == null ? UNKNOWN : address(s)));
}
/** {@code ip:port}, what the copy button next to it puts on the clipboard; null when unknown. */
public static String copyableAddress(ConnectionStats s) {
if (s == null || s.ip.isEmpty()) return null;
return s.port > 0 ? s.ip + ":" + s.port : s.ip;
}
private static String address(ConnectionStats s) {
String address = copyableAddress(s);
return address == null ? HIDDEN : address;
}
/** One traffic tab's table; only the totals carry the file transfer row. */
public static List<TrafficRow> trafficRows(ConnectionStats s, ConnectionStats.Kind kind) {
ConnectionStats.Traffic t = s == null ? new ConnectionStats.Traffic() : s.traffic(kind);
List<TrafficRow> rows = new ArrayList<>(List.of(
new TrafficRow("Packet loss", loss(t.lossTotal()), loss(t.lossIn), loss(t.lossOut)),
new TrafficRow("Packets transferred", "", count(t.packetsIn), count(t.packetsOut)),
new TrafficRow("Bytes transferred", "", bytes(t.bytesIn), bytes(t.bytesOut)),
new TrafficRow("Bandwidth last second", "",
rate(t.bandwidthInLastSecond), rate(t.bandwidthOutLastSecond)),
new TrafficRow("Bandwidth last minute", "",
rate(t.bandwidthInLastMinute), rate(t.bandwidthOutLastMinute))));
if (kind == null) {
long in = s == null ? -1 : s.filetransferBandwidthReceived;
long out = s == null ? -1 : s.filetransferBandwidthSent;
rows.add(new TrafficRow("File transfer bandwidth", "", rate(in), rate(out)));
}
return rows;
}
/**
* The quota tab: downloads, then uploads. Only our own limits are known, so another
* client's groups hold just the month's figure.
*/
public static List<List<Row>> quotaGroups(ConnectionStats s) {
ConnectionStats k = s == null ? new ConnectionStats() : s;
return List.of(
quota(k, "download", "Downloaded this month:", k.monthBytesDownloaded, k.downloadQuotaMb),
quota(k, "upload", "Uploaded this month:", k.monthBytesUploaded, k.uploadQuotaMb));
}
private static List<Row> quota(ConnectionStats s, String direction, String label, long used, long quotaMb) {
Row month = new Row(label, bytes(used));
if (!s.self) return List.of(month);
String available = quotaMb < 0 ? UNLIMITED : bytes(quotaMb * 1024 * 1024);
String remaining;
if (quotaMb < 0) remaining = UNLIMITED;
else if (used < 0) remaining = UNKNOWN;
else if (used > quotaMb * 1024 * 1024) remaining = EXCEEDED;
else remaining = bytes(quotaMb * 1024 * 1024 - used);
return List.of(month,
new Row("Available " + direction + " quota:", available),
new Row("Remaining " + direction + " this month:", remaining));
} }
/** The voice our playback received; every value is a dash when nothing was heard. */ /** The voice our playback received; every value is a dash when nothing was heard. */
@@ -127,18 +125,62 @@ public final class ConnectionStatsFormat {
new Row("Discarded (copies)", known ? countOf(s.duplicates(), s.received()) : UNKNOWN)); new Row("Discarded (copies)", known ? countOf(s.duplicates(), s.received()) : UNKNOWN));
} }
// ---- figures ----
/** {@code 153 ms ± 217.0}. */
public static String ping(double ms, double deviationMs) {
if (ms < 0) return UNKNOWN;
String base = Math.round(ms) + " ms";
if (deviationMs >= 0) base += " ± " + new DecimalFormat("0.0").format(deviationMs);
return base;
}
/** A fraction 0..1 as a percentage. */
public static String loss(double fraction) {
if (fraction < 0) return UNKNOWN;
return new DecimalFormat("0.00").format(fraction * 100.0) + " %";
}
/** {@code 133}, {@code 2.12 k}, {@code 1.05 M}. */
public static String count(long n) {
if (n < 0) return UNKNOWN;
if (n < 1000) return Long.toString(n);
DecimalFormat f = new DecimalFormat("0.00");
if (n < 1_000_000) return f.format(n / 1e3) + " k";
return f.format(n / 1e6) + " M";
}
/** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */
public static String countOf(long n, long of) {
if (n < 0) return UNKNOWN;
if (of <= 0) return count(n);
return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)";
}
public static String bytes(long bytes) {
if (bytes < 0) return UNKNOWN;
if (bytes < 1024) return bytes + " Bytes";
DecimalFormat f = new DecimalFormat("0.00");
double kib = bytes / 1024.0;
if (kib < 1024) return f.format(kib) + " KiB";
double mib = kib / 1024.0;
if (mib < 1024) return f.format(mib) + " MiB";
return f.format(mib / 1024.0) + " GiB";
}
public static String rate(long bytesPerSecond) {
return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s";
}
/** {@code 04:34}, or {@code 15:35:17} from an hour on. */
public static String duration(long ms) { public static String duration(long ms) {
if (ms < 0) return UNKNOWN; if (ms < 0) return UNKNOWN;
long totalSeconds = ms / 1000; long totalSeconds = ms / 1000;
long days = totalSeconds / 86400; long hours = totalSeconds / 3600;
long hours = (totalSeconds % 86400) / 3600;
long minutes = (totalSeconds % 3600) / 60; long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60; long seconds = totalSeconds % 60;
StringBuilder sb = new StringBuilder(); return hours > 0
if (days > 0) sb.append(days).append("d "); ? String.format("%02d:%02d:%02d", hours, minutes, seconds)
if (days > 0 || hours > 0) sb.append(hours).append("h "); : String.format("%02d:%02d", minutes, seconds);
if (days > 0 || hours > 0 || minutes > 0) sb.append(minutes).append("m ");
sb.append(seconds).append("s");
return sb.toString();
} }
} }
@@ -155,9 +155,14 @@ public final class ServerModel {
* never reported a non-default value for it). * never reported a non-default value for it).
*/ */
public synchronized int selfPermissionValue(String name) { public synchronized int selfPermissionValue(String name) {
return selfPermissionValue(name, 0);
}
/** As {@link #selfPermissionValue(String)}, with {@code absent} for a permission not (yet) reported. */
public synchronized int selfPermissionValue(String name, int absent) {
Integer id = permissionIds.get(name); Integer id = permissionIds.get(name);
Integer value = id == null ? null : selfPermissionValues.get(id); Integer value = id == null ? null : selfPermissionValues.get(id);
return value == null ? 0 : value; return value == null ? absent : value;
} }
/** /**
@@ -1421,7 +1421,7 @@ public final class TeamspeakConnection implements TS3Listener {
return sock; return sock;
} }
/** Package-private for {@link ChannelAdmin}. */ /** Package-private for {@link ChannelAdmin} and {@link ConnectionStatsCollector}. */
FileTransferManager fileTransfers() { FileTransferManager fileTransfers() {
return fileTransfers; return fileTransfers;
} }
@@ -30,6 +30,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier; import java.util.function.Supplier;
/** /**
@@ -61,6 +62,9 @@ public final class FileTransferManager {
/** Host we are connected to, used when the server reports no dedicated file-transfer host. */ /** Host we are connected to, used when the server reports no dedicated file-transfer host. */
private final Supplier<String> fallbackHost; private final Supplier<String> fallbackHost;
private final AtomicInteger clientTransferId = new AtomicInteger(1); private final AtomicInteger clientTransferId = new AtomicInteger(1);
/** Every byte moved so far, for the connection info's transfer rate. */
private final AtomicLong bytesSent = new AtomicLong();
private final AtomicLong bytesReceived = new AtomicLong();
private final ExecutorService transferPool = Executors.newCachedThreadPool(r -> { private final ExecutorService transferPool = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "ts3j-filetransfer"); Thread t = new Thread(r, "ts3j-filetransfer");
t.setDaemon(true); t.setDaemon(true);
@@ -95,6 +99,14 @@ public final class FileTransferManager {
socket.addListener(ftEventListener); socket.addListener(ftEventListener);
} }
public long bytesSent() {
return bytesSent.get();
}
public long bytesReceived() {
return bytesReceived.get();
}
// ---- directory operations ---- // ---- directory operations ----
/** /**
@@ -233,6 +245,7 @@ public final class FileTransferManager {
int read = in.read(data, offset, data.length - offset); int read = in.read(data, offset, data.length - offset);
if (read < 0) throw new IOException("File server closed the connection early"); if (read < 0) throw new IOException("File server closed the connection early");
offset += read; offset += read;
bytesReceived.addAndGet(read);
} }
} }
return data; return data;
@@ -274,6 +287,7 @@ public final class FileTransferManager {
if (read < 0) throw new IOException("File server closed the connection early"); if (read < 0) throw new IOException("File server closed the connection early");
fileOut.write(buffer, 0, read); fileOut.write(buffer, 0, read);
remaining -= read; remaining -= read;
bytesReceived.addAndGet(read);
transfer.addTransferred(read); transfer.addTransferred(read);
} }
} }
@@ -328,6 +342,7 @@ public final class FileTransferManager {
if (read < 0) break; // file shorter than announced; stop if (read < 0) break; // file shorter than announced; stop
out.write(buffer, 0, read); out.write(buffer, 0, read);
remaining -= read; remaining -= read;
bytesSent.addAndGet(read);
transfer.addTransferred(read); transfer.addTransferred(read);
} }
out.flush(); out.flush();
@@ -2,72 +2,84 @@ package com.ts3client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale; import com.formdev.flatlaf.util.UIScale;
import com.ts3client.net.ClientEntry;
import com.ts3client.net.ConnectionStats; import com.ts3client.net.ConnectionStats;
import com.ts3client.net.ConnectionStatsFormat; import com.ts3client.net.ConnectionStatsFormat;
import com.ts3client.net.ConnectionStatsFormat.Row; import com.ts3client.net.ConnectionStatsFormat.Row;
import com.ts3client.net.ConnectionStatsFormat.TrafficRow;
import com.ts3client.net.TeamspeakConnection; import com.ts3client.net.TeamspeakConnection;
import com.ts3client.net.avatar.Avatar;
import javax.swing.Box; import javax.swing.Box;
import javax.swing.BoxLayout; import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton; import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog; import javax.swing.JDialog;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane; import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame; import java.awt.Frame;
import java.awt.GridBagConstraints; import java.awt.GridBagConstraints;
import java.awt.GridBagLayout; import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets; import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Live "Client Connection Info" window, reachable from a client's right-click * Live "Client Connection Info" window, laid out as TeamSpeak 3's: name, times, ping and
* menu. Mirrors the TeamSpeak 3 dialog: a summary header (address, version, * address beside the avatar, above a tab per traffic category whose table has Total / In /
* platform, idle/connected time, ping, filetransfer) above a * Out columns, and a Quota tab. A <em>Voice received</em> tab adds what our own playback
* <em>Total / Speech / Keep Alive / Control</em> tab strip, each tab showing * made of the client's voice (everyone's, for ourselves). Polls once a second while open.
* that category's packet loss, packet and byte totals and live bandwidth, plus a
* <em>Voice received</em> tab with what our own playback made of the client's voice
* (everyone's, for ourselves): missed, out-of-order, late and duplicate packets.
*
* <p>Polls the {@link TeamspeakConnection} once a second while open; for the
* local client the figures update live from local counters, for a remote client
* they refresh from the server's connection report.
*/ */
public final class ConnectionInfoDialog extends JDialog { public final class ConnectionInfoDialog extends JDialog {
private static final int REFRESH_MS = 1000; private static final int REFRESH_MS = 1000;
/** Wide enough for the tab strip to stay on one row. */ /** Avatar box, about the official window's. */
private static final int MIN_WIDTH = 560; private static final int AVATAR_SIZE = 80;
private static final String SELF_ADDRESS = "This computer"; /** Sample texts sizing the columns, as the official window does, so they don't jitter. */
private static final String TOTAL_SAMPLE = "100.00 %";
private static final String VALUE_SAMPLE = "1023.00 KiB/s";
private final TeamspeakConnection conn; private final TeamspeakConnection conn;
private final int clientId; private final int clientId;
private final String nickname;
private final javax.swing.Timer timer; private final javax.swing.Timer timer;
private final java.util.concurrent.atomic.AtomicBoolean inFlight = private final AtomicBoolean inFlight = new AtomicBoolean();
new java.util.concurrent.atomic.AtomicBoolean();
private final Rows summary = new Rows(ConnectionStatsFormat.summaryRows(null, SELF_ADDRESS)); private final Figures summary;
private final Rows total = tab(ConnectionStatsFormat.trafficRows(null, null)); private final JButton copyAddress = new JButton(Icons.of("COPY"));
private final Rows speech = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.SPEECH)); private final JLabel avatar = new JLabel();
private final Rows keepAlive = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.KEEPALIVE)); private Avatar shownAvatar;
private final Rows control = tab(ConnectionStatsFormat.trafficRows(null, ConnectionStats.Kind.CONTROL)); private ConnectionStats latest;
private final Rows voice = tab(ConnectionStatsFormat.voiceRows(null));
private final List<TrafficTable> traffic = new ArrayList<>();
private Figures quota;
private final Figures voice = new Figures(List.of(ConnectionStatsFormat.voiceRows(null)), false);
public ConnectionInfoDialog(Frame owner, TeamspeakConnection conn, int clientId, String nickname) { public ConnectionInfoDialog(Frame owner, TeamspeakConnection conn, int clientId, String nickname) {
super(owner, "Connection Info — " + nickname, false); super(owner, "Connection Info - " + nickname, false);
this.conn = conn; this.conn = conn;
this.clientId = clientId; this.clientId = clientId;
this.nickname = nickname;
this.summary = new Figures(List.of(ConnectionStatsFormat.summaryRows(null, nickname)), true);
JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(10))); JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(12)));
content.setBackground(Theme.windowBg()); content.setBackground(Theme.windowBg());
content.setBorder(new ScaledEmptyBorder(12, 14, 12, 14)); content.setBorder(new ScaledEmptyBorder(10, 10, 10, 10));
content.add(summary, BorderLayout.NORTH); content.add(buildHeader(), BorderLayout.NORTH);
content.add(buildTabs(), BorderLayout.CENTER); content.add(buildTabs(), BorderLayout.CENTER);
content.add(buildButtons(), BorderLayout.SOUTH); content.add(buildButtons(), BorderLayout.SOUTH);
setContentPane(content); setContentPane(content);
@@ -75,7 +87,7 @@ public final class ConnectionInfoDialog extends JDialog {
Dialogs.closeOnEscape(this); Dialogs.closeOnEscape(this);
// Disposing is what stops the refresh timer, so the window button must not merely hide. // Disposing is what stops the refresh timer, so the window button must not merely hide.
setDefaultCloseOperation(DISPOSE_ON_CLOSE); setDefaultCloseOperation(DISPOSE_ON_CLOSE);
fit(); pack();
setLocationRelativeTo(owner); setLocationRelativeTo(owner);
addWindowListener(new WindowAdapter() { addWindowListener(new WindowAdapter() {
@@ -92,35 +104,68 @@ public final class ConnectionInfoDialog extends JDialog {
// ---- construction ---- // ---- construction ----
private JPanel buildHeader() {
copyAddress.setToolTipText("Copy client address to clipboard");
copyAddress.setMargin(UIScale.scale(new Insets(1, 1, 1, 1)));
copyAddress.setEnabled(false);
copyAddress.addActionListener(e -> {
String address = ConnectionStatsFormat.copyableAddress(latest);
if (address != null) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(address), null);
}
});
summary.addTrailing(copyAddress);
avatar.setVerticalAlignment(SwingConstants.TOP);
avatar.setBorder(new ScaledEmptyBorder(0, 16, 0, 0));
JPanel header = new JPanel(new BorderLayout());
header.setOpaque(false);
header.add(summary, BorderLayout.CENTER);
header.add(avatar, BorderLayout.EAST);
return header;
}
private JTabbedPane buildTabs() { private JTabbedPane buildTabs() {
JTabbedPane tabs = new JTabbedPane(); JTabbedPane tabs = new JTabbedPane();
tabs.setFont(Theme.uiFont()); tabs.setFont(Theme.uiFont());
tabs.setBackground(Theme.windowBg()); for (ConnectionStatsFormat.Tab tab : ConnectionStatsFormat.TRAFFIC_TABS) {
tabs.addTab("Total", total); TrafficTable table = new TrafficTable(tab.kind());
tabs.addTab("Speech", speech); traffic.add(table);
tabs.addTab("Keep Alive", keepAlive); tabs.addTab(tab.title(), table);
tabs.addTab("Control", control); }
tabs.addTab("Voice received", voice); tabs.addTab(ConnectionStatsFormat.QUOTA_TAB, buildQuota());
tabs.addTab(ConnectionStatsFormat.VOICE_TAB, page(voice));
return tabs; return tabs;
} }
private JComponent buildQuota() {
// Laid out for ourselves, the longer form; another client's extra rows hide on the first update.
ConnectionStats self = new ConnectionStats();
self.self = true;
quota = new Figures(ConnectionStatsFormat.quotaGroups(self), false);
return page(quota);
}
private static JComponent page(JComponent body) {
JPanel page = new JPanel(new BorderLayout());
page.setOpaque(false);
page.setBorder(new ScaledEmptyBorder(8, 10, 8, 10));
page.add(body, BorderLayout.NORTH);
return page;
}
private JPanel buildButtons() { private JPanel buildButtons() {
JPanel bar = new JPanel(); JPanel bar = new JPanel();
bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS));
bar.setBackground(Theme.windowBg()); bar.setOpaque(false);
bar.add(Box.createHorizontalGlue()); bar.add(Box.createHorizontalGlue());
JButton close = new JButton("Close"); JButton close = new JButton("Close", Icons.of("CLOSE"));
close.addActionListener(e -> dispose()); close.addActionListener(e -> dispose());
bar.add(close); bar.add(close);
return bar; return bar;
} }
private static Rows tab(List<Row> rows) {
Rows tab = new Rows(rows);
tab.setBorder(new ScaledEmptyBorder(10, 12, 10, 12));
return tab;
}
// ---- live update ---- // ---- live update ----
private void refresh() { private void refresh() {
@@ -137,72 +182,156 @@ public final class ConnectionInfoDialog extends JDialog {
private void apply(ConnectionStats s) { private void apply(ConnectionStats s) {
if (!isDisplayable()) return; if (!isDisplayable()) return;
summary.update(ConnectionStatsFormat.summaryRows(s, SELF_ADDRESS)); latest = s;
total.update(ConnectionStatsFormat.trafficRows(s, null)); summary.update(List.of(ConnectionStatsFormat.summaryRows(s, nickname)));
speech.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.SPEECH)); copyAddress.setEnabled(ConnectionStatsFormat.copyableAddress(s) != null);
keepAlive.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.KEEPALIVE)); for (TrafficTable table : traffic) table.update(s);
control.update(ConnectionStatsFormat.trafficRows(s, ConnectionStats.Kind.CONTROL)); quota.update(ConnectionStatsFormat.quotaGroups(s));
voice.update(ConnectionStatsFormat.voiceRows(s.voiceReceived)); voice.update(List.of(ConnectionStatsFormat.voiceRows(s.voiceReceived)));
growToFit(); showAvatar();
}
private void showAvatar() {
ClientEntry client = conn.getModel().getClient(clientId);
Avatar current = conn.avatarOf(client);
if (current == shownAvatar) return;
shownAvatar = current;
avatar.setIcon(current == null ? null : avatarIcon(current));
pack();
}
private static ImageIcon avatarIcon(Avatar avatar) {
if (avatar.file() == null) return null;
Dimension size = AvatarHtml.fit(AvatarHtml.dimensions(avatar.data()), UIScale.scale(AVATAR_SIZE));
ImageIcon icon = new ImageIcon(avatar.data());
if (size == null) return icon;
return new ImageIcon(icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH));
}
// ---- figures ----
private static JLabel label(String text) {
JLabel l = new JLabel(text);
l.setFont(Theme.uiFont());
return l;
}
/** Pins a label's width to that of {@code sample}, so a growing figure doesn't resize the window. */
private static JLabel sized(JLabel l, String sample) {
Dimension pref = l.getPreferredSize();
int width = l.getFontMetrics(l.getFont()).stringWidth(sample);
l.setPreferredSize(new Dimension(Math.max(pref.width, width), pref.height));
return l;
}
private static GridBagConstraints cell(int x, int y, int anchor, Insets insets) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.anchor = anchor;
c.insets = UIScale.scale(insets);
return c;
} }
/** /**
* The window is first packed around placeholder text; once real (longer) * Labelled figures, one per row, in groups set apart by a rule; refreshed in place, and
* values arrive it may need more room. Grow to fit, but never shrink, so the * rows an update leaves out hide.
* window doesn't jitter as counters tick up each second.
*/ */
private void growToFit() { private static final class Figures extends JPanel {
Dimension pref = getContentPane().getPreferredSize(); private final List<List<JLabel[]>> groups = new ArrayList<>();
Dimension have = getContentPane().getSize(); private int lastRow;
if (pref.width > have.width || pref.height > have.height) {
fit();
}
}
private void fit() { Figures(List<List<Row>> rows, boolean valuesRight) {
pack();
setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), getHeight());
}
/** A grid of labelled figures, laid out once and refreshed in place. */
private static final class Rows extends JPanel {
private final JLabel[] values;
Rows(List<Row> rows) {
super(new GridBagLayout()); super(new GridBagLayout());
setBackground(Theme.windowBg()); setOpaque(false);
values = new JLabel[rows.size()]; int y = 0;
for (int i = 0; i < values.length; i++) { for (List<Row> group : rows) {
values[i] = new JLabel(rows.get(i).value()); if (y > 0) {
values[i].setFont(Theme.uiFont()); GridBagConstraints rule = cell(0, y++, GridBagConstraints.WEST, new Insets(6, 0, 6, 0));
values[i].setForeground(Theme.treeText()); rule.gridwidth = 2;
addRow(i, rows.get(i).label(), values[i]); rule.fill = GridBagConstraints.HORIZONTAL;
add(new JSeparator(), rule);
} }
} List<JLabel[]> labels = new ArrayList<>();
for (Row row : group) {
void update(List<Row> rows) { JLabel key = label(row.label());
for (int i = 0; i < values.length; i++) values[i].setText(rows.get(i).value()); JLabel value = label(row.value());
} labels.add(new JLabel[]{key, value});
add(key, cell(0, y, GridBagConstraints.WEST, new Insets(3, 0, 3, 16)));
private void addRow(int row, String label, JLabel valueLabel) { GridBagConstraints vc = cell(1, y, valuesRight ? GridBagConstraints.EAST : GridBagConstraints.WEST,
GridBagConstraints lc = new GridBagConstraints(); new Insets(3, 0, 3, 0));
lc.gridx = 0;
lc.gridy = row;
lc.anchor = GridBagConstraints.WEST;
lc.insets = UIScale.scale(new Insets(2, 0, 2, 16));
JLabel key = new JLabel(label);
key.setFont(Theme.uiFont());
key.setForeground(new Color(0x5A6B7B));
add(key, lc);
GridBagConstraints vc = new GridBagConstraints();
vc.gridx = 1;
vc.gridy = row;
vc.weightx = 1; vc.weightx = 1;
vc.anchor = GridBagConstraints.WEST; add(value, vc);
vc.fill = GridBagConstraints.HORIZONTAL; lastRow = y++;
vc.insets = UIScale.scale(new Insets(2, 0, 2, 0)); }
add(valueLabel, vc); groups.add(labels);
}
}
/** Puts {@code c} after the last row's value. */
void addTrailing(JComponent c) {
add(c, cell(2, lastRow, GridBagConstraints.EAST, new Insets(0, 6, 0, 0)));
}
void update(List<List<Row>> rows) {
for (int g = 0; g < groups.size(); g++) {
List<JLabel[]> labels = groups.get(g);
List<Row> group = rows.get(g);
for (int i = 0; i < labels.size(); i++) {
boolean shown = i < group.size();
labels.get(i)[0].setVisible(shown);
labels.get(i)[1].setVisible(shown);
if (shown) labels.get(i)[1].setText(group.get(i).value());
}
}
}
}
/** One traffic category: a row per figure under Total / In / Out headings. */
private static final class TrafficTable extends JPanel {
private final ConnectionStats.Kind kind;
private final JLabel[][] cells;
TrafficTable(ConnectionStats.Kind kind) {
super(new GridBagLayout());
this.kind = kind;
setOpaque(false);
setBorder(new ScaledEmptyBorder(8, 10, 8, 10));
List<String> columns = ConnectionStatsFormat.COLUMNS;
for (int c = 0; c < columns.size(); c++) {
JLabel heading = label(columns.get(c));
heading.setFont(heading.getFont().deriveFont(Font.ITALIC));
add(heading, column(c + 1, 0));
}
List<TrafficRow> rows = ConnectionStatsFormat.trafficRows(null, kind);
cells = new JLabel[rows.size()][];
for (int r = 0; r < rows.size(); r++) {
TrafficRow row = rows.get(r);
add(label(row.label()), cell(0, r + 1, GridBagConstraints.WEST, new Insets(3, 0, 3, 8)));
cells[r] = new JLabel[]{
sized(label(row.total()), TOTAL_SAMPLE), sized(label(row.in()), VALUE_SAMPLE),
sized(label(row.out()), VALUE_SAMPLE)};
for (int c = 0; c < cells[r].length; c++) add(cells[r][c], column(c + 1, r + 1));
}
GridBagConstraints filler = cell(0, rows.size() + 1, GridBagConstraints.WEST, new Insets(0, 0, 0, 0));
filler.weighty = 1;
add(Box.createGlue(), filler);
}
private static GridBagConstraints column(int x, int y) {
GridBagConstraints c = cell(x, y, GridBagConstraints.WEST, new Insets(3, 8, 3, 8));
c.weightx = 1;
return c;
}
void update(ConnectionStats s) {
List<TrafficRow> rows = ConnectionStatsFormat.trafficRows(s, kind);
for (int r = 0; r < rows.size(); r++) {
cells[r][0].setText(rows.get(r).total());
cells[r][1].setText(rows.get(r).in());
cells[r][2].setText(rows.get(r).out());
}
} }
} }
} }