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>
This commit is contained in:
2026-10-08 20:58:44 +00:00
co-authored by Claude Opus 5.5
parent e54623bc47
commit 023b449fba
20 changed files with 1496 additions and 5 deletions
@@ -44,6 +44,8 @@ public final class ClientEntry {
/** The message published with the away state, empty when there is none. */ /** The message published with the away state, empty when there is none. */
public volatile String awayMessage = ""; public volatile String awayMessage = "";
public volatile boolean channelCommander; public volatile boolean channelCommander;
/** Unread messages in the client's offline message inbox ({@code client_unread_messages}). */
public volatile int unreadMessages;
public volatile boolean self; public volatile boolean self;
public ClientEntry(int id, String nickname) { public ClientEntry(int id, String nickname) {
@@ -52,6 +52,7 @@ final class ConnectionEventHandler implements TS3Listener {
c.databaseId = e.getClientDatabaseId(); c.databaseId = e.getClientDatabaseId();
c.serverGroupIds = parseIntList(e.getClientServerGroups()); c.serverGroupIds = parseIntList(e.getClientServerGroups());
c.channelGroupId = e.getClientChannelGroupId(); c.channelGroupId = e.getClientChannelGroupId();
c.unreadMessages = safeInt(e, "client_unread_messages");
c.self = (e.getClientId() == conn.getSelfClientId()); c.self = (e.getClientId() == conn.getSelfClientId());
// Query clients stay out of sight, as they do in the tree and in TS3's log. // Query clients stay out of sight, as they do in the tree and in TS3's log.
if (!c.self && !c.isQuery()) { if (!c.self && !c.isQuery()) {
@@ -350,6 +351,11 @@ final class ConnectionEventHandler implements TS3Listener {
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"));
if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country")); if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country"));
if (has(e, "client_unread_messages")) {
int before = c.unreadMessages;
c.unreadMessages = safeInt(e, "client_unread_messages");
if (c.id == conn.getSelfClientId()) conn.unreadMessagesChanged(before);
}
announceClientUpdate(e, c, renamed, oldName); announceClientUpdate(e, c, renamed, oldName);
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -676,6 +682,7 @@ final class ConnectionEventHandler implements TS3Listener {
else if ("notifytokenadd".equals(e.getCommand())) conn.privilegeKeys.onAdded(e); else if ("notifytokenadd".equals(e.getCommand())) conn.privilegeKeys.onAdded(e);
else if ("notifycomplainlist".equals(e.getCommand())) conn.complaints.onListEntry(e); else if ("notifycomplainlist".equals(e.getCommand())) conn.complaints.onListEntry(e);
else if ("notifyserverlog".equals(e.getCommand())) conn.serverLog.onLine(e); else if ("notifyserverlog".equals(e.getCommand())) conn.serverLog.onLine(e);
else conn.offlineMessages.onReply(e);
} }
// ---- helpers ---- // ---- helpers ----
@@ -51,6 +51,10 @@ public interface ConnectionListener {
*/ */
void onServerLog(String message); void onServerLog(String message);
/** Our offline message inbox's unread count changed, or became known on connecting. */
default void onUnreadMessagesChanged(int unread) {
}
/** A server-log line already rendered in TS3's HTML log format. */ /** A server-log line already rendered in TS3's HTML log format. */
default void onServerLogHtml(String html) { default void onServerLogHtml(String html) {
onServerLog(html == null ? "" : html); onServerLog(html == null ? "" : html);
@@ -0,0 +1,9 @@
package com.ts3client.net;
/**
* A client the server's database knows, online or not: what an offline message is addressed to.
*
* @param nickname the nickname they last used on this server
*/
public record DatabaseClient(String uniqueId, int databaseId, String nickname) {
}
@@ -0,0 +1,39 @@
package com.ts3client.net;
import java.util.Map;
/**
* A message in our offline message inbox on the server, without its body: {@code messagelist}
* leaves that out, and reading it costs a {@code messageget} each.
*
* @param senderName the sender's last known nickname, or their unique id when the server has forgotten them
*/
public record OfflineMessage(int id, String senderUid, String senderName, String subject,
long timestampEpochSeconds, boolean read) {
/** Reads a message off a {@code notifymessagelist} event's fields. */
static OfflineMessage from(Map<String, String> fields, String senderName) {
return new OfflineMessage((int) parseLong(fields.get("msgid")),
orEmpty(fields.get("cluid")),
senderName,
orEmpty(fields.get("subject")),
parseLong(fields.get("timestamp")),
"1".equals(fields.get("flag_read")));
}
public OfflineMessage withRead(boolean read) {
return new OfflineMessage(id, senderUid, senderName, subject, timestampEpochSeconds, read);
}
static String orEmpty(String s) {
return s == null || s.equals("null") ? "" : s;
}
private static long parseLong(String s) {
try {
return s == null ? 0 : Long.parseLong(s.trim());
} catch (NumberFormatException e) {
return 0;
}
}
}
@@ -0,0 +1,163 @@
package com.ts3client.net;
import com.github.manevolent.ts3j.command.CommandException;
import com.github.manevolent.ts3j.command.SingleCommand;
import com.github.manevolent.ts3j.command.parameter.CommandParameter;
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
import com.github.manevolent.ts3j.protocol.ProtocolRole;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Our offline message inbox on the server, sending offline messages, and finding the
* database clients to send them to.
*
* <p>Split out of {@link TeamspeakConnection} like {@link ComplaintAdmin}. Every reply comes as
* notifications ahead of the command's completion, collected into {@link #replies}; calls are
* serialised so two requests never share it. Every call blocks and must run off the UI thread.
*/
final class OfflineMessageAdmin {
/** What a listing answers when it has nothing to list. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
/** What a unique id or database id lookup answers when the server has no such client. */
private static final int ERROR_INVALID_CLIENT_ID = 0x0200;
/** The most matches a nickname search names; each costs a lookup, and lookups flood quickly. */
private static final int MAX_SEARCH_RESULTS = 10;
private final TeamspeakConnection conn;
/** Senders' nicknames by unique id; they cost a lookup each, so a connection asks once. */
private final Map<String, String> names = new ConcurrentHashMap<>();
/** The notification the request in flight is answered by, and what has arrived of it. */
private volatile String awaited;
private volatile List<Map<String, String>> replies;
OfflineMessageAdmin(TeamspeakConnection conn) {
this.conn = conn;
}
/** Forgets what the last server told us; a reconnect may be to another server. */
void reset() {
names.clear();
}
void onReply(UnknownTeamspeakEvent e) {
List<Map<String, String>> collected = replies;
if (collected != null && e.getCommand().equals(awaited)) collected.add(e.getMap());
}
/** Runs a command and returns the {@code notification} rows it was answered with; none when the result is empty. */
private synchronized List<Map<String, String>> query(String notification, String command,
CommandParameter... params) throws Exception {
List<Map<String, String>> collected = Collections.synchronizedList(new ArrayList<>());
awaited = notification;
replies = collected;
try {
conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
conn.awaitEventsProcessed();
} catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally {
replies = null;
awaited = null;
}
return new ArrayList<>(collected);
}
private synchronized void execute(String command, CommandParameter... params) throws Exception {
conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete();
}
private static CommandSingleParameter param(String key, Object value) {
return new CommandSingleParameter(key, String.valueOf(value));
}
// ---- inbox ----
List<OfflineMessage> list() throws Exception {
List<OfflineMessage> messages = new ArrayList<>();
for (Map<String, String> row : query("notifymessagelist", "messagelist")) {
String sender = OfflineMessage.orEmpty(row.get("cluid"));
messages.add(OfflineMessage.from(row, senderName(sender)));
}
return messages;
}
private String senderName(String uniqueId) throws Exception {
if (uniqueId.isEmpty()) return "";
String known = names.get(uniqueId);
if (known != null) return known;
DatabaseClient client = lookupUid(uniqueId);
String name = client != null ? client.nickname() : uniqueId;
names.put(uniqueId, name);
return name;
}
/** Reads a message's body; this does not mark it read. */
String body(int messageId) throws Exception {
List<Map<String, String>> rows = query("notifymessage", "messageget", param("msgid", messageId));
if (rows.isEmpty()) throw new IllegalStateException("The message is gone.");
return OfflineMessage.orEmpty(rows.get(0).get("message"));
}
void setRead(int messageId, boolean read) throws Exception {
execute("messageupdateflag", param("msgid", messageId), param("flag", read ? 1 : 0));
}
void delete(int messageId) throws Exception {
execute("messagedel", param("msgid", messageId));
}
void send(String recipientUid, String subject, String message) throws Exception {
execute("messageadd", param("cluid", recipientUid), param("subject", subject), param("message", message));
}
// ---- recipients ----
/** @return the client with this unique id, or {@code null} when the server has never seen them */
DatabaseClient lookupUid(String uniqueId) throws Exception {
try {
List<Map<String, String>> rows = query("notifyclientnamefromuid", "clientgetnamefromuid",
param("cluid", uniqueId));
return rows.isEmpty() ? null : fromNameReply(rows.get(0));
} catch (CommandException e) {
if (e.getErrorId() == ERROR_INVALID_CLIENT_ID) return null;
throw e;
}
}
/**
* Clients whose last nickname contains {@code nickname}. Needs
* {@code b_virtualserver_client_dbsearch}, which the server never reports to us up front.
*/
List<DatabaseClient> search(String nickname) throws Exception {
List<Map<String, String>> found = query("notifyclientdbfind", "clientdbfind",
param("pattern", "%" + nickname + "%"));
List<DatabaseClient> clients = new ArrayList<>();
for (Map<String, String> row : found) {
if (clients.size() == MAX_SEARCH_RESULTS) break;
List<Map<String, String>> named = query("notifyclientnamefromdbid", "clientgetnamefromdbid",
param("cldbid", OfflineMessage.orEmpty(row.get("cldbid"))));
if (!named.isEmpty()) clients.add(fromNameReply(named.get(0)));
}
for (DatabaseClient c : clients) names.put(c.uniqueId(), c.nickname());
return clients;
}
private static DatabaseClient fromNameReply(Map<String, String> row) {
int dbId;
try {
dbId = Integer.parseInt(OfflineMessage.orEmpty(row.get("cldbid")).trim());
} catch (NumberFormatException e) {
dbId = 0;
}
return new DatabaseClient(OfflineMessage.orEmpty(row.get("cluid")), dbId,
OfflineMessage.orEmpty(row.get("name")));
}
}
@@ -65,6 +65,12 @@ public final class TeamspeakConnection implements TS3Listener {
public static final int KICK_REASON_LIMIT = 40; public static final int KICK_REASON_LIMIT = 40;
/** The longest reason a complaint may carry. */ /** The longest reason a complaint may carry. */
public static final int COMPLAINT_REASON_LIMIT = 200; public static final int COMPLAINT_REASON_LIMIT = 200;
/** The longest subject and body an offline message may carry, in characters. */
public static final int OFFLINE_MESSAGE_SUBJECT_LIMIT = 200;
public static final int OFFLINE_MESSAGE_LIMIT = 4096;
/** What {@link #searchDatabaseClients} reports when the server will not let us search. */
public static final String SEARCH_NOT_PERMITTED =
"You have no permission to search for users on this server, so you can only use contacts or unique IDs.";
/** The protocol's reason ids for the two flavours of <b>clientkick</b>. */ /** The protocol's reason ids for the two flavours of <b>clientkick</b>. */
private static final int REASON_KICK_CHANNEL = 4; private static final int REASON_KICK_CHANNEL = 4;
@@ -105,6 +111,8 @@ public final class TeamspeakConnection implements TS3Listener {
final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this); final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this);
final ComplaintAdmin complaints = new ComplaintAdmin(this); final ComplaintAdmin complaints = new ComplaintAdmin(this);
final ServerLogAdmin serverLog = new ServerLogAdmin(this); final ServerLogAdmin serverLog = new ServerLogAdmin(this);
/** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */
final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(this);
private final AvatarAdmin avatarAdmin = new AvatarAdmin(this); private final AvatarAdmin avatarAdmin = new AvatarAdmin(this);
/* /*
@@ -364,6 +372,7 @@ public final class TeamspeakConnection implements TS3Listener {
leaving = false; leaving = false;
disconnectAnnounced = false; disconnectAnnounced = false;
deafened = false; deafened = false;
offlineMessages.reset();
loadChatLogs(); loadChatLogs();
ui.onConnected(); ui.onConnected();
requestPermissionNames(); requestPermissionNames();
@@ -375,6 +384,7 @@ public final class TeamspeakConnection implements TS3Listener {
joinDefaultChannelIfNeeded(channel, channelPassword); joinDefaultChannelIfNeeded(channel, channelPassword);
ui.onStatus("Connected to " + model.getServerName()); ui.onStatus("Connected to " + model.getServerName());
sound(SoundEvent.CONNECTION_CONNECTED, serverVars()); sound(SoundEvent.CONNECTION_CONNECTED, serverVars());
unreadMessagesChanged(0);
// Only captures if this connection holds the microphone. // Only captures if this connection holds the microphone.
applyMicrophoneState(); applyMicrophoneState();
@@ -1129,6 +1139,94 @@ public final class TeamspeakConnection implements TS3Listener {
}); });
} }
// ---- offline messages ----
/** Unread messages in our offline message inbox on this server. */
public int unreadOfflineMessages() {
ClientEntry self = model.getClient(selfClientId);
return self == null ? 0 : self.unreadMessages;
}
/** Whether the server lets us send offline messages. */
public boolean canSendOfflineMessages() {
return model.permits("b_client_offline_textmessage_send");
}
/** Our unread count changed from {@code before}; more unread means new mail, which the log announces. */
void unreadMessagesChanged(int before) {
int unread = unreadOfflineMessages();
if (unread > before) {
String count = unread == 1 ? "1 unread offline message" : unread + " unread offline messages";
log("You have " + TsLink.offlineMessagesBBCode(count));
}
ui.onUnreadMessagesChanged(unread);
}
/** Lists our offline message inbox, delivering it (or a failure message) off the UI thread. */
public void requestOfflineMessages(BiConsumer<List<OfflineMessage>, String> callback) {
run(callback, offlineMessages::list);
}
/** Reads a message's body, delivering it (or a failure message) off the UI thread. */
public void requestOfflineMessageBody(int messageId, BiConsumer<String, String> callback) {
run(callback, () -> offlineMessages.body(messageId));
}
/**
* Marks messages read or unread, stopping at the first the server refuses.
*
* @param callback given {@code null} on success, or the failure message
*/
public void markOfflineMessages(Collection<Integer> messageIds, boolean read, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
for (int id : messageIds) offlineMessages.setRead(id, read);
return null;
});
}
/** @param callback given {@code null} on success, or the failure message */
public void deleteOfflineMessages(Collection<Integer> messageIds, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
for (int id : messageIds) offlineMessages.delete(id);
return null;
});
}
/**
* Sends one offline message to each recipient, stopping at the first the server refuses.
*
* @param callback given {@code null} on success, or the failure message
*/
public void sendOfflineMessage(Collection<String> recipientUids, String subject, String message,
Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
for (String uid : recipientUids) offlineMessages.send(uid, subject, message);
log("Offline message sent.");
return null;
});
}
/** Looks a client up by unique id; delivers {@code null} when the server has never seen them. */
public void lookupDatabaseClient(String uniqueId, BiConsumer<DatabaseClient, String> callback) {
run(callback, () -> offlineMessages.lookupUid(uniqueId));
}
/**
* Finds clients whose last nickname contains {@code nickname}.
*
* @param callback given the matches, or {@link #SEARCH_NOT_PERMITTED} or another failure message
*/
public void searchDatabaseClients(String nickname, BiConsumer<List<DatabaseClient>, String> callback) {
run(callback, () -> {
try {
return offlineMessages.search(nickname);
} catch (CommandException e) {
if (isPermissionError(e)) throw new IllegalStateException(SEARCH_NOT_PERMITTED);
throw e;
}
});
}
// ---- server log ---- // ---- server log ----
/** /**
@@ -1792,7 +1890,7 @@ public final class TeamspeakConnection implements TS3Listener {
} }
/** Whether the server refused for lack of permission, wherever in the cause chain it said so. */ /** Whether the server refused for lack of permission, wherever in the cause chain it said so. */
private static boolean isPermissionError(Throwable t) { static boolean isPermissionError(Throwable t) {
for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) {
if (c instanceof CommandException ce) { if (c instanceof CommandException ce) {
int id = ce.getErrorId(); int id = ce.getErrorId();
@@ -678,5 +678,10 @@ public final class ServerSession {
public void onServerLogHtml(String html) { public void onServerLogHtml(String html) {
listener.onServerLogHtml(html); listener.onServerLogHtml(html);
} }
@Override
public void onUnreadMessagesChanged(int unread) {
listener.onUnreadMessagesChanged(unread);
}
} }
} }
@@ -28,10 +28,10 @@ public final class BBCode {
private static final Pattern COLOR = Pattern.compile("#[0-9a-fA-F]{3,6}|[a-zA-Z]{3,20}"); private static final Pattern COLOR = Pattern.compile("#[0-9a-fA-F]{3,6}|[a-zA-Z]{3,20}");
/** Web links plus TeamSpeak's own {@code client://} / {@code channel://} / {@code ts3server://} schemes. */ /** Web links plus TeamSpeak's own {@code client://} / {@code channel://} / {@code ts3server://} schemes. */
private static final Pattern SAFE_URL = private static final Pattern SAFE_URL =
Pattern.compile("(?i)(https?|ftp|client|channel|ts3server|ts3file)://[^\\s\"'<>]*"); Pattern.compile("(?i)(https?|ftp|client|channel|ts3server|ts3file|offline)://[^\\s\"'<>]*");
/** TeamSpeak's own protocols, which are rendered without an underline. */ /** TeamSpeak's own protocols, which are rendered without an underline. */
private static final Pattern TS_PROTOCOL = private static final Pattern TS_PROTOCOL =
Pattern.compile("(?i)^(client|channel|ts3server|ts3file)://"); Pattern.compile("(?i)^(client|channel|ts3server|ts3file|offline)://");
private static final Pattern CLIENT_PROTOCOL = Pattern.compile("(?i)^client://"); private static final Pattern CLIENT_PROTOCOL = Pattern.compile("(?i)^client://");
/** CSS class on {@code client://} links, styled like a message author's name. */ /** CSS class on {@code client://} links, styled like a message author's name. */
@@ -13,6 +13,8 @@ public final class TsLink {
public static final String CLIENT_SCHEME = "client://"; public static final String CLIENT_SCHEME = "client://";
public static final String CHANNEL_SCHEME = "channel://"; public static final String CHANNEL_SCHEME = "channel://";
/** Opens the offline message inbox, as the "unread offline messages" log line does. */
public static final String OFFLINE_MESSAGES_HREF = "offline://";
/** A parsed {@code client://} or {@code channel://} link. */ /** A parsed {@code client://} or {@code channel://} link. */
public static final class Ref { public static final class Ref {
@@ -67,6 +69,14 @@ public final class TsLink {
return new Ref(client, id, decode(uid), decode(name)); return new Ref(client, id, decode(uid), decode(name));
} }
public static boolean isOfflineMessages(String href) {
return href != null && startsWithIgnoreCase(href, OFFLINE_MESSAGES_HREF);
}
public static String offlineMessagesBBCode(String label) {
return "[URL=" + OFFLINE_MESSAGES_HREF + "]" + label + "[/URL]";
}
public static String clientHref(int clientId, String uniqueId, String nickname) { public static String clientHref(int clientId, String uniqueId, String nickname) {
return CLIENT_SCHEME + clientId + "/" + encode(uniqueId) + "~" + encode(nickname); return CLIENT_SCHEME + clientId + "/" + encode(uniqueId) + "~" + encode(nickname);
} }
@@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class ConnectionEventHandlerTest { class ConnectionEventHandlerTest {
private int modelChanges; private int modelChanges;
private int unreadReports;
private final Settings settings = new Settings(); private final Settings settings = new Settings();
private final TeamspeakConnection conn = new TeamspeakConnection(settings, null, new ConnectionListener() { private final TeamspeakConnection conn = new TeamspeakConnection(settings, null, new ConnectionListener() {
@Override @Override
@@ -76,6 +77,11 @@ class ConnectionEventHandlerTest {
@Override @Override
public void onServerLog(String message) { public void onServerLog(String message) {
} }
@Override
public void onUnreadMessagesChanged(int unread) {
unreadReports++;
}
}, new SoundNotifier(settings), ContactStore.load()); }, new SoundNotifier(settings), ContactStore.load());
private final ConnectionEventHandler events = new ConnectionEventHandler(conn); private final ConnectionEventHandler events = new ConnectionEventHandler(conn);
private final ServerModel model = conn.getModel(); private final ServerModel model = conn.getModel();
@@ -136,6 +142,17 @@ class ConnectionEventHandlerTest {
assertEquals("abc", alice.avatarFlag); assertEquals("abc", alice.avatarFlag);
} }
@Test
void tracksAClientsUnreadOfflineMessages() {
model.putChannel(1, "Lobby", 0, 0);
join(5, "alice", 1);
assertEquals(0, model.getClient(5).unreadMessages);
events.onClientChanged(new ClientUpdatedEvent(fields("notifyclientupdated clid=5 client_unread_messages=3")));
assertEquals(3, model.getClient(5).unreadMessages);
assertEquals(0, unreadReports, "only our own count is reported");
}
@Test @Test
void clearedFieldsAreCleared() { void clearedFieldsAreCleared() {
model.putChannel(1, "Lobby", 0, 0); model.putChannel(1, "Lobby", 0, 0);
@@ -22,6 +22,14 @@ class BBCodeLinksTest {
assertTrue(html.contains(">Lobby</a>"), html); assertTrue(html.contains(">Lobby</a>"), html);
} }
@Test
void rendersTheOfflineMessagesLink() {
String html = BBCode.linksToHtml("You have " + TsLink.offlineMessagesBBCode("2 unread offline messages"));
assertTrue(html.contains("href=\"offline://\""), html);
assertTrue(html.contains(">2 unread offline messages</a>"), html);
assertTrue(TsLink.isOfflineMessages("offline://"));
}
@Test @Test
void leavesOtherMarkupLiteral() { void leavesOtherMarkupLiteral() {
assertEquals("[b]not bold[/b] &amp; &lt;i&gt;", BBCode.linksToHtml("[b]not bold[/b] & <i>")); assertEquals("[b]not bold[/b] &amp; &lt;i&gt;", BBCode.linksToHtml("[b]not bold[/b] & <i>"));
@@ -61,6 +61,9 @@ public final class ChatPanel extends JPanel {
void onClientLink(TsLink.Ref ref, Component source, int x, int y); void onClientLink(TsLink.Ref ref, Component source, int x, int y);
void onChannelLink(TsLink.Ref ref, Component source, int x, int y); void onChannelLink(TsLink.Ref ref, Component source, int x, int y);
/** The "unread offline messages" log line was clicked. */
void onOfflineMessagesLink();
} }
private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM); private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM);
@@ -447,6 +450,10 @@ public final class ChatPanel extends JPanel {
private void onLink(String href) { private void onLink(String href) {
if (href == null) return; if (href == null) return;
if (TsLink.isOfflineMessages(href)) {
if (linkHandler != null) linkHandler.onOfflineMessagesLink();
return;
}
TsLink.Ref ref = TsLink.parse(href); TsLink.Ref ref = TsLink.parse(href);
if (ref == null) { if (ref == null) {
Links.open(href, ChatPanel.this); Links.open(href, ChatPanel.this);
@@ -169,6 +169,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
}); });
statusBar = new StatusBar(() -> { statusBar = new StatusBar(() -> {
if (selected != null) selected.session().stopRecording(); if (selected != null) selected.session().stopRecording();
}, () -> {
if (selected != null) selected.showOfflineMessages();
}); });
statusBar.setVisible(settings.showStatusBar); statusBar.setVisible(settings.showStatusBar);
add(statusBar, BorderLayout.SOUTH); add(statusBar, BorderLayout.SOUTH);
@@ -323,6 +325,11 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
if (selected != null) selected.session().stopRecording(); if (selected != null) selected.session().stopRecording();
} }
@Override
public void onShowOfflineMessages() {
if (selected != null) selected.showOfflineMessages();
}
@Override @Override
public boolean canViewBanList() { public boolean canViewBanList() {
return selected != null && selected.session().canViewBanList(); return selected != null && selected.session().canViewBanList();
@@ -1049,6 +1056,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
toolbar.showHostButton(hostButtonOf(selected)); toolbar.showHostButton(hostButtonOf(selected));
menuBar.refresh(connected, anyConnected, micMuted, deaf, active, away, commander); menuBar.refresh(connected, anyConnected, micMuted, deaf, active, away, commander);
statusBar.showRecording(connected && selected.session().isRecording()); statusBar.showRecording(connected && selected.session().isRecording());
statusBar.showUnreadMessages(connected ? selected.connection().unreadOfflineMessages() : 0);
updateTray(); updateTray();
} }
@@ -78,6 +78,8 @@ final class MainMenuBar extends JMenuBar {
void onShowContacts(); void onShowContacts();
void onShowOfflineMessages();
/** Whether the current tab is recording; asked as the Tools menu opens. */ /** Whether the current tab is recording; asked as the Tools menu opens. */
boolean isRecording(); boolean isRecording();
@@ -137,6 +139,7 @@ final class MainMenuBar extends JMenuBar {
private JMenuItem startRecordingItem; private JMenuItem startRecordingItem;
private JMenuItem startMultitrackItem; private JMenuItem startMultitrackItem;
private JMenuItem stopRecordingItem; private JMenuItem stopRecordingItem;
private JMenuItem offlineMessagesItem;
private JMenuItem banListItem; private JMenuItem banListItem;
private JMenuItem complaintsItem; private JMenuItem complaintsItem;
private JMenuItem serverLogItem; private JMenuItem serverLogItem;
@@ -286,6 +289,9 @@ final class MainMenuBar extends JMenuBar {
JMenuItem contactsItem = new JMenuItem("Contacts…", Icons.ofAny("CONTACT", "EDIT_FRIEND_FOE_STATUS")); JMenuItem contactsItem = new JMenuItem("Contacts…", Icons.ofAny("CONTACT", "EDIT_FRIEND_FOE_STATUS"));
contactsItem.setAccelerator(KeyStroke.getKeyStroke("control shift O")); contactsItem.setAccelerator(KeyStroke.getKeyStroke("control shift O"));
contactsItem.addActionListener(e -> listener.onShowContacts()); contactsItem.addActionListener(e -> listener.onShowContacts());
offlineMessagesItem = new JMenuItem("Offline Messages", Icons.of("OFFLINE_MESSAGES"));
offlineMessagesItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
offlineMessagesItem.addActionListener(e -> listener.onShowOfflineMessages());
startRecordingItem = new JMenuItem("Start Recording", Icons.of("RECORDING_START")); startRecordingItem = new JMenuItem("Start Recording", Icons.of("RECORDING_START"));
startRecordingItem.addActionListener(e -> listener.onStartRecording(false)); startRecordingItem.addActionListener(e -> listener.onStartRecording(false));
startMultitrackItem = new JMenuItem("Start Multitrack Recording", Icons.of("RECORDING_START")); startMultitrackItem = new JMenuItem("Start Multitrack Recording", Icons.of("RECORDING_START"));
@@ -314,6 +320,7 @@ final class MainMenuBar extends JMenuBar {
JPopupMenu.Separator adminSeparator = new JPopupMenu.Separator(); JPopupMenu.Separator adminSeparator = new JPopupMenu.Separator();
tools.add(identitiesItem); tools.add(identitiesItem);
tools.add(contactsItem); tools.add(contactsItem);
tools.add(offlineMessagesItem);
tools.addSeparator(); tools.addSeparator();
tools.add(startRecordingItem); tools.add(startRecordingItem);
tools.add(startMultitrackItem); tools.add(startMultitrackItem);
@@ -381,6 +388,7 @@ final class MainMenuBar extends JMenuBar {
deleteAvatarItem.setEnabled(connected); deleteAvatarItem.setEnabled(connected);
startRecordingItem.setEnabled(connected); startRecordingItem.setEnabled(connected);
startMultitrackItem.setEnabled(connected); startMultitrackItem.setEnabled(connected);
offlineMessagesItem.setEnabled(connected);
banListItem.setEnabled(connected); banListItem.setEnabled(connected);
complaintsItem.setEnabled(connected); complaintsItem.setEnabled(connected);
serverLogItem.setEnabled(connected); serverLogItem.setEnabled(connected);
@@ -0,0 +1,457 @@
package com.ts3client.ui;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.contacts.Contact;
import com.ts3client.contacts.ContactStore;
import com.ts3client.contacts.ContactType;
import com.ts3client.net.DatabaseClient;
import com.ts3client.net.OfflineMessage;
import com.ts3client.net.TeamspeakConnection;
import com.ts3client.text.BBCode;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Writing an offline message, as the official client's New / Reply Offline Message window:
* recipients, subject and text on the left, the clients one may pick from on the right.
*
* <p>A recipient is typed as a unique id or a nickname. Unlike the official client, which
* only searches the server's database, a unique id is looked up directly, which needs no
* permission; a nickname needs {@code b_virtualserver_client_dbsearch}.
*/
final class OfflineMessageComposeDialog extends JDialog {
private static final Pattern UNIQUE_ID = Pattern.compile("[A-Za-z0-9+/]{27}=");
/** The client property naming the recipient a chip stands for. */
private static final String CHIP_UID = "ts3.recipientUid";
private final TeamspeakConnection conn;
/** Recipients by unique id, in the order they were added. */
private final Map<String, DatabaseClient> recipients = new LinkedHashMap<>();
private final JPanel recipientChips = new JPanel(new FlowLayout(FlowLayout.LEADING, UIScale.scale(4), UIScale.scale(2)));
private final JTextField recipientField = new JTextField();
private final JLabel recipientError = new JLabel();
private final JTextField subjectField = new JTextField();
private final JTextArea bodyArea = new JTextArea();
private final JLabel limitLabel = new JLabel(" ");
private final DefaultListModel<DatabaseClient> available = new DefaultListModel<>();
private final JList<DatabaseClient> availableList = new JList<>(available);
private final JButton sendButton = new JButton("Send");
private boolean sending;
static OfflineMessageComposeDialog compose(Window owner, TeamspeakConnection conn, ContactStore contacts) {
return new OfflineMessageComposeDialog(owner, "New Offline Message", conn, contacts);
}
/** A reply to {@code message}, quoting {@code body}. */
static OfflineMessageComposeDialog reply(Window owner, TeamspeakConnection conn, ContactStore contacts,
OfflineMessage message, String body) {
OfflineMessageComposeDialog d = new OfflineMessageComposeDialog(owner, "Reply Offline Message", conn, contacts);
d.addRecipient(new DatabaseClient(message.senderUid(), 0, message.senderName()));
String subject = message.subject().regionMatches(true, 0, "Re:", 0, 3)
? message.subject() : "Re: " + message.subject();
d.subjectField.setText(subject.length() > TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT
? subject.substring(0, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT) : subject);
d.bodyArea.setText(quote(message.senderName(), body));
d.bodyArea.setCaretPosition(d.bodyArea.getDocument().getLength());
return d;
}
/** The reply's opening, as the official client writes it: who wrote, then their text marked with "&gt; ". */
private static String quote(String sender, String body) {
StringBuilder out = new StringBuilder("\"").append(sender).append("\" wrote:\n");
for (String line : body.split("\n", -1)) out.append("> ").append(line).append('\n');
return out.toString();
}
private OfflineMessageComposeDialog(Window owner, String title, TeamspeakConnection conn, ContactStore contacts) {
super(owner, title, ModalityType.MODELESS);
this.conn = conn;
limit(subjectField, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT);
limit(bodyArea, TeamspeakConnection.OFFLINE_MESSAGE_LIMIT);
for (Contact c : contacts.all()) {
if (c.type != ContactType.BLOCKED) {
available.addElement(new DatabaseClient(c.uniqueId, 0, c.nickname.isEmpty() ? c.uniqueId : c.nickname));
}
}
sortAvailable();
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, buildMessage(), buildAvailable());
split.setResizeWeight(1);
split.setBorder(null);
split.setOpaque(false);
JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8)));
content.setBackground(Theme.windowBg());
content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12));
content.add(split, BorderLayout.CENTER);
content.add(buildButtons(), BorderLayout.SOUTH);
setContentPane(content);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cancel();
}
});
Dialogs.closeOnEscape(this, this::cancel);
setPreferredSize(UIScale.scale(new Dimension(620, 460)));
pack();
setLocationRelativeTo(owner);
updateSendButton();
}
// ---- construction ----
private JPanel buildMessage() {
recipientChips.setOpaque(false);
recipientField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "Nickname or unique ID");
recipientField.addActionListener(e -> resolveTyped());
recipientField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && recipientField.getText().isEmpty()
&& !recipients.isEmpty()) {
removeRecipient(new ArrayList<>(recipients.keySet()).get(recipients.size() - 1));
}
}
});
recipientField.getDocument().addDocumentListener(onChange(() -> recipientError.setVisible(false)));
recipientError.setForeground(UIManager.getColor("Actions.Red"));
recipientError.setVisible(false);
JPanel recipientBox = new JPanel();
recipientBox.setLayout(new BoxLayout(recipientBox, BoxLayout.Y_AXIS));
recipientBox.setOpaque(false);
recipientBox.add(left(recipientChips));
recipientBox.add(left(recipientField));
recipientBox.add(left(recipientError));
JPanel subjectRow = new JPanel(new BorderLayout(UIScale.scale(6), 0));
subjectRow.setOpaque(false);
JLabel subjectLabel = new JLabel("Subject:");
subjectLabel.setDisplayedMnemonic(KeyEvent.VK_S);
subjectLabel.setLabelFor(subjectField);
subjectRow.add(subjectLabel, BorderLayout.WEST);
subjectRow.add(subjectField, BorderLayout.CENTER);
JPanel top = new JPanel();
top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS));
top.setOpaque(false);
top.add(left(new JLabel("Recipients:")));
top.add(left(recipientBox));
top.add(Box.createVerticalStrut(UIScale.scale(8)));
top.add(left(subjectRow));
bodyArea.setLineWrap(true);
bodyArea.setWrapStyleWord(true);
bodyArea.setFont(Theme.uiFont());
bodyArea.getDocument().addDocumentListener(onChange(this::updateSendButton));
limitLabel.setForeground(UIManager.getColor("Actions.Red"));
JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(6)));
panel.setOpaque(false);
panel.setBorder(new ScaledEmptyBorder(0, 0, 0, 6));
panel.add(top, BorderLayout.NORTH);
panel.add(new JScrollPane(bodyArea), BorderLayout.CENTER);
panel.add(limitLabel, BorderLayout.SOUTH);
return panel;
}
private JPanel buildAvailable() {
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
availableList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean selected, boolean focused) {
DatabaseClient c = (DatabaseClient) value;
String text = c.databaseId() > 0 ? c.nickname() + " (" + c.databaseId() + ")" : c.nickname();
super.getListCellRendererComponent(list, text, index, selected, focused);
setToolTipText(c.uniqueId());
return this;
}
});
availableList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) addChosen();
}
});
availableList.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) addChosen();
}
});
JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(4)));
panel.setOpaque(false);
panel.setBorder(new ScaledEmptyBorder(0, 6, 0, 0));
panel.add(new JLabel("Available Contacts:"), BorderLayout.NORTH);
panel.add(new JScrollPane(availableList), BorderLayout.CENTER);
panel.setPreferredSize(UIScale.scale(new Dimension(170, 0)));
return panel;
}
private JPanel buildButtons() {
sendButton.addActionListener(e -> send());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(e -> cancel());
JPanel row = new JPanel(new BorderLayout());
row.setOpaque(false);
row.add(sendButton, BorderLayout.WEST);
row.add(cancel, BorderLayout.EAST);
return row;
}
/** Lines a component up on the left of a vertical box; a text field keeps its height. */
private static Component left(JComponent c) {
c.setAlignmentX(LEFT_ALIGNMENT);
if (c instanceof JTextField) c.setMaximumSize(new Dimension(Integer.MAX_VALUE, c.getPreferredSize().height));
return c;
}
private static DocumentListener onChange(Runnable action) {
return new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
action.run();
}
@Override
public void removeUpdate(DocumentEvent e) {
action.run();
}
@Override
public void changedUpdate(DocumentEvent e) {
action.run();
}
};
}
/** Caps a field at what the server accepts, saying so when typing runs into it. */
private void limit(JTextComponent field, int max) {
((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
throws BadLocationException {
replace(fb, offset, 0, text, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
String added = text == null ? "" : text;
int room = max - (fb.getDocument().getLength() - length);
if (added.length() > room) {
added = added.substring(0, Math.max(0, room));
limitLabel.setText("Character limit reached (" + max + ")");
}
super.replace(fb, offset, length, added, attrs);
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
super.remove(fb, offset, length);
limitLabel.setText(" ");
}
});
}
// ---- recipients ----
private void addRecipient(DatabaseClient client) {
if (client.uniqueId().isEmpty() || recipients.containsKey(client.uniqueId())) return;
recipients.put(client.uniqueId(), client);
recipientChips.add(chip(client));
recipientChips.revalidate();
recipientChips.repaint();
updateSendButton();
}
private void removeRecipient(String uniqueId) {
if (recipients.remove(uniqueId) == null) return;
for (Component c : recipientChips.getComponents()) {
if (uniqueId.equals(((JPanel) c).getClientProperty(CHIP_UID))) recipientChips.remove(c);
}
recipientChips.revalidate();
recipientChips.repaint();
updateSendButton();
}
/** A recipient's name with a cross that takes them off again. */
private JPanel chip(DatabaseClient client) {
JLabel name = new JLabel(client.nickname().isEmpty() ? client.uniqueId() : client.nickname());
name.setToolTipText(client.uniqueId());
JLabel remove = new JLabel("×");
remove.setToolTipText("Remove");
remove.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
remove.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
removeRecipient(client.uniqueId());
}
});
JPanel chip = new JPanel(new FlowLayout(FlowLayout.LEADING, UIScale.scale(4), 0));
chip.putClientProperty(CHIP_UID, client.uniqueId());
chip.setBackground(Theme.treeBg());
chip.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Theme.border()),
new ScaledEmptyBorder(1, 2, 1, 2)));
chip.add(name);
chip.add(remove);
return chip;
}
private void addChosen() {
DatabaseClient chosen = availableList.getSelectedValue();
if (chosen != null) addRecipient(chosen);
}
/** Turns what was typed into a recipient: a unique id directly, a nickname by contacts or a server search. */
private void resolveTyped() {
String typed = recipientField.getText().trim();
if (typed.isEmpty()) return;
if (UNIQUE_ID.matcher(typed).matches()) {
conn.lookupDatabaseClient(typed, (client, error) -> SwingUtilities.invokeLater(() -> {
if (error != null) showRecipientError(error);
else if (client == null) showRecipientError("The unique ID is unknown on this server.");
else accept(client);
}));
return;
}
for (int i = 0; i < available.size(); i++) {
if (available.get(i).nickname().equalsIgnoreCase(typed)) {
accept(available.get(i));
return;
}
}
conn.searchDatabaseClients(typed, (found, error) -> SwingUtilities.invokeLater(() -> {
if (error != null) {
showRecipientError(error);
} else if (found.isEmpty()) {
showRecipientError("The nickname is unknown on this server.");
} else {
offer(found);
DatabaseClient exact = found.stream().filter(c -> c.nickname().equalsIgnoreCase(typed))
.findFirst().orElse(found.size() == 1 ? found.get(0) : null);
if (exact != null) accept(exact);
}
}));
}
private void accept(DatabaseClient client) {
addRecipient(client);
recipientField.setText("");
}
/** Lists search results among the contacts, so a match can be picked from them. */
private void offer(List<DatabaseClient> found) {
for (DatabaseClient c : found) {
boolean listed = false;
for (int i = 0; i < available.size() && !listed; i++) {
listed = available.get(i).uniqueId().equals(c.uniqueId());
}
if (!listed) available.addElement(c);
}
sortAvailable();
availableList.setSelectedValue(found.get(0), true);
}
private void sortAvailable() {
List<DatabaseClient> sorted = new ArrayList<>();
for (int i = 0; i < available.size(); i++) sorted.add(available.get(i));
sorted.sort(Comparator.comparing(DatabaseClient::nickname, String.CASE_INSENSITIVE_ORDER));
available.clear();
sorted.forEach(available::addElement);
}
private void showRecipientError(String message) {
if (!isDisplayable()) return;
recipientError.setText("<html>" + BBCode.escape(message) + "</html>");
recipientError.setVisible(true);
recipientError.getParent().revalidate();
}
// ---- sending ----
private void updateSendButton() {
sendButton.setEnabled(!sending && !recipients.isEmpty() && !bodyArea.getText().isBlank());
}
private void send() {
if (!sendButton.isEnabled()) return;
sending = true;
updateSendButton();
conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText(),
error -> SwingUtilities.invokeLater(() -> {
sending = false;
if (!isDisplayable()) return;
if (error == null) {
dispose();
return;
}
updateSendButton();
JOptionPane.showMessageDialog(this, "Failed to send offline message: " + error, getTitle(),
JOptionPane.ERROR_MESSAGE);
}));
}
private void cancel() {
if (!recipients.isEmpty()) {
int answer = JOptionPane.showConfirmDialog(this,
"The list of recipients is not empty and the message has not yet been sent.\nDo you want to cancel?",
"Please Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return;
}
dispose();
}
}
@@ -0,0 +1,573 @@
package com.ts3client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.net.OfflineMessage;
import com.ts3client.net.TeamspeakConnection;
import com.ts3client.text.BBCode;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Our offline message inbox on one server, as the official client's Tools &gt; Offline Messages
* window: the messages above, the selected one's subject and text below. Viewing a message
* marks it read.
*
* <p>One per server tab and modeless; the tab closes it when the connection goes away.
*/
final class OfflineMessagesDialog extends JDialog {
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/** Where Compose and Reply lead: the tab opens the compose window. */
interface Composer {
void compose();
void reply(OfflineMessage message, String body);
}
private enum Column {
STATE("", 24),
SUBJECT("Subject", 200),
SENDER("Sender", 110),
DATE("Date", 150);
final String title;
final int width;
Column(String title, int width) {
this.title = title;
this.width = width;
}
}
private final TeamspeakConnection conn;
private final Composer composer;
private final MessageTableModel tableModel = new MessageTableModel();
private final JTable table = new JTable(tableModel) {
/**
* The popup acts on what was clicked; Swing asks here before showing it. As in the
* official client, that selects the row without opening it in the reader.
*/
@Override
public Point getPopupLocation(MouseEvent e) {
int row = e == null ? -1 : rowAtPoint(e.getPoint());
if (row >= 0 && !isRowSelected(row)) {
selectingForPopup = true;
try {
setRowSelectionInterval(row, row);
} finally {
selectingForPopup = false;
}
}
return super.getPopupLocation(e);
}
};
private final JButton composeButton = new JButton("Compose");
private final JButton replyButton = new JButton("Reply");
private final JButton deleteButton = new JButton("Delete");
private final JTextField subjectField = new JTextField();
private final JEditorPane bodyPane = HtmlStyles.pane("font-family:sans-serif; font-size:11px;");
private final JLabel status = new JLabel(" ");
/** Bodies already read, by message id; each costs a {@code messageget}. */
private final Map<Integer, String> bodies = new HashMap<>();
/** The message the reader shows or is loading, or -1. */
private int shownId = -1;
/** Set while a right-click selects its row, which leaves the reader alone. */
private boolean selectingForPopup;
private boolean loading;
OfflineMessagesDialog(Frame owner, TeamspeakConnection conn, Composer composer) {
super(owner, "Offline Messages", false);
this.conn = conn;
this.composer = composer;
JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buildTable(), buildReader());
split.setResizeWeight(0.45);
split.setBorder(null);
split.setOpaque(false);
JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6)));
content.setBackground(Theme.windowBg());
content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12));
content.add(buildToolbar(), BorderLayout.NORTH);
content.add(split, BorderLayout.CENTER);
content.add(buildBottom(), BorderLayout.SOUTH);
setContentPane(content);
bindKeys();
serverNameChanged();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setPreferredSize(UIScale.scale(new Dimension(600, 560)));
pack();
setLocationRelativeTo(owner);
updateButtons();
reload();
}
// ---- construction ----
private JPanel buildToolbar() {
composeButton.setMnemonic(KeyEvent.VK_C);
composeButton.setToolTipText("<html>Compose a new message<br>(Ctrl+N)");
composeButton.addActionListener(e -> compose());
replyButton.setMnemonic(KeyEvent.VK_R);
replyButton.setToolTipText("Reply to message");
replyButton.addActionListener(e -> replySelected());
deleteButton.setMnemonic(KeyEvent.VK_D);
deleteButton.setToolTipText("<html>Delete selected messages<br>(Del)");
deleteButton.addActionListener(e -> deleteSelected());
JPanel bar = new JPanel();
bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS));
bar.setOpaque(false);
bar.add(composeButton);
bar.add(Box.createHorizontalStrut(UIScale.scale(6)));
bar.add(replyButton);
bar.add(Box.createHorizontalGlue());
bar.add(deleteButton);
return bar;
}
private JScrollPane buildTable() {
table.setFont(Theme.uiFont());
table.setRowHeight(UIScale.scale(20));
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setFillsViewportHeight(true);
table.setShowGrid(false);
table.getTableHeader().setReorderingAllowed(false);
table.setComponentPopupMenu(tablePopup());
table.getSelectionModel().addListSelectionListener(e -> {
if (e.getValueIsAdjusting()) return;
updateButtons();
if (!selectingForPopup) showSelected();
});
MessageCellRenderer renderer = new MessageCellRenderer();
for (Column c : Column.values()) {
table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width));
table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer);
}
table.getColumnModel().getColumn(Column.STATE.ordinal()).setMaxWidth(UIScale.scale(Column.STATE.width));
TableRowSorter<MessageTableModel> sorter = new TableRowSorter<>(tableModel);
sorter.setComparator(Column.SUBJECT.ordinal(), String.CASE_INSENSITIVE_ORDER);
sorter.setComparator(Column.SENDER.ordinal(), String.CASE_INSENSITIVE_ORDER);
sorter.setSortKeys(List.of(new RowSorter.SortKey(Column.DATE.ordinal(), SortOrder.ASCENDING)));
table.setRowSorter(sorter);
JScrollPane scroll = new JScrollPane(table);
scroll.getViewport().setBackground(Theme.treeBg());
scroll.setMinimumSize(UIScale.scale(new Dimension(0, 80)));
return scroll;
}
private JPanel buildReader() {
subjectField.setEditable(false);
bodyPane.addHyperlinkListener(e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) Links.open(e.getDescription(), this);
});
JPanel subjectRow = new JPanel(new BorderLayout(UIScale.scale(6), 0));
subjectRow.setOpaque(false);
subjectRow.add(new JLabel("Subject:"), BorderLayout.WEST);
subjectRow.add(subjectField, BorderLayout.CENTER);
JScrollPane bodyScroll = new JScrollPane(bodyPane);
HtmlStyles.fillViewport(bodyPane);
JPanel reader = new JPanel(new BorderLayout(0, UIScale.scale(6)));
reader.setOpaque(false);
reader.setBorder(new ScaledEmptyBorder(6, 0, 0, 0));
reader.add(subjectRow, BorderLayout.NORTH);
reader.add(bodyScroll, BorderLayout.CENTER);
reader.setMinimumSize(UIScale.scale(new Dimension(0, 100)));
return reader;
}
private JPanel buildBottom() {
JButton reload = new JButton("Reload", Icons.of("REFRESH"));
reload.setToolTipText("<html>Reload messages<br>(F5)");
reload.addActionListener(e -> reload());
JButton close = new JButton("Close");
close.addActionListener(e -> dispose());
JPanel row = new JPanel(new BorderLayout());
row.setOpaque(false);
row.add(reload, BorderLayout.WEST);
row.add(close, BorderLayout.EAST);
JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8)));
bottom.setOpaque(false);
bottom.add(status, BorderLayout.NORTH);
bottom.add(row, BorderLayout.SOUTH);
status.setForeground(Theme.chatEvent());
return bottom;
}
private JPopupMenu tablePopup() {
JMenuItem reply = item("Reply to message", this::replySelected);
JMenuItem delete = item("Delete message", this::deleteSelected);
JMenuItem markRead = item("Mark as Read", () -> markSelected(true));
JMenuItem markUnread = item("Mark as Unread", () -> markSelected(false));
JPopupMenu menu = new JPopupMenu();
menu.add(reply);
menu.add(delete);
menu.addSeparator();
menu.add(item("Reload messages", this::reload));
menu.addSeparator();
menu.add(markRead);
menu.add(markUnread);
menu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
List<OfflineMessage> selected = selectedMessages();
reply.setEnabled(replyButton.isEnabled());
delete.setEnabled(!selected.isEmpty());
markRead.setEnabled(selected.stream().anyMatch(m -> !m.read()));
markUnread.setEnabled(selected.stream().anyMatch(OfflineMessage::read));
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
return menu;
}
private static JMenuItem item(String text, Runnable action) {
JMenuItem item = new JMenuItem(text);
item.addActionListener(e -> action.run());
return item;
}
private void bindKeys() {
bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload);
bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::compose);
bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose);
bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
this::deleteSelected);
Dialogs.closeOnEscape(this);
}
private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) {
String name = "ts3-offline-messages-" + key;
target.getInputMap(condition).put(key, name);
target.getActionMap().put(name, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
action.run();
}
});
}
// ---- data ----
void serverNameChanged() {
String name = conn.getModel().getServerName();
setTitle(name == null || name.isBlank() ? "Offline Messages" : "Offline Messages on " + name);
}
void connectionLost() {
dispose();
}
/** Reads the inbox again, keeping the selection where the messages are still there. */
void reload() {
if (loading) return;
loading = true;
status.setText("Loading…");
conn.requestOfflineMessages((messages, error) -> SwingUtilities.invokeLater(() -> {
loading = false;
if (!isDisplayable()) return;
if (error != null) {
status.setText("Failed to list offline messages: " + error);
return;
}
setMessages(messages);
status.setText(messages.isEmpty() ? "No messages" : " ");
}));
}
private void setMessages(List<OfflineMessage> messages) {
Set<Integer> selected = new HashSet<>();
for (OfflineMessage m : selectedMessages()) selected.add(m.id());
tableModel.setMessages(messages);
for (int i = 0; i < messages.size(); i++) {
if (!selected.contains(messages.get(i).id())) continue;
int view = table.convertRowIndexToView(i);
if (view >= 0) table.addRowSelectionInterval(view, view);
}
updateButtons();
showSelected();
}
private List<OfflineMessage> selectedMessages() {
List<OfflineMessage> out = new ArrayList<>();
for (int view : table.getSelectedRows()) out.add(tableModel.get(table.convertRowIndexToModel(view)));
return out;
}
private OfflineMessage singleSelected() {
List<OfflineMessage> selected = selectedMessages();
return selected.size() == 1 ? selected.get(0) : null;
}
private void updateButtons() {
boolean canSend = conn.canSendOfflineMessages();
composeButton.setEnabled(canSend);
replyButton.setEnabled(canSend && singleSelected() != null);
deleteButton.setEnabled(table.getSelectedRowCount() > 0);
}
/** Shows the selected message in the reader, reading its body first if need be, and marks it read. */
private void showSelected() {
OfflineMessage message = singleSelected();
if (message == null) {
shownId = -1;
subjectField.setText("");
bodyPane.setText("");
return;
}
if (message.id() == shownId) return;
shownId = message.id();
subjectField.setText(message.subject());
subjectField.setCaretPosition(0);
String body = bodies.get(message.id());
if (body != null) {
showBody(message, body);
return;
}
bodyPane.setText("");
conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> {
if (!isDisplayable()) return;
if (error != null) {
if (shownId == message.id()) status.setText("Failed to get offline message: " + error);
return;
}
bodies.put(message.id(), text);
if (shownId == message.id()) showBody(message, text);
}));
}
private void showBody(OfflineMessage message, String body) {
bodyPane.setText("<html><body>" + BBCode.toHtml(body) + "</body></html>");
bodyPane.setCaretPosition(0);
if (!message.read()) mark(List.of(message), true);
}
// ---- actions ----
private void compose() {
if (composeButton.isEnabled()) composer.compose();
}
private void replySelected() {
OfflineMessage message = singleSelected();
if (message == null || !replyButton.isEnabled()) return;
String body = bodies.get(message.id());
if (body != null) {
composer.reply(message, body);
return;
}
conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> {
if (!isDisplayable()) return;
if (error != null) {
status.setText("Failed to get offline message: " + error);
return;
}
bodies.put(message.id(), text);
composer.reply(message, text);
}));
}
private void markSelected(boolean read) {
mark(selectedMessages().stream().filter(m -> m.read() != read).toList(), read);
}
/** Flags messages read or unread, showing the change straight away. */
private void mark(List<OfflineMessage> messages, boolean read) {
if (messages.isEmpty()) return;
for (OfflineMessage m : messages) tableModel.replace(m.withRead(read));
conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read,
error -> SwingUtilities.invokeLater(() -> {
if (error == null || !isDisplayable()) return;
status.setText("Failed to update offline message: " + error);
reload();
}));
}
private void deleteSelected() {
List<OfflineMessage> selected = selectedMessages();
if (selected.isEmpty()) return;
List<OfflineMessage> unread = selected.stream().filter(m -> !m.read()).toList();
if (!unread.isEmpty()) {
String question = unread.size() == 1
? "<html>Do you really want to delete the unread message<br>with subject: <strong>\""
+ BBCode.escape(subjectOrPlaceholder(unread.get(0))) + "\"</strong>?"
: "Do you really want to delete " + unread.size() + " unread messages?";
int answer = JOptionPane.showConfirmDialog(this, question, "Delete Offline Message",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer != JOptionPane.YES_OPTION) return;
}
conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList(),
error -> SwingUtilities.invokeLater(() -> {
if (!isDisplayable()) return;
if (error != null) {
JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + error,
getTitle(), JOptionPane.ERROR_MESSAGE);
}
for (OfflineMessage m : selected) bodies.remove(m.id());
reload();
}));
}
private static String subjectOrPlaceholder(OfflineMessage m) {
return m.subject().isEmpty() ? "<no Subject>" : m.subject();
}
// ---- table ----
private static final class MessageTableModel extends AbstractTableModel {
private List<OfflineMessage> messages = List.of();
void setMessages(List<OfflineMessage> messages) {
this.messages = new ArrayList<>(messages);
fireTableDataChanged();
}
OfflineMessage get(int row) {
return messages.get(row);
}
void replace(OfflineMessage message) {
for (int i = 0; i < messages.size(); i++) {
if (messages.get(i).id() != message.id()) continue;
messages.set(i, message);
fireTableRowsUpdated(i, i);
return;
}
}
@Override
public int getRowCount() {
return messages.size();
}
@Override
public int getColumnCount() {
return Column.values().length;
}
@Override
public String getColumnName(int column) {
return Column.values()[column].title;
}
@Override
public Class<?> getColumnClass(int column) {
return switch (Column.values()[column]) {
case STATE -> Boolean.class;
case DATE -> Long.class;
default -> String.class;
};
}
@Override
public Object getValueAt(int row, int column) {
OfflineMessage m = messages.get(row);
return switch (Column.values()[column]) {
case STATE -> m.read();
case SUBJECT -> m.subject();
case SENDER -> m.senderName();
case DATE -> m.timestampEpochSeconds();
};
}
}
/** Unread messages in bold, as the official client shows them; a missing subject greyed out. */
private final class MessageCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable t, Object value, boolean selected,
boolean focused, int row, int column) {
// setForeground sticks as the renderer's unselected colour; clear it so the
// table's own colour applies again after a greyed cell.
setForeground(null);
OfflineMessage m = tableModel.get(t.convertRowIndexToModel(row));
Column c = Column.values()[column];
Object shown = switch (c) {
case STATE -> "";
case SUBJECT -> subjectOrPlaceholder(m);
case DATE -> m.timestampEpochSeconds() <= 0 ? "" : DATE.format(
Instant.ofEpochSecond(m.timestampEpochSeconds()).atZone(ZoneId.systemDefault()));
default -> value;
};
super.getTableCellRendererComponent(t, shown, selected, focused, row, column);
setFont(m.read() ? t.getFont() : t.getFont().deriveFont(Font.BOLD));
setBorder(new ScaledEmptyBorder(0, 2, 0, 2));
setHorizontalAlignment(c == Column.STATE ? CENTER : LEADING);
setIcon(c == Column.STATE ? stateIcon(m.read()) : null);
setToolTipText(c == Column.SENDER && !m.senderUid().equals(m.senderName()) ? m.senderUid() : null);
if (c == Column.SUBJECT && m.subject().isEmpty() && !selected) {
setForeground(UIManager.getColor("Label.disabledForeground"));
}
return this;
}
}
private static Icon stateIcon(boolean read) {
return read ? Icons.of("MESSAGES") : Icons.of("OFFLINE_MESSAGES");
}
}
@@ -8,6 +8,7 @@ import com.ts3client.contacts.ContactStore;
import com.ts3client.net.ChannelNode; import com.ts3client.net.ChannelNode;
import com.ts3client.net.ClientEntry; import com.ts3client.net.ClientEntry;
import com.ts3client.net.ConnectionListener.ChatScope; import com.ts3client.net.ConnectionListener.ChatScope;
import com.ts3client.net.OfflineMessage;
import com.ts3client.net.PictureDownloads; import com.ts3client.net.PictureDownloads;
import com.ts3client.net.TeamspeakConnection; import com.ts3client.net.TeamspeakConnection;
import com.ts3client.net.avatar.Avatar; import com.ts3client.net.avatar.Avatar;
@@ -20,6 +21,7 @@ import javax.swing.JOptionPane;
import javax.swing.JSplitPane; import javax.swing.JSplitPane;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import java.awt.Component; import java.awt.Component;
import java.awt.Window;
import java.awt.event.ComponentAdapter; import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent; import java.awt.event.ComponentEvent;
@@ -38,6 +40,7 @@ final class ServerTab {
private final Settings settings; private final Settings settings;
private final ServerSession session; private final ServerSession session;
private final ContactStore contacts;
private final TeamspeakConnection conn; private final TeamspeakConnection conn;
private final GroupIcons groupIcons; private final GroupIcons groupIcons;
private final ServerTabTreeActions treeActions; private final ServerTabTreeActions treeActions;
@@ -57,11 +60,15 @@ final class ServerTab {
private PrivilegeKeysDialog privilegeKeys; private PrivilegeKeysDialog privilegeKeys;
private ComplaintsDialog complaints; private ComplaintsDialog complaints;
private ServerLogDialog serverLog; private ServerLogDialog serverLog;
private OfflineMessagesDialog offlineMessages;
/** The unread count last reported, to tell new mail from messages being read. */
private int unreadMessages;
ServerTab(MainFrame host, Settings settings, IdentityStore identities, AudioBackend audio, ServerTab(MainFrame host, Settings settings, IdentityStore identities, AudioBackend audio,
SoundNotifier sounds, ContactStore contacts, PictureDownloads pictures) { SoundNotifier sounds, ContactStore contacts, PictureDownloads pictures) {
this.host = host; this.host = host;
this.settings = settings; this.settings = settings;
this.contacts = contacts;
this.infoPanel = new InfoPanel(settings, pictures, host.infoZoom()); this.infoPanel = new InfoPanel(settings, pictures, host.infoZoom());
// ServerTabConnectionEvents must exist before the session (which needs a listener // ServerTabConnectionEvents must exist before the session (which needs a listener
@@ -89,6 +96,11 @@ final class ServerTab {
public void onChannelLink(TsLink.Ref ref, Component source, int x, int y) { public void onChannelLink(TsLink.Ref ref, Component source, int x, int y) {
treeActions.handleChannelLink(ref, source, x, y); treeActions.handleChannelLink(ref, source, x, y);
} }
@Override
public void onOfflineMessagesLink() {
showOfflineMessages();
}
}); });
chatPanel.setInputEnabled(false); chatPanel.setInputEnabled(false);
@@ -212,6 +224,40 @@ final class ServerTab {
serverLog.toFront(); serverLog.toFront();
} }
/** Opens our offline message inbox, or brings the already open window forward. */
void showOfflineMessages() {
if (!session.isConnected()) return;
if (offlineMessages == null || !offlineMessages.isDisplayable()) {
offlineMessages = new OfflineMessagesDialog(host, conn, new OfflineMessagesDialog.Composer() {
@Override
public void compose() {
composeOfflineMessage();
}
@Override
public void reply(OfflineMessage message, String body) {
if (!session.isConnected()) return;
OfflineMessageComposeDialog.reply(offlineMessages, conn, contacts, message, body).setVisible(true);
}
});
}
offlineMessages.setVisible(true);
offlineMessages.toFront();
}
void composeOfflineMessage() {
if (!session.isConnected() || !conn.canSendOfflineMessages()) return;
Window owner = offlineMessages != null && offlineMessages.isShowing() ? offlineMessages : host;
OfflineMessageComposeDialog.compose(owner, conn, contacts).setVisible(true);
}
/** New mail refreshes an open inbox; a message being read does not need to. */
void unreadMessagesChanged(int unread) {
boolean newMail = unread > unreadMessages;
unreadMessages = unread;
if (newMail && offlineMessages != null && offlineMessages.isDisplayable()) offlineMessages.reload();
}
/** Asks for a privilege key and redeems it on this server. */ /** Asks for a privilege key and redeems it on this server. */
void usePrivilegeKey() { void usePrivilegeKey() {
if (!session.isConnected()) return; if (!session.isConnected()) return;
@@ -253,6 +299,11 @@ final class ServerTab {
if (connected) privilegeKeys.serverNameChanged(); if (connected) privilegeKeys.serverNameChanged();
else privilegeKeys.connectionLost(); else privilegeKeys.connectionLost();
} }
if (offlineMessages != null) {
if (connected) offlineMessages.serverNameChanged();
else offlineMessages.connectionLost();
}
if (!connected) unreadMessages = 0;
} }
/** The contact list changed: names, colours and per-client playback follow. */ /** The contact list changed: names, colours and per-client playback follow. */
@@ -73,6 +73,14 @@ final class ServerTabConnectionEvents implements ServerSession.Listener {
}); });
} }
@Override
public void onUnreadMessagesChanged(int unread) {
SwingUtilities.invokeLater(() -> {
tab.unreadMessagesChanged(unread);
host.tabUpdated(tab);
});
}
@Override @Override
public void onStatus(String text) { public void onStatus(String text) {
// Reaches the tab through onSessionChanged. // Reaches the tab through onSessionChanged.
@@ -13,15 +13,17 @@ import java.awt.event.MouseEvent;
/** /**
* The strip at the bottom of the window: connection status on the left, codec info on the * The strip at the bottom of the window: connection status on the left, codec info on the
* right, and while the server on screen is being recorded, a label that stops it. * right, and while the server on screen is being recorded, a label that stops it. An envelope
* shows while that server holds unread offline messages for us, and opens them.
*/ */
final class StatusBar extends JPanel { final class StatusBar extends JPanel {
private final JLabel statusLabel = new JLabel("Not connected"); private final JLabel statusLabel = new JLabel("Not connected");
private final JLabel codecLabel = new JLabel(); private final JLabel codecLabel = new JLabel();
private final JLabel recordingLabel = new JLabel("Recording", Icons.of("RECORDING_STOP"), JLabel.LEADING); private final JLabel recordingLabel = new JLabel("Recording", Icons.of("RECORDING_STOP"), JLabel.LEADING);
private final JLabel unreadLabel = new JLabel(Icons.of("OFFLINE_MESSAGES"));
StatusBar(Runnable onStopRecording) { StatusBar(Runnable onStopRecording, Runnable onOpenOfflineMessages) {
super(new BorderLayout()); super(new BorderLayout());
setBackground(Theme.statusBg()); setBackground(Theme.statusBg());
setBorder(new ScaledEmptyBorder(3, 8, 3, 8)); setBorder(new ScaledEmptyBorder(3, 8, 3, 8));
@@ -38,8 +40,17 @@ final class StatusBar extends JPanel {
onStopRecording.run(); onStopRecording.run();
} }
}); });
unreadLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
unreadLabel.setVisible(false);
unreadLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
onOpenOfflineMessages.run();
}
});
JPanel east = new JPanel(new FlowLayout(FlowLayout.TRAILING, UIScale.scale(12), 0)); JPanel east = new JPanel(new FlowLayout(FlowLayout.TRAILING, UIScale.scale(12), 0));
east.setOpaque(false); east.setOpaque(false);
east.add(unreadLabel);
east.add(recordingLabel); east.add(recordingLabel);
east.add(codecLabel); east.add(codecLabel);
// In the centre, a long status is cut short rather than drawn over the labels beside it. // In the centre, a long status is cut short rather than drawn over the labels beside it.
@@ -51,6 +62,12 @@ final class StatusBar extends JPanel {
recordingLabel.setVisible(recording); recordingLabel.setVisible(recording);
} }
void showUnreadMessages(int unread) {
unreadLabel.setVisible(unread > 0);
unreadLabel.setToolTipText("<html><p style='white-space:nowrap'>You have <strong>" + unread + "</strong> unread "
+ (unread == 1 ? "offline message" : "offline messages") + "</p>");
}
void setStatus(String text) { void setStatus(String text) {
statusLabel.setText(text); statusLabel.setText(text);
} }