Share pictures and files in chat, the way TeamSpeak 6 does

A shared file goes to the sender's myTeamSpeak cloud storage, and an
ordinary text message carries TeamSpeak 6's ts.file.myts pointer to it, so
TeamSpeak 6 users see the file and we see theirs. Pictures show inline
through the description picture cache, other files as a link to save;
logged history shows them too. Sharing and fetching need a myTeamSpeak
sign-in.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 11:23:25 +00:00
co-authored by Claude Opus 5.5
parent 1bb788b501
commit ad9dfa5be0
32 changed files with 1834 additions and 66 deletions
@@ -0,0 +1,128 @@
package com.ts3client.ui;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* Takes files and pictures dropped or pasted onto a chat view as files to share, and leaves
* everything else (text, client links) to the component's own handler.
*/
final class AttachmentTransferHandler extends TransferHandler {
interface Sink {
/** @return whether the files were taken */
boolean files(List<File> files);
boolean image(BufferedImage image);
}
/** How file managers that Java does not translate hand over files. */
private static final DataFlavor URI_LIST = flavor("text/uri-list;class=java.lang.String");
private final TransferHandler delegate;
private final Sink sink;
AttachmentTransferHandler(TransferHandler delegate, Sink sink) {
this.delegate = delegate;
this.sink = sink;
}
@Override
public boolean canImport(TransferSupport support) {
if (isFiles(support.getDataFlavors()) || isPicture(support.getDataFlavors())) return true;
return delegate != null && delegate.canImport(support);
}
@Override
public boolean importData(TransferSupport support) {
DataFlavor[] flavors = support.getDataFlavors();
Transferable t = support.getTransferable();
try {
if (isFiles(flavors)) {
List<File> files = files(t);
if (!files.isEmpty()) return sink.files(files);
} else if (isPicture(flavors)) {
return sink.image(buffered((Image) t.getTransferData(DataFlavor.imageFlavor)));
}
} catch (UnsupportedFlavorException | IOException e) {
return false;
}
return delegate != null && delegate.importData(support);
}
@Override
public int getSourceActions(JComponent c) {
return delegate == null ? NONE : delegate.getSourceActions(c);
}
@Override
public void exportToClipboard(JComponent comp, Clipboard clip, int action) {
if (delegate != null) delegate.exportToClipboard(comp, clip, action);
}
private static boolean isFiles(DataFlavor[] flavors) {
for (DataFlavor f : flavors) {
if (f.equals(DataFlavor.javaFileListFlavor) || f.equals(URI_LIST)) return true;
}
return false;
}
/** A picture alone: one that comes with text is text that also offers a rendering of itself. */
private static boolean isPicture(DataFlavor[] flavors) {
boolean image = false;
for (DataFlavor f : flavors) {
if (f.equals(DataFlavor.imageFlavor)) image = true;
else if (f.equals(DataFlavor.stringFlavor)) return false;
}
return image;
}
@SuppressWarnings("unchecked")
private static List<File> files(Transferable t) throws UnsupportedFlavorException, IOException {
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return new ArrayList<>((List<File>) t.getTransferData(DataFlavor.javaFileListFlavor));
}
List<File> files = new ArrayList<>();
for (String line : ((String) t.getTransferData(URI_LIST)).split("\r?\n")) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) continue;
try {
URI uri = URI.create(line);
if (!"file".equals(uri.getScheme())) return List.of();
files.add(new File(uri));
} catch (IllegalArgumentException e) {
return List.of();
}
}
return files;
}
private static BufferedImage buffered(Image image) {
if (image instanceof BufferedImage b) return b;
BufferedImage b = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = b.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return b;
}
private static DataFlavor flavor(String mime) {
try {
return new DataFlavor(mime);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,145 @@
package com.ts3client.ui;
import com.ts3client.myts.ChatAttachment;
import com.ts3client.myts.ChatAttachments;
import com.ts3client.myts.MyTsException;
import com.ts3client.net.ConnectionListener.ChatScope;
import com.ts3client.net.PictureDownloads;
import com.ts3client.session.ServerSession;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.function.Function;
/**
* Shares files in one server's chats through myTeamSpeak, and shows and saves the files
* shared there. Failures land in the chat as system lines.
*/
final class ChatAttachmentActions implements ChatPanel.AttachmentHandler {
private static final String SIGN_IN = "Sign in to myTeamSpeak to share files";
private static final String PASTED_NAME = "image.png";
/** Where files were last shared from or saved to, for every server alike. */
private static File lastDirectory;
private final MainFrame host;
private final ServerSession session;
private final ChatPanel chat;
private final PictureDownloads pictures;
private final Function<ChatPanel.Target, ChatScope> scopes;
ChatAttachmentActions(MainFrame host, ServerSession session, ChatPanel chat, PictureDownloads pictures,
Function<ChatPanel.Target, ChatScope> scopes) {
this.host = host;
this.session = session;
this.chat = chat;
this.pictures = pictures;
this.scopes = scopes;
}
@Override
public void choose(ChatPanel.Target target, int clientId) {
if (!signedIn()) return;
JFileChooser chooser = new JFileChooser(lastDirectory);
chooser.setMultiSelectionEnabled(true);
chooser.setDialogTitle("Share files");
if (chooser.showOpenDialog(host) != JFileChooser.APPROVE_OPTION) return;
File[] files = chooser.getSelectedFiles();
if (files.length > 0) lastDirectory = files[0].getParentFile();
share(target, clientId, List.of(files));
}
@Override
public void share(ChatPanel.Target target, int clientId, List<File> files) {
if (!signedIn()) return;
for (File file : files) {
if (!file.isFile()) continue;
if (file.length() > ChatAttachments.MAX_UPLOAD_BYTES) {
chat.appendSystem(file.getName() + " is over " + (ChatAttachments.MAX_UPLOAD_BYTES >> 20) + " MB.");
continue;
}
try {
session.sendAttachment(scopes.apply(target), clientId, host.attachments(),
new FileInputStream(file), file.length(), file.getName());
} catch (IOException e) {
chat.appendSystem("Could not share " + file.getName() + ": " + e.getMessage());
}
}
}
@Override
public void share(ChatPanel.Target target, int clientId, BufferedImage image) {
if (!signedIn()) return;
ByteArrayOutputStream png = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", png);
} catch (IOException e) {
chat.appendSystem("Could not share the picture: " + e.getMessage());
return;
}
session.sendAttachment(scopes.apply(target), clientId, host.attachments(),
new ByteArrayInputStream(png.toByteArray()), png.size(), PASTED_NAME);
}
@Override
public void open(String href, boolean picture) {
ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href);
if (ref == null) return;
File shown = picture ? pictures.get(href) : null;
BufferedImage image = shown == null ? null : read(shown);
if (image != null) {
new PictureViewer(host, ref.fileName(), image, () -> save(ref, shown)).setVisible(true);
} else {
save(ref, null);
}
}
/** Asks where to save the file, then copies it there: from {@code have} when given, else fetched. */
private void save(ChatAttachment.Ref ref, File have) {
if (have == null && !signedIn()) return;
JFileChooser chooser = new JFileChooser(lastDirectory);
chooser.setDialogTitle("Save " + ref.fileName());
chooser.setSelectedFile(new File(lastDirectory, ref.fileName()));
if (chooser.showSaveDialog(host) != JFileChooser.APPROVE_OPTION) return;
File target = chooser.getSelectedFile();
lastDirectory = target.getParentFile();
ChatAttachments attachments = host.attachments();
Thread.ofVirtual().name("chat-attachment-save").start(() -> {
try {
if (have != null) {
Files.copy(have.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
Files.write(target.toPath(), attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES));
}
} catch (IOException | MyTsException e) {
SwingUtilities.invokeLater(() ->
chat.appendSystem("Could not save " + ref.fileName() + ": " + e.getMessage()));
}
});
}
private boolean signedIn() {
if (host.canShareFiles()) return true;
chat.appendSystem(SIGN_IN + ".");
return false;
}
private static BufferedImage read(File file) {
try {
return ImageIO.read(file);
} catch (IOException e) {
return null;
}
}
}
@@ -24,7 +24,7 @@ final class ChatLogsPanel extends FormPanel {
private final JCheckBox enabled = new JCheckBox("Keep chat logs");
private final JTextField folder = new JTextField(18);
private final JButton browse = new JButton("Browse…");
private final JCheckBox pictures = new JCheckBox("Show pictures in descriptions");
private final JCheckBox pictures = new JCheckBox("Show pictures in descriptions and chat");
ChatLogsPanel(Settings settings) {
this.settings = settings;
@@ -2,6 +2,9 @@ package com.ts3client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.config.Settings;
import com.ts3client.myts.ChatAttachment;
import com.ts3client.net.PictureDownloads;
import com.ts3client.text.BBCode;
import com.ts3client.text.ChatHtml;
import com.ts3client.text.HtmlText;
@@ -11,9 +14,12 @@ import com.ts3client.text.TsLink;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
@@ -21,6 +27,9 @@ import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import java.awt.BorderLayout;
import java.awt.Component;
@@ -30,15 +39,20 @@ import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Chat area with one tab per conversation (server, current channel and one per
@@ -66,11 +80,32 @@ public final class ChatPanel extends JPanel {
void onOfflineMessagesLink();
}
/** Files shared in the chats, which the host sends, fetches and shows. */
public interface AttachmentHandler {
/** Asks which files to share in the conversation. */
void choose(Target target, int clientId);
void share(Target target, int clientId, List<File> files);
void share(Target target, int clientId, BufferedImage image);
/**
* A shared file was clicked.
*
* @param picture whether the picture shown for it was, rather than its name
*/
void open(String href, boolean picture);
}
private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM);
private final JTextField input = new JTextField();
/** Tab strip height, so a tab with no icon still lines up with the others. */
private static final int HEADER_HEIGHT = 20;
/** The largest a shared picture is drawn in the log. */
private static final int PICTURE_WIDTH = 320;
private static final int PICTURE_HEIGHT = 240;
private static final int PICTURE_WIDTH_STEP = 40;
private static final String NO_SERVER = "Server";
private static final String NO_CHANNEL = "Channel";
@@ -100,11 +135,25 @@ public final class ChatPanel extends JPanel {
private SendHandler sendHandler;
private LinkHandler linkHandler;
private AttachmentHandler attachmentHandler;
private final TextZoom zoom;
private final PictureDownloads downloads;
private final DescriptionPictures pictures;
/** The server's unique identifier, which shared files are kept under; null while unknown. */
private final Supplier<String> room;
private final JButton attach = new JButton(Icons.of("UPLOAD"));
private boolean inputEnabled;
private boolean sharingAvailable;
private final Runnable onPicture = () -> SwingUtilities.invokeLater(() -> {
for (Tab t : allTabs()) t.picturesChanged();
});
public ChatPanel(TextZoom zoom) {
public ChatPanel(TextZoom zoom, Settings settings, PictureDownloads downloads, Supplier<String> room) {
super(new BorderLayout());
this.zoom = zoom;
this.downloads = downloads;
this.pictures = new DescriptionPictures(downloads, settings);
this.room = room;
tabs.setFont(Theme.uiFont());
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
@@ -139,9 +188,19 @@ public final class ChatPanel extends JPanel {
JPanel bottom = new JPanel(new BorderLayout(UIScale.scale(4), 0));
bottom.setBorder(new ScaledEmptyBorder(4, 0, 0, 0));
bottom.add(input, BorderLayout.CENTER);
bottom.add(attach, BorderLayout.EAST);
add(bottom, BorderLayout.SOUTH);
input.addActionListener(e -> fireSend());
input.setTransferHandler(attachmentTransfer(input));
attach.putClientProperty("JButton.buttonType", "toolBarButton");
attach.setFocusable(false);
attach.addActionListener(e -> {
Tab tab = selectedTab();
if (attachmentHandler != null && tab != null && tab.target != null) {
attachmentHandler.choose(tab.target, tab.clientId);
}
});
setInputEnabled(false);
}
@@ -154,6 +213,30 @@ public final class ChatPanel extends JPanel {
this.linkHandler = h;
}
public void setAttachmentHandler(AttachmentHandler h) {
this.attachmentHandler = h;
}
/** Whether files can be shared at all, i.e. signed in to myTeamSpeak. */
public void setSharingAvailable(boolean available) {
edt(() -> {
sharingAvailable = available;
updateAttach();
});
}
@Override
public void addNotify() {
super.addNotify();
downloads.addListener(onPicture);
}
@Override
public void removeNotify() {
downloads.removeListener(onPicture);
super.removeNotify();
}
/** Opens the find bar on the selected conversation. */
public void openFind() {
edt(search::open);
@@ -180,6 +263,34 @@ public final class ChatPanel extends JPanel {
public void setInputEnabled(boolean enabled) {
input.setEnabled(enabled);
inputEnabled = enabled;
updateAttach();
}
private void updateAttach() {
attach.setEnabled(inputEnabled && sharingAvailable);
attach.setToolTipText(sharingAvailable ? "Share file" : "Sign in to myTeamSpeak to share files");
}
/** Takes dropped and pasted files and pictures as files to share, leaving the rest to {@code c}'s own handling. */
private AttachmentTransferHandler attachmentTransfer(JComponent c) {
return new AttachmentTransferHandler(c.getTransferHandler(), new AttachmentTransferHandler.Sink() {
@Override
public boolean files(List<File> files) {
Tab tab = selectedTab();
if (attachmentHandler == null || tab == null || tab.target == null) return false;
attachmentHandler.share(tab.target, tab.clientId, files);
return true;
}
@Override
public boolean image(BufferedImage image) {
Tab tab = selectedTab();
if (attachmentHandler == null || tab == null || tab.target == null) return false;
attachmentHandler.share(tab.target, tab.clientId, image);
return true;
}
});
}
/** Opens (or focuses) the private chat with {@code clientId}. */
@@ -385,6 +496,11 @@ public final class ChatPanel extends JPanel {
return all;
}
private String room() {
String id = room.get();
return id == null ? "" : id;
}
private void edt(Runnable r) {
if (SwingUtilities.isEventDispatchThread()) r.run();
else SwingUtilities.invokeLater(r);
@@ -409,6 +525,10 @@ public final class ChatPanel extends JPanel {
private final List<String> entries = new ArrayList<>();
/** Only messages matching this are on screen; {@code null} shows all. */
private TextQuery filter;
/** The shared pictures the entries show, and how they stood when last drawn. */
private final List<String> pictureUrls = new ArrayList<>();
private String pictureState = "";
private int renderedPictureWidth;
Tab(Target target, int clientId, String title, Icon icon) {
this(target, clientId, "", title, icon, null, null);
@@ -436,20 +556,35 @@ public final class ChatPanel extends JPanel {
log.setText("<html><body><div id=\"chatlog\"></div></body></html>");
log.addHyperlinkListener(e -> {
if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return;
onLink(e.getDescription());
onLink(e.getDescription(), isPicture(e.getSourceElement()));
});
log.setTransferHandler(attachmentTransfer(log));
scroll = new JScrollPane(log);
HtmlStyles.fillViewport(log);
scroll.setBorder(BorderFactory.createEmptyBorder());
scroll.getViewport().addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (!pictureUrls.isEmpty() && pictureWidth() != renderedPictureWidth) keepingScroll();
}
});
}
private static boolean isPicture(Element element) {
return element != null && element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.IMG;
}
void setClientUniqueId(String uniqueId) {
if (uniqueId != null && !uniqueId.isBlank()) clientUniqueId = uniqueId;
}
private void onLink(String href) {
private void onLink(String href, boolean picture) {
if (href == null) return;
if (ChatAttachment.isHref(href)) {
if (attachmentHandler != null) attachmentHandler.open(href, picture);
return;
}
if (TsLink.isOfflineMessages(href)) {
if (linkHandler != null) linkHandler.onOfflineMessagesLink();
return;
@@ -521,13 +656,16 @@ public final class ChatPanel extends JPanel {
void appendMessage(int fromId, String fromUniqueId, String from, String text) {
append(ChatHtml.message(fromId,
fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text));
fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text,
room()));
}
void setHistory(List<String> htmlEntries) {
entries.clear();
pictureUrls.clear();
if (htmlEntries != null) {
for (String entry : htmlEntries) entries.add(ChatHtml.logEntry(entry));
String room = room();
for (String entry : htmlEntries) add(ChatHtml.logEntry(entry, room));
}
render();
}
@@ -535,10 +673,49 @@ public final class ChatPanel extends JPanel {
/** Replaces the whole log with fixed content; used by static-content tabs. */
void setStaticContent(String html) {
entries.clear();
pictureUrls.clear();
entries.add(html);
render();
}
private void add(String entry) {
entries.add(entry);
// Static content comes with its pictures already in place.
if (noteKey == null && DescriptionPictures.hasPictures(entry)) {
pictureUrls.addAll(DescriptionPictures.urls(entry));
}
}
/** The entry as drawn: its shared pictures as they stand now. */
private String drawn(String entry) {
if (noteKey != null || !DescriptionPictures.hasPictures(entry)) return entry;
return pictures.html(entry, renderedPictureWidth, UIScale.scale(PICTURE_HEIGHT));
}
/**
* How wide a shared picture may be: the log's width inside its margins, in steps so that
* dragging a divider does not rebuild the log on every pixel.
*/
private int pictureWidth() {
int step = UIScale.scale(PICTURE_WIDTH_STEP);
int width = scroll.getViewport().getWidth() - UIScale.scale(24);
return Math.min(UIScale.scale(PICTURE_WIDTH), Math.max(step, width / step * step));
}
/** A picture came or failed: redrawn if it is one of this log's. */
void picturesChanged() {
if (!pictureUrls.isEmpty() && !pictures.state(pictureUrls).equals(pictureState)) keepingScroll();
}
/** Redraws the log, staying where the reader is unless that is at the end. */
private void keepingScroll() {
JScrollBar bar = scroll.getVerticalScrollBar();
boolean atEnd = bar.getValue() + bar.getVisibleAmount() >= bar.getMaximum() - UIScale.scale(8);
Point at = scroll.getViewport().getViewPosition();
render();
if (!atEnd || search.isOpen()) SwingUtilities.invokeLater(() -> scroll.getViewport().setViewPosition(at));
}
void showMatching(TextQuery filter) {
if (Objects.equals(this.filter, filter)) return;
this.filter = filter;
@@ -550,20 +727,29 @@ public final class ChatPanel extends JPanel {
}
private void render() {
// Read before drawing, so a picture coming meanwhile still counts as a change.
pictureState = pictures.state(pictureUrls);
renderedPictureWidth = pictureWidth();
StringBuilder html = new StringBuilder();
for (String entry : entries) {
if (shows(entry)) html.append(entry);
if (shows(entry)) html.append(drawn(entry));
}
log.setText("<html><body><div id=\"chatlog\">" + html + "</div></body></html>");
log.setCaretPosition(noteKey != null ? 0 : log.getDocument().getLength());
}
void append(String entry) {
entries.add(entry);
if (shows(entry)) {
boolean stale = !pictures.state(pictureUrls).equals(pictureState);
add(entry);
if (stale) {
// A picture already shown changed and is about to be redrawn; this joins it.
render();
} else if (shows(entry)) {
pictureState = pictures.state(pictureUrls);
if (renderedPictureWidth == 0) renderedPictureWidth = pictureWidth();
try {
HTMLDocument doc = (HTMLDocument) log.getDocument();
doc.insertBeforeEnd(doc.getElement("chatlog"), entry);
doc.insertBeforeEnd(doc.getElement("chatlog"), drawn(entry));
// Following new lines would pull the view away from the match being read.
if (!search.isOpen()) log.setCaretPosition(doc.getLength());
} catch (BadLocationException | IOException ignored) {
@@ -2,8 +2,10 @@ package com.ts3client.ui;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.config.Settings;
import com.ts3client.myts.ChatAttachment;
import com.ts3client.net.PictureDownloads;
import com.ts3client.text.BBCode;
import com.ts3client.text.ChatHtml;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
@@ -11,7 +13,9 @@ import javax.imageio.stream.ImageInputStream;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
@@ -44,6 +48,11 @@ final class DescriptionPictures {
/** @param maxWidth the widest a picture may be drawn */
String html(String html, int maxWidth) {
return html(html, maxWidth, Integer.MAX_VALUE);
}
/** @param maxHeight the tallest a picture may be drawn */
String html(String html, int maxWidth, int maxHeight) {
StringBuilder out = new StringBuilder();
Matcher m = TAG.matcher(html);
String anchor = null;
@@ -53,7 +62,8 @@ final class DescriptionPictures {
out.append(html, last, m.start());
last = m.end();
if (m.group(1) != null) {
out.append(picture(unescape(m.group(1)), anchor, href == null ? null : unescape(href), maxWidth));
out.append(picture(unescape(m.group(1)), anchor, href == null ? null : unescape(href),
maxWidth, maxHeight));
} else if (m.group(2) != null) {
anchor = m.group();
href = m.group(2);
@@ -67,7 +77,30 @@ final class DescriptionPictures {
return out.append(html.substring(last)).toString();
}
private String picture(String url, String anchor, String href, int maxWidth) {
/** The pictures {@code html} shows, by address. */
static List<String> urls(String html) {
List<String> urls = new ArrayList<>();
Matcher m = TAG.matcher(html);
while (m.find()) {
if (m.group(1) != null) urls.add(unescape(m.group(1)));
}
return urls;
}
/**
* How the pictures stand, one letter each: it changes when one of them comes or fails,
* and asks for those not on their way yet.
*/
String state(List<String> urls) {
if (!settings.descriptionPictures) return "";
StringBuilder state = new StringBuilder(urls.size());
for (String url : urls) {
state.append(downloads.get(url) != null ? 'y' : downloads.failed(url) ? 'n' : '-');
}
return state.toString();
}
private String picture(String url, String anchor, String href, int maxWidth, int maxHeight) {
if (!settings.descriptionPictures) return link("ICONVIEWER", url, anchor, href);
File file = downloads.get(url);
if (file == null) {
@@ -77,28 +110,37 @@ final class DescriptionPictures {
if (size.width <= 0 || size.height <= 0) return link("BROKEN_IMAGE", url, anchor, href);
int width = Math.min(UIScale.scale(size.width), Math.max(1, maxWidth));
int height = (int) ((long) size.height * width / size.width);
if (height > maxHeight) {
height = Math.max(1, maxHeight);
width = Math.max(1, (int) ((long) size.width * height / size.height));
}
// Swing frames a picture inside a link unless told not to.
return "<img src='" + file.toURI() + "' width='" + width + "' height='" + height + "' border='0'>";
}
/**
* The picture's address as a link behind {@code iconKey}, shortened: Swing never breaks a
* long one, so it would widen the view past its edge. Inside another link, that link is
* closed around it and shown after it, so it is not lost with the picture that carried it.
* long one, so it would widen the view past its edge; a file shared in chat goes by its
* name. Inside another link, that link is closed around it and shown after it, so it is
* not lost with the picture that carried it.
*/
private static String link(String iconKey, String url, String anchor, String href) {
String own = icon(iconKey) + "<a class=\"" + BBCode.linkClass(url) + "\" href=\"" + BBCode.escape(url) + "\">"
+ BBCode.escape(BBCode.shortAddress(url)) + "</a>";
ChatAttachment.Ref attachment = ChatAttachment.Ref.parse(url);
String label = attachment != null ? attachment.fileName() : BBCode.shortAddress(url);
String linkClass = attachment != null ? ChatHtml.ATTACHMENT_CLASS : BBCode.linkClass(url);
// A link to the picture itself already is the link this would be.
if (anchor != null && href.equals(url)) return icon(iconKey) + BBCode.escape(label);
String own = icon(iconKey) + "<a class=\"" + linkClass + "\" href=\"" + BBCode.escape(url) + "\">"
+ BBCode.escape(label) + "</a>";
if (anchor == null) return own;
String outer = href.equals(url) ? "" : " " + anchor + BBCode.escape(href) + "</a>";
return "</a>" + own + outer + anchor;
return "</a>" + own + " " + anchor + BBCode.escape(href) + "</a>" + anchor;
}
private static String icon(String key) {
int size = UIScale.scale(ICON);
File file = IconFiles.of(key, size);
if (file == null) return "";
return "<img src='" + file.toURI() + "' width='" + size + "' height='" + size + "'> ";
return "<img src='" + file.toURI() + "' width='" + size + "' height='" + size + "' border='0'> ";
}
/** The picture's size in pixels, read from its header; zero when it is no picture Swing can show. */
@@ -6,6 +6,7 @@ import com.ts3client.notify.desktop.DesktopNotifications;
import com.ts3client.notify.desktop.DesktopNotifications.Notice;
import com.ts3client.notify.desktop.FreedesktopNotifications;
import com.ts3client.text.BBCode;
import com.ts3client.text.ChatHtml;
import com.ts3client.ui.tray.AwtTray;
import javax.swing.SwingUtilities;
@@ -74,7 +75,7 @@ final class DesktopNotifier {
void privateMessage(ServerTab tab, int clientId, String from, String message) {
if (!wanted()) return;
String text = BBCode.toPlain(message);
String text = ChatHtml.plainMessage(message);
Conversation key = new Conversation(tab, clientId);
worker.execute(() -> {
DesktopNotifications out = backend();
@@ -2,6 +2,7 @@ package com.ts3client.ui;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.text.BBCode;
import com.ts3client.text.ChatHtml;
import javax.swing.JEditorPane;
import javax.swing.JViewport;
@@ -106,6 +107,8 @@ final class HtmlStyles {
// External links are underlined so they can't be mistaken for an identity.
css.addRule("a." + BBCode.EXTERNAL_LINK_CLASS
+ " { color:" + hex(Theme.link()) + "; text-decoration:underline; }");
css.addRule("a." + ChatHtml.ATTACHMENT_CLASS
+ " { color:" + hex(Theme.link()) + "; text-decoration:underline; }");
kit.setStyleSheet(css);
pane.setEditorKit(kit);
@@ -10,6 +10,7 @@ import com.ts3client.config.Bookmark;
import com.ts3client.config.Bookmarks;
import com.ts3client.config.IdentityStore;
import com.ts3client.config.Settings;
import com.ts3client.myts.ChatAttachments;
import com.ts3client.myts.MyTeamSpeakLogin;
import com.ts3client.teamspeak.TeamSpeakImporter;
import com.ts3client.contacts.ContactStore;
@@ -68,6 +69,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
private final ContactStore contacts = ContactStore.load();
private final AudioBackend audio = new DesktopAudioBackend();
private final PictureDownloads pictures = new PictureDownloads(new File(AppDirs.profile(), "pictures"), true);
/** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */
private final ChatAttachments attachments = new ChatAttachments(myTeamSpeak);
private final TextZoom chatZoom;
private final TextZoom infoZoom;
/** Sound pack playback, shared by every connection. */
@@ -122,6 +125,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
this.soundPlayer = audio.createSoundPlayer(settings);
this.sounds.setPlayer(soundPlayer);
this.notifier = new DesktopNotifier(this, settings);
pictures.addSource("tsattach:", attachments::fetchPicture);
// Any of the client's windows coming to the front counts, a dialog included.
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("activeWindow", e -> {
if (e.getNewValue() != null) notifier.windowActivated();
@@ -931,6 +935,12 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
hotkeys.dispose();
if (tray != null) tray.dispose();
notifier.shutdown();
// Ends the sharing session if myTeamSpeak answers soon; it expires on its own otherwise.
try {
Thread.ofVirtual().start(attachments::close).join(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/** Leaves every server and ends the process. */
@@ -983,7 +993,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
selected == null ? null : selected.connection().getPlayback(),
sounds, hotkeys,
new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings),
menuBar::rebuildBookmarks),
menuBar::rebuildBookmarks, this::myTeamSpeakChanged),
() -> {
applyOutputSettingsToAllTabs();
contactsChanged();
@@ -991,6 +1001,26 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
dlg.setVisible(true);
}
/** Signed in to or out of myTeamSpeak: sharing in chat follows. */
private void myTeamSpeakChanged() {
boolean signedIn = myTeamSpeak.isSignedIn();
for (ServerTab tab : tabs) tab.chat().setSharingAvailable(signedIn);
if (signedIn) {
pictures.retryFailed();
} else {
Thread.ofVirtual().name("myteamspeak-sign-out").start(attachments::close);
}
}
ChatAttachments attachments() {
return attachments;
}
/** Whether files can be shared in chat: that needs a myTeamSpeak account. */
boolean canShareFiles() {
return myTeamSpeak.isSignedIn();
}
/** Master volume, output device and receive buffer are global, so push them to every open connection. */
private void applyOutputSettingsToAllTabs() {
soundPlayer.setOutputDevice(settings.outputDevice);
@@ -45,6 +45,8 @@ final class MyTeamSpeakPanel extends JPanel {
private final MyTeamSpeakLogin login;
private final TeamSpeakImporter importer;
private final Runnable onImported;
/** Runs when the client signs in or out, the saved sign-in being turned away included. */
private final Runnable onSignInChanged;
private final CardLayout cards = new CardLayout();
@@ -63,10 +65,12 @@ final class MyTeamSpeakPanel extends JPanel {
private List<SyncItem> accountItems = List.of();
private boolean fetched;
MyTeamSpeakPanel(MyTeamSpeakLogin login, TeamSpeakImporter importer, Runnable onImported) {
MyTeamSpeakPanel(MyTeamSpeakLogin login, TeamSpeakImporter importer, Runnable onImported,
Runnable onSignInChanged) {
this.login = login;
this.importer = importer;
this.onImported = onImported;
this.onSignInChanged = onSignInChanged;
setLayout(cards);
add(buildSignedOut(), SIGNED_OUT);
add(buildSignedIn(), SIGNED_IN);
@@ -163,6 +167,7 @@ final class MyTeamSpeakPanel extends JPanel {
status(signInStatus, " ", false);
showState();
showItems(result);
onSignInChanged.run();
});
}, message -> {
setSignInBusy(false);
@@ -180,6 +185,7 @@ final class MyTeamSpeakPanel extends JPanel {
fetched = false;
email.setText("");
showState();
onSignInChanged.run();
}
private void fetch() {
@@ -198,7 +204,10 @@ final class MyTeamSpeakPanel extends JPanel {
status(dataStatus, message, true);
// A rejected sign-in has signed out.
showState();
if (!login.isSignedIn()) status(signInStatus, message, true);
if (!login.isSignedIn()) {
status(signInStatus, message, true);
onSignInChanged.run();
}
});
}
@@ -0,0 +1,78 @@
package com.ts3client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
/** A picture at full size, or as large as the screen allows, with a way to save it. */
final class PictureViewer extends JDialog {
private static final int MIN_WIDTH = 360;
private static final int MIN_HEIGHT = 240;
PictureViewer(Window owner, String title, BufferedImage picture, Runnable onSave) {
super(owner, title, ModalityType.MODELESS);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JLabel view = new JLabel(new ImageIcon(fitted(picture, owner)));
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
dispose();
}
});
JScrollPane scroll = new JScrollPane(view);
scroll.setBorder(null);
JButton save = new JButton("Save…");
save.addActionListener(e -> onSave.run());
JButton close = new JButton("Close");
close.addActionListener(e -> dispose());
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(4), 0));
buttons.setBorder(new ScaledEmptyBorder(6, 6, 6, 6));
buttons.add(save);
buttons.add(close);
add(scroll, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
getRootPane().registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke("ESCAPE"),
JComponent.WHEN_IN_FOCUSED_WINDOW);
getRootPane().setDefaultButton(close);
pack();
// A small picture still gets a window its title and buttons fit in.
setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), Math.max(getHeight(), UIScale.scale(MIN_HEIGHT)));
setLocationRelativeTo(owner);
}
/** The picture narrowed to most of the owner's screen; small ones are left as they are. */
private static Image fitted(BufferedImage picture, Window owner) {
GraphicsConfiguration gc = owner != null ? owner.getGraphicsConfiguration() : null;
Rectangle screen = gc != null ? gc.getBounds() : new Rectangle(new Dimension(1280, 800));
int maxWidth = screen.width * 85 / 100;
int maxHeight = screen.height * 75 / 100;
int width = picture.getWidth();
int height = picture.getHeight();
double scale = Math.min(1, Math.min(maxWidth / (double) width, maxHeight / (double) height));
if (scale >= 1) return picture;
return picture.getScaledInstance(Math.max(1, (int) (width * scale)), Math.max(1, (int) (height * scale)),
Image.SCALE_SMOOTH);
}
}
@@ -79,7 +79,7 @@ final class ServerTab {
this.session = new ServerSession(settings, identities, audio, sounds, contacts, events);
this.conn = session.connection();
this.groupIcons = new GroupIcons(conn.getIcons());
this.chatPanel = new ChatPanel(host.chatZoom());
this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId);
this.treeActions = new ServerTabTreeActions(host, this, conn, chatPanel, infoPanel, groupIcons);
this.treePanel = new ServerTreePanel(conn.getModel(), groupIcons, contacts, settings, treeActions);
treeActions.attach(treePanel);
@@ -102,6 +102,8 @@ final class ServerTab {
showOfflineMessages();
}
});
chatPanel.setAttachmentHandler(new ChatAttachmentActions(host, session, chatPanel, pictures, ServerTab::scope));
chatPanel.setSharingAvailable(host.canShareFiles());
chatPanel.setInputEnabled(false);
infoPanel.setDescriptionHandler(new InfoPanel.DescriptionHandler() {
@@ -322,12 +324,15 @@ final class ServerTab {
// ---- chat ----
private void onSendChat(ChatPanel.Target target, int clientId, String text) {
ChatScope scope = switch (target) {
session.sendChat(scope(target), clientId, text);
}
private static ChatScope scope(ChatPanel.Target target) {
return switch (target) {
case SERVER -> ChatScope.SERVER;
case PRIVATE -> ChatScope.PRIVATE;
default -> ChatScope.CHANNEL;
};
session.sendChat(scope, clientId, text);
}
/** Opens the file repository browser for a channel, as the "Browse Files" hotkey/menu action does. */