Soundboard: WAV and Opus sounds sent with the microphone

Core: ClipMixer mixes clips into the capturing VoiceInput's frames (after
APM/VAD), transmitting past the gate while one plays; a mute still wins and
the clip runs out unheard. Sessions owns the mixer so sounds follow the
microphone between servers, and drops them when nobody captures. Soundboard
decodes (SoundFiles: wave or Ogg Opus, sniffed by content) off the caller's
thread, caches, and plays a local copy via the new stoppable
SoundPlayer.play(float[], volume). Sounds live in soundboard.properties.

Desktop: Self > Soundboard window (tile grid, click to play/stop, drop files
to add, edit/move/remove, sent and local volume), toolbar action, and hotkeys
Play Sound, Play/Stop Sound, Stop All Sounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 21:03:05 +00:00
co-authored by Claude Opus 5.5
parent d96339b72b
commit b33f1fd25a
26 changed files with 1426 additions and 22 deletions
@@ -397,6 +397,22 @@ public final class MainCommands {
frame.showGiantPtt();
}
void showSoundboard() {
frame.soundboard().show();
}
public void playSound(String name) {
frame.soundboard().play(name);
}
public void toggleSound(String name) {
frame.soundboard().toggle(name);
}
public void stopSounds() {
frame.soundboard().stopAll();
}
void showIdentities() {
new IdentitiesDialog(frame, identities, settings, bookmarks, null).setVisible(true);
}
@@ -21,6 +21,7 @@ import eu.lixko.ts3j.client.session.SelfState;
import eu.lixko.ts3j.client.session.ServerLink;
import eu.lixko.ts3j.client.session.ServerSession;
import eu.lixko.ts3j.client.session.Sessions;
import eu.lixko.ts3j.client.soundboard.Soundboard;
import eu.lixko.ts3j.client.sound.SoundNotifier;
import eu.lixko.ts3j.client.sound.SoundPlayer;
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter;
@@ -35,6 +36,7 @@ import eu.lixko.ts3j.client.ui.manage.ContactsDialog;
import eu.lixko.ts3j.client.ui.options.MyTeamSpeakPanel;
import eu.lixko.ts3j.client.ui.options.SettingsDialog;
import eu.lixko.ts3j.client.ui.server.ServerTab;
import eu.lixko.ts3j.client.ui.soundboard.SoundboardActions;
import eu.lixko.ts3j.client.ui.tray.TrayBackend;
import javax.swing.AbstractAction;
@@ -82,6 +84,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
/** Sound pack playback, shared by every connection. */
private final SoundNotifier sounds;
private final SoundPlayer soundPlayer;
private final SoundboardActions soundboard;
private final List<ServerTab> tabs = new ArrayList<>();
/** The tabs' sessions: who holds the microphone, and the state shared by every server. */
@@ -129,6 +132,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
this.sounds = new SoundNotifier(settings);
this.soundPlayer = audio.createSoundPlayer(settings);
this.sounds.setPlayer(soundPlayer);
this.soundboard = new SoundboardActions(this, settings,
new Soundboard(sessions.clips(), sessions::onAir, audio.opus(), soundPlayer, settings));
this.notifier = new DesktopNotifier(this, settings);
Setting.onAnyChange(this::applyOutputSettingsToAllTabs,
settings.outputDevice, settings.outputVolume, settings.masterVolume, settings.receiveBuffer);
@@ -396,6 +401,10 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
sessions.setPushToTalk(talking);
}
SoundboardActions soundboard() {
return soundboard;
}
void showGiantPtt() {
if (giantPtt == null || !giantPtt.isDisplayable()) {
giantPtt = new GiantPttWindow(this, sessions::setForceTransmit, () -> {
@@ -479,6 +488,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
for (eu.lixko.ts3j.client.sound.SoundPack pack : sounds.availablePacks()) out.add(pack.name());
}
}
case SOUND -> out.addAll(soundboard.names());
case CHANNEL -> {
if (selected != null && selected.session().isConnected()) {
out.addAll(selected.session().channelPaths());
@@ -593,6 +603,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
}
sessions.shutdown();
contacts.flush();
soundboard.shutdown();
soundPlayer.shutdown();
hotkeys.dispose();
if (tray != null) tray.dispose();
@@ -139,11 +139,14 @@ final class MainMenuBar extends JMenuBar {
deleteAvatarItem.addActionListener(e -> commands.deleteAvatar());
JMenuItem giantPtt = new JMenuItem("Giant PTT", Icons.of("CAPTURE"));
giantPtt.addActionListener(e -> commands.showGiantPtt());
JMenuItem soundboard = new JMenuItem("Soundboard", Icons.of("MUSIC"));
soundboard.addActionListener(e -> commands.showSoundboard());
self.add(awayMenu);
self.add(activateItem);
self.add(muteItem);
self.add(deafItem);
self.add(giantPtt);
self.add(soundboard);
self.addSeparator();
self.add(commanderItem);
self.addSeparator();
@@ -111,6 +111,7 @@ final class ToolbarActions {
add("deleteAvatar", Category.SELF, "Delete Avatar", commands::deleteAvatar, "DELETE_AVATAR")
.enabledWhen(() -> is(ServerSession::hasAvatar));
add("giantPtt", Category.SELF, "Giant PTT", commands::showGiantPtt, "CAPTURE");
add("soundboard", Category.SELF, "Soundboard", commands::showSoundboard, "MUSIC");
}
private void addDialogs() {
@@ -87,6 +87,10 @@ public final class HotkeyActions implements HotkeyEngine.Handler {
case SOUND_UNMUTE -> frame.setSoundsMuted(false);
case SOUND_TOGGLE -> frame.setSoundsMuted(!frame.areSoundsMuted());
case SOUNDBOARD_PLAY -> commands.playSound(hotkey.argument);
case SOUNDBOARD_TOGGLE -> commands.toggleSound(hotkey.argument);
case SOUNDBOARD_STOP -> commands.stopSounds();
case VOLUME_INCREASE -> frame.adjustMasterVolume(VOLUME_STEP);
case VOLUME_DECREASE -> frame.adjustMasterVolume(-VOLUME_STEP);
@@ -291,6 +291,7 @@ public final class HotkeyDialog extends JDialog {
case BOOKMARK -> "Bookmark:";
case CHANNEL -> "Channel path:";
case PROFILE -> "Profile:";
case SOUND -> "Sound:";
default -> "Parameter:";
};
}
@@ -0,0 +1,76 @@
package eu.lixko.ts3j.client.ui.soundboard;
import com.formdev.flatlaf.util.UIScale;
import eu.lixko.ts3j.client.soundboard.SoundboardSound;
import eu.lixko.ts3j.client.ui.widget.FormPanel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.io.File;
/** Edits a soundboard sound's name, file and volume. */
final class SoundEditDialog {
private SoundEditDialog() {
}
/** @return whether the sound was changed */
static boolean edit(Component parent, SoundboardSound sound) {
JTextField name = new JTextField(sound.name, 24);
JTextField file = new JTextField(sound.file, 24);
JButton browse = new JButton("…");
browse.addActionListener(e -> {
JFileChooser chooser = new JFileChooser(new File(file.getText()).getParentFile());
chooser.setFileFilter(new FileNameExtensionFilter("Sounds (WAV, Opus)", "wav", "wave", "opus", "ogg"));
if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
file.setText(chooser.getSelectedFile().getAbsolutePath());
}
});
int max = (int) Math.round(SoundboardSound.MAX_VOLUME * 100);
JSlider volume = new JSlider(0, max, (int) Math.round(sound.volume * 100));
JLabel percent = new JLabel();
volume.addChangeListener(e -> percent.setText(volume.getValue() + " %"));
percent.setText(volume.getValue() + " %");
JPanel fileRow = new JPanel(new BorderLayout(UIScale.scale(4), 0));
fileRow.add(file, BorderLayout.CENTER);
fileRow.add(browse, BorderLayout.EAST);
JPanel volumeRow = new JPanel(new BorderLayout(UIScale.scale(4), 0));
volumeRow.add(volume, BorderLayout.CENTER);
volumeRow.add(percent, BorderLayout.EAST);
FormPanel form = new FormPanel(false);
row(form, 0, "Name:", name);
row(form, 1, "File:", fileRow);
row(form, 2, "Volume:", volumeRow);
if (JOptionPane.showConfirmDialog(parent, form, "Edit Sound", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) {
return false;
}
if (!name.getText().isBlank()) sound.name = name.getText().trim();
if (!file.getText().isBlank()) sound.file = file.getText().trim();
sound.volume = volume.getValue() / 100.0;
return true;
}
private static void row(FormPanel form, int y, String label, Component field) {
GridBagConstraints c = FormPanel.gbc();
c.gridy = y;
c.gridx = 0;
c.weightx = 0;
form.add(new JLabel(label), c);
c.gridx = 1;
c.weightx = 1;
form.add(field, c);
}
}
@@ -0,0 +1,82 @@
package eu.lixko.ts3j.client.ui.soundboard;
import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.soundboard.Soundboard;
import eu.lixko.ts3j.client.soundboard.SoundboardSound;
import eu.lixko.ts3j.client.soundboard.SoundboardSounds;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionException;
/** The soundboard as the window and the hotkeys reach it. Driven from the event dispatch thread. */
public final class SoundboardActions {
private final JFrame owner;
private final Settings settings;
private final Soundboard soundboard;
private final SoundboardSounds sounds = SoundboardSounds.load();
private SoundboardWindow window;
public SoundboardActions(JFrame owner, Settings settings, Soundboard soundboard) {
this.owner = owner;
this.settings = settings;
this.soundboard = soundboard;
}
public void show() {
if (window == null || !window.isDisplayable()) {
window = new SoundboardWindow(owner, settings, soundboard, sounds, this::play);
}
window.setVisible(true);
window.toFront();
}
/** Starts the sound with this name, from the top if it is playing. */
public void play(String name) {
SoundboardSound sound = sounds.find(name);
if (sound == null) {
report("No sound named " + name);
return;
}
play(sound);
}
/** Starts the sound with this name, or stops it while it plays. */
public void toggle(String name) {
SoundboardSound sound = sounds.find(name);
if (sound != null && soundboard.isPlaying(sound)) soundboard.stop(sound);
else play(name);
}
public void stopAll() {
soundboard.stopAll();
}
/** The sounds' names, for hotkey arguments. */
public List<String> names() {
List<String> out = new ArrayList<>();
for (SoundboardSound s : sounds.all()) out.add(s.name);
return out;
}
public void shutdown() {
soundboard.shutdown();
}
private void play(SoundboardSound sound) {
if (window != null) window.report("");
soundboard.play(sound).exceptionally(e -> {
Throwable cause = e instanceof CompletionException && e.getCause() != null ? e.getCause() : e;
SwingUtilities.invokeLater(() -> report(cause.getMessage()));
return null;
});
}
/** Shows a failure in the window; a hotkey pressed with it closed fails quietly rather than steal focus. */
private void report(String message) {
if (window != null && window.isDisplayable()) window.report(message);
}
}
@@ -0,0 +1,386 @@
package eu.lixko.ts3j.client.ui.soundboard;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.config.Setting;
import eu.lixko.ts3j.client.sound.SoundFiles;
import eu.lixko.ts3j.client.soundboard.Soundboard;
import eu.lixko.ts3j.client.soundboard.SoundboardSound;
import eu.lixko.ts3j.client.soundboard.SoundboardSounds;
import eu.lixko.ts3j.client.ui.Theme;
import eu.lixko.ts3j.client.ui.icons.Icons;
import eu.lixko.ts3j.client.ui.widget.Dialogs;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.ActionEvent;
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.io.File;
import java.util.List;
import java.util.function.Consumer;
/**
* The soundboard: a grid of sounds, each played onto the air with a click and stopped with
* another. Files dropped on it are added; the context menu edits, reorders and removes.
*/
final class SoundboardWindow extends JDialog {
private static final int TILE_WIDTH = 150;
private static final int TILE_HEIGHT = 48;
private final Settings settings;
private final Soundboard soundboard;
private final SoundboardSounds sounds;
private final Consumer<SoundboardSound> play;
private final DefaultListModel<SoundboardSound> model = new DefaultListModel<>();
private final JList<SoundboardSound> grid = new JList<>(model);
private final JButton stopAll = new JButton("Stop all", Icons.ofAny("STOP", "RECORDING_STOP"));
private final JLabel status = new JLabel(" ");
private final Runnable playingChanged = () -> SwingUtilities.invokeLater(this::playingChanged);
private File lastDirectory;
SoundboardWindow(JFrame owner, Settings settings, Soundboard soundboard, SoundboardSounds sounds,
Consumer<SoundboardSound> play) {
super(owner, "Soundboard", false);
this.settings = settings;
this.soundboard = soundboard;
this.sounds = sounds;
this.play = play;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
sounds.all().forEach(model::addElement);
grid.setLayoutOrientation(JList.HORIZONTAL_WRAP);
grid.setVisibleRowCount(-1);
grid.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
grid.setFixedCellWidth(UIScale.scale(TILE_WIDTH));
grid.setFixedCellHeight(UIScale.scale(TILE_HEIGHT));
grid.setCellRenderer(new TileRenderer());
grid.setTransferHandler(new FileDrop());
grid.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int index = tileAt(e);
if (index < 0) {
grid.clearSelection();
if (e.isPopupTrigger()) emptyMenu().show(grid, e.getX(), e.getY());
return;
}
grid.setSelectedIndex(index);
if (e.isPopupTrigger()) {
tileMenu(model.get(index)).show(grid, e.getX(), e.getY());
} else if (SwingUtilities.isLeftMouseButton(e)) {
toggle(model.get(index));
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (!e.isPopupTrigger()) return;
int index = tileAt(e);
if (index >= 0) tileMenu(model.get(index)).show(grid, e.getX(), e.getY());
else emptyMenu().show(grid, e.getX(), e.getY());
}
});
bindKey("ENTER", "play", () -> selected(this::toggle));
bindKey("DELETE", "remove", () -> selected(this::remove));
bindKey("F2", "edit", () -> selected(this::edit));
JScrollPane scroll = new JScrollPane(grid);
scroll.setPreferredSize(UIScale.scale(new Dimension(4 * TILE_WIDTH + 24, 4 * TILE_HEIGHT + 8)));
JButton add = new JButton("Add…", Icons.of("ADD"));
add.addActionListener(e -> chooseFiles());
stopAll.addActionListener(e -> soundboard.stopAll());
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), 0));
buttons.add(add);
buttons.add(stopAll);
buttons.add(Box.createHorizontalStrut(UIScale.scale(12)));
buttons.add(new JLabel("Volume"));
buttons.add(volumeSlider(settings.soundboardVolume, 200));
buttons.add(new JLabel("Local"));
buttons.add(volumeSlider(settings.soundboardLocalVolume, 100));
status.setForeground(Theme.blocked());
JPanel south = new JPanel();
south.setLayout(new BoxLayout(south, BoxLayout.Y_AXIS));
buttons.setAlignmentX(LEFT_ALIGNMENT);
status.setAlignmentX(LEFT_ALIGNMENT);
south.add(buttons);
south.add(Box.createVerticalStrut(UIScale.scale(4)));
south.add(status);
JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8)));
content.setBorder(new ScaledEmptyBorder(8, 8, 8, 8));
content.add(scroll, BorderLayout.CENTER);
content.add(south, BorderLayout.SOUTH);
setContentPane(content);
soundboard.addListener(playingChanged);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
soundboard.removeListener(playingChanged);
}
});
Dialogs.closeOnEscape(this);
playingChanged();
pack();
setLocationRelativeTo(owner);
}
/** Shows why a sound did not play; empty clears it. */
void report(String message) {
status.setText(message == null || message.isEmpty() ? " " : message);
}
// ---- playing ----
private void toggle(SoundboardSound sound) {
if (soundboard.isPlaying(sound)) soundboard.stop(sound);
else play.accept(sound);
}
private void playingChanged() {
stopAll.setEnabled(soundboard.isPlaying());
grid.repaint();
}
// ---- editing ----
private void chooseFiles() {
JFileChooser chooser = new JFileChooser(lastDirectory);
chooser.setMultiSelectionEnabled(true);
chooser.setFileFilter(new FileNameExtensionFilter("Sounds (WAV, Opus)", "wav", "wave", "opus", "ogg"));
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
lastDirectory = chooser.getCurrentDirectory();
add(List.of(chooser.getSelectedFiles()));
}
private void add(List<File> files) {
int added = 0;
for (File f : files) {
if (!f.isFile() || !SoundFiles.isSupported(f)) continue;
SoundboardSound sound = new SoundboardSound(baseName(f), f.getAbsolutePath());
sounds.all().add(sound);
model.addElement(sound);
added++;
}
if (added > 0) {
sounds.save();
grid.setSelectedIndex(model.size() - 1);
grid.ensureIndexIsVisible(model.size() - 1);
report("");
} else {
report("Only WAV and Opus files");
}
}
private void edit(SoundboardSound sound) {
if (!SoundEditDialog.edit(this, sound)) return;
sounds.save();
grid.repaint();
}
private void remove(SoundboardSound sound) {
soundboard.stop(sound);
sounds.all().remove(sound);
model.removeElement(sound);
sounds.save();
}
private void move(SoundboardSound sound, int delta) {
int from = sounds.all().indexOf(sound);
int to = from + delta;
if (from < 0 || to < 0 || to >= sounds.all().size()) return;
sounds.all().remove(from);
sounds.all().add(to, sound);
model.remove(from);
model.add(to, sound);
grid.setSelectedIndex(to);
sounds.save();
}
private JPopupMenu tileMenu(SoundboardSound sound) {
JPopupMenu menu = new JPopupMenu();
boolean playing = soundboard.isPlaying(sound);
menu.add(item(playing ? "Stop" : "Play", () -> toggle(sound)));
menu.addSeparator();
menu.add(item("Edit…", () -> edit(sound)));
JMenuItem left = item("Move left", () -> move(sound, -1));
left.setEnabled(sounds.all().indexOf(sound) > 0);
JMenuItem right = item("Move right", () -> move(sound, 1));
right.setEnabled(sounds.all().indexOf(sound) < sounds.all().size() - 1);
menu.add(left);
menu.add(right);
menu.addSeparator();
menu.add(item("Remove", () -> remove(sound)));
return menu;
}
private JPopupMenu emptyMenu() {
JPopupMenu menu = new JPopupMenu();
menu.add(item("Add…", this::chooseFiles));
return menu;
}
// ---- helpers ----
private int tileAt(MouseEvent e) {
int index = grid.locationToIndex(e.getPoint());
return index >= 0 && grid.getCellBounds(index, index).contains(e.getPoint()) ? index : -1;
}
private void selected(Consumer<SoundboardSound> action) {
SoundboardSound sound = grid.getSelectedValue();
if (sound != null) action.accept(sound);
}
private void bindKey(String key, String name, Runnable action) {
grid.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(key), name);
grid.getActionMap().put(name, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
action.run();
}
});
}
private static JMenuItem item(String label, Runnable action) {
JMenuItem item = new JMenuItem(label);
item.addActionListener(e -> action.run());
return item;
}
private JSlider volumeSlider(Setting<Double> setting, int maxPercent) {
JSlider slider = new JSlider(0, maxPercent, (int) Math.round(setting.get() * 100));
slider.setPreferredSize(new Dimension(UIScale.scale(100), slider.getPreferredSize().height));
slider.addChangeListener(e -> {
setting.set(slider.getValue() / 100.0);
slider.setToolTipText(slider.getValue() + " %");
if (!slider.getValueIsAdjusting()) settings.save();
});
slider.setToolTipText(slider.getValue() + " %");
return slider;
}
private static String baseName(File f) {
String name = f.getName();
int dot = name.lastIndexOf('.');
return dot > 0 ? name.substring(0, dot) : name;
}
/** Accepts sound files dragged in from a file manager. */
private final class FileDrop extends TransferHandler {
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
@Override
@SuppressWarnings("unchecked")
public boolean importData(TransferSupport support) {
if (!canImport(support)) return false;
try {
add((List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));
return true;
} catch (Exception e) {
return false;
}
}
}
/** A sound as a rounded tile, lit while it plays. */
private final class TileRenderer extends JComponent implements ListCellRenderer<SoundboardSound> {
private SoundboardSound sound;
private boolean selected;
private boolean playing;
TileRenderer() {
setBorder(BorderFactory.createEmptyBorder());
}
@Override
public Component getListCellRendererComponent(JList<? extends SoundboardSound> list, SoundboardSound value,
int index, boolean isSelected, boolean cellHasFocus) {
sound = value;
selected = isSelected;
playing = soundboard.isPlaying(value);
boolean missing = !new File(value.file).isFile();
setToolTipText(missing ? "Missing: " + value.file : value.file);
setFont(list.getFont());
setForeground(missing ? Theme.idleClient() : playing ? Color.WHITE : list.getForeground());
return this;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int gap = UIScale.scale(3);
int arc = UIScale.scale(10);
int w = getWidth() - 2 * gap;
int h = getHeight() - 2 * gap;
g2.setColor(playing ? Theme.talking() : Theme.hover());
g2.fillRoundRect(gap, gap, w, h, arc, arc);
g2.setColor(selected ? Theme.accent() : Theme.border());
g2.drawRoundRect(gap, gap, w - 1, h - 1, arc, arc);
g2.setFont(getFont());
g2.setColor(getForeground());
FontMetrics fm = g2.getFontMetrics();
String text = ellipsize(sound.name, fm, w - 2 * UIScale.scale(8));
g2.drawString(text, (getWidth() - fm.stringWidth(text)) / 2,
(getHeight() - fm.getHeight()) / 2 + fm.getAscent());
g2.dispose();
}
private static String ellipsize(String text, FontMetrics fm, int width) {
if (fm.stringWidth(text) <= width) return text;
String dots = "…";
int end = text.length();
while (end > 0 && fm.stringWidth(text.substring(0, end) + dots) > width) end--;
return text.substring(0, end) + dots;
}
}
}