#2723 Full JavaFX application. (#2725)

* Removes the FlatLaf, JIDE, MigLayout and jiconfont-swing dependencies; the runtime image no longer includes javafx.swing.
* Removes the Swing channelizer developer viewers and the Swing spectrum panel; the symbol, sync and filter debug viewers are plain JavaFX windows.
* ChannelMapModel is no longer a Swing list model; removes unused Swing color menu items and models.
* Removes the Swing image methods from the icon classes; icons load as JavaFX images.
* Themes no longer use FlatLaf: each theme stores its palette and ThemeManager styles JavaFX only.
* The channel auto-start countdown, the event and message filter editor and the alias and deadlock alerts are now JavaFX.  The main window only stores split pane divider positions after the user drags a divider.
* Main window converted to JavaFX, with a spectrum and waterfall display that can be hidden.
* A hidden spectrum and waterfall is disposed so that it uses no processing or memory.  Show or hide it from the View menu, Ctrl+Shift+S, the display settings panel or the bar shown while it is hidden.
* Streaming status panel converted to JavaFX with status chips, a summary, configurable columns and a shortcut to the streaming editor.
* BroadcastModel is no longer a Swing table model.
* Audio panel converted to JavaFX and redesigned as a prominent playback display at the top of the main window.
* Mono and stereo outputs show one display per channel with the TO alias, icon and color, the FROM radio, system/site/channel, elapsed time, a level meter and per-channel mute. The master section has mute all, volume and audio device settings.
* Renames JavaFxWindowManager to WindowManager and removes its standalone launcher and the remaining Swing-era comments.

Co-authored-by: denny <dennis.sheirer@gmail.com>
This commit is contained in:
Denny Sheirer
2026-11-20 07:23:42 -05:00
committed by GitHub
parent 8431fe66ad
commit cfc9df4318
85 changed files with 4321 additions and 8578 deletions

View File

@@ -145,18 +145,13 @@ dependencies {
implementation 'ch.qos.logback:logback-classic:1.6.6'
implementation 'ch.qos.logback:logback-core:1.6.6'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.23.0'
implementation 'com.formdev:flatlaf:3.8'
implementation 'com.formdev:flatlaf-intellij-themes:3.8' //Not imported - Theme.java loads these themes by class name
implementation 'com.github.jiconfont:jiconfont-font_awesome:4.7.0.1'
implementation 'com.github.jiconfont:jiconfont-javafx:1.0.0'
implementation 'com.github.jiconfont:jiconfont-swing:1.0.1'
implementation('com.github.wendykierp:JTransforms:3.2') {
exclude group: 'junit' //JLargeArrays 1.7 declares junit as a compile dependency
}
implementation 'com.google.code.gson:gson:2.15.0'
implementation 'com.google.guava:guava:33.8.0-jre'
implementation 'com.jidesoft:jide-oss:3.6.18'
implementation 'com.miglayout:miglayout-swing:11.5.2'
implementation 'com.mpatric:mp3agic:0.9.1'
implementation 'commons-io:commons-io:2.22.0'
implementation 'io.github.dsheirer:jairspy:1.0.12.1' //Airspy tuners - GitHub release, see settings.gradle
@@ -195,7 +190,6 @@ tasks.withType(JavaCompile).configureEach {
*/
def jvmArgsWindows =
['--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED', //Needed for controls-fx.jar
'--add-exports=java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED', //windows users for JIDE
'--add-modules=jdk.incubator.vector', //Project Panama vector API is still in incubator
'--enable-preview', //Project Panama Vector API is still in incubator
'--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls
@@ -315,9 +309,9 @@ def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//jdk.incubator.vector - needed for Project Panama foreign function and vector apis
//jdk.accessibility is used with assistive technologies like screen readers
//java.management for JVM resource monitoring
//java.base, java.logging, java.net.http, java.prefs, javafx.controls, javafx.swing - required by sdrtrunk (jdeps)
//java.base, java.desktop, java.logging, java.net.http, java.prefs, javafx.controls - required by sdrtrunk (jdeps)
rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management',
'java.base', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'javafx.swing')
'java.base', 'java.desktop', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls')
//Use only the modules listed above. The runtime plugin's module auto-detection uses a bundled ASM library that
//can't read Java 27 class files and logs a 'Failed to scan' error for each sdrtrunk class. The jdeps module check

View File

@@ -1,81 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package com.sun.java.swing.plaf.windows;
import javax.swing.LookAndFeel;
import javax.swing.UIDefaults;
/**
* No-op stub for the JDK's Windows look-and-feel.
*
* <p>JIDE 3.6.18's {@code LookAndFeelFactory} contains compile-time
* {@code instanceof com.sun.java.swing.plaf.windows.WindowsLookAndFeel} checks throughout its
* dispatch logic. On Linux and macOS JDK builds that class is genuinely absent from
* {@code java.desktop}, so the JVM throws {@link NoClassDefFoundError} the first time JIDE's
* dispatch code executes the {@code instanceof} bytecode. That happens during
* {@link com.jidesoft.swing.JideSplitPane#updateUI()} on every LAF change.
*
* <p>This stub lives in the classpath so the class reference resolves on non-Windows JDKs.
* On Windows JDK builds the real {@code WindowsLookAndFeel} is loaded from the
* {@code java.desktop} module via the boot class loader and shadows this class.
*
* <p>The stub reports itself as not native and not supported - JIDE never instantiates this
* class, it only uses it for {@code instanceof} comparisons against the active LAF. Since
* sdrtrunk never installs this LAF, the {@code instanceof} check always returns false and
* JIDE proceeds to its next branch.
*/
public class WindowsLookAndFeel extends LookAndFeel
{
@Override
public String getName()
{
return "Windows (stub)";
}
@Override
public String getID()
{
return "WindowsStub";
}
@Override
public String getDescription()
{
return "Compatibility stub for JIDE's instanceof checks on non-Windows JDKs.";
}
@Override
public boolean isNativeLookAndFeel()
{
return false;
}
@Override
public boolean isSupportedLookAndFeel()
{
return false;
}
@Override
public UIDefaults getDefaults()
{
return new UIDefaults();
}
}

View File

@@ -19,14 +19,16 @@
package io.github.dsheirer.alias.action;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.message.IMessage;
import io.github.dsheirer.util.ThreadPool;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -62,23 +64,28 @@ public abstract class RecurringAction extends AliasAction
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS);
StringBuilder sb = new StringBuilder();
sb.append("<html><div width='250'>Alias [");
sb.append(alias.getName());
sb.append("] is active in message [");
sb.append(message.toString());
sb.append("]</div></html>");
final String text = sb.toString();
EventQueue.invokeLater(() -> {
JOptionPane.showMessageDialog(null, text,
"Alias Alert", JOptionPane.INFORMATION_MESSAGE);
String text = "Alias [" + alias.getName() + "] is active in message [" + message + "]";
Runnable dismissed = () -> {
dismiss(false);
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
});
};
if(FxToolkit.isStarted())
{
//The action repeats until the user closes the alert
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION, text);
alert.setTitle("Alias Alert");
alert.setHeaderText(null);
alert.setOnHidden(event -> dismissed.run());
alert.show();
});
}
else
{
dismissed.run();
}
break;
default:
}

View File

@@ -46,9 +46,8 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel;
public class BroadcastModel extends AbstractTableModel implements Listener<AudioRecording>
public class BroadcastModel implements Listener<AudioRecording>
{
private final static Logger mLog = LoggerFactory.getLogger(BroadcastModel.class);
@@ -57,18 +56,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
private static final String UNIQUE_NAME_REGEX = "(.*)\\((\\d*)\\)";
public static final int COLUMN_BROADCAST_SERVER_TYPE = 0;
public static final int COLUMN_STREAM_NAME = 1;
public static final int COLUMN_BROADCASTER_STATUS = 2;
public static final int COLUMN_BROADCASTER_QUEUE_SIZE = 3;
public static final int COLUMN_BROADCASTER_STREAMED_COUNT = 4;
public static final int COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT = 5;
public static final int COLUMN_BROADCASTER_AGED_OFF_COUNT = 6;
public static final int COLUMN_BROADCASTER_ERROR_COUNT = 7;
public static final String[] COLUMN_NAMES = new String[]
{"Stream Type", "Name", "Status", "Queued", "Streamed/Uploaded", "Duplicate Rejected", "Aged Off", "Upload Error"};
private ObservableList<ConfiguredBroadcast> mConfiguredBroadcasts =
FXCollections.observableArrayList(ConfiguredBroadcast.extractor());
private List<AudioRecording> mRecordingQueue = new CopyOnWriteArrayList<>();
@@ -171,8 +158,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
{
configuredBroadcast = new ConfiguredBroadcast(configuration);
mConfiguredBroadcasts.add(configuredBroadcast);
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
fireTableRowsInserted(index, index);
process(new BroadcastEvent(configuration, BroadcastEvent.Event.CONFIGURATION_ADD));
return configuredBroadcast;
}
@@ -274,8 +259,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
if(configuredBroadcast != null)
{
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
mConfiguredBroadcasts.remove(configuredBroadcast);
if(configuredBroadcast.hasAudioBroadcaster())
@@ -286,8 +269,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
}
process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE));
fireTableRowsDeleted(index, index);
}
}
@@ -354,13 +335,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
audioBroadcaster.setListener(mBroadcastEventListener);
mBroadcasterMap.put(audioBroadcaster.getBroadcastConfiguration().getId(), audioBroadcaster);
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(audioBroadcaster, BroadcastEvent.Event.BROADCASTER_ADD));
ThreadPool.CACHED.submit(() -> audioBroadcaster.start());
}
@@ -383,13 +357,6 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
broadcaster.removeListener();
broadcaster.dispose();
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE));
}
}
@@ -498,186 +465,17 @@ public class BroadcastModel extends AbstractTableModel implements Listener<Audio
ThreadPool.SCHEDULED.schedule(new DelayedBroadcasterStartup(broadcastConfiguration),
1, TimeUnit.SECONDS);
}
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
fireTableRowsUpdated(index, index);
break;
case CONFIGURATION_DELETE:
deleteBroadcaster(getConfiguredBroadcast(broadcastEvent.getBroadcastConfiguration()));
break;
}
}
else if(broadcastEvent.isAudioBroadcasterEvent())
{
ConfiguredBroadcast configuredBroadcast = getConfiguredBroadcast(broadcastEvent.getAudioBroadcaster());
int row = mConfiguredBroadcasts.indexOf(configuredBroadcast);
switch(broadcastEvent.getEvent())
{
case BROADCASTER_QUEUE_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_QUEUE_SIZE);
}
break;
case BROADCASTER_STATE_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_STATUS);
}
break;
case BROADCASTER_STREAMED_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_STREAMED_COUNT);
}
break;
case BROADCASTER_DUPLICATE_REJECTED_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT);
}
break;
case BROADCASTER_AGED_OFF_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_AGED_OFF_COUNT);
}
case BROADCASTER_ERROR_COUNT_CHANGE:
if(row >= 0)
{
fireTableCellUpdated(row, COLUMN_BROADCASTER_ERROR_COUNT);
}
break;
}
}
//Rebroadcast the event to any listeners of this model
broadcast(broadcastEvent);
}
@Override
public int getRowCount()
{
return mConfiguredBroadcasts.size();
}
@Override
public int getColumnCount()
{
return COLUMN_NAMES.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
try
{
if(rowIndex <= mConfiguredBroadcasts.size())
{
ConfiguredBroadcast configuredBroadcast = mConfiguredBroadcasts.get(rowIndex);
if(configuredBroadcast != null)
{
switch(columnIndex)
{
case COLUMN_BROADCAST_SERVER_TYPE:
return configuredBroadcast.getBroadcastServerType();
case COLUMN_STREAM_NAME:
return configuredBroadcast.getBroadcastConfiguration().getName();
case COLUMN_BROADCASTER_STATUS:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getBroadcastState();
}
else if(!configuredBroadcast.getBroadcastConfiguration().isEnabled())
{
return BroadcastState.DISABLED;
}
else if(!configuredBroadcast.getBroadcastConfiguration().isValid())
{
return BroadcastState.INVALID_SETTINGS;
}
else
{
return BroadcastState.ERROR;
}
case COLUMN_BROADCASTER_QUEUE_SIZE:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getAudioQueueSize();
}
break;
case COLUMN_BROADCASTER_STREAMED_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getStreamedAudioCount();
}
break;
case COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getDuplicateRejectedAudioCount();
}
break;
case COLUMN_BROADCASTER_AGED_OFF_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getAgedOffAudioCount();
}
break;
case COLUMN_BROADCASTER_ERROR_COUNT:
if(configuredBroadcast.hasAudioBroadcaster())
{
return configuredBroadcast.getAudioBroadcaster().getAudioErrorCount();
}
break;
default:
break;
}
}
}
}
catch(Exception e)
{
mLog.error("Error accessing data in broadcast model", e);
}
return null;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch(columnIndex)
{
case COLUMN_BROADCASTER_STATUS:
return BroadcastState.class;
case COLUMN_BROADCASTER_AGED_OFF_COUNT:
case COLUMN_BROADCASTER_QUEUE_SIZE:
case COLUMN_BROADCASTER_STREAMED_COUNT:
case COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT:
case COLUMN_BROADCASTER_ERROR_COUNT:
return Integer.class;
case COLUMN_BROADCAST_SERVER_TYPE:
return BroadcastServerType.class;
case COLUMN_STREAM_NAME:
default:
return String.class;
}
}
@Override
public String getColumnName(int column)
{
if(0 <= column && column < COLUMN_NAMES.length)
{
return COLUMN_NAMES[column];
}
return null;
}
/**
* Cleanup method to remove a temporary recording file from disk.
*

View File

@@ -1,186 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.broadcast;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
import java.awt.Color;
import java.awt.Component;
import net.miginfocom.swing.MigLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
/**
* Table of broadcast streams and statuses.
*/
public class BroadcastStatusPanel extends JPanel
{
private JTable mTable;
private JTableColumnWidthMonitor mColumnWidthMonitor;
private JScrollPane mScrollPane;
private BroadcastModel mBroadcastModel;
private UserPreferences mUserPreferences;
private String mPreferenceKey;
/**
* Constructs an instance
* @param broadcastModel to access the streams
* @param userPreferences for configuring the panel
* @param preferenceKey to store column preferences for this panel.
*/
public BroadcastStatusPanel(BroadcastModel broadcastModel, UserPreferences userPreferences, String preferenceKey)
{
mBroadcastModel = broadcastModel;
mUserPreferences = userPreferences;
mPreferenceKey = preferenceKey;
init();
}
public JTable getTable()
{
return mTable;
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));
mTable = new JTable(mBroadcastModel);
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)mTable.getDefaultRenderer(String.class);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCASTER_STATUS).setCellRenderer(new StatusCellRenderer());
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCAST_SERVER_TYPE).setCellRenderer(new ServerTypeRenderer());
mColumnWidthMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTable, mPreferenceKey);
mScrollPane = new JScrollPane(mTable);
add(mScrollPane);
}
public class ServerTypeRenderer extends DefaultTableCellRenderer
{
public ServerTypeRenderer()
{
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof BroadcastServerType broadcastServerType)
{
component.setText(broadcastServerType.toString());
Icon icon = new Icon("empty", broadcastServerType.getIconPath());
ImageIcon imageIcon = icon.getIcon();
ImageIcon scaledIcon = IconModel.getScaledIcon(imageIcon, 13);
component.setIcon(scaledIcon);
}
else
{
component.setText(null);
component.setIcon(null);
}
return component;
}
}
/**
* Custom cell renderer for the broadcast state column.
*/
public class StatusCellRenderer extends DefaultTableCellRenderer
{
public StatusCellRenderer()
{
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected)
{
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
else
{
if(value instanceof BroadcastState)
{
BroadcastState state = (BroadcastState)value;
if(state == BroadcastState.CONNECTED)
{
setBackground(Color.GREEN);
setForeground(table.getForeground());
}
else if(state == BroadcastState.DISABLED)
{
setBackground(table.getBackground());
//Use the LAF's disabled-foreground so the cell reads correctly on any
//theme - LIGHT_GRAY is invisible on a light background.
Color disabled = javax.swing.UIManager.getColor("Label.disabledForeground");
setForeground(disabled != null ? disabled : table.getForeground());
}
else if(state == BroadcastState.INVALID_SETTINGS ||
state == BroadcastState.NETWORK_UNAVAILABLE)
{
setBackground(Color.YELLOW);
setForeground(table.getForeground());
}
else if(state.isErrorState())
{
setBackground(Color.RED);
setForeground(table.getForeground());
}
else
{
setBackground(table.getBackground());
setForeground(table.getForeground());
}
}
else
{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
return this;
}
}
}

View File

@@ -151,6 +151,30 @@ public class ConfiguredBroadcast
return mAudioBroadcaster != null;
}
/**
* Current status for display: the broadcaster's state when there is a broadcaster, otherwise the reason that
* there isn't one.
*/
public BroadcastState getStatus()
{
AbstractAudioBroadcaster broadcaster = mAudioBroadcaster;
if(broadcaster != null)
{
return broadcaster.getBroadcastState();
}
else if(!mBroadcastConfiguration.isEnabled())
{
return BroadcastState.DISABLED;
}
else if(!mBroadcastConfiguration.isValid())
{
return BroadcastState.INVALID_SETTINGS;
}
return BroadcastState.ERROR;
}
/**
* Creates an observable property extractor for use with observable lists to detect changes internal to this object.
*/

View File

@@ -31,6 +31,7 @@ import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import java.util.Arrays;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
@@ -58,6 +59,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>();
private final UserPreferences mUserPreferences;
private final String mChannelName;
private final AtomicInteger mPeakLevelBits = new AtomicInteger();
private AudioSegment mCurrentAudioSegment;
private Listener<IdentifierCollection> mIdentifierCollectionListener;
@@ -174,20 +176,68 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
public float[] getAudio()
{
if(mAudioBuffer.isFull())
{
float[] audio = mAudioBuffer.get();
float[] audio = getNextAudio();
if(audio != null)
{
updatePeakLevel(audio);
//Muted channels return silence. The peak level is measured before muting so that the display can still
//show that the muted channel has audio.
if(isMuted())
{
return new float[SAMPLES_PER_INTERVAL];
}
else
}
return audio;
}
/**
* Peak absolute sample value of the audio provided by this channel since the last call to this method, measured
* before muting. The audio output pulls audio ahead of playback, so this leads what is heard by the playback
* device buffer latency. Thread safe.
* @return peak level in the range 0.0 to 1.0 (or higher, if the audio is clipping) and resets it to zero.
*/
public float getAndResetPeakLevel()
{
return Float.intBitsToFloat(mPeakLevelBits.getAndSet(0));
}
/**
* Updates the peak level with the maximum absolute sample value of the audio buffer.
*/
private void updatePeakLevel(float[] audio)
{
float peak = 0.0f;
for(float sample: audio)
{
float magnitude = Math.abs(sample);
if(magnitude > peak)
{
return audio;
peak = magnitude;
}
}
final float bufferPeak = peak;
//Non-negative float bit patterns sort the same as the float values
mPeakLevelBits.accumulateAndGet(Float.floatToIntBits(bufferPeak), Math::max);
}
/**
* Next interval of audio from the audio buffer or the current audio segment, before muting.
* @return audio or null
*/
private float[] getNextAudio()
{
if(mAudioBuffer.isFull())
{
return mAudioBuffer.get();
}
if(mCurrentAudioSegment == null)
{
loadNextAudioSegment();
@@ -249,12 +299,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
audio = mAudioBuffer.flush();
}
//Finally, if we have buffer audio and we're muted, return silence
if(isMuted() && audio != null)
{
audio = new float[SAMPLES_PER_INTERVAL];
}
return audio;
}

View File

@@ -1,373 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.playback;
import com.google.common.base.Joiner;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.settings.ColorSetting;
import io.github.dsheirer.settings.Setting;
import io.github.dsheirer.settings.SettingChangeListener;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* UI to wrap an audio channel and provide display of metadata and playback state information.
*/
public class AudioChannelPanel extends JPanel implements Listener<AudioEvent>, SettingChangeListener
{
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(AudioChannelPanel.class);
public static final String PROPERTY_PREFIX = "audio.channel.panel.color.";
public static final String PROPERTY_COLOR_BACKGROUND = PROPERTY_PREFIX + "background";
public static final String PROPERTY_COLOR_LABEL = PROPERTY_PREFIX + "label";
public static final String PROPERTY_COLOR_MUTED = PROPERTY_PREFIX + "muted";
public static final String PROPERTY_COLOR_VALUE = PROPERTY_PREFIX + "value";
private final AudioChannel mAudioChannel;
private final AliasModel mAliasModel;
private final IconModel mIconModel;
private final SettingsManager mSettingsManager;
private final UserPreferences mUserPreferences;
private final TalkgroupFormatPreference mTalkgroupFormatPreference;
private Identifier mIdentifier;
private List<Alias> mAliases = Collections.EMPTY_LIST;
private final Lock mLock = new ReentrantLock();
private final Font mFont = new Font(Font.MONOSPACED, Font.PLAIN, 16);
private final Color mBackgroundColor;
private final Color mLabelColor;
private final Color mMutedColor;
private final Color mValueColor;
private final JLabel mMutedLabel = new JLabel("M");
private JLabel mChannelName = new JLabel(" ");
private final JLabel mIconLabel = new JLabel(" ");
private final JLabel mIdentifierLabel = new JLabel("-----");
/**
* Constructs an instance
* @param audioChannel to wrap by this panel
* @param aliasModel for alias lookup
* @param iconModel for icon lookup
* @param settingsManager for monitoring changes to tone insertion
* @param userPreferences for lookup of tone and other preferences
*/
public AudioChannelPanel(AudioChannel audioChannel, AliasModel aliasModel, IconModel iconModel,
SettingsManager settingsManager, UserPreferences userPreferences)
{
mIconModel = iconModel;
mSettingsManager = settingsManager;
mSettingsManager.addListener(this);
mAliasModel = aliasModel;
mUserPreferences = userPreferences;
mTalkgroupFormatPreference = mUserPreferences.getTalkgroupFormatPreference();
mAudioChannel = audioChannel;
if(mAudioChannel != null)
{
mAudioChannel.addAudioEventListener(this);
mAudioChannel.setIdentifierCollectionListener(new AudioMetadataProcessor());
}
mBackgroundColor = SystemProperties.getInstance().get(PROPERTY_COLOR_BACKGROUND, Color.BLACK);
mLabelColor = SystemProperties.getInstance().get(PROPERTY_COLOR_LABEL, Color.LIGHT_GRAY);
mMutedColor = SystemProperties.getInstance().get(PROPERTY_COLOR_MUTED, Color.RED);
mValueColor = SystemProperties.getInstance().get(PROPERTY_COLOR_VALUE, Color.GREEN);
init();
}
/**
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
updateLabels();
}
}
public void dispose()
{
//Deregister from receiving preference update notifications
MyEventBus.getGlobalEventBus().unregister(this);
if(mAudioChannel != null)
{
mAudioChannel.removeAudioEventListener(this);
mAudioChannel.removeAudioMetadataListener();
}
}
private void init()
{
//Register to receive preference updates
MyEventBus.getGlobalEventBus().register(this);
setLayout(new MigLayout("align center center, insets 0 0 0 0",
"[][][align right]0[grow,fill]", ""));
setBackground(mBackgroundColor);
mMutedLabel.setFont(mFont);
mMutedLabel.setForeground(mMutedColor);
mMutedLabel.setVisible(false);
add(mMutedLabel);
mChannelName = new JLabel(mAudioChannel != null ? mAudioChannel.getChannelName() : " ");
mChannelName.setFont(mFont);
mChannelName.setForeground(mLabelColor);
add(mChannelName);
mIconLabel.setFont(mFont);
mIconLabel.setForeground(mValueColor);
add(mIconLabel);
mIdentifierLabel.setFont(mFont);
mIdentifierLabel.setForeground(mValueColor);
add(mIdentifierLabel, "wmin 10lp");
}
@Override
public void receive(final AudioEvent audioEvent)
{
switch(audioEvent.getType())
{
case AUDIO_STOPPED:
EventQueue.invokeLater(this::resetLabels);
break;
case AUDIO_MUTED:
case AUDIO_UNMUTED:
EventQueue.invokeLater(() -> mMutedLabel.setVisible(mAudioChannel.isMuted()));
break;
default:
break;
}
}
/**
* Resets the from and to labels.
*/
private void resetLabels()
{
//Protect access to mIdentifier and mAliases
mLock.lock();
try
{
boolean updated = mIdentifier != null;
mIdentifier = null;
mAliases = Collections.EMPTY_LIST;
//Hold the lock through the label update
if(updated)
{
updateLabels();
}
}
finally
{
mLock.unlock();
}
}
private void updateIdentifiers(IdentifierCollection identifierCollection)
{
if(identifierCollection == null || identifierCollection.isEmpty())
{
resetLabels();
return;
}
List<Identifier> toIds = identifierCollection.getIdentifiers(IdentifierClass.USER, Role.TO);
if(toIds.isEmpty())
{
resetLabels();
return;
}
boolean updated = false;
//Protect access to mIdentifier and mAliases
mLock.lock();
try
{
if(toIds.size() == 1)
{
Identifier currentIdentifier = mIdentifier;
if(currentIdentifier == null || currentIdentifier != toIds.get(0))
{
mIdentifier = toIds.get(0);
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
if(aliasList != null)
{
mAliases = aliasList.getAliases(mIdentifier);
}
updated = true;
}
}
else
{
mIdentifier = toIds.get(0);
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
if(aliasList != null)
{
mAliases = aliasList.getAliases(mIdentifier);
}
updated = true;
}
//Hold the lock through the label update
if(updated)
{
updateLabels();
}
}
finally
{
mLock.unlock();
}
}
/**
* Updates the alias label with text and icon from the alias.
*/
private void updateLabels()
{
String identifier = null;
String iconName = null;
//Protect access to mIdentifier and mAliases
mLock.lock();
try
{
if(mAliases.size() == 1)
{
identifier = mAliases.get(0).getName();
iconName = mAliases.get(0).getIconName();
}
else if(mAliases.size() > 1)
{
identifier = Joiner.on(", ").skipNulls().join(mAliases);
}
if(identifier == null && mIdentifier != null)
{
identifier = mTalkgroupFormatPreference.format(mIdentifier);
}
if(identifier == null)
{
identifier = "-----";
}
final ImageIcon icon = iconName != null ? mIconModel.getIcon(iconName, 18) : null;
final String identifierText = identifier;
EventQueue.invokeLater(() -> {
mIdentifierLabel.setText(identifierText);
mIconLabel.setIcon(icon);
});
}
finally
{
mLock.unlock();
}
}
/**
* Processes audio metadata to update this panel's display values
*/
public class AudioMetadataProcessor implements Listener<IdentifierCollection>
{
@Override
public void receive(final IdentifierCollection identifierCollection)
{
updateIdentifiers(identifierCollection);
}
}
@Override
public void settingChanged(Setting setting)
{
if(setting instanceof ColorSetting)
{
ColorSetting colorSetting = (ColorSetting)setting;
switch(colorSetting.getColorSettingName())
{
case CHANNEL_STATE_LABEL_DECODER:
EventQueue.invokeLater(() -> {
if(mIdentifierLabel != null)
{
mIdentifierLabel.setForeground(mLabelColor);
}
if(mIconLabel != null)
{
mIconLabel.setForeground(mLabelColor);
}
});
break;
default:
break;
}
}
}
@Override
public void settingDeleted(Setting setting)
{
}
}

View File

@@ -1,98 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.playback;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.IAudioController;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.Component;
import net.miginfocom.swing.MigLayout;
import javax.swing.JPanel;
import javax.swing.JSeparator;
/**
* Displays one or more audio channel panels.
*/
public class AudioChannelsPanel extends JPanel
{
/**
* Constructs an instance
* @param iconModel for icon access
* @param userPreferences to monitor for audio playback changes
* @param settingsManager for tone insertion settings
* @param controller for the audio channels
* @param aliasModel for accessing aliases
*/
public AudioChannelsPanel(IconModel iconModel, UserPreferences userPreferences, SettingsManager settingsManager,
IAudioController controller, AliasModel aliasModel)
{
setLayout(new MigLayout("insets 0 0 0 0",
"[][sizegroup abc,grow,fill][][sizegroup abc,grow,fill]", "[grow,fill]"));
setBackground(Color.BLACK);
addSeparator();
for(int x = 0; x < controller.getAudioChannels().size(); x++)
{
add(new AudioChannelPanel(controller.getAudioChannels().get(x), aliasModel, iconModel, settingsManager, userPreferences));
if(x < controller.getAudioChannels().size() - 1)
{
addSeparator();
}
}
/* Add an empty channel panel so that the panel is sized appropriately
* for either a single channel or two channels */
if(controller.getAudioChannels().size() == 1)
{
addSeparator();
add(new AudioChannelPanel(null, aliasModel, iconModel, settingsManager, userPreferences), "growx");
}
}
/**
* Prepares for dispose to allow deregistering from services
*/
public void dispose()
{
for(Component component: getComponents())
{
if(component instanceof AudioChannelPanel)
{
((AudioChannelPanel)component).dispose();
}
}
}
/**
* Adds a separator to this panel.
*/
private void addSeparator()
{
JSeparator separator = new JSeparator(JSeparator.VERTICAL);
separator.setBackground(Color.DARK_GRAY);
add(separator);
}
}

View File

@@ -1,305 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.playback;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import jiconfont.icons.font_awesome.FontAwesome;
import io.github.dsheirer.gui.theme.ThemedFontIcon;
import net.miginfocom.swing.MigLayout;
import javax.sound.sampled.FloatControl;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
/**
* Audio playback panel
*/
public class AudioPanel extends JPanel implements Listener<AudioEvent>
{
private static final ImageIcon MUTED_ICON = IconModel.getScaledIcon("images/audio_muted.png", 20);
private static final ImageIcon UNMUTED_ICON = IconModel.getScaledIcon("images/audio_unmuted.png", 20);
private final AliasModel mAliasModel;
private final AudioPlaybackManager mAudioPlaybackManager;
private final IconModel mIconModel;
private final SettingsManager mSettingsManager;
private final UserPreferences mUserPreferences;
private AudioChannelsPanel mAudioChannelsPanel;
private JButton mMuteButton;
/**
* Constructs an instance
* @param iconModel for icon lookup
* @param userPreferences for preference lookup
* @param settingsManager to monitor for changes
* @param audioPlaybackManager for accessing the audio output
* @param aliasModel for alias lookup
*/
public AudioPanel(IconModel iconModel, UserPreferences userPreferences, SettingsManager settingsManager,
AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel)
{
mIconModel = iconModel;
mSettingsManager = settingsManager;
mAudioPlaybackManager = audioPlaybackManager;
mAliasModel = aliasModel;
mUserPreferences = userPreferences;
mAudioPlaybackManager.addAudioEventListener(this);
init();
}
/**
* Initialize the display
*/
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[]0[grow,fill]", "[fill]0[]"));
setBackground(Color.BLACK);
mMuteButton = new MuteButton();
mMuteButton.setBackground(getBackground());
add(mMuteButton);
mAudioChannelsPanel = new AudioChannelsPanel(mIconModel, mUserPreferences, mSettingsManager, mAudioPlaybackManager, mAliasModel);
add(mAudioChannelsPanel);
addMouseListener(new MouseSelectionListener());
}
/**
* Receive audio event notifications from the audio playback controller
*/
@Override
public void receive(AudioEvent event)
{
switch(event.getType())
{
case AUDIO_CONFIGURATION_CHANGE_STARTED:
break;
case AUDIO_CONFIGURATION_CHANGE_COMPLETE:
EventQueue.invokeLater(() -> {
remove(mAudioChannelsPanel);
mAudioChannelsPanel.dispose();
mAudioChannelsPanel = new AudioChannelsPanel(mIconModel, mUserPreferences, mSettingsManager, mAudioPlaybackManager, mAliasModel);
add(mAudioChannelsPanel);
mAudioChannelsPanel.repaint();
revalidate();
repaint();
});
break;
default:
break;
}
}
/**
* Audio output mute control menu item.
*/
public static class AudioOutputMuteItem extends JMenuItem
{
private final AudioOutput mAudioOutput;
/**
* Constructs an instance
* @param audioOutput to mute/unmute
*/
public AudioOutputMuteItem(AudioOutput audioOutput)
{
super(audioOutput.isMuted() ? "Unmute" : "Mute");
mAudioOutput = audioOutput;
addActionListener(e -> mAudioOutput.setMuted(!mAudioOutput.isMuted()));
}
}
/**
* Mouse listener
*/
public class MouseSelectionListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent event)
{
if(SwingUtilities.isRightMouseButton(event))
{
JPopupMenu popup = new JPopupMenu();
JMenuItem outputMenu = new JMenuItem("Audio Playback Device ...");
Icon icon = new ThemedFontIcon(FontAwesome.COG, 14);
outputMenu.setIcon(icon);
outputMenu.addActionListener(e -> MyEventBus.getGlobalEventBus()
.post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.AUDIO_OUTPUT)));
popup.add(outputMenu);
//Add optional gain controller for th eaudio output
if(mAudioPlaybackManager.getAudioOutput() != null && mAudioPlaybackManager.getAudioOutput().hasGainControl())
{
popup.add(new JPopupMenu.Separator());
JMenuItem volume = new JMenuItem("Audio Volume");
volume.setEnabled(false);
Icon volumeIcon = new ThemedFontIcon(FontAwesome.VOLUME_UP, 14);
volume.setIcon(volumeIcon);
popup.add(volume);
popup.add(new VolumeSlider(mAudioPlaybackManager.getAudioOutput().getGainControl()));
}
popup.show(event.getComponent(), event.getX(), event.getY());
}
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
}
@Override
public void mouseExited(MouseEvent e)
{
}
}
/**
* Audio volume (gain) adjustment slider control
*/
public static class VolumeSlider extends JSlider
{
private final FloatControl mFloatControl;
/**
* Constructs an instance
* @param control to be controlled
*/
public VolumeSlider(FloatControl control)
{
super(0, 100, 0);
setMajorTickSpacing(25);
setMinorTickSpacing(5);
setPaintTicks(true);
setPaintLabels(true);
mFloatControl = control;
setValue(getIntegerValue(mFloatControl.getValue()));
addChangeListener(event -> mFloatControl.shift(mFloatControl.getValue(),
getFloatValue(VolumeSlider.this.getValue()),
1000));
addMouseListener(new MouseListener()
{
@Override
public void mouseClicked(MouseEvent event)
{
if(event.getClickCount() == 2)
{
VolumeSlider.this.setValue(50);
}
}
public void mouseReleased(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
});
}
/**
* Converts the integer value to a floating point value to use in the
* float control. Assumes an integer value of 50 is the 0.0 dB mid
* point (ie no gain ) value.
*/
private int getIntegerValue(float value)
{
if(value == 0.0f)
{
return 50;
}
else if(value < 0.0f)
{
float ratio = value / mFloatControl.getMinimum();
return 50 - (int) (ratio * 50.0f);
}
else
{
float ratio = value / mFloatControl.getMaximum();
return 50 + (int) (ratio * 50.0f);
}
}
private float getFloatValue(int value)
{
if(value == 50)
{
return 0.0f;
}
else if(value < 50)
{
return (float) (50 - value) / 50.0f * mFloatControl.getMinimum();
}
else
{
return (float) (value - 50) / 50.0f * mFloatControl.getMaximum();
}
}
}
/**
* Mute button to mute all audio output channels exposed by the audio
* controller
*/
public class MuteButton extends JButton
{
private boolean mMuted = false;
public MuteButton()
{
setIcon(UNMUTED_ICON);
setBorderPainted(false);
getAccessibleContext().setAccessibleName("Mute");
addActionListener(e -> {
mMuted = !mMuted;
mAudioPlaybackManager.getAudioOutput().setMuted(mMuted);
EventQueue.invokeLater(() -> {
setIcon(mMuted ? MUTED_ICON : UNMUTED_ICON);
getAccessibleContext().setAccessibleName(mMuted ? "Unmute" : "Mute");
});
});
}
}
}

View File

@@ -1,120 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.controller;
import com.jidesoft.swing.JideTabbedPane;
import io.github.dsheirer.audio.playback.AudioPanel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.nowplaying.NowPlayingPanel;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.map.MapPanel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerViewPanel;
import java.awt.Dimension;
import jiconfont.icons.font_awesome.FontAwesome;
import io.github.dsheirer.gui.theme.ThemedFontIcon;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ControllerPanel extends JPanel
{
private final static Logger mLog = LoggerFactory.getLogger(ControllerPanel.class);
private static final long serialVersionUID = 1L;
private int mSettingsTabIndex = -1;
private AudioPanel mAudioPanel;
private NowPlayingPanel mNowPlayingPanel;
private MapPanel mMapPanel;
private TunerViewPanel mTunerManagerPanel;
private JideTabbedPane mTabbedPane;
public ControllerPanel(PlaylistManager playlistManager, AudioPlaybackManager audioPlaybackManager,
IconModel iconModel, MapService mapService, SettingsManager settingsManager,
TunerManager tunerManager, UserPreferences userPreferences, boolean detailTabsVisible)
{
mAudioPanel = new AudioPanel(iconModel, userPreferences, settingsManager, audioPlaybackManager,
playlistManager.getAliasModel());
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, detailTabsVisible);
mMapPanel = new MapPanel(mapService, iconModel, userPreferences,
playlistManager.getRadioReference() != null ? playlistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(playlistManager));
mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences);
init();
}
/**
* Now playing panel.
*/
public NowPlayingPanel getNowPlayingPanel()
{
return mNowPlayingPanel;
}
private void init()
{
//Disable visual padding. MigLayout otherwise assumes the tabbed pane has native Aqua margins on macOS and
//expands it past the bounds of this panel, clipping the tab content on the left, right and bottom edges.
setLayout(new MigLayout("insets 0 0 0 0, novisualpadding", "[grow,fill]", "[]0[grow,fill]0[]"));
add(mAudioPanel, "wrap");
mTabbedPane = new JideTabbedPane()
{
@Override
public void setSelectedIndex(int index)
{
if(index == mSettingsTabIndex)
{
MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest());
}
else
{
super.setSelectedIndex(index);
}
}
};
mTabbedPane.setFont(this.getFont());
mTabbedPane.addTab("Now Playing", mNowPlayingPanel);
mTabbedPane.addTab("Map", mMapPanel);
mTabbedPane.addTab("Tuners", mTunerManagerPanel);
Icon playIcon = new ThemedFontIcon(FontAwesome.PLAY_CIRCLE_O, 20);
mTabbedPane.addTab("Playlist Editor", playIcon, new JLabel("Show Playlist Manager"));
mSettingsTabIndex = mTabbedPane.getTabCount() - 1;
//Set preferred size to influence the split between these panels
mTabbedPane.setPreferredSize(new Dimension(880, 500));
add(mTabbedPane, "wrap");
}
}

View File

@@ -1,105 +0,0 @@
/*******************************************************************************
* sdr-trunk
* Copyright (C) 2014-2018 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/
package io.github.dsheirer.controller.channel;
import javax.swing.table.AbstractTableModel;
import java.util.List;
/**
* Auto-Start Channel Model
*/
public class AutoStartChannelModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
public static final int COLUMN_ORDER = 0;
public static final int COLUMN_SYSTEM = 1;
public static final int COLUMN_SITE = 2;
public static final int COLUMN_NAME = 3;
public static final int COLUMN_DECODER = 4;
private static final String[] COLUMN_NAMES = new String[] {"Order", "System", "Site", "Name", "Decoder"};
private List<Channel> mChannels;
public AutoStartChannelModel(List<Channel> autoStartChannels)
{
mChannels = autoStartChannels;
}
@Override
public int getRowCount()
{
return mChannels.size();
}
@Override
public int getColumnCount()
{
return COLUMN_NAMES.length;
}
@Override
public String getColumnName(int columnIndex)
{
if(columnIndex < COLUMN_NAMES.length)
{
return COLUMN_NAMES[columnIndex];
}
return null;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
Channel channel = mChannels.get(rowIndex);
switch(columnIndex)
{
case COLUMN_ORDER:
return channel.getAutoStartOrder();
case COLUMN_SYSTEM:
return channel.getSystem();
case COLUMN_SITE:
return channel.getSite();
case COLUMN_NAME:
return channel.getName();
case COLUMN_DECODER:
return channel.getDecodeConfiguration().getDecoderType().getShortDisplayString();
}
return null;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
throw new IllegalArgumentException("Not yet implemented");
}
}

View File

@@ -1,242 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.controller.channel;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.util.ThreadPool;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class ChannelAutoStartFrame extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelAutoStartFrame.class);
private Listener<ChannelEvent> mChannelEventListener;
private List<Channel> mChannels;
private JLabel mCountdownLabel;
private JButton mStartButton;
private JButton mCancelButton;
private JTable mChannelTable;
private AtomicBoolean mChannelsStarted = new AtomicBoolean();
private int mAutoStartTimeoutSeconds;
private ScheduledFuture<?> mTimerFuture;
/**
* Creates and displays a channel auto-start gui for presenting the user with a list of channels that
* will be automatically started once the countdown timer reaches zero, or the user chooses to start
* now or cancel.
*
* @param listener to receive channel start/enable request(s)
* @param channels to auto-start
*/
public ChannelAutoStartFrame(Listener<ChannelEvent> listener, List<Channel> channels, UserPreferences userPreferences)
{
mChannelEventListener = listener;
mChannels = channels;
mAutoStartTimeoutSeconds = userPreferences.getApplicationPreference().getChannelAutoStartTimeout();
init();
EventQueue.invokeLater(() -> {
setVisible(true);
toFront();
startTimer();
});
}
private void init()
{
setTitle("Auto-Start Channels");
setSize(new Dimension(400, 300));
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent event)
{
mLog.info("Channel auto-start canceled by user - window closed");
stopTimer();
super.windowClosing(event);
}
});
JPanel panel = new JPanel();
panel.setLayout(new MigLayout("", "[grow,fill][grow,fill]",
"[][][grow,fill][]"));
panel.add(new JLabel("The following channels will be automatically"), "span");
mCountdownLabel = new JLabel(getCountdownText(mAutoStartTimeoutSeconds));
panel.add(mCountdownLabel, "span");
panel.add(new JScrollPane(getChannelTable()), "span");
mStartButton = new JButton("Start Now");
mStartButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLog.info("Starting [" + mChannels.size() + "] channels now - user invoked");
startChannels();
stopTimer();
}
});
panel.add(mStartButton);
mCancelButton = new JButton("Cancel");
mCancelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLog.info("Channel auto-start canceled by user");
stopTimer();
}
});
panel.add(mCancelButton);
setContentPane(panel);
}
private String getCountdownText(int value)
{
return "started in: " + value + " seconds.";
}
/**
* Updates the countdown text label on the swing event thread
*
* @param value for the countdown
*/
private void updateCountdownText(final int value)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
mCountdownLabel.setText(getCountdownText(value));
}
});
}
/**
* Creates (once) a table of auto-start channels
*/
private JTable getChannelTable()
{
if(mChannelTable == null)
{
AutoStartChannelModel model = new AutoStartChannelModel(mChannels);
mChannelTable = new JTable(model);
}
return mChannelTable;
}
/**
* Sends an enable (ie start) request for each of the auto start channels.
*
* This method is thread-safe and will only be executed once.
*
* Although the redundant channel-start request would be ignored, this once-only will prevent the chance
* that both the timer and the user would attempt to start the channels at the same time.
*/
private void startChannels()
{
if(mChannelsStarted.compareAndSet(false, true))
{
if(mChannelEventListener != null)
{
for(Channel channel : mChannels)
{
mChannelEventListener.receive(new ChannelEvent(channel, ChannelEvent.Event.REQUEST_ENABLE));
}
}
}
}
/**
* Starts the countdown timer to fire once a second.
*/
private void startTimer()
{
if(mTimerFuture == null)
{
mTimerFuture = ThreadPool.SCHEDULED.scheduleAtFixedRate(new CountdownTimer(), 0, 1, TimeUnit.SECONDS);
}
}
/**
* Stops the countdown timer and disposes this frame
*/
private void stopTimer()
{
if(mTimerFuture != null)
{
mTimerFuture.cancel(true);
mTimerFuture = null;
}
EventQueue.invokeLater(() -> dispose());
}
/**
* Updates the countdown text and auto-starts the channels once the timer falls below zero.
*/
public class CountdownTimer implements Runnable
{
private int mCount = mAutoStartTimeoutSeconds;
@Override
public void run()
{
if(mCount >= 0)
{
updateCountdownText(mCount);
mCount--;
}
else
{
mLog.info("Starting [" + mChannels.size() + "] now - timer invoked");
startChannels();
stopTimer();
}
}
}
}

View File

@@ -0,0 +1,215 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.controller.channel;
import io.github.dsheirer.gui.ApplicationIcons;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.util.ThreadPool;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Lists the channels that are set to start automatically and starts them when the countdown ends. The user can
* start them now, or cancel by pressing Cancel or closing the window.
*/
public class ChannelAutoStartWindow
{
private static final Logger mLog = LoggerFactory.getLogger(ChannelAutoStartWindow.class);
private final Listener<ChannelEvent> mChannelEventListener;
private final List<Channel> mChannels;
private final int mTimeoutSeconds;
private final AtomicBoolean mFinished = new AtomicBoolean();
private final Stage mStage = new Stage();
private final Label mCountdownLabel = new Label();
private final ProgressBar mProgressBar = new ProgressBar(1.0);
private final Timeline mTimeline;
private int mRemainingSeconds;
/**
* Constructs an instance. JavaFX thread only.
* @param listener to receive the channel start requests
* @param channels to start, in auto-start order
* @param userPreferences for the countdown length
* @param owner window, or null
*/
public ChannelAutoStartWindow(Listener<ChannelEvent> listener, List<Channel> channels,
UserPreferences userPreferences, Window owner)
{
mChannelEventListener = listener;
mChannels = channels;
mTimeoutSeconds = Math.max(0, userPreferences.getApplicationPreference().getChannelAutoStartTimeout());
mRemainingSeconds = mTimeoutSeconds;
Label title = new Label("Starting " + channels.size() + (channels.size() == 1 ? " channel" : " channels"));
title.setStyle("-fx-font-size: 1.25em; -fx-font-weight: bold;");
mProgressBar.setMaxWidth(Double.MAX_VALUE);
TableView<Channel> table = new TableView<>(FXCollections.observableArrayList(channels));
table.getColumns().addAll(List.of(
column("Order", 60, channel -> String.valueOf(channel.getAutoStartOrder())),
column("System", 140, Channel::getSystem),
column("Site", 120, Channel::getSite),
column("Name", 180, Channel::getName),
column("Decoder", 100, channel -> channel.getDecodeConfiguration().getDecoderType()
.getShortDisplayString())));
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN);
VBox.setVgrow(table, Priority.ALWAYS);
Button startButton = new Button("Start Now");
startButton.setDefaultButton(true);
startButton.setOnAction(event -> {
mLog.info("Starting [" + mChannels.size() + "] channels now - user invoked");
finish(true);
});
Button cancelButton = new Button("Cancel");
cancelButton.setCancelButton(true);
cancelButton.setOnAction(event -> {
mLog.info("Channel auto-start canceled by user");
finish(false);
});
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox buttons = new HBox(8, spacer, cancelButton, startButton);
buttons.setAlignment(Pos.CENTER_RIGHT);
VBox root = new VBox(8, title, mCountdownLabel, mProgressBar, table, buttons);
root.setPadding(new Insets(12));
Scene scene = new Scene(root, 640, 340);
ThemeManager.getInstance().register(scene);
mStage.setScene(scene);
mStage.setTitle("Auto-Start Channels");
ApplicationIcons.apply(mStage);
if(owner != null)
{
mStage.initOwner(owner);
}
mStage.setOnCloseRequest(event -> {
mLog.info("Channel auto-start canceled by user - window closed");
finish(false);
});
mTimeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> tick()));
mTimeline.setCycleCount(Timeline.INDEFINITE);
updateCountdown();
}
/**
* Shows the window and starts the countdown. JavaFX thread only.
*/
public void show()
{
mStage.show();
mStage.toFront();
if(mTimeoutSeconds == 0)
{
mLog.info("Starting [" + mChannels.size() + "] now - no auto-start delay");
finish(true);
}
else
{
mTimeline.play();
}
}
private void tick()
{
mRemainingSeconds--;
if(mRemainingSeconds <= 0)
{
mLog.info("Starting [" + mChannels.size() + "] now - timer invoked");
finish(true);
}
else
{
updateCountdown();
}
}
private void updateCountdown()
{
mCountdownLabel.setText("These channels start automatically in " + mRemainingSeconds +
(mRemainingSeconds == 1 ? " second." : " seconds."));
mProgressBar.setProgress(mTimeoutSeconds > 0 ? (double)mRemainingSeconds / mTimeoutSeconds : 0.0);
}
/**
* Stops the countdown, closes the window and optionally starts the channels. Only the first call has an
* effect, so that the timer and the user can't both start the channels.
*/
private void finish(boolean start)
{
if(!mFinished.compareAndSet(false, true))
{
return;
}
mTimeline.stop();
mStage.close();
if(start && mChannelEventListener != null)
{
//Starting channels can block while tuners start, so start them off the JavaFX thread, in order
ThreadPool.CACHED.submit(() -> {
for(Channel channel: mChannels)
{
mChannelEventListener.receive(new ChannelEvent(channel, ChannelEvent.Event.REQUEST_ENABLE));
}
});
}
}
private static TableColumn<Channel,String> column(String title, double width, Function<Channel,String> value)
{
TableColumn<Channel,String> column = new TableColumn<>(title);
column.setPrefWidth(width);
column.setCellValueFactory(param -> new ReadOnlyStringWrapper(value.apply(param.getValue())));
return column;
}
}

View File

@@ -30,13 +30,11 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.AbstractListModel;
import java.util.ArrayList;
import java.util.List;
public class ChannelMapModel extends AbstractListModel<ChannelMap>
public class ChannelMapModel
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(ChannelMapModel.class);
private ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor());
@@ -108,17 +106,6 @@ public class ChannelMapModel extends AbstractListModel<ChannelMap>
*/
public void broadcast(ChannelMapEvent event)
{
if(event.getEvent() == ChannelMapEvent.Event.CHANGE ||
event.getEvent() == ChannelMapEvent.Event.RENAME)
{
int index = mChannelMaps.indexOf(event.getChannelMap());
if(index >= 0)
{
fireContentsChanged(this, index, index);
}
}
mEventBroadcaster.broadcast(event);
}
@@ -142,10 +129,6 @@ public class ChannelMapModel extends AbstractListModel<ChannelMap>
{
mChannelMaps.add(channelMap);
int index = mChannelMaps.indexOf(channelMap);
fireIntervalAdded(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.ADD));
}
}
@@ -157,36 +140,9 @@ public class ChannelMapModel extends AbstractListModel<ChannelMap>
{
if(mChannelMaps.contains(channelMap))
{
int index = mChannelMaps.indexOf(channelMap);
mChannelMaps.remove(channelMap);
fireIntervalRemoved(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.DELETE));
}
}
/**
* Size/Number of channel maps in this model
*/
@Override
public int getSize()
{
return mChannelMaps.size();
}
/**
* Returns the channel map at the specified index
*/
@Override
public ChannelMap getElementAt(int index)
{
if(index <= mChannelMaps.size())
{
return mChannelMaps.get(index);
}
return null;
}
}

View File

@@ -1,295 +0,0 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2020 Dennis Sheirer
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>
* * *****************************************************************************
*
*
*/
package io.github.dsheirer.controller.channel.map;
import javax.swing.table.AbstractTableModel;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ChannelRangeModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private static final int START = 0;
private static final int STOP = 1;
private static final int BASE = 2;
private static final int SIZE = 3;
private static final int ERROR = 4;
protected int[] mColumnWidths = { 110, 110, 110, -1, 80 };
protected String[] mHeaders = new String[] { "Begin",
"End",
"Base",
"Size",
"Error" };
private List<ChannelRange> mRanges = new CopyOnWriteArrayList<>();
private ChannelRangeEventListener mListener;
public ChannelRangeModel()
{
}
public void setListener( ChannelRangeEventListener listener )
{
mListener = listener;
}
private void broadcastChange()
{
if( mListener != null )
{
mListener.channelRangesChanged();
}
}
public void clear()
{
for( ChannelRange range: mRanges )
{
removeRange( range );
}
broadcastChange();
}
public List<ChannelRange> getChannelRanges()
{
return mRanges;
}
public void addRanges( List<ChannelRange> ranges )
{
for( ChannelRange range: ranges )
{
addRange( range );
}
broadcastChange();
}
public void addRange( ChannelRange range )
{
if( range != null && !mRanges.contains( range ) )
{
mRanges.add( range );
int index = mRanges.indexOf( range );
fireTableRowsInserted( index, index );
}
validate();
broadcastChange();
}
public void removeRange( ChannelRange range )
{
if( range != null && mRanges.contains( range ) )
{
int index = mRanges.indexOf( range );
mRanges.remove( range );
fireTableRowsDeleted( index, index );
}
validate();
broadcastChange();
}
public int[] getColumnWidths()
{
return mColumnWidths;
}
public void setColumnWidths( int[] widths )
{
if( widths.length != mHeaders.length )
{
throw new IllegalArgumentException( "ChannelMapRangeModel - "
+ "column widths array should have " +
mHeaders.length + " elements" );
}
else
{
mColumnWidths = widths;
}
}
@Override
public int getRowCount()
{
return mRanges.size();
}
@Override
public int getColumnCount()
{
return mHeaders.length;
}
public String getColumnName( int column )
{
return mHeaders[ column ];
}
public ChannelRange getChannelRange( int index )
{
if( index < mRanges.size() )
{
return mRanges.get( index );
}
return null;
}
@Override
public Object getValueAt( int rowIndex, int columnIndex )
{
ChannelRange range = getChannelRange( rowIndex );
if( range != null )
{
switch( columnIndex )
{
case START:
return range.getFirstChannelNumber();
case STOP:
return range.getLastChannelNumber();
case BASE:
return range.getBaseFrequency();
case SIZE:
return range.getStepSize();
case ERROR:
StringBuilder sb = new StringBuilder();
if( !range.isValid() )
{
sb.append( "Sequence" );
}
if( range.isOverlapping() )
{
if( sb.length() > 0 )
{
sb.append( "," );
}
sb.append( "Overlap" );
}
return sb.toString();
default:
break;
}
}
return null;
}
/**
* Validates each of the channel ranges for overlap
*/
private void validate()
{
for( int x = 0; x < mRanges.size(); x++ )
{
mRanges.get( x ).setOverlapping( false );
fireTableCellUpdated( x, ERROR );
}
for( int x = 0; x < mRanges.size(); x++ )
{
for( int y = x + 1; y < mRanges.size(); y++ )
{
if( mRanges.get( x ).overlaps( mRanges.get( y ) ) )
{
mRanges.get( x ).setOverlapping( true );
fireTableCellUpdated( x, ERROR );
mRanges.get( y ).setOverlapping( true );
fireTableCellUpdated( y, ERROR );
}
}
}
}
public boolean isCellEditable( int row, int column )
{
return row < mRanges.size() && column != ERROR;
}
public void setValueAt( Object value, int row, int column )
{
int parsedValue = -1;
try
{
parsedValue = Integer.parseInt( (String)value );
}
catch( Exception e )
{
//Do nothing ... we'll use 0
}
if( parsedValue >= 0 )
{
ChannelRange range = getChannelRange( row );
if( range != null )
{
switch( column )
{
case START:
range.setFirstChannelNumber( parsedValue );
break;
case STOP:
range.setLastChannelNumber( parsedValue );
break;
case BASE:
range.setBaseFrequency( parsedValue );
break;
case SIZE:
range.setStepSize( parsedValue );
break;
}
validate();
broadcastChange();
}
else
{
throw new IllegalArgumentException( "Invalid channel range row index" );
}
}
}
public interface ChannelRangeEventListener
{
public void channelRangesChanged();
}
}

View File

@@ -1,16 +1,14 @@
package io.github.dsheirer.dsp.filter.design;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
public class FilterViewerLauncher
{
private JFXPanel mJFXPanel;
public FilterViewerLauncher()
{
mJFXPanel = new JFXPanel();
FxToolkit.ensureStarted();
Platform.runLater(() ->
{

View File

@@ -19,54 +19,191 @@
package io.github.dsheirer.filter;
import java.awt.Component;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import io.github.dsheirer.gui.ApplicationIcons;
import io.github.dsheirer.gui.theme.ThemeManager;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.StringConverter;
/**
* Filter editor
* @param <T> item type for editing
* Window for turning filters and filter elements on and off. Each filter shows how many of its elements are
* enabled. Checking a filter turns all of its elements on or off. Changes apply immediately.
*
* @param <T> type of item that is filtered
*/
public class FilterEditor<T> extends JFrame
public class FilterEditor<T>
{
private FilterEditorPanel<T> mEditorPanel;
private final Stage mStage = new Stage();
private final TreeView<Object> mTreeView = new TreeView<>();
/**
* Constructor
* @param title for the editor window frame
* @param owner to register the popup location
* @param filterSet to use initially
* Constructs an instance. JavaFX thread only.
* @param title for the window
* @param owner window, or null
* @param filterSet to edit
*/
public FilterEditor(String title, Component owner, FilterSet<T> filterSet)
public FilterEditor(String title, Window owner, FilterSet<T> filterSet)
{
if(filterSet == null)
{
throw new IllegalArgumentException("Unable to construct FilterEditor - FilterSet cannot be null");
}
setTitle(title);
setSize(600, 400);
setLocationRelativeTo(owner);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new MigLayout("", "[grow,fill]", "[grow,fill][]"));
mEditorPanel = new FilterEditorPanel<>(filterSet);
JScrollPane scroller = new JScrollPane(mEditorPanel);
scroller.getVerticalScrollBar().setUnitIncrement(16);
scroller.setViewportView(mEditorPanel);
add(scroller, "wrap");
JButton close = new JButton("Close");
close.addActionListener(e -> dispose());
add(close);
mTreeView.setShowRoot(true);
mTreeView.setCellFactory(CheckBoxTreeCell.forTreeView(item -> ((CheckBoxTreeItem<Object>)item)
.selectedProperty(), new LabelConverter()));
VBox.setVgrow(mTreeView, Priority.ALWAYS);
Button expand = new Button("Expand All");
expand.setOnAction(event -> setExpanded(mTreeView.getRoot(), true));
Button collapse = new Button("Collapse All");
collapse.setOnAction(event -> {
setExpanded(mTreeView.getRoot(), false);
mTreeView.getRoot().setExpanded(true);
});
Button close = new Button("Close");
close.setCancelButton(true);
close.setDefaultButton(true);
close.setOnAction(event -> mStage.close());
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox buttons = new HBox(8, expand, collapse, spacer, close);
buttons.setAlignment(Pos.CENTER_LEFT);
VBox root = new VBox(8, mTreeView, buttons);
root.setPadding(new Insets(10));
Scene scene = new Scene(root, 600, 500);
ThemeManager.getInstance().register(scene);
mStage.setScene(scene);
mStage.setTitle(title);
ApplicationIcons.apply(mStage);
if(owner != null)
{
mStage.initOwner(owner);
}
updateFilterSet(filterSet);
}
/**
* Updates this editor with the filterset.
* @param filterSet to use in this editor.
* Shows the window and brings it to the front. JavaFX thread only.
*/
public void show()
{
mStage.show();
mStage.toFront();
}
/**
* Updates this editor with the filter set. JavaFX thread only.
* @param filterSet to edit
*/
public void updateFilterSet(FilterSet<T> filterSet)
{
mEditorPanel.updateFilterSet(filterSet);
CheckBoxTreeItem<Object> root = new CheckBoxTreeItem<>(filterSet);
root.setExpanded(true);
addFilterSet(filterSet, root);
mTreeView.setRoot(root);
}
/**
* Tree view, for testing.
*/
TreeView<Object> getTreeView()
{
return mTreeView;
}
private void addFilterSet(FilterSet<?> filterSet, CheckBoxTreeItem<Object> parent)
{
for(IFilter<?> filter: filterSet.getFilters())
{
CheckBoxTreeItem<Object> item = new CheckBoxTreeItem<>(filter);
parent.getChildren().add(item);
if(filter instanceof FilterSet<?> childFilterSet)
{
addFilterSet(childFilterSet, item);
}
else if(filter instanceof Filter<?,?> childFilter)
{
addFilter(childFilter, item);
}
}
}
private void addFilter(Filter<?,?> filter, CheckBoxTreeItem<Object> parent)
{
List<FilterElement<?>> elements = new ArrayList<>(filter.getFilterElements());
elements.sort(Comparator.comparing(FilterElement::getName));
for(FilterElement<?> element: elements)
{
CheckBoxTreeItem<Object> item = new CheckBoxTreeItem<>(element);
parent.getChildren().add(item);
//Set the state after adding the item, so that the parent check boxes follow their elements
item.setSelected(element.isEnabled());
item.selectedProperty().addListener((observable, wasSelected, selected) -> {
element.setEnabled(selected);
//Update the enabled counts shown on the filters
mTreeView.refresh();
});
}
}
private static void setExpanded(TreeItem<Object> item, boolean expanded)
{
if(item != null)
{
item.setExpanded(expanded);
item.getChildren().forEach(child -> setExpanded(child, expanded));
}
}
/**
* Label for each tree item: a filter's name and enabled count, or a filter element's name.
*/
private static class LabelConverter extends StringConverter<TreeItem<Object>>
{
@Override
public String toString(TreeItem<Object> item)
{
Object value = item != null ? item.getValue() : null;
if(value instanceof IFilter<?> filter)
{
return filter.getName() + " (" + filter.getEnabledCount() + "/" + filter.getElementCount() + ")";
}
else if(value instanceof FilterElement<?> element)
{
return element.getName();
}
return value != null ? value.toString() : "";
}
@Override
public TreeItem<Object> fromString(String string)
{
return null;
}
}
}

View File

@@ -1,444 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.filter;
import java.awt.Component;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.CellEditorListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreeSelectionModel;
/**
* Editor panel for managing the state of a filter set.
*
* @param <T> element type for the filter set.
*/
public class FilterEditorPanel<T> extends JPanel
{
private static final long serialVersionUID = 1L;
private JTree mTree;
private DefaultTreeModel mModel;
private FilterSet<T> mFilterSet;
/**
* Constructs an instance
* @param filterSet to manage
*/
public FilterEditorPanel(FilterSet<T> filterSet)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mFilterSet = filterSet;
init();
}
/**
* Initializes the panel and the tree model.
*/
private void init()
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode(mFilterSet);
mModel = new DefaultTreeModel(root);
addFilterSet(mFilterSet, root);
mTree = new JTree(mModel);
mTree.setShowsRootHandles(true);
mTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
mTree.setCellRenderer(new EditorTreeCellRenderer());
mTree.setCellEditor(new FilterTreeCellEditor());
mTree.setEditable(true);
add(mTree);
}
/**
* Updates the filter set for this editor panel
* @param filterSet to use
*/
public void updateFilterSet(FilterSet<T> filterSet)
{
remove(mTree);
mFilterSet = filterSet;
init();
revalidate();
}
/**
* Adds the filter set as a child tree node to the parent.
* @param filterSet to add to the tree
* @param parent node for the filter set child tree node.
*/
private void addFilterSet(FilterSet<T> filterSet, DefaultMutableTreeNode parent)
{
List<IFilter<T>> filters = filterSet.getFilters();
for(IFilter<T> filter : filters)
{
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(filter);
mModel.insertNodeInto(childNode, parent, parent.getChildCount());
if(filter instanceof FilterSet childFilterSet)
{
addFilterSet(childFilterSet, childNode);
}
else if(filter instanceof Filter childFilter)
{
addFilter(childFilter, childNode);
}
}
}
/**
* Adds the filter as a child tree node to the parent.
*
* @param filter to add
* @param parent tree node
*/
private void addFilter(Filter filter, DefaultMutableTreeNode parent)
{
List<FilterElement<?>> elements = filter.getFilterElements();
elements.sort(Comparator.comparing(FilterElement::getName));
for(FilterElement<?> element : elements)
{
DefaultMutableTreeNode child = new DefaultMutableTreeNode(element);
mModel.insertNodeInto(child, parent, parent.getChildCount());
}
}
/**
* Accesses the tree's root tree node.
* @return root node.
*/
private DefaultMutableTreeNode getRoot()
{
if(mTree.getModel().getRoot() instanceof DefaultMutableTreeNode root)
{
return root;
}
return null;
}
/**
* Recursively sets the enabled state on all filter node children below the specified parent node.
*
* @param model - model containing the tree nodes
* @param node - parent node
* @param enabled - true or false to enable or disable the filters
*/
private void setFilterEnabled(DefaultTreeModel model, DefaultMutableTreeNode node, boolean enabled)
{
Object obj = node.getUserObject();
if(obj instanceof FilterElement filterElement)
{
filterElement.setEnabled(enabled);
}
/* Recursively set the children of this node */
Enumeration<?> children = node.children();
while(children.hasMoreElements())
{
Object child = children.nextElement();
if(child instanceof DefaultMutableTreeNode childNode)
{
setFilterEnabled(model, childNode, enabled);
}
}
model.nodeChanged(node);
}
/**
* Recursively searches the tree to find the tree node containing the specified filter element.
*
* @param node to start search
* @param element to find
*/
private DefaultMutableTreeNode findFilterElementNode(DefaultMutableTreeNode node, FilterElement<?> element)
{
if(node != null)
{
if(node.getUserObject() instanceof FilterElement<?> selfFilterElement && selfFilterElement.equals(element))
{
return node;
}
for(int x = 0; x < node.getChildCount(); x++)
{
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
{
DefaultMutableTreeNode found = findFilterElementNode(child, element);
if(found != null)
{
return found;
}
}
}
}
return null;
}
/**
* Updates the display value for the specified node and all parents in the nodes parentage.
* @param node to update
*/
private void updateParentage(DefaultMutableTreeNode node)
{
mModel.nodeChanged(node);
TreeNode parent = node.getParent();
while(parent != null)
{
mModel.nodeChanged(parent);
parent = parent.getParent();
}
}
/**
* Recursively searches the tree to find the tree node containing the specified filter.
*
* @param node to start search
* @param filter to find
*/
private DefaultMutableTreeNode findFilterNode(DefaultMutableTreeNode node, IFilter<?> filter)
{
if(node != null)
{
if(node.getUserObject() instanceof IFilter<?> selfFilter && selfFilter.equals(filter))
{
return node;
}
for(int x = 0; x < node.getChildCount(); x++)
{
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
{
DefaultMutableTreeNode found = findFilterNode(child, filter);
if(found != null)
{
return found;
}
}
}
}
else
{
System.out.println("Can't evaluate - node is null");
}
return null;
}
/**
* Custom cell renderer
*/
public class EditorTreeCellRenderer extends DefaultTreeCellRenderer
{
private static final long serialVersionUID = 1L;
public Component getTreeCellRendererComponent(JTree tree, Object treeNode, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus)
{
if(treeNode instanceof DefaultMutableTreeNode)
{
Object userObject = ((DefaultMutableTreeNode) treeNode).getUserObject();
JCheckBox checkBox = null;
if(userObject instanceof IFilter filter)
{
checkBox = new FilterCheckBox(filter);
checkBox.setSelected(filter.isEnabled());
}
else if(userObject instanceof FilterElement element)
{
checkBox = new FilterElementCheckBox(element);
checkBox.setSelected(element.isEnabled());
}
if(checkBox != null)
{
if(selected)
{
checkBox.setForeground(getTextSelectionColor());
checkBox.setBackground(getBackgroundSelectionColor());
}
else
{
checkBox.setForeground(getTextNonSelectionColor());
checkBox.setBackground(getBackgroundNonSelectionColor());
}
return checkBox;
}
}
return super.getTreeCellRendererComponent(tree, treeNode, selected, expanded, leaf, row, hasFocus);
}
}
/**
* Check box used in filter tree nodes
*/
public class FilterCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private IFilter<?> mFilter;
/**
* Constructs an instance
*
* @param filter
*/
public FilterCheckBox(IFilter<?> filter)
{
mFilter = filter;
setSelected(mFilter.isEnabled());
addItemListener(e -> {
DefaultMutableTreeNode selfNode = findFilterNode(getRoot(), mFilter);
if(selfNode != null)
{
setFilterEnabled(mModel, selfNode, FilterCheckBox.this.isSelected());
updateLabel();
updateParentage(selfNode);
}
});
}
@Override
public void setSelected(boolean b)
{
super.setSelected(b);
updateLabel();
}
public void updateLabel()
{
setText(mFilter.getName() + " (" + mFilter.getEnabledCount() + "/" + mFilter.getElementCount() + ")");
}
}
/**
* Check box used in filter element tree nodes
*/
public class FilterElementCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private FilterElement<?> mFilter;
/**
* Constructs an instance
*
* @param filter element
*/
public FilterElementCheckBox(FilterElement<?> filter)
{
super(filter.getName());
mFilter = filter;
setSelected(mFilter.isEnabled());
addItemListener(arg0 -> {
mFilter.setEnabled(FilterElementCheckBox.this.isSelected());
DefaultMutableTreeNode self = findFilterElementNode(getRoot(), mFilter);
if(self != null)
{
updateParentage(self);
}
});
}
}
/**
* Editor for filter tree nodes
*/
public class FilterTreeCellEditor implements TreeCellEditor
{
@Override
public Component getTreeCellEditorComponent(JTree tree, Object node, boolean isSelected, boolean expanded, boolean leaf, int row)
{
if(node instanceof DefaultMutableTreeNode mutableTreeNode)
{
Object userObject = mutableTreeNode.getUserObject();
if(userObject instanceof IFilter filter)
{
return new FilterCheckBox(filter);
}
else if(userObject instanceof FilterElement filterElement)
{
return new FilterElementCheckBox(filterElement);
}
}
return new JLabel(node.toString());
}
@Override
public void addCellEditorListener(CellEditorListener l) {}
@Override
public void cancelCellEditing() {}
@Override
public Object getCellEditorValue()
{
return null;
}
@Override
public boolean isCellEditable(EventObject anEvent)
{
return true;
}
@Override
public void removeCellEditorListener(CellEditorListener l) {}
@Override
public boolean shouldSelectCell(EventObject anEvent)
{
return false;
}
@Override
public boolean stopCellEditing()
{
return false;
}
}
}

View File

@@ -19,13 +19,8 @@
package io.github.dsheirer.gui;
import java.awt.AWTEvent;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Taskbar;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
@@ -40,9 +35,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* sdrtrunk application icon for Swing frames and dialogs, JavaFX stages and the macOS Dock.
* sdrtrunk application icon for JavaFX stages and the macOS Dock.
*
* Call installSwing() once at startup and installJavaFx() once the JavaFX toolkit is running. After that, each
* Call installJavaFx() once the JavaFX toolkit is running, which also sets the macOS Dock icon. After that, each
* window that opens without its own icon gets the sdrtrunk icon, so individual windows don't have to set it.
*/
public final class ApplicationIcons
@@ -54,7 +49,7 @@ public final class ApplicationIcons
private static List<Image> sAwtImages;
private static List<javafx.scene.image.Image> sFxImages;
private static boolean sSwingInstalled;
private static boolean sTaskbarInstalled;
private static boolean sJavaFxInstalled;
private ApplicationIcons()
@@ -62,7 +57,7 @@ public final class ApplicationIcons
}
/**
* Application icon in each available size, smallest first, for Swing/AWT windows.
* Application icon in each available size, smallest first, as AWT images for the macOS Dock.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<Image> getAwtImages()
@@ -141,17 +136,6 @@ public final class ApplicationIcons
return sFxImages;
}
/**
* Sets the application icon on the Swing/AWT window if it doesn't already have one.
*/
public static void apply(java.awt.Window window)
{
if(window != null && window.getIconImages().isEmpty() && !getAwtImages().isEmpty())
{
window.setIconImages(getAwtImages());
}
}
/**
* Sets the application icon on the JavaFX stage if it doesn't already have one. Call on the FX thread.
*/
@@ -164,27 +148,18 @@ public final class ApplicationIcons
}
/**
* Sets the macOS Dock icon and gives each Swing frame and dialog that opens without an icon the application
* icon. Safe to call more than once. Does nothing in a headless environment.
* Sets the macOS Dock icon. Windows and Linux take the icon from each window instead. Safe to call more than
* once. Does nothing in a headless environment.
*/
public static synchronized void installSwing()
public static synchronized void installTaskbarIcon()
{
if(sSwingInstalled || java.awt.GraphicsEnvironment.isHeadless())
if(sTaskbarInstalled || java.awt.GraphicsEnvironment.isHeadless())
{
return;
}
sSwingInstalled = true;
sTaskbarInstalled = true;
Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
if(event.getID() == WindowEvent.WINDOW_OPENED &&
(event.getSource() instanceof Frame || event.getSource() instanceof Dialog))
{
apply((java.awt.Window)event.getSource());
}
}, AWTEvent.WINDOW_EVENT_MASK);
//The Dock icon on macOS. Windows and Linux take the icon from each window instead.
try
{
if(Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
@@ -219,6 +194,7 @@ public final class ApplicationIcons
}
sJavaFxInstalled = true;
installTaskbarIcon();
Platform.runLater(() -> {
for(Window window: Window.getWindows())
@@ -243,7 +219,7 @@ public final class ApplicationIcons
*/
private static void onFxWindowShown(Window window)
{
//Only stages are top-level windows. JFXPanel content and popups (menus, tooltips) are other Window types.
//Only stages are top-level windows. Popups (menus, tooltips) are other Window types.
if(window instanceof Stage stage)
{
apply(stage);

View File

@@ -0,0 +1,131 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui;
import java.awt.image.BufferedImage;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
/**
* Starts the JavaFX toolkit, runs work on the JavaFX application thread and converts images for ImageIO.
*/
public class FxToolkit
{
private static boolean sStarted;
private FxToolkit()
{
}
/**
* Starts the JavaFX toolkit if it isn't running. Safe to call more than once and from any thread except the
* JavaFX application thread before the toolkit starts.
*/
public static synchronized void ensureStarted()
{
if(sStarted)
{
return;
}
try
{
Platform.startup(() -> {});
}
catch(IllegalStateException alreadyStarted)
{
//The toolkit is already running
}
Platform.setImplicitExit(false);
ApplicationIcons.installJavaFx();
sStarted = true;
}
/**
* Indicates if the toolkit was started.
*/
public static synchronized boolean isStarted()
{
return sStarted;
}
/**
* Runs the callable on the JavaFX application thread and waits for the result.
* @throws Exception thrown by the callable
*/
public static <T> T callAndWait(Callable<T> callable) throws Exception
{
if(Platform.isFxApplicationThread())
{
return callable.call();
}
CompletableFuture<T> future = new CompletableFuture<>();
Platform.runLater(() -> {
try
{
future.complete(callable.call());
}
catch(Throwable t)
{
future.completeExceptionally(t);
}
});
try
{
return future.get();
}
catch(ExecutionException e)
{
if(e.getCause() instanceof Exception exception)
{
throw exception;
}
throw e;
}
}
/**
* Converts the JavaFX image to an AWT image for writing with ImageIO.
*/
public static BufferedImage toBufferedImage(Image image)
{
int width = (int)image.getWidth();
int height = (int)image.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
PixelReader reader = image.getPixelReader();
int[] row = new int[width];
for(int y = 0; y < height; y++)
{
reader.getPixels(0, y, width, 1, javafx.scene.image.PixelFormat.getIntArgbInstance(), row, 0, width);
bufferedImage.setRGB(0, y, width, 1, row, 0, width);
}
return bufferedImage;
}
}

View File

@@ -0,0 +1,756 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.audio.AudioView;
import io.github.dsheirer.gui.broadcast.BroadcastStatusView;
import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
import io.github.dsheirer.gui.map.MapView;
import io.github.dsheirer.gui.nowplaying.NowPlayingView;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.gui.spectrum.MainSpectralDisplay;
import io.github.dsheirer.gui.spectrum.TunerSpectralDisplay;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.monitor.DiagnosticMonitor;
import io.github.dsheirer.monitor.ResourceMonitor;
import io.github.dsheirer.monitor.StatusBox;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.util.ThreadPool;
import io.github.dsheirer.util.TimeStamp;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconFontFX;
import jiconfont.javafx.IconNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main application window: menu bar, audio playback display, the spectrum and waterfall, the Now Playing, Map and
* Tuners tabs, the optional streaming status and the optional resource status bar.
*
* The spectrum and waterfall can be hidden from the View menu, the hide button in the display settings panel or a
* keyboard shortcut. A hidden spectrum is disposed so that it uses no processing or memory.
*/
public class MainWindow
{
private static final Logger mLog = LoggerFactory.getLogger(MainWindow.class);
public static final String STAGE_MONITOR_KEY = "main.window";
private static final String PREFERENCE_BROADCAST_STATUS_VISIBLE = "sdrtrunk.broadcast.status.visible";
private static final String PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE = "sdrtrunk.now.playing.details.visible";
private static final String PREFERENCE_RESOURCE_STATUS_VISIBLE = "sdrtrunk.resource.status.visible";
private static final String PREFERENCE_SPECTRAL_DISPLAY_VISIBLE = "sdrtrunk.spectral.display.visible";
private static final String PREFERENCE_SPECTRAL_DIVIDER = "sdrtrunk.main.window.spectral.fraction";
private static final String PREFERENCE_BROADCAST_DIVIDER = "sdrtrunk.main.window.streaming.fraction";
private static final double DEFAULT_SPECTRAL_DIVIDER = 0.38;
private static final double DEFAULT_BROADCAST_FRACTION = 0.18;
static final KeyCombination SPECTRAL_TOGGLE_SHORTCUT = new KeyCodeCombination(KeyCode.S,
KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN);
private final Preferences mPreferences = Preferences.userNodeForPackage(SDRTrunk.class);
private final UserPreferences mUserPreferences;
private final PlaylistManager mPlaylistManager;
private final TunerManager mTunerManager;
private final DiagnosticMonitor mDiagnosticMonitor;
private final ResourceMonitor mResourceMonitor;
private final Runnable mExitHandler;
private final String mTitle;
private final Stage mStage;
private final BorderPane mRoot = new BorderPane();
private final SplitPane mSplitPane = new SplitPane();
private final VBox mCenter = new VBox();
private final AudioView mAudioView;
private final MainSpectralDisplay mSpectralDisplay;
private final HBox mSpectralHiddenBar;
private final NowPlayingView mNowPlayingView;
private final TabPane mTabPane = new TabPane();
private BroadcastStatusView mBroadcastStatusView;
private StatusBox mStatusBox;
private final CheckMenuItem mSpectralMenuItem = new CheckMenuItem("Show Spectrum & Waterfall");
private final CheckMenuItem mBroadcastMenuItem = new CheckMenuItem("Show Streaming Status");
private final CheckMenuItem mResourceMenuItem = new CheckMenuItem("Show Resource Status");
private final CheckMenuItem mNowPlayingDetailsMenuItem = new CheckMenuItem("Show Now Playing Channel Details");
private double mSpectralDivider;
private double mBroadcastFraction;
private boolean mUpdatingDividers;
static
{
IconFontFX.register(FontAwesome.getIconFont());
}
/**
* Constructs the main window. JavaFX thread only.
* @param userPreferences for the views
* @param playlistManager for the channels, aliases and streams
* @param tunerManager for the tuners
* @param audioPlaybackManager for the audio display
* @param aliasModel for alias lookup
* @param iconModel for alias icons
* @param mapService for the map
* @param resourceMonitor for the status bar
* @param diagnosticMonitor for the reports
* @param exitHandler that shuts down the application, invoked on a background thread
*/
public MainWindow(UserPreferences userPreferences, PlaylistManager playlistManager, TunerManager tunerManager,
AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel, IconModel iconModel,
MapService mapService, ResourceMonitor resourceMonitor, DiagnosticMonitor diagnosticMonitor,
Runnable exitHandler)
{
mUserPreferences = userPreferences;
mPlaylistManager = playlistManager;
mTunerManager = tunerManager;
mResourceMonitor = resourceMonitor;
mDiagnosticMonitor = diagnosticMonitor;
mExitHandler = exitHandler;
mTitle = SystemProperties.getInstance().getApplicationName();
mSpectralDivider = clamp(mPreferences.getDouble(PREFERENCE_SPECTRAL_DIVIDER, DEFAULT_SPECTRAL_DIVIDER));
mBroadcastFraction = clamp(mPreferences.getDouble(PREFERENCE_BROADCAST_DIVIDER, DEFAULT_BROADCAST_FRACTION));
mAudioView = new AudioView(audioPlaybackManager, aliasModel, iconModel, userPreferences);
boolean spectralVisible = mPreferences.getBoolean(PREFERENCE_SPECTRAL_DISPLAY_VISIBLE, true);
mSpectralDisplay = new MainSpectralDisplay(playlistManager, tunerManager.getDiscoveredTunerModel(),
spectralVisible);
mSpectralDisplay.setHideRequestHandler(() -> setSpectralDisplayVisible(false));
mSpectralHiddenBar = createSpectralHiddenBar();
boolean detailsVisible = mPreferences.getBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, true);
mNowPlayingView = new NowPlayingView(playlistManager, iconModel, userPreferences, detailsVisible);
createTabs(mapService, iconModel);
URL stylesheet = MainWindow.class.getResource("/main_window.css");
if(stylesheet != null)
{
mRoot.getStylesheets().add(stylesheet.toExternalForm());
}
mRoot.getStyleClass().add("main-window");
mSplitPane.setOrientation(javafx.geometry.Orientation.VERTICAL);
mSplitPane.getStyleClass().add("main-split-pane");
//The split pane moves its dividers while it lays out, so only store the positions after the user drags one
mSplitPane.addEventFilter(javafx.scene.input.MouseEvent.MOUSE_RELEASED, event -> storeDividers());
mSpectralDisplay.setMinHeight(80);
mTabPane.setMinHeight(150);
VBox.setVgrow(mSplitPane, Priority.ALWAYS);
mCenter.getChildren().addAll(mSpectralHiddenBar, mSplitPane);
mRoot.setTop(new VBox(createMenuBar(), mAudioView));
mRoot.setCenter(mCenter);
mSpectralMenuItem.setSelected(spectralVisible);
mNowPlayingDetailsMenuItem.setSelected(detailsVisible);
mBroadcastMenuItem.setSelected(mPreferences.getBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, false));
mResourceMenuItem.setSelected(mPreferences.getBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, true));
updateSplitPaneItems();
updateStatusBar();
mStage = new Stage();
mStage.setTitle(mTitle);
ApplicationIcons.apply(mStage);
Scene scene = new Scene(mRoot, 1280, 800);
ThemeManager.getInstance().register(scene);
scene.getAccelerators().put(SPECTRAL_TOGGLE_SHORTCUT,
() -> setSpectralDisplayVisible(!mSpectralDisplay.displayVisibleProperty().get()));
mStage.setScene(scene);
mStage.setMinWidth(640);
mStage.setMinHeight(480);
mStage.setOnCloseRequest(event -> {
event.consume();
exit();
});
migrateSwingWindowLocation();
mUserPreferences.getJavaFxPreferences().monitor(mStage, STAGE_MONITOR_KEY);
}
/**
* Main window stage.
*/
public Stage getStage()
{
return mStage;
}
/**
* Spectrum and waterfall display.
*/
public MainSpectralDisplay getSpectralDisplay()
{
return mSpectralDisplay;
}
/**
* Shows the window. JavaFX thread only.
*/
public void show()
{
mStage.show();
//The split pane only applies divider positions once it has a size
Platform.runLater(this::applyDividers);
}
/**
* Shows the stage's title with the tuner name, or the application name when the tuner is null. Any thread.
*/
public void updateTitle(String tunerName)
{
String title = tunerName != null ? mTitle + " - " + tunerName : mTitle;
Platform.runLater(() -> mStage.setTitle(title));
}
/**
* Handles tuner events for the main spectral display. Any thread.
*/
public void receive(TunerEvent event)
{
switch(event.getEvent())
{
case REQUEST_MAIN_SPECTRAL_DISPLAY:
//The user asked to see a tuner, so show the display if it's hidden
Platform.runLater(() -> setSpectralDisplayVisible(true));
updateTitle(event.getTuner().getPreferredName());
break;
case REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY:
updateTitle(null);
break;
case NOTIFICATION_SHUTTING_DOWN:
Tuner currentTuner = mSpectralDisplay.getTuner();
if(currentTuner == null || (event.hasTuner() && event.getTuner().equals(currentTuner)))
{
updateTitle(null);
}
break;
default:
break;
}
}
/**
* Saves the divider positions and stops the views. Called during application shutdown.
*/
public void dispose()
{
mAudioView.dispose();
if(mBroadcastStatusView != null)
{
mBroadcastStatusView.dispose();
}
mSpectralDisplay.dispose();
}
/**
* Shows or hides the spectrum and waterfall. A hidden display is disposed. JavaFX thread only.
*/
public void setSpectralDisplayVisible(boolean visible)
{
mSpectralMenuItem.setSelected(visible);
if(visible != mSpectralDisplay.displayVisibleProperty().get())
{
mPreferences.putBoolean(PREFERENCE_SPECTRAL_DISPLAY_VISIBLE, visible);
mSpectralDisplay.setDisplayVisible(visible);
updateSplitPaneItems();
applyDividers();
}
}
private HBox createSpectralHiddenBar()
{
IconNode icon = new IconNode(FontAwesome.EYE_SLASH);
icon.setIconSize(13);
icon.getStyleClass().add("main-hidden-bar-icon");
Label label = new Label("Spectrum and waterfall are hidden and turned off, so they use no processing or memory.");
label.getStyleClass().add("main-hidden-bar-label");
label.setMinWidth(0);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
IconNode showIcon = new IconNode(FontAwesome.EYE);
showIcon.setIconSize(12);
Button show = new Button("Show Spectrum & Waterfall", showIcon);
showIcon.fillProperty().bind(show.textFillProperty());
show.setOnAction(event -> setSpectralDisplayVisible(true));
HBox bar = new HBox(8, icon, label, spacer, show);
bar.getStyleClass().add("main-hidden-bar");
bar.setAlignment(Pos.CENTER_LEFT);
return bar;
}
private void createTabs(MapService mapService, IconModel iconModel)
{
MapView mapView = new MapView(mapService, iconModel, mUserPreferences,
mPlaylistManager.getRadioReference() != null ?
mPlaylistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(mPlaylistManager), true);
Tab nowPlaying = new Tab("Now Playing", mNowPlayingView);
Tab map = new Tab("Map", mapView);
Tab tuners = new Tab("Tuners", new io.github.dsheirer.source.tuner.ui.TunerView(mTunerManager,
mUserPreferences));
//The playlist editor tab opens the playlist editor window and stays on the current tab
IconNode playIcon = new IconNode(FontAwesome.PLAY_CIRCLE_O);
playIcon.setIconSize(15);
playIcon.getStyleClass().add("main-playlist-tab-icon");
Tab playlist = new Tab("Playlist Editor");
playlist.setGraphic(playIcon);
playlist.setContent(new Region());
mTabPane.getTabs().addAll(nowPlaying, map, tuners, playlist);
mTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
mTabPane.getStyleClass().add("main-tab-pane");
mTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
if(newTab == playlist)
{
MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest());
Platform.runLater(() -> mTabPane.getSelectionModel().select(oldTab != null ? oldTab : nowPlaying));
}
});
}
/**
* Updates the split pane to hold the visible panes: spectrum (optional), tabs and streaming status (optional).
*/
private void updateSplitPaneItems()
{
mUpdatingDividers = true;
List<Node> items = new ArrayList<>();
boolean spectralVisible = mSpectralDisplay.displayVisibleProperty().get();
if(spectralVisible)
{
items.add(mSpectralDisplay);
}
items.add(mTabPane);
if(mBroadcastMenuItem.isSelected())
{
if(mBroadcastStatusView == null)
{
mBroadcastStatusView = new BroadcastStatusView(mPlaylistManager.getBroadcastModel(),
mUserPreferences.getSwingPreference());
mBroadcastStatusView.setMinHeight(70);
}
items.add(mBroadcastStatusView);
}
mSplitPane.getItems().setAll(items);
SplitPane.setResizableWithParent(mTabPane, true);
if(mBroadcastStatusView != null)
{
SplitPane.setResizableWithParent(mBroadcastStatusView, false);
}
mSpectralHiddenBar.setVisible(!spectralVisible);
mSpectralHiddenBar.setManaged(!spectralVisible);
mUpdatingDividers = false;
}
/**
* Applies the stored divider positions to the split pane.
*/
private void applyDividers()
{
mUpdatingDividers = true;
List<SplitPane.Divider> dividers = mSplitPane.getDividers();
int index = 0;
if(mSpectralDisplay.displayVisibleProperty().get() && index < dividers.size())
{
dividers.get(index++).setPosition(mSpectralDivider);
}
if(mBroadcastMenuItem.isSelected() && index < dividers.size())
{
dividers.get(index).setPosition(1.0 - mBroadcastFraction);
}
mUpdatingDividers = false;
}
/**
* Stores the divider positions after the user moves a divider.
*/
private void storeDividers()
{
if(mUpdatingDividers || !mStage.isShowing() || mSplitPane.getDividers().isEmpty())
{
return;
}
List<SplitPane.Divider> dividers = mSplitPane.getDividers();
int index = 0;
if(mSpectralDisplay.displayVisibleProperty().get() && index < dividers.size())
{
mSpectralDivider = clamp(dividers.get(index++).getPosition());
mPreferences.putDouble(PREFERENCE_SPECTRAL_DIVIDER, mSpectralDivider);
}
if(mBroadcastMenuItem.isSelected() && index < dividers.size())
{
mBroadcastFraction = clamp(1.0 - dividers.get(index).getPosition());
mPreferences.putDouble(PREFERENCE_BROADCAST_DIVIDER, mBroadcastFraction);
}
}
private static double clamp(double value)
{
return Double.isNaN(value) ? 0.3 : Math.max(0.05, Math.min(0.6, value));
}
private void updateStatusBar()
{
if(mResourceMenuItem.isSelected())
{
if(mStatusBox == null)
{
mStatusBox = new StatusBox(mResourceMonitor);
}
mRoot.setBottom(mStatusBox);
}
else
{
mRoot.setBottom(null);
}
}
private MenuBar createMenuBar()
{
//File
MenuItem processingReport = new MenuItem("Processing Diagnostic Report");
processingReport.setOnAction(event -> createReport("Processing Status Report",
() -> mDiagnosticMonitor.generateProcessingDiagnosticReport("User initiated diagnostic report")));
MenuItem threadDumpReport = new MenuItem("Thread Dump Report");
threadDumpReport.setOnAction(event -> createReport("Thread Dump Report",
mDiagnosticMonitor::generateThreadDumpReport));
Menu reports = new Menu("Reports", null, processingReport, threadDumpReport);
MenuItem screenCapture = new MenuItem("Screen Capture", icon(FontAwesome.CAMERA));
screenCapture.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN));
screenCapture.setOnAction(event -> captureScreen());
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(event -> exit());
Menu file = new Menu("File", null, reports, screenCapture, new SeparatorMenuItem(), exit);
//View
MenuItem playlistEditor = new MenuItem("Playlist Editor", icon(FontAwesome.PLAY_CIRCLE_O));
playlistEditor.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest()));
MenuItem logs = folderItem("Application Log Files",
() -> mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog());
MenuItem recordings = folderItem("Audio Recordings",
() -> mUserPreferences.getDirectoryPreference().getDirectoryRecording());
MenuItem eventLogs = folderItem("Channel Event Log Files",
() -> mUserPreferences.getDirectoryPreference().getDirectoryEventLog());
MenuItem screenCaptures = folderItem("Screen Captures",
() -> mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture());
MenuItem iconManager = new MenuItem("Icon Manager", icon(FontAwesome.PICTURE_O));
iconManager.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewIconManagerRequest()));
MenuItem recordingViewer = new MenuItem("Message Recording Viewer (.bits)", icon(FontAwesome.BRAILLE));
recordingViewer.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewRecordingViewerRequest()));
MenuItem preferences = new MenuItem("User Preferences", icon(FontAwesome.COG));
preferences.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest()));
Menu tuners = new Menu("Tuners");
tuners.getItems().add(new MenuItem("(none)"));
tuners.setOnShowing(event -> updateTunersMenu(tuners));
mSpectralMenuItem.setAccelerator(SPECTRAL_TOGGLE_SHORTCUT);
mSpectralMenuItem.setOnAction(event -> setSpectralDisplayVisible(mSpectralMenuItem.isSelected()));
mNowPlayingDetailsMenuItem.setOnAction(event -> {
mNowPlayingView.setDetailTabsVisible(mNowPlayingDetailsMenuItem.isSelected());
mPreferences.putBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, mNowPlayingDetailsMenuItem.isSelected());
});
mBroadcastMenuItem.setOnAction(event -> {
mPreferences.putBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, mBroadcastMenuItem.isSelected());
updateSplitPaneItems();
applyDividers();
});
mResourceMenuItem.setOnAction(event -> {
mPreferences.putBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, mResourceMenuItem.isSelected());
updateStatusBar();
});
Menu view = new Menu("View", null, playlistEditor, new SeparatorMenuItem(), logs, recordings, eventLogs,
iconManager, recordingViewer, screenCaptures, preferences, new SeparatorMenuItem(), tuners,
new SeparatorMenuItem(), mSpectralMenuItem, mNowPlayingDetailsMenuItem, mBroadcastMenuItem,
mResourceMenuItem);
MenuBar menuBar = new MenuBar(file, view);
menuBar.setUseSystemMenuBar(true);
return menuBar;
}
/**
* Lists the available tuners, each of which shows the tuner in the main spectral display.
*/
private void updateTunersMenu(Menu menu)
{
menu.getItems().clear();
for(DiscoveredTuner discoveredTuner: mTunerManager.getAvailableTuners())
{
Tuner tuner = discoveredTuner.getTuner();
if(tuner != null)
{
MenuItem item = new MenuItem("Show: " + tuner.getPreferredName());
item.setOnAction(event -> ThreadPool.CACHED.submit(() -> {
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true);
mTunerManager.getDiscoveredTunerModel().broadcast(new TunerEvent(tuner,
TunerEvent.Event.REQUEST_MAIN_SPECTRAL_DISPLAY));
}));
menu.getItems().add(item);
}
}
if(menu.getItems().isEmpty())
{
MenuItem none = new MenuItem("No tuners available");
none.setDisable(true);
menu.getItems().add(none);
}
}
private static IconNode icon(FontAwesome code)
{
IconNode icon = new IconNode(code);
icon.setIconSize(12);
icon.getStyleClass().add("main-menu-icon");
return icon;
}
/**
* Supplies a path that can throw an IO exception.
*/
private interface PathSupplier
{
Path get() throws IOException;
}
private MenuItem folderItem(String title, PathSupplier folder)
{
MenuItem item = new MenuItem(title, icon(FontAwesome.FOLDER_OPEN_O));
item.setOnAction(event -> ThreadPool.CACHED.submit(() -> {
File directory = null;
try
{
directory = folder.get().toFile();
Desktop.getDesktop().open(directory);
}
catch(Exception e)
{
mLog.error("Couldn't open file explorer", e);
String location = directory != null ? directory.toString() : "unknown";
Platform.runLater(() -> showAlert(Alert.AlertType.ERROR, "Can't launch file explorer",
"Can't launch the file explorer. The files are located at:\n\n" + location));
}
}));
return item;
}
private void createReport(String title, PathSupplier report)
{
ThreadPool.CACHED.submit(() -> {
try
{
Path path = report.get();
Platform.runLater(() -> showAlert(Alert.AlertType.INFORMATION, title + " Created",
"Report created:\n\n" + path));
}
catch(IOException ioe)
{
mLog.error("Error creating " + title, ioe);
Platform.runLater(() -> showAlert(Alert.AlertType.ERROR, title + " Failed",
"Unable to create the report file. Please see the application log for details."));
}
});
}
/**
* Shows a message dialog owned by the main window. JavaFX thread only.
*/
public void showAlert(Alert.AlertType type, String title, String message)
{
Alert alert = new Alert(type, message);
alert.setTitle(title);
alert.setHeaderText(null);
alert.initOwner(mStage);
alert.show();
}
/**
* Warns that the library folder holds more than one version of some libraries. JavaFX thread only.
* @param details listing the duplicate libraries
* @param folder holding the libraries
*/
public void showDuplicateLibraries(String details, String folder)
{
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Duplicate Library Versions");
alert.setHeaderText("The sdrtrunk library folder has more than one version of some libraries");
alert.setContentText("This happens when a new version of sdrtrunk is unzipped over an older one. sdrtrunk " +
"can load the older library code, which can cause crashes or errors that the newer version fixed.\n\n" +
"Close sdrtrunk, delete the sdrtrunk folder that contains this library folder and unzip the release " +
"into a new, empty folder:\n\n" + folder + "\n\nYour playlist and settings are stored in your user " +
"folder and won't be affected.");
TextArea libraries = new TextArea(details);
libraries.setEditable(false);
libraries.setPrefRowCount(8);
alert.getDialogPane().setExpandableContent(libraries);
alert.getDialogPane().setExpanded(true);
alert.initOwner(mStage);
alert.show();
}
/**
* Saves an image of the main window to the screen captures folder.
*/
private void captureScreen()
{
WritableImage image = mStage.getScene().snapshot(null);
String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png";
ThreadPool.CACHED.submit(() -> {
Path file = null;
try
{
file = mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture().resolve(filename);
ImageIO.write(FxToolkit.toBufferedImage(image), "png", file.toFile());
}
catch(Exception e)
{
mLog.error("Couldn't write screen capture to file [" + file + "]", e);
}
});
}
/**
* Hides the window and shuts down the application on a background thread, since stopping the tuners can block.
*/
private void exit()
{
mStage.hide();
Thread thread = new Thread(() -> {
try
{
mExitHandler.run();
}
catch(Throwable t)
{
mLog.error("Error during shutdown", t);
}
System.exit(0);
}, "sdrtrunk shutdown");
thread.start();
}
/**
* Moves the main window size and location from the Swing window preferences to the JavaFX stage preferences,
* once, so that users keep their window placement.
*/
private void migrateSwingWindowLocation()
{
if(mUserPreferences.getJavaFxPreferences().hasStoredLocation(STAGE_MONITOR_KEY))
{
return;
}
String swingKey = "sdrtrunk.main.window.frame";
java.awt.Point location = mUserPreferences.getSwingPreference().getLocation(swingKey);
java.awt.Dimension size = mUserPreferences.getSwingPreference().getDimension(swingKey);
if(location != null && size != null)
{
mUserPreferences.getJavaFxPreferences().storeLocation(STAGE_MONITOR_KEY, location.x, location.y,
size.width, size.height, mUserPreferences.getSwingPreference().getMaximized(swingKey, false));
}
else
{
mStage.centerOnScreen();
}
}
}

View File

@@ -18,28 +18,21 @@
*/
package io.github.dsheirer.gui;
import com.jidesoft.swing.JideSplitPane;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.DuplicateCallDetector;
import io.github.dsheirer.audio.broadcast.AudioStreamingManager;
import io.github.dsheirer.audio.broadcast.BroadcastFormat;
import io.github.dsheirer.audio.broadcast.BroadcastStatusPanel;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.controller.ControllerPanel;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelAutoStartFrame;
import io.github.dsheirer.controller.channel.ChannelAutoStartWindow;
import io.github.dsheirer.controller.channel.ChannelException;
import io.github.dsheirer.controller.channel.ChannelSelectionManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.gui.preference.CalibrateRequest;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.gui.preference.calibration.CalibrationDialog;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.gui.theme.ThemedFontIcon;
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.log.ApplicationLog;
import io.github.dsheirer.map.MapService;
@@ -55,29 +48,12 @@ import io.github.dsheirer.settings.MapViewSetting;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerSpectralDisplayManager;
import io.github.dsheirer.spectrum.DisableSpectrumWaterfallMenuItem;
import io.github.dsheirer.spectrum.ShowTunerMenuItem;
import io.github.dsheirer.gui.spectrum.SpectralDisplayPanel;
import io.github.dsheirer.util.DuplicateLibraryDetector;
import io.github.dsheirer.util.ThreadPool;
import io.github.dsheirer.util.TimeStamp;
import io.github.dsheirer.vector.calibrate.CalibrationManager;
import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
@@ -85,63 +61,29 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.prefs.Preferences;
import java.util.concurrent.CountDownLatch;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.swing.IconFontSwing;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class SDRTrunk implements Listener<TunerEvent>
{
private final static Logger mLog = LoggerFactory.getLogger(SDRTrunk.class);
private Preferences mPreferences = Preferences.userNodeForPackage(SDRTrunk.class);
private static final String PREFERENCE_BROADCAST_STATUS_VISIBLE = "sdrtrunk.broadcast.status.visible";
private static final String PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE = "sdrtrunk.now.playing.details.visible";
private static final String PREFERENCE_RESOURCE_STATUS_VISIBLE = "sdrtrunk.resource.status.visible";
private static final String BASE_WINDOW_NAME = "sdrtrunk.main.window";
private static final String CONTROLLER_PANEL_IDENTIFIER = BASE_WINDOW_NAME + ".control.panel";
private static final String SPECTRAL_PANEL_IDENTIFIER = BASE_WINDOW_NAME + ".spectral.panel";
private static final String WINDOW_FRAME_IDENTIFIER = BASE_WINDOW_NAME + ".frame";
private boolean mBroadcastStatusVisible;
private boolean mResourceStatusVisible;
private boolean mNowPlayingDetailsVisible;
private AudioRecordingManager mAudioRecordingManager;
private AudioStreamingManager mAudioStreamingManager;
private BroadcastStatusPanel mBroadcastStatusPanel;
private ControllerPanel mControllerPanel;
private DiagnosticMonitor mDiagnosticMonitor;
private IconModel mIconModel = new IconModel();
private PlaylistManager mPlaylistManager;
private SettingsManager mSettingsManager;
private SpectralDisplayPanel mSpectralPanel;
private JFrame mMainGui;
private JideSplitPane mSplitPane;
private JavaFxWindowManager mJavaFxWindowManager;
private MainWindow mMainWindow;
private WindowManager mWindowManager;
private UserPreferences mUserPreferences = new UserPreferences();
private TunerManager mTunerManager;
private ApplicationLog mApplicationLog;
private ResourceMonitor mResourceMonitor;
private JFXPanel mResourceStatusPanel;
private String mTitle;
public SDRTrunk()
{
@@ -158,15 +100,13 @@ public class SDRTrunk implements Listener<TunerEvent>
/**
* Creates and starts the application components and shows the main window.
*/
private void initialize()
private void initialize() throws Exception
{
if(!GraphicsEnvironment.isHeadless())
{
//Initialize the theme manager before any Swing components are realized so the chosen
//look-and-feel applies to the very first window that is created.
//Initialize the theme manager before any windows are created so that the chosen theme applies to the
//first window.
ThemeManager.getInstance().initialize(mUserPreferences);
ApplicationIcons.installSwing();
mMainGui = new JFrame();
}
mApplicationLog = new ApplicationLog(mUserPreferences);
@@ -193,8 +133,6 @@ public class SDRTrunk implements Listener<TunerEvent>
//Log current properties setting
SystemProperties.getInstance().logCurrentSettings();
//Register FontAwesome so we can use the fonts in Swing windows
IconFontSwing.register(FontAwesome.getIconFont());
mTunerManager = new TunerManager(mUserPreferences);
mTunerManager.start();
@@ -222,7 +160,7 @@ public class SDRTrunk implements Listener<TunerEvent>
if(!headless)
{
mJavaFxWindowManager = new JavaFxWindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
mWindowManager = new WindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
}
CalibrationManager calibrationManager = CalibrationManager.getInstance(mUserPreferences);
@@ -250,95 +188,85 @@ public class SDRTrunk implements Listener<TunerEvent>
MapService mapService = new MapService(aliasModel, mIconModel);
mPlaylistManager.getChannelProcessingManager().addDecodeEventListener(mapService);
mNowPlayingDetailsVisible = mPreferences.getBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, true);
if(!GraphicsEnvironment.isHeadless())
{
mControllerPanel = new ControllerPanel(mPlaylistManager, audioPlaybackManager, mIconModel, mapService,
mSettingsManager, mTunerManager, mUserPreferences, mNowPlayingDetailsVisible);
}
if(!headless)
{
mSpectralPanel = new SpectralDisplayPanel(mPlaylistManager, mTunerManager.getDiscoveredTunerModel());
mResourceMonitor.start();
mMainWindow = FxToolkit.callAndWait(() -> new MainWindow(mUserPreferences, mPlaylistManager,
mTunerManager, audioPlaybackManager, aliasModel, mIconModel, mapService, mResourceMonitor,
mDiagnosticMonitor, this::processShutdown));
}
TunerSpectralDisplayManager tunerSpectralDisplayManager = new TunerSpectralDisplayManager(mSpectralPanel,
mPlaylistManager, mTunerManager.getDiscoveredTunerModel());
TunerSpectralDisplayManager tunerSpectralDisplayManager = new TunerSpectralDisplayManager(
mMainWindow != null ? mMainWindow.getSpectralDisplay() : null, mPlaylistManager,
mTunerManager.getDiscoveredTunerModel());
mTunerManager.getDiscoveredTunerModel().addListener(tunerSpectralDisplayManager);
mTunerManager.getDiscoveredTunerModel().addListener(this);
mPlaylistManager.init();
if(GraphicsEnvironment.isHeadless())
if(headless)
{
mLog.info("starting main application headless");
}
else
{
mLog.info("starting main application gui");
//Initialize the GUI
initGUI();
autoStartChannels();
return;
}
//Start the gui
EventQueue.invokeLater(() -> {
mLog.info("starting main application gui");
Platform.runLater(() -> {
try
{
if(!GraphicsEnvironment.isHeadless())
mMainWindow.show();
//The JVM only closes the splash screen when the first AWT window shows, so close it here.
Splash.close();
Tuner tuner = tunerSpectralDisplayManager.showFirstTuner();
if(tuner != null)
{
mMainGui.setVisible(true);
//The JVM closes the splash when the first window shows. Close it here as well in case it didn't.
Splash.close();
Tuner tuner = tunerSpectralDisplayManager.showFirstTuner();
if(tuner != null)
{
updateTitle(tuner.getPreferredName());
}
if(!duplicateLibraries.isEmpty())
{
showDuplicateLibrariesDialog(duplicateLibraries);
}
mMainWindow.updateTitle(tuner.getPreferredName());
}
if(calibrating && !GraphicsEnvironment.isHeadless())
if(!duplicateLibraries.isEmpty())
{
Platform.runLater(() ->
{
CalibrationDialog calibrationDialog = mJavaFxWindowManager.getCalibrationDialog(mUserPreferences);
Optional<ButtonType> calibrate = calibrationDialog.showAndWait();
if(calibrate.isPresent() && calibrate.get().getText().equals("Calibrate"))
{
//Request focus and execute calibration
MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.VECTOR_CALIBRATION));
MyEventBus.getGlobalEventBus().post(new CalibrateRequest());
}
else
{
autoStartChannels();
}
});
}
else
{
autoStartChannels();
mMainWindow.showDuplicateLibraries(DuplicateLibraryDetector.describe(duplicateLibraries),
String.valueOf(DuplicateLibraryDetector.getFolder(duplicateLibraries)));
}
}
catch(Exception e)
{
if(mMainGui != null && !mMainGui.isVisible())
if(!mMainWindow.getStage().isShowing())
{
//The main window didn't open, so the user has no way to close the application.
startupFailed(e);
}
else
{
mLog.error("Error while starting the application", e);
ThreadPool.CACHED.submit(() -> startupFailed(e));
return;
}
mLog.error("Error while starting the application", e);
}
if(calibrating)
{
//Show the calibration dialog after the main window is showing
Platform.runLater(() -> {
CalibrationDialog calibrationDialog = mWindowManager.getCalibrationDialog(mUserPreferences);
Optional<ButtonType> calibrate = calibrationDialog.showAndWait();
if(calibrate.isPresent() && calibrate.get().getText().equals("Calibrate"))
{
MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest(
PreferenceEditorType.VECTOR_CALIBRATION));
MyEventBus.getGlobalEventBus().post(new CalibrateRequest());
}
else
{
autoStartChannels();
}
});
}
else
{
autoStartChannels();
}
});
}
@@ -371,303 +299,12 @@ public class SDRTrunk implements Listener<TunerEvent>
}
else
{
new ChannelAutoStartFrame(mPlaylistManager.getChannelProcessingManager(), channels, mUserPreferences);
Platform.runLater(() -> new ChannelAutoStartWindow(mPlaylistManager.getChannelProcessingManager(),
channels, mUserPreferences, mMainWindow != null ? mMainWindow.getStage() : null).show());
}
}
}
/**
* Initialize the contents of the frame.
*/
private void initGUI()
{
mMainGui.setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]0[shrink 0]"));
/**
* Setup main JFrame window
*/
mTitle = SystemProperties.getInstance().getApplicationName();
mMainGui.setTitle(mTitle);
ApplicationIcons.apply(mMainGui);
Point location = mUserPreferences.getSwingPreference().getLocation(WINDOW_FRAME_IDENTIFIER);
if(location != null)
{
mMainGui.setLocation(location);
}
else
{
mMainGui.setLocationRelativeTo(null);
}
mMainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mMainGui.addWindowListener(new ShutdownMonitor());
Dimension dimension = mUserPreferences.getSwingPreference().getDimension(WINDOW_FRAME_IDENTIFIER);
mSpectralPanel.setPreferredSize(new Dimension(1280, 300));
mControllerPanel.setPreferredSize(new Dimension(1280, 500));
if(dimension != null)
{
Dimension spectral = mUserPreferences.getSwingPreference().getDimension(SPECTRAL_PANEL_IDENTIFIER);
if(spectral != null)
{
Dimension pref = mSpectralPanel.getPreferredSize();
mSpectralPanel.setPreferredSize(new Dimension(pref.width, spectral.height));
// mSpectralPanel.setSize(spectral);
}
Dimension controller = mUserPreferences.getSwingPreference().getDimension(CONTROLLER_PANEL_IDENTIFIER);
if(controller != null)
{
Dimension pref = mControllerPanel.getPreferredSize();
mControllerPanel.setPreferredSize(new Dimension(pref.width, controller.height));
// mControllerPanel.setSize(controller);
}
mMainGui.setSize(dimension);
if(mUserPreferences.getSwingPreference().getMaximized(WINDOW_FRAME_IDENTIFIER, false))
{
mMainGui.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
else
{
mMainGui.setSize(new Dimension(1280, 800));
}
mSplitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT);
mSplitPane.setDividerSize(5);
mSplitPane.add(mSpectralPanel);
mSplitPane.add(mControllerPanel);
mBroadcastStatusVisible = mPreferences.getBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, false);
//Show broadcast status panel when user requests - disabled by default
if(mBroadcastStatusVisible)
{
mSplitPane.add(getBroadcastStatusPanel());
}
mMainGui.add(mSplitPane, "cell 0 0,span,grow");
mResourceMonitor.start();
mResourceStatusVisible = mPreferences.getBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, true);
if(mResourceStatusVisible)
{
mMainGui.add(getResourceStatusPanel(), "span,growx");
}
/**
* Menu items
*/
JMenuBar menuBar = new JMenuBar();
mMainGui.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem processingStatusReportMenuItem = new JMenuItem("Processing Diagnostic Report");
processingStatusReportMenuItem.addActionListener(e -> {
try
{
Path path = mDiagnosticMonitor.generateProcessingDiagnosticReport("User initiated diagnostic report");
JOptionPane.showMessageDialog(mMainGui, "Report created: " +
path.toString(), "Processing Status Report Created", JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException ioe)
{
mLog.error("Error creating processing status report file", ioe);
JOptionPane.showMessageDialog(mMainGui, "Unable to create report file. Please " +
"see application log for details.", "Processing Status Report Failed", JOptionPane.ERROR_MESSAGE);
}
});
JMenuItem threadDumpReportMenuItem = new JMenuItem("Thread Dump Report");
threadDumpReportMenuItem.addActionListener(e -> {
try
{
Path path = mDiagnosticMonitor.generateThreadDumpReport();
JOptionPane.showMessageDialog(mMainGui, "Report created: " +
path.toString(), "Thread Dump Report Created", JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException ioe)
{
mLog.error("Error creating thread dump report file", ioe);
JOptionPane.showMessageDialog(mMainGui, "Unable to create report file. Please " +
"see application log for details.", "Thread Dump Report Failed", JOptionPane.ERROR_MESSAGE);
}
});
JMenu diagnosticMenu = new JMenu(("Reports"));
diagnosticMenu.add(processingStatusReportMenuItem);
diagnosticMenu.add(threadDumpReportMenuItem);
fileMenu.add(diagnosticMenu);
fileMenu.add(new JSeparator(JSeparator.HORIZONTAL));
JMenuItem exitMenu = new JMenuItem("Exit");
exitMenu.addActionListener(event -> {
processShutdown();
System.exit(0);
}
);
fileMenu.add(exitMenu);
JMenu viewMenu = new JMenu("View");
JMenuItem viewPlaylistItem = new JMenuItem("Playlist Editor");
viewPlaylistItem.setIcon(new ThemedFontIcon(FontAwesome.PLAY_CIRCLE_O, 12));
viewPlaylistItem.addActionListener(e -> MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest()));
viewMenu.add(viewPlaylistItem);
viewMenu.add(new JSeparator());
JMenuItem viewApplicationLogsMenu = new JMenuItem("Application Log Files");
viewApplicationLogsMenu.setIcon(new ThemedFontIcon(FontAwesome.FOLDER_OPEN_O, 12));
viewApplicationLogsMenu.addActionListener(arg0 -> {
File logsDirectory = mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog().toFile();
try
{
Desktop.getDesktop().open(logsDirectory);
}
catch(Exception e)
{
mLog.error("Couldn't open file explorer");
JOptionPane.showMessageDialog(mMainGui,
"Can't launch file explorer - files are located at: " + logsDirectory,
"Can't launch file explorer",
JOptionPane.ERROR_MESSAGE);
}
});
viewMenu.add(viewApplicationLogsMenu);
JMenuItem viewRecordingsMenuItem = new JMenuItem("Audio Recordings");
viewRecordingsMenuItem.setIcon(new ThemedFontIcon(FontAwesome.FOLDER_OPEN_O, 12));
viewRecordingsMenuItem.addActionListener(arg0 -> {
File recordingsDirectory = mUserPreferences.getDirectoryPreference().getDirectoryRecording().toFile();
try
{
Desktop.getDesktop().open(recordingsDirectory);
}
catch(Exception e)
{
mLog.error("Couldn't open file explorer");
JOptionPane.showMessageDialog(mMainGui,
"Can't launch file explorer - files are located at: " +
recordingsDirectory,
"Can't launch file explorer",
JOptionPane.ERROR_MESSAGE);
}
});
viewMenu.add(viewRecordingsMenuItem);
JMenuItem viewEventLogsMenu = new JMenuItem("Channel Event Log Files");
viewEventLogsMenu.setIcon(new ThemedFontIcon(FontAwesome.FOLDER_OPEN_O, 12));
viewEventLogsMenu.addActionListener(arg0 -> {
File eventLogsDirectory = mUserPreferences.getDirectoryPreference().getDirectoryEventLog().toFile();
try
{
Desktop.getDesktop().open(eventLogsDirectory);
}
catch(Exception e)
{
mLog.error("Couldn't open file explorer");
JOptionPane.showMessageDialog(mMainGui,
"Can't launch file explorer - files are located at: " + eventLogsDirectory,
"Can't launch file explorer",
JOptionPane.ERROR_MESSAGE);
}
});
viewMenu.add(viewEventLogsMenu);
JMenuItem iconManagerMenu = new JMenuItem("Icon Manager");
iconManagerMenu.setIcon(new ThemedFontIcon(FontAwesome.PICTURE_O, 12));
iconManagerMenu.addActionListener(arg0 -> MyEventBus.getGlobalEventBus().post(new ViewIconManagerRequest()));
viewMenu.add(iconManagerMenu);
JMenuItem recordingViewerMenu = new JMenuItem("Message Recording Viewer (.bits)");
recordingViewerMenu.setIcon(new ThemedFontIcon(FontAwesome.BRAILLE, 12));
recordingViewerMenu.addActionListener(e -> MyEventBus.getGlobalEventBus().post(new ViewRecordingViewerRequest()));
viewMenu.add(recordingViewerMenu);
JMenuItem viewScreenCapturesMenu = new JMenuItem("Screen Captures");
viewScreenCapturesMenu.setIcon(new ThemedFontIcon(FontAwesome.FOLDER_OPEN_O, 12));
viewScreenCapturesMenu.addActionListener(arg0 -> {
File screenCapturesDirectory = mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture().toFile();
try
{
Desktop.getDesktop().open(screenCapturesDirectory);
}
catch(Exception e)
{
mLog.error("Couldn't open file explorer");
JOptionPane.showMessageDialog(mMainGui,
"Can't launch file explorer - files are located at: " + screenCapturesDirectory,
"Can't launch file explorer",
JOptionPane.ERROR_MESSAGE);
}
});
viewMenu.add(viewScreenCapturesMenu);
JMenuItem preferencesItem = new JMenuItem("User Preferences");
preferencesItem.setIcon(new ThemedFontIcon(FontAwesome.COG, 12));
preferencesItem.addActionListener(e -> MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest()));
viewMenu.add(preferencesItem);
viewMenu.add(new JSeparator());
viewMenu.add(new TunersMenu());
viewMenu.add(new JSeparator());
viewMenu.add(new DisableSpectrumWaterfallMenuItem(mSpectralPanel));
viewMenu.add(new NowPlayingChannelDetailsVisibleMenuItem());
viewMenu.add(new BroadcastStatusVisibleMenuItem());
viewMenu.add(new ResourceStatusVisibleMenuItem());
menuBar.add(viewMenu);
JMenuItem screenCaptureItem = new JMenuItem("Screen Capture");
screenCaptureItem.setIcon(new ThemedFontIcon(FontAwesome.CAMERA, 12));
screenCaptureItem.setMnemonic(KeyEvent.VK_C);
screenCaptureItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK));
screenCaptureItem.setMaximumSize(screenCaptureItem.getPreferredSize());
screenCaptureItem.addActionListener(arg0 -> {
try
{
Robot robot = new Robot();
final BufferedImage image = robot.createScreenCapture(mMainGui.getBounds());
String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png";
final Path captureFile = mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture().resolve(filename);
ThreadPool.CACHED.submit(() -> {
try
{
ImageIO.write(image, "png", captureFile.toFile());
}
catch(IOException e)
{
mLog.error("Couldn't write screen capture to file [" + captureFile + "]", e);
}
});
}
catch(AWTException e)
{
mLog.error("Exception while taking screen capture", e);
}
});
menuBar.add(screenCaptureItem);
}
/**
* Performs shutdown operations
*/
@@ -675,15 +312,18 @@ public class SDRTrunk implements Listener<TunerEvent>
{
mLog.info("Application shutdown started ...");
mDiagnosticMonitor.stop();
mUserPreferences.getSwingPreference().setLocation(WINDOW_FRAME_IDENTIFIER, mMainGui.getLocation());
mUserPreferences.getSwingPreference().setDimension(WINDOW_FRAME_IDENTIFIER, mMainGui.getSize());
mUserPreferences.getSwingPreference().setMaximized(WINDOW_FRAME_IDENTIFIER,
(mMainGui.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH);
mUserPreferences.getSwingPreference().setDimension(SPECTRAL_PANEL_IDENTIFIER, mSpectralPanel.getSize());
mUserPreferences.getSwingPreference().setDimension(CONTROLLER_PANEL_IDENTIFIER, mControllerPanel.getSize());
mLog.info("Stopping spectral display ...");
mSpectralPanel.dispose();
mJavaFxWindowManager.shutdown();
if(mMainWindow != null)
{
mMainWindow.dispose();
}
if(mWindowManager != null)
{
mWindowManager.shutdown();
}
mLog.info("Stopping channels ...");
mPlaylistManager.getChannelProcessingManager().shutdown();
mAudioRecordingManager.stop();
@@ -695,93 +335,6 @@ public class SDRTrunk implements Listener<TunerEvent>
mApplicationLog.stop();
}
/**
* Lazy constructor for broadcast status panel
*/
private BroadcastStatusPanel getBroadcastStatusPanel()
{
if(mBroadcastStatusPanel == null)
{
mBroadcastStatusPanel = new BroadcastStatusPanel(mPlaylistManager.getBroadcastModel(), mUserPreferences,
"application.broadcast.status.panel");
mBroadcastStatusPanel.setPreferredSize(new Dimension(880, 70));
mBroadcastStatusPanel.getTable().setEnabled(false);
}
return mBroadcastStatusPanel;
}
/**
* Toggles visibility of the broadcast channels status panel at the bottom of the controller panel
*/
private void toggleBroadcastStatusPanelVisibility()
{
mBroadcastStatusVisible = !mBroadcastStatusVisible;
EventQueue.invokeLater(() -> {
if(mBroadcastStatusVisible)
{
mSplitPane.add(getBroadcastStatusPanel());
}
else
{
mSplitPane.remove(getBroadcastStatusPanel());
}
mMainGui.revalidate();
});
mPreferences.putBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, mBroadcastStatusVisible);
}
/**
* Lazy constructor for resource status panel
*/
private JFXPanel getResourceStatusPanel()
{
if(mResourceStatusPanel == null)
{
mResourceStatusPanel = mJavaFxWindowManager.getStatusPanel(mResourceMonitor);
}
return mResourceStatusPanel;
}
/**
* Toggles visibility of the resource status panel at the bottom of the main UI window
*/
private void toggleResourceStatusPanelVisibility()
{
mResourceStatusVisible = !mResourceStatusVisible;
EventQueue.invokeLater(() -> {
if(mResourceStatusVisible)
{
mMainGui.add(getResourceStatusPanel(), "span,growx");
}
else
{
mMainGui.remove(getResourceStatusPanel());
}
mMainGui.revalidate();
});
mPreferences.putBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, mResourceStatusVisible);
}
/**
* Toggles visibility of the Now Playing channel details panel
*/
private void toggleNowPlayingDetailsPanelVisibility()
{
mNowPlayingDetailsVisible = !mNowPlayingDetailsVisible;
mControllerPanel.getNowPlayingPanel().setDetailTabsVisible(mNowPlayingDetailsVisible);
mPreferences.putBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, mNowPlayingDetailsVisible);
}
/**
* Loads the application properties file from the user's home directory,
* creating the properties file for the first-time, if necessary
@@ -848,153 +401,12 @@ public class SDRTrunk implements Listener<TunerEvent>
@Override
public void receive(TunerEvent event)
{
switch(event.getEvent())
if(mMainWindow != null)
{
case REQUEST_MAIN_SPECTRAL_DISPLAY:
updateTitle(event.getTuner().getPreferredName());
break;
case REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY:
updateTitle(null);
break;
case NOTIFICATION_SHUTTING_DOWN:
Tuner currentTuner = mSpectralPanel != null ? mSpectralPanel.getTuner() : null;
if(event.hasTuner() && event.getTuner().equals(currentTuner) || currentTuner == null)
{
updateTitle(null);
}
break;
mMainWindow.receive(event);
}
}
/**
* Updates the title bar with the tuner name. No-op when running headless (no main window).
* @param tunerName optional
*/
private void updateTitle(String tunerName)
{
if(mMainGui == null)
{
return;
}
if(tunerName != null)
{
mMainGui.setTitle(mTitle + " - " + tunerName);
}
else
{
mMainGui.setTitle(mTitle);
}
}
public class ShutdownMonitor extends WindowAdapter
{
@Override
public void windowClosing(WindowEvent e)
{
processShutdown();
}
}
/**
* Broadcast status panel visible toggle menu item
*/
public class BroadcastStatusVisibleMenuItem extends JCheckBoxMenuItem
{
public BroadcastStatusVisibleMenuItem()
{
super("Show Streaming Status");
setSelected(mBroadcastStatusVisible);
addActionListener(e -> {
toggleBroadcastStatusPanelVisibility();
setSelected(mBroadcastStatusVisible);
});
}
}
/**
* Resource status panel visible toggle menu item
*/
public class ResourceStatusVisibleMenuItem extends JCheckBoxMenuItem
{
public ResourceStatusVisibleMenuItem()
{
super("Show Resource Status");
setSelected(mResourceStatusVisible);
addActionListener(e -> {
toggleResourceStatusPanelVisibility();
setSelected(mResourceStatusVisible);
});
}
}
/**
* Now Playing channel details visible toggle menu item
*/
public class NowPlayingChannelDetailsVisibleMenuItem extends JCheckBoxMenuItem
{
public NowPlayingChannelDetailsVisibleMenuItem()
{
super("Show Now Playing Channel Details");
setSelected(mNowPlayingDetailsVisible);
addActionListener(e -> {
toggleNowPlayingDetailsPanelVisibility();
setSelected(mNowPlayingDetailsVisible);
});
}
}
public class TunersMenu extends JMenu
{
public TunersMenu()
{
super("Tuners");
addMenuListener(new MenuListener()
{
@Override
public void menuSelected(MenuEvent e)
{
removeAll();
for(DiscoveredTuner discoveredTuner: mTunerManager.getAvailableTuners())
{
add(new ShowTunerMenuItem(mTunerManager.getDiscoveredTunerModel(), discoveredTuner.getTuner()));
}
}
@Override
public void menuDeselected(MenuEvent e) { }
@Override
public void menuCanceled(MenuEvent e) { }
});
}
}
/**
* Warns the user that the library folder holds more than one version of some libraries, which happens when a new
* release is unzipped over an older one. The launch scripts put every jar in the library folder on the class
* path, so the older library code can load instead of the newer code.
* @param duplicates library name to jar paths, from DuplicateLibraryDetector
*/
private void showDuplicateLibrariesDialog(Map<String,List<String>> duplicates)
{
String message = "<html><body style='width: 450px'>" +
"<p>The sdrtrunk library folder has more than one version of these libraries:</p><br>" +
"<pre>" + DuplicateLibraryDetector.describe(duplicates) + "</pre>" +
"<p>This happens when a new version of sdrtrunk is unzipped over an older one. sdrtrunk can load " +
"the older library code, which can cause crashes or errors that the newer version fixed.</p><br>" +
"<p>Close sdrtrunk, delete the sdrtrunk folder that contains this library folder and unzip the " +
"release into a new, empty folder:</p><br>" +
"<p><b>" + DuplicateLibraryDetector.getFolder(duplicates) + "</b></p><br>" +
"<p>Your playlist and settings are stored in your user folder and won't be affected.</p>" +
"</body></html>";
JOptionPane.showMessageDialog(mMainGui, message, "Duplicate Library Versions", JOptionPane.WARNING_MESSAGE);
}
/**
* Handles an error that stops the application from starting. Stops the tuners that already started, so that they
* are released for the next start, then reports the error and exits. Without this, the threads that the
@@ -1049,29 +461,31 @@ public class SDRTrunk implements Listener<TunerEvent>
Splash.close();
if(!GraphicsEnvironment.isHeadless())
if(FxToolkit.isStarted())
{
String message = "<html><body style='width: 450px'>" +
"<p>sdrtrunk couldn't start because of this error:</p><br>" +
"<p><b>" + escapeHtml(String.valueOf(t)) + "</b></p><br>" +
(logsDirectory != null ? "<p>The application log has the details:</p><p>" +
escapeHtml(logsDirectory) + "</p><br>" : "") +
"<p>See Help / Support on the sdrtrunk wiki for help.</p>" +
"</body></html>";
String message = "sdrtrunk couldn't start because of this error:\n\n" + t +
(logsDirectory != null ? "\n\nThe application log has the details:\n" + logsDirectory : "") +
"\n\nSee Help / Support on the sdrtrunk wiki for help.";
CountDownLatch latch = new CountDownLatch(1);
try
{
Runnable dialog = () -> JOptionPane.showMessageDialog(null, message, "sdrtrunk Startup Error",
JOptionPane.ERROR_MESSAGE);
if(EventQueue.isDispatchThread())
{
dialog.run();
}
else
{
EventQueue.invokeAndWait(dialog);
}
Platform.runLater(() -> {
try
{
Alert alert = new Alert(Alert.AlertType.ERROR, message);
alert.setTitle("sdrtrunk Startup Error");
alert.setHeaderText("sdrtrunk couldn't start");
ApplicationIcons.apply((javafx.stage.Stage)alert.getDialogPane().getScene().getWindow());
alert.showAndWait();
}
finally
{
latch.countDown();
}
});
latch.await();
}
catch(Throwable t2)
{
@@ -1082,14 +496,6 @@ public class SDRTrunk implements Listener<TunerEvent>
System.exit(1);
}
/**
* Escapes text for display in a Swing HTML label.
*/
private static String escapeHtml(String text)
{
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
}
/**
* Launch the application.
*/
@@ -1098,6 +504,18 @@ public class SDRTrunk implements Listener<TunerEvent>
String version = SDRTrunk.class.getPackage().getImplementationVersion();
Splash.showVersion(version != null ? "v" + version : null);
if(!GraphicsEnvironment.isHeadless())
{
try
{
FxToolkit.ensureStarted();
}
catch(Throwable t)
{
exitAfterStartupError(t, null);
}
}
try
{
new SDRTrunk();

View File

@@ -20,36 +20,25 @@
package io.github.dsheirer.gui;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.controller.channel.map.ChannelMap;
import io.github.dsheirer.controller.channel.map.ChannelRange;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.icon.IconManager;
import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
import io.github.dsheirer.gui.playlist.PlaylistEditor;
import io.github.dsheirer.gui.playlist.PlaylistEditorRequest;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.gui.playlist.channelMap.ChannelMapEditor;
import io.github.dsheirer.gui.playlist.channelMap.ViewChannelMapEditorRequest;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.UserPreferencesEditor;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.gui.preference.calibration.CalibrationDialog;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.gui.viewer.MessageRecordingViewer;
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.jmbe.JmbeEditor;
import io.github.dsheirer.jmbe.JmbeEditorRequest;
import io.github.dsheirer.module.log.EventLogManager;
import io.github.dsheirer.monitor.ResourceMonitor;
import io.github.dsheirer.monitor.StatusBox;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.stage.Stage;
import jiconfont.javafx.IconFontFX;
@@ -57,17 +46,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Java FX window manager. Handles all secondary Java FX windows that are used within this primarily
* Swing application.
* Opens the application's tool windows (playlist editor, user preferences, icon manager, channel map editor, JMBE
* library editor and message recording viewer) when it receives their request events on the event bus. Each window
* is created once, then restored and brought to the front on later requests, and its size and location are kept
* across sessions.
*/
public class JavaFxWindowManager extends Application
public class WindowManager
{
private final static Logger mLog = LoggerFactory.getLogger(JavaFxWindowManager.class);
private final static Logger mLog = LoggerFactory.getLogger(WindowManager.class);
public static final String CHANNEL_MAP_EDITOR = "channelmap";
public static final String ICON_MANAGER = "iconmanager";
public static final String PLAYLIST_EDITOR = "playlist";
public static final String USER_PREFERENCES_EDITOR = "preferences";
public static final String STAGE_MONITOR_KEY_CALIBRATION_DIALOG = "calibration.dialog";
public static final String STAGE_MONITOR_KEY_CHANNEL_MAP_EDITOR = "channel.map";
public static final String STAGE_MONITOR_KEY_RECORDING_VIEWER = "recording.viewer";
@@ -76,7 +63,6 @@ public class JavaFxWindowManager extends Application
public static final String STAGE_MONITOR_KEY_PLAYLIST_EDITOR = "playlist";
public static final String STAGE_MONITOR_KEY_USER_PREFERENCES_EDITOR = "user.preferences";
private JFXPanel mJFXPanel;
private ChannelMapEditor mChannelMapEditor;
private IconManager mIconManager;
private JmbeEditor mJmbeEditor;
@@ -93,12 +79,14 @@ public class JavaFxWindowManager extends Application
private Stage mPlaylistStage;
private Stage mUserPreferencesStage;
private Stage mRecordingViewerStage;
private JFXPanel mStatusPanel;
/**
* Constructs an instance. Note: this constructor is used for Swing applications.
* Constructs an instance and registers it to receive window requests on the event bus.
* @param userPreferences for the windows and their stored locations
* @param tunerManager for the playlist editor
* @param playlistManager for the playlist and channel map editors
*/
public JavaFxWindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager)
public WindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager)
{
mUserPreferences = userPreferences;
mTunerManager = tunerManager;
@@ -107,43 +95,6 @@ public class JavaFxWindowManager extends Application
setup();
}
/**
* Constructs an instance. Note: this constructor is used for standalone JavaFX application testing
*/
public JavaFxWindowManager()
{
mUserPreferences = new UserPreferences();
AliasModel aliasModel = new AliasModel();
EventLogManager eventLogManager = new EventLogManager(aliasModel, mUserPreferences);
mTunerManager = new TunerManager(mUserPreferences);
mTunerManager.start();
mPlaylistManager = new PlaylistManager(mUserPreferences, mTunerManager, aliasModel, eventLogManager, new IconModel());
mPlaylistManager.init();
setup();
}
/**
* Creates or accesses the JavaFX status panel, used by the main application GUI.
* @param resourceMonitor for statistics
* @return JFXPanel accessible on Swing thread that delegates JavaFX scene creation to the FX event thread.
*/
public JFXPanel getStatusPanel(ResourceMonitor resourceMonitor)
{
if(mStatusPanel == null)
{
mStatusPanel = new JFXPanel();
//JFXPanel has to be populated on the FX event thread
Platform.runLater(() -> {
Scene scene = new Scene(new StatusBox(resourceMonitor));
ThemeManager.getInstance().register(scene);
mStatusPanel.setScene(scene);
});
}
return mStatusPanel;
}
private void setup()
{
//Register this class to receive events via each method annotated with @Subscribe
@@ -152,7 +103,7 @@ public class JavaFxWindowManager extends Application
//Register JavaFX icon fonts
IconFontFX.register(jiconfont.icons.font_awesome.FontAwesome.getIconFont());
createJFXPanel();
startToolkit();
}
/**
@@ -160,7 +111,7 @@ public class JavaFxWindowManager extends Application
*/
private void execute(Runnable runnable)
{
createJFXPanel();
startToolkit();
if(Platform.isFxApplicationThread())
{
@@ -173,16 +124,11 @@ public class JavaFxWindowManager extends Application
}
/**
* Creates a JavaFX panel for Swing application compatibility
* Starts the JavaFX toolkit if it is not running
*/
private void createJFXPanel()
private void startToolkit()
{
if(mJFXPanel == null)
{
mJFXPanel = new JFXPanel();
Platform.setImplicitExit(false);
ApplicationIcons.installJavaFx();
}
FxToolkit.ensureStarted();
}
/**
@@ -197,7 +143,7 @@ public class JavaFxWindowManager extends Application
public CalibrationDialog getCalibrationDialog(UserPreferences userPreferences)
{
createJFXPanel();
startToolkit();
return new CalibrationDialog(userPreferences);
}
@@ -208,7 +154,7 @@ public class JavaFxWindowManager extends Application
{
if(mRecordingViewerStage == null)
{
createJFXPanel();
startToolkit();
Scene scene = new Scene(getRecordingViewer(), 1100, 800);
ThemeManager.getInstance().register(scene);
mRecordingViewerStage = new Stage();
@@ -234,7 +180,7 @@ public class JavaFxWindowManager extends Application
{
if(mIconManagerStage == null)
{
createJFXPanel();
startToolkit();
Scene scene = new Scene(getIconManager(), 500, 500);
ThemeManager.getInstance().register(scene);
mIconManagerStage = new Stage();
@@ -283,7 +229,7 @@ public class JavaFxWindowManager extends Application
{
if(mJmbeEditorStage == null)
{
createJFXPanel();
startToolkit();
Scene scene = new Scene(getJmbeEditor(), 650, 650);
ThemeManager.getInstance().register(scene);
mJmbeEditorStage = new Stage();
@@ -325,7 +271,7 @@ public class JavaFxWindowManager extends Application
{
if(mPlaylistStage == null)
{
createJFXPanel();
startToolkit();
Scene scene = new Scene(getPlaylistEditor(), 1000, 750);
ThemeManager.getInstance().register(scene);
mPlaylistStage = new Stage();
@@ -376,7 +322,7 @@ public class JavaFxWindowManager extends Application
{
if(mUserPreferencesStage == null)
{
createJFXPanel();
startToolkit();
Scene scene = new Scene(getUserPreferencesEditor(), 900, 500);
ThemeManager.getInstance().register(scene);
mUserPreferencesStage = new Stage();
@@ -420,7 +366,7 @@ public class JavaFxWindowManager extends Application
{
if(mChannelMapStage == null)
{
createJFXPanel();
startToolkit();
Scene scene = new Scene(getChannelMapEditor(), 500, 500);
ThemeManager.getInstance().register(scene);
mChannelMapStage = new Stage();
@@ -470,75 +416,4 @@ public class JavaFxWindowManager extends Application
stage.requestFocus();
stage.toFront();
}
@Override
public void start(Stage primaryStage) throws Exception
{
mLog.debug("Starting ...");
Parameters parameters = getParameters();
mLog.debug("Parameters: " + (parameters != null));
boolean valid = false;
if(parameters != null && parameters.getRaw().size() == 1)
{
String window = parameters.getRaw().get(0);
if(window != null)
{
switch(window)
{
case CHANNEL_MAP_EDITOR:
//Generate some test data for the editor
ChannelMap channelMap1 = new ChannelMap("Test Map 1");
channelMap1.addRange(new ChannelRange(1,199,150000000, 12500));
channelMap1.addRange(new ChannelRange(200,299,160000000, 25000));
channelMap1.addRange(new ChannelRange(300,399,170000000, 12500));
channelMap1.addRange(new ChannelRange(400,499,180000000, 25000));
mPlaylistManager.getChannelMapModel().addChannelMap(channelMap1);
ChannelMap channelMap2 = new ChannelMap("Test Map 2");
channelMap2.addRange(new ChannelRange(1,199,450000000, 12500));
channelMap2.addRange(new ChannelRange(200,299,460000000, 25000));
channelMap2.addRange(new ChannelRange(300,399,470000000, 12500));
channelMap2.addRange(new ChannelRange(400,499,480000000, 25000));
mPlaylistManager.getChannelMapModel().addChannelMap(channelMap2);
valid = true;
process(new ViewChannelMapEditorRequest());
break;
case ICON_MANAGER:
valid = true;
process(new ViewIconManagerRequest());
break;
case PLAYLIST_EDITOR:
valid = true;
process(new ViewPlaylistRequest());
break;
case USER_PREFERENCES_EDITOR:
valid = true;
process(new ViewUserPreferenceEditorRequest(PreferenceEditorType.DEFAULT));
break;
default:
break;
}
}
}
if(!valid)
{
StringBuilder sb = new StringBuilder();
sb.append("An argument is required to launch JavaFX windows from this window manager. " +
"Valid options are:\n\tchannelmap\tChannel Map Editor\n\ticonmanager\tIcon Manager\n\tplaylist\tPlaylist Editor\n" +
"\tpreferences\tUser Preferences Editor\n");
sb.append("Supplied Argument(s): ").append(parameters.getRaw());
mLog.error(sb.toString());
}
}
public static void main(String[] args)
{
mLog.info("Application Start - Parameters: " + args);
launch(args);
}
}

View File

@@ -0,0 +1,548 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.audio;
import com.google.common.base.Joiner;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.audio.playback.AudioChannel;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.sample.Listener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconNode;
/**
* Display for one audio playback channel (mono, or the left/right channel of a stereo output). Shows the call that
* is playing: the TO alias or identifier as the headline with the alias icon and color, the FROM radio, the system,
* site and channel, the elapsed call time and an audio level meter, plus a per-channel mute. When the call ends,
* the last call stays on the display, dimmed, until the next call starts.
*/
public class AudioChannelView extends HBox
{
private static final String NO_CALL = "No audio";
private static final Color DEFAULT_ACCENT = Color.web("#3ddc84");
private static final Color DISPLAY_BACKGROUND = Color.web("#161b22");
private final AudioChannel mAudioChannel;
private final AliasModel mAliasModel;
private final IconModel mIconModel;
private final TalkgroupFormatPreference mTalkgroupFormatPreference;
private final Runnable mMuteChangeListener;
private final Listener<AudioEvent> mAudioEventListener = this::receive;
private final Listener<IdentifierCollection> mMetadataListener = this::receive;
private final Region mAccentStrip = new Region();
private final StackPane mIconPane = new StackPane();
private final ImageView mAliasImage = new ImageView();
private final IconNode mPlaceholderIcon = new IconNode(FontAwesome.HEADPHONES);
private final Label mChannelTag = new Label();
private final Label mStatusLabel = new Label();
private final Label mElapsedLabel = new Label();
private final ToggleButton mMuteButton = new ToggleButton();
private final IconNode mMuteIcon = new IconNode(FontAwesome.VOLUME_UP);
private final Label mToLabel = new Label(NO_CALL);
private final Label mToDetailLabel = new Label();
private final Label mFromLabel = new Label();
private final Label mContextLabel = new Label();
private final HBox mFromBox;
private final LevelMeter mLevelMeter;
private IdentifierCollection mIdentifierCollection;
private Identifier mCallToIdentifier;
private boolean mActive;
private boolean mHasPlayed;
private long mCallStartNanos;
private long mCallEndNanos;
/**
* Constructs an instance
* @param audioChannel to display
* @param aliasModel for alias lookup
* @param iconModel for alias icons
* @param talkgroupFormatPreference for identifier formatting
* @param updatesPerSecond rate that {@link #tick()} is invoked
* @param muteChangeListener notified on the FX thread when this channel's mute state changes
*/
public AudioChannelView(AudioChannel audioChannel, AliasModel aliasModel, IconModel iconModel,
TalkgroupFormatPreference talkgroupFormatPreference, double updatesPerSecond,
Runnable muteChangeListener)
{
mAudioChannel = audioChannel;
mAliasModel = aliasModel;
mIconModel = iconModel;
mTalkgroupFormatPreference = talkgroupFormatPreference;
mMuteChangeListener = muteChangeListener;
mLevelMeter = new LevelMeter(updatesPerSecond);
getStyleClass().add("audio-channel");
setFillHeight(true);
setMinWidth(0);
setPrefWidth(420);
setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(this, Priority.ALWAYS);
mAccentStrip.getStyleClass().add("audio-accent");
mAccentStrip.setMinWidth(5);
mAccentStrip.setPrefWidth(5);
mAccentStrip.setMaxHeight(Double.MAX_VALUE);
mAliasImage.setPreserveRatio(true);
mAliasImage.setFitHeight(36);
mAliasImage.setFitWidth(36);
mAliasImage.setSmooth(true);
mPlaceholderIcon.setIconSize(26);
mPlaceholderIcon.getStyleClass().add("audio-placeholder-icon");
mIconPane.getStyleClass().add("audio-icon-pane");
mIconPane.setMinSize(52, 52);
mIconPane.setPrefSize(52, 52);
mIconPane.setMaxSize(52, 52);
mIconPane.getChildren().addAll(mPlaceholderIcon, mAliasImage);
VBox iconColumn = new VBox(mIconPane);
iconColumn.setAlignment(Pos.CENTER);
mChannelTag.setText(audioChannel.getChannelName());
mChannelTag.getStyleClass().add("audio-channel-tag");
mStatusLabel.getStyleClass().add("audio-status");
mElapsedLabel.getStyleClass().add("audio-elapsed");
mMuteIcon.setIconSize(15);
mMuteIcon.getStyleClass().add("audio-button-icon");
mMuteButton.setGraphic(mMuteIcon);
mMuteButton.getStyleClass().add("audio-icon-button");
mMuteButton.setFocusTraversable(true);
mMuteButton.setOnAction(event -> {
mAudioChannel.setMuted(mMuteButton.isSelected());
updateMuted();
});
Region headerSpacer = new Region();
HBox.setHgrow(headerSpacer, Priority.ALWAYS);
HBox header = new HBox(8, mChannelTag, mStatusLabel, headerSpacer, mElapsedLabel, mMuteButton);
header.setAlignment(Pos.CENTER_LEFT);
mToLabel.getStyleClass().add("audio-to");
mToLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
mToLabel.setMinWidth(0);
mToDetailLabel.getStyleClass().add("audio-to-detail");
mToDetailLabel.setMinWidth(Region.USE_PREF_SIZE);
HBox toBox = new HBox(10, mToLabel, mToDetailLabel);
toBox.setAlignment(Pos.BASELINE_LEFT);
IconNode fromIcon = new IconNode(FontAwesome.MICROPHONE);
fromIcon.setIconSize(12);
fromIcon.getStyleClass().add("audio-detail-icon");
mFromLabel.getStyleClass().add("audio-detail");
mFromLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
mFromLabel.setMinWidth(0);
mFromLabel.setMaxWidth(280);
mFromBox = new HBox(5, fromIcon, mFromLabel);
mFromBox.setAlignment(Pos.CENTER_LEFT);
//The FROM radio keeps its width and the system/site/channel text shrinks first
mFromBox.setMinWidth(Region.USE_PREF_SIZE);
mContextLabel.getStyleClass().add("audio-context");
mContextLabel.setTextOverrun(OverrunStyle.LEADING_ELLIPSIS);
mContextLabel.setMinWidth(0);
HBox.setHgrow(mContextLabel, Priority.ALWAYS);
mContextLabel.setMaxWidth(Double.MAX_VALUE);
mContextLabel.setAlignment(Pos.CENTER_RIGHT);
HBox detailBox = new HBox(14, mFromBox, mContextLabel);
detailBox.setAlignment(Pos.CENTER_LEFT);
mLevelMeter.setMaxWidth(Double.MAX_VALUE);
VBox content = new VBox(2, header, toBox, detailBox, mLevelMeter);
content.getStyleClass().add("audio-channel-content");
content.setMinWidth(0);
VBox.setMargin(mLevelMeter, new javafx.geometry.Insets(6, 0, 0, 0));
HBox.setHgrow(content, Priority.ALWAYS);
getChildren().addAll(mAccentStrip, iconColumn, content);
updateDisplay();
updateMuted();
mAudioChannel.addAudioEventListener(mAudioEventListener);
mAudioChannel.setIdentifierCollectionListener(mMetadataListener);
}
/**
* Deregisters from the audio channel.
*/
public void dispose()
{
mAudioChannel.removeAudioEventListener(mAudioEventListener);
mAudioChannel.removeAudioMetadataListener();
}
/**
* Channel displayed by this view
*/
public AudioChannel getAudioChannel()
{
return mAudioChannel;
}
/**
* Periodic update of the level meter and elapsed time. Invoke on the FX application thread.
*/
public void tick()
{
mLevelMeter.update(mAudioChannel.getAndResetPeakLevel());
if(mActive)
{
updateElapsed();
}
}
/**
* Refreshes the identifier text, for example when the identifier format preference changes.
*/
public void refresh()
{
updateDisplay();
}
/**
* Updates the muted display after the channel or the whole output was (un)muted.
*/
public void updateMuted()
{
boolean muted = mAudioChannel.isMuted();
mMuteButton.setSelected(muted);
mMuteIcon.setIconCode(muted ? FontAwesome.VOLUME_OFF : FontAwesome.VOLUME_UP);
mMuteButton.setTooltip(new Tooltip(muted ? "Unmute " + getChannelDescription() : "Mute " +
getChannelDescription()));
mMuteButton.setAccessibleText(muted ? "Unmute" : "Mute");
mLevelMeter.setDimmed(muted);
pseudoClassStateChanged(AudioView.MUTED, muted);
updateStatus();
}
private String getChannelDescription()
{
return switch(mAudioChannel.getChannelName())
{
case "LEFT" -> "left channel";
case "RIGHT" -> "right channel";
default -> "audio";
};
}
/**
* Audio channel events, received on the audio thread.
*/
private void receive(AudioEvent audioEvent)
{
switch(audioEvent.getType())
{
case AUDIO_STOPPED -> Platform.runLater(() -> setIdentifierCollection(null));
case AUDIO_MUTED, AUDIO_UNMUTED -> Platform.runLater(() -> {
updateMuted();
mMuteChangeListener.run();
});
default -> {}
}
}
/**
* Audio metadata for the playing call, received on the audio thread. Null when playback ends.
*/
private void receive(IdentifierCollection identifierCollection)
{
Platform.runLater(() -> setIdentifierCollection(identifierCollection));
}
/**
* Updates the call metadata. FX thread only.
*/
private void setIdentifierCollection(IdentifierCollection identifierCollection)
{
Identifier to = identifierCollection != null ? identifierCollection.getToIdentifier() : null;
if(identifierCollection == null || to == null)
{
if(mActive)
{
mActive = false;
mCallEndNanos = System.nanoTime();
updateElapsed();
mLevelMeter.reset();
}
//Keep the last call's identifiers so that the display shows the last call, dimmed.
updateStatus();
pseudoClassStateChanged(AudioView.ACTIVE, false);
return;
}
if(!mActive || !to.equals(mCallToIdentifier))
{
mCallStartNanos = System.nanoTime();
}
mActive = true;
mHasPlayed = true;
mCallToIdentifier = to;
mIdentifierCollection = identifierCollection;
pseudoClassStateChanged(AudioView.ACTIVE, true);
updateDisplay();
updateElapsed();
}
/**
* Updates the status chip text.
*/
private void updateStatus()
{
String status;
if(mActive)
{
status = mAudioChannel.isMuted() ? "MUTED" : "PLAYING";
}
else if(mAudioChannel.isMuted())
{
status = "MUTED";
}
else
{
status = mHasPlayed ? "LAST CALL" : "IDLE";
}
mStatusLabel.setText(status);
mElapsedLabel.setVisible(mHasPlayed);
}
private void updateElapsed()
{
long end = mActive ? System.nanoTime() : mCallEndNanos;
long seconds = Math.max(0, (end - mCallStartNanos) / 1_000_000_000L);
String text = seconds >= 3600 ? String.format("%d:%02d:%02d", seconds / 3600, (seconds / 60) % 60,
seconds % 60) : String.format("%d:%02d", seconds / 60, seconds % 60);
if(!text.equals(mElapsedLabel.getText()))
{
mElapsedLabel.setText(text);
}
}
/**
* Updates the identifiers, alias icon and accent color from the current identifier collection.
*/
private void updateDisplay()
{
updateStatus();
IdentifierCollection collection = mIdentifierCollection;
if(collection == null)
{
mToLabel.setText(NO_CALL);
mToDetailLabel.setText("");
mFromBox.setVisible(false);
mContextLabel.setText("");
setAlias(null);
return;
}
AliasList aliasList = mAliasModel != null ? mAliasModel.getAliasList(collection) : null;
Identifier to = collection.getToIdentifier();
List<Alias> toAliases = getAliases(aliasList, to);
String toId = format(to);
if(toAliases.isEmpty())
{
mToLabel.setText(toId != null ? toId : "Unknown");
mToDetailLabel.setText("");
setAlias(null);
}
else
{
mToLabel.setText(Joiner.on(", ").skipNulls().join(toAliases));
mToDetailLabel.setText(toId != null ? toId : "");
setAlias(toAliases.getFirst());
}
String from = getFromText(collection, aliasList);
mFromLabel.setText(from != null ? from : "");
mFromBox.setVisible(from != null);
mContextLabel.setText(getContextText(collection));
}
/**
* FROM radio alias and/or identifier text, or null when the call has no FROM identifier.
*/
private String getFromText(IdentifierCollection collection, AliasList aliasList)
{
Identifier from = collection.getFromIdentifier();
String fromId = format(from);
String fromName = null;
List<Alias> fromAliases = getAliases(aliasList, from);
if(!fromAliases.isEmpty())
{
fromName = Joiner.on(", ").skipNulls().join(fromAliases);
}
else
{
List<Identifier> talkerAliases = collection.getIdentifiers(Form.TALKER_ALIAS);
if(!talkerAliases.isEmpty())
{
Object value = talkerAliases.getFirst().getValue();
fromName = value != null ? value.toString() : null;
}
}
if(fromName != null && fromId != null)
{
return fromName + " " + fromId;
}
return fromName != null ? fromName : fromId;
}
/**
* System, site, channel name and protocol text.
*/
private static String getContextText(IdentifierCollection collection)
{
List<String> parts = new ArrayList<>();
add(parts, collection, Form.SYSTEM);
add(parts, collection, Form.SITE);
add(parts, collection, Form.CHANNEL_NAME);
add(parts, collection, Form.DECODER_TYPE);
return String.join(" · ", parts);
}
private static void add(List<String> parts, IdentifierCollection collection, Form form)
{
List<Identifier> identifiers = collection.getIdentifiers(IdentifierClass.CONFIGURATION, form);
if(!identifiers.isEmpty())
{
String text = identifiers.getFirst().toString();
if(text != null && !text.isBlank() && !parts.contains(text))
{
parts.add(text);
}
}
}
private static List<Alias> getAliases(AliasList aliasList, Identifier identifier)
{
if(aliasList == null || identifier == null)
{
return Collections.emptyList();
}
List<Alias> aliases = aliasList.getAliases(identifier);
return aliases != null ? aliases : Collections.emptyList();
}
private String format(Identifier identifier)
{
if(identifier == null)
{
return null;
}
return mTalkgroupFormatPreference != null ? mTalkgroupFormatPreference.format(identifier) :
identifier.toString();
}
/**
* Applies the alias icon and color, or the defaults when the alias is null.
*/
private void setAlias(Alias alias)
{
Icon icon = alias != null && alias.getIconName() != null && mIconModel != null ?
mIconModel.getIcon(alias.getIconName()) : null;
mAliasImage.setImage(icon != null ? icon.getFxImage() : null);
mPlaceholderIcon.setVisible(mAliasImage.getImage() == null);
Color accent = alias != null ? toReadable(alias.getColor()) : DEFAULT_ACCENT;
String rgb = toWeb(accent);
setStyle("-audio-accent: " + rgb + ";");
}
/**
* Converts the alias RGB color to a color that stands out against the dark display background.
*/
static Color toReadable(int rgb)
{
Color color = Color.rgb((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);
double luminance = luminance(color);
double background = luminance(DISPLAY_BACKGROUND);
//WCAG contrast ratio of at least 3:1 for the accent against the display background
int steps = 0;
while((luminance + 0.05) / (background + 0.05) < 3.0 && steps++ < 10)
{
color = color.interpolate(Color.WHITE, 0.2);
luminance = luminance(color);
}
return color;
}
private static double luminance(Color color)
{
return 0.2126 * linear(color.getRed()) + 0.7152 * linear(color.getGreen()) + 0.0722 * linear(color.getBlue());
}
private static double linear(double channel)
{
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
}
private static String toWeb(Color color)
{
return String.format("#%02x%02x%02x", (int)Math.round(color.getRed() * 255),
(int)Math.round(color.getGreen() * 255), (int)Math.round(color.getBlue() * 255));
}
}

View File

@@ -0,0 +1,392 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.audio;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.audio.AudioEvent;
import io.github.dsheirer.audio.playback.AudioChannel;
import io.github.dsheirer.audio.playback.AudioOutput;
import io.github.dsheirer.audio.playback.AudioPlaybackDeviceDescriptor;
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Slider;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import javax.sound.sampled.FloatControl;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconFontFX;
import jiconfont.javafx.IconNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Audio playback display. A master section with the output mute, volume and audio device settings, followed by one
* display per audio channel: a single wide display for a mono output or side by side left and right displays for a
* stereo output. Rebuilds the channel displays when the audio playback device configuration changes.
*/
public class AudioView extends HBox
{
private static final Logger mLog = LoggerFactory.getLogger(AudioView.class);
static final PseudoClass ACTIVE = PseudoClass.getPseudoClass("active");
static final PseudoClass MUTED = PseudoClass.getPseudoClass("muted");
private static final double UPDATES_PER_SECOND = 25.0;
private final AudioPlaybackManager mAudioPlaybackManager;
private final AliasModel mAliasModel;
private final IconModel mIconModel;
private final UserPreferences mUserPreferences;
private final Listener<AudioEvent> mAudioEventListener = this::receive;
private final List<AudioChannelView> mChannelViews = new ArrayList<>();
private final HBox mChannelsBox = new HBox(8);
private final ToggleButton mMuteButton = new ToggleButton();
private final IconNode mMuteIcon = new IconNode(FontAwesome.VOLUME_UP);
private final Label mDeviceLabel = new Label();
private final HBox mVolumeBox;
private final Slider mVolumeSlider = new Slider(0, 100, 50);
private final Timeline mTimeline;
private FloatControl mGainControl;
static
{
IconFontFX.register(FontAwesome.getIconFont());
}
/**
* Constructs an instance
* @param audioPlaybackManager for the audio output and channels
* @param aliasModel for alias lookup
* @param iconModel for alias icons
* @param userPreferences for identifier formatting
*/
public AudioView(AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel, IconModel iconModel,
UserPreferences userPreferences)
{
mAudioPlaybackManager = audioPlaybackManager;
mAliasModel = aliasModel;
mIconModel = iconModel;
mUserPreferences = userPreferences;
getStyleClass().add("audio-view");
URL stylesheet = AudioView.class.getResource("/audio_panel.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
setSpacing(8);
setFillHeight(true);
//Master controls
Label title = new Label("AUDIO");
title.getStyleClass().add("audio-master-title");
mDeviceLabel.getStyleClass().add("audio-device");
mDeviceLabel.setMaxWidth(150);
mMuteIcon.setIconSize(22);
mMuteIcon.getStyleClass().add("audio-button-icon");
mMuteButton.setGraphic(mMuteIcon);
mMuteButton.getStyleClass().addAll("audio-icon-button", "audio-master-mute");
mMuteButton.setOnAction(event -> setOutputMuted(mMuteButton.isSelected()));
IconNode settingsIcon = new IconNode(FontAwesome.COG);
settingsIcon.setIconSize(16);
settingsIcon.getStyleClass().add("audio-button-icon");
Button settingsButton = new Button();
settingsButton.setGraphic(settingsIcon);
settingsButton.getStyleClass().add("audio-icon-button");
settingsButton.setTooltip(new Tooltip("Audio playback device and preferences"));
settingsButton.setAccessibleText("Audio settings");
settingsButton.setOnAction(event -> showAudioPreferences());
HBox buttons = new HBox(6, mMuteButton, settingsButton);
buttons.setAlignment(Pos.CENTER_LEFT);
IconNode volumeIcon = new IconNode(FontAwesome.VOLUME_DOWN);
volumeIcon.setIconSize(12);
volumeIcon.getStyleClass().add("audio-detail-icon");
mVolumeSlider.getStyleClass().add("audio-volume");
mVolumeSlider.setPrefWidth(110);
mVolumeSlider.setTooltip(new Tooltip("Volume (double-click to reset)"));
mVolumeSlider.setAccessibleText("Volume");
mVolumeSlider.valueProperty().addListener((observable, oldValue, newValue) -> applyVolume(newValue.intValue()));
mVolumeSlider.setOnMouseClicked(event -> {
if(event.getClickCount() == 2)
{
mVolumeSlider.setValue(50);
}
});
mVolumeBox = new HBox(5, volumeIcon, mVolumeSlider);
mVolumeBox.setAlignment(Pos.CENTER_LEFT);
VBox master = new VBox(6, title, buttons, mVolumeBox, mDeviceLabel);
master.getStyleClass().add("audio-master");
master.setMinWidth(VBox.USE_PREF_SIZE);
HBox.setHgrow(mChannelsBox, Priority.ALWAYS);
mChannelsBox.setFillHeight(true);
mChannelsBox.setMinWidth(0);
getChildren().addAll(master, mChannelsBox);
ContextMenu contextMenu = new ContextMenu();
MenuItem preferences = new MenuItem("Audio Playback Device ...");
IconNode cog = new IconNode(FontAwesome.COG);
cog.setIconSize(14);
preferences.setGraphic(cog);
preferences.setOnAction(event -> showAudioPreferences());
contextMenu.getItems().add(preferences);
setOnMouseClicked(event -> {
if(event.getButton() == MouseButton.SECONDARY)
{
contextMenu.show(this, event.getScreenX(), event.getScreenY());
}
else
{
contextMenu.hide();
}
});
mTimeline = new Timeline(new KeyFrame(Duration.millis(1000.0 / UPDATES_PER_SECOND), event -> tick()));
mTimeline.setCycleCount(Animation.INDEFINITE);
rebuild();
mAudioPlaybackManager.addAudioEventListener(mAudioEventListener);
MyEventBus.getGlobalEventBus().register(this);
mTimeline.play();
}
/**
* Stops updates and deregisters from the audio playback manager.
*/
public void dispose()
{
mTimeline.stop();
mAudioPlaybackManager.removeAudioEventListener(mAudioEventListener);
MyEventBus.getGlobalEventBus().unregister(this);
disposeChannelViews();
}
/**
* Updates the identifier display when the identifier format preference changes.
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
Platform.runLater(() -> mChannelViews.forEach(AudioChannelView::refresh));
}
}
/**
* Audio playback manager events, received on the calling thread.
*/
private void receive(AudioEvent event)
{
if(event.getType() == AudioEvent.Type.AUDIO_CONFIGURATION_CHANGE_COMPLETE)
{
Platform.runLater(this::rebuild);
}
}
private void tick()
{
for(AudioChannelView channelView: mChannelViews)
{
channelView.tick();
}
}
private void disposeChannelViews()
{
mChannelViews.forEach(AudioChannelView::dispose);
mChannelViews.clear();
mChannelsBox.getChildren().clear();
}
/**
* Rebuilds the channel displays and master controls for the current audio output. FX thread only.
*/
private void rebuild()
{
disposeChannelViews();
List<AudioChannel> channels = mAudioPlaybackManager.getAudioChannels();
for(AudioChannel channel: channels)
{
AudioChannelView view = new AudioChannelView(channel, mAliasModel, mIconModel,
mUserPreferences.getTalkgroupFormatPreference(), UPDATES_PER_SECOND, this::updateMuted);
mChannelViews.add(view);
mChannelsBox.getChildren().add(view);
}
AudioOutput output = mAudioPlaybackManager.getAudioOutput();
mGainControl = output != null && output.hasGainControl() ? output.getGainControl() : null;
mVolumeBox.setVisible(mGainControl != null);
mVolumeBox.setManaged(mGainControl != null);
if(mGainControl != null)
{
mVolumeSlider.setValue(toSliderValue(mGainControl.getValue()));
}
AudioPlaybackDeviceDescriptor device = mAudioPlaybackManager.getAudioPlaybackDevice();
String deviceName = device != null ? device.toString() : "No audio device";
String layout = switch(channels.size())
{
case 0 -> "";
case 1 -> "Mono";
case 2 -> "Stereo";
default -> channels.size() + " channels";
};
mDeviceLabel.setText(layout.isEmpty() ? deviceName : layout + " · " + deviceName);
mDeviceLabel.setTooltip(new Tooltip(mDeviceLabel.getText()));
if(channels.isEmpty())
{
Label none = new Label("No audio playback device available");
none.getStyleClass().add("audio-detail");
mChannelsBox.getChildren().add(none);
}
mMuteButton.setDisable(output == null);
updateMuted();
}
/**
* Updates the master mute button. The output is muted when every channel is muted.
*/
private void updateMuted()
{
boolean muted = !mChannelViews.isEmpty();
for(AudioChannelView view: mChannelViews)
{
muted &= view.getAudioChannel().isMuted();
}
mMuteButton.setSelected(muted);
mMuteIcon.setIconCode(muted ? FontAwesome.VOLUME_OFF : FontAwesome.VOLUME_UP);
mMuteButton.setTooltip(new Tooltip(muted ? "Unmute all audio" : "Mute all audio"));
mMuteButton.setAccessibleText(muted ? "Unmute all audio" : "Mute all audio");
}
private void setOutputMuted(boolean muted)
{
AudioOutput output = mAudioPlaybackManager.getAudioOutput();
if(output != null)
{
output.setMuted(muted);
}
mChannelViews.forEach(AudioChannelView::updateMuted);
updateMuted();
}
private void showAudioPreferences()
{
MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.AUDIO_OUTPUT));
}
private void applyVolume(int value)
{
FloatControl control = mGainControl;
if(control != null)
{
try
{
control.shift(control.getValue(), toGain(control, value), 1000);
}
catch(Exception e)
{
mLog.warn("Unable to set audio output gain", e);
}
}
}
/**
* Converts a gain control value in dB to the slider value, where 50 is the 0 dB (no gain) mid-point.
*/
private int toSliderValue(float gain)
{
FloatControl control = mGainControl;
if(control == null || gain == 0.0f)
{
return 50;
}
else if(gain < 0.0f)
{
return 50 - (int)(gain / control.getMinimum() * 50.0f);
}
else
{
return 50 + (int)(gain / control.getMaximum() * 50.0f);
}
}
/**
* Converts the slider value to a gain control value in dB, where 50 is the 0 dB (no gain) mid-point.
*/
static float toGain(FloatControl control, int value)
{
if(value == 50)
{
return 0.0f;
}
else if(value < 50)
{
return (float)(50 - value) / 50.0f * control.getMinimum();
}
else
{
return (float)(value - 50) / 50.0f * control.getMaximum();
}
}
}

View File

@@ -0,0 +1,207 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.audio;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
/**
* Segmented horizontal audio level meter in dBFS with peak hold and level ballistics. Feed it with peak sample
* levels via {@link #update(float)} at a steady rate from the JavaFX application thread.
*/
public class LevelMeter extends Region
{
public static final double MINIMUM_DB = -48.0;
public static final double MAXIMUM_DB = 0.0;
private static final double WARNING_DB = -12.0;
private static final double CLIP_DB = -3.0;
private static final double SEGMENT_WIDTH = 4.0;
private static final double SEGMENT_GAP = 2.0;
private static final double PREFERRED_HEIGHT = 8.0;
private static final Color NORMAL_ON = Color.web("#3ddc84");
private static final Color WARNING_ON = Color.web("#f5c542");
private static final Color CLIP_ON = Color.web("#ff5c5c");
private static final Color NORMAL_OFF = Color.web("#3ddc84", 0.12);
private static final Color WARNING_OFF = Color.web("#f5c542", 0.12);
private static final Color CLIP_OFF = Color.web("#ff5c5c", 0.12);
private final Canvas mCanvas = new Canvas();
private final double mFallPerUpdateDb;
private final int mPeakHoldUpdates;
private double mLevelDb = MINIMUM_DB;
private double mPeakDb = MINIMUM_DB;
private int mPeakHoldCount;
private boolean mDimmed;
private boolean mDirty = true;
private double mDrawnLevelDb = Double.NaN;
private double mDrawnPeakDb = Double.NaN;
/**
* Constructs an instance
* @param updatesPerSecond rate that {@link #update(float)} is invoked, to scale the level fall and peak hold.
*/
public LevelMeter(double updatesPerSecond)
{
mFallPerUpdateDb = 30.0 / updatesPerSecond; //30 dB per second fall
mPeakHoldUpdates = (int)Math.round(1.5 * updatesPerSecond); //1.5 second peak hold
getStyleClass().add("level-meter");
getChildren().add(mCanvas);
setMinHeight(PREFERRED_HEIGHT);
setPrefHeight(PREFERRED_HEIGHT);
setMaxHeight(PREFERRED_HEIGHT);
setMinWidth(40);
}
/**
* Updates the meter with the peak sample level measured since the previous update.
* @param peak absolute sample peak, where 1.0 is full scale.
*/
public void update(float peak)
{
double db = peak > 0.0f ? Math.max(MINIMUM_DB, Math.min(MAXIMUM_DB, 20.0 * Math.log10(peak))) : MINIMUM_DB;
double level = Math.max(db, mLevelDb - mFallPerUpdateDb);
if(db >= mPeakDb)
{
mPeakDb = db;
mPeakHoldCount = mPeakHoldUpdates;
}
else if(mPeakHoldCount > 0)
{
mPeakHoldCount--;
}
else
{
mPeakDb = Math.max(MINIMUM_DB, mPeakDb - mFallPerUpdateDb);
}
mLevelDb = level;
if(mDirty || mLevelDb != mDrawnLevelDb || mPeakDb != mDrawnPeakDb)
{
draw();
}
}
/**
* Sets the meter to draw in a dimmed state, for example when the channel is muted.
*/
public void setDimmed(boolean dimmed)
{
if(mDimmed != dimmed)
{
mDimmed = dimmed;
mCanvas.setOpacity(dimmed ? 0.45 : 1.0);
}
}
/**
* Resets the meter to silence.
*/
public void reset()
{
mLevelDb = MINIMUM_DB;
mPeakDb = MINIMUM_DB;
mPeakHoldCount = 0;
draw();
}
@Override
protected void layoutChildren()
{
double width = snapSizeX(getWidth());
double height = snapSizeY(getHeight());
if(mCanvas.getWidth() != width || mCanvas.getHeight() != height)
{
mCanvas.setWidth(width);
mCanvas.setHeight(height);
draw();
}
}
@Override
protected double computePrefWidth(double height)
{
return 200;
}
/**
* Fraction of the meter span for the dB value.
*/
private static double toFraction(double db)
{
return (db - MINIMUM_DB) / (MAXIMUM_DB - MINIMUM_DB);
}
private void draw()
{
mDirty = false;
mDrawnLevelDb = mLevelDb;
mDrawnPeakDb = mPeakDb;
double width = mCanvas.getWidth();
double height = mCanvas.getHeight();
GraphicsContext gc = mCanvas.getGraphicsContext2D();
gc.clearRect(0, 0, width, height);
if(width <= 0 || height <= 0)
{
return;
}
int segments = (int)Math.floor((width + SEGMENT_GAP) / (SEGMENT_WIDTH + SEGMENT_GAP));
if(segments <= 0)
{
return;
}
//Spread the remainder across the gaps so the meter fills the width
double step = segments > 1 ? (width - SEGMENT_WIDTH) / (segments - 1) : 0;
double levelFraction = toFraction(mLevelDb);
double peakFraction = toFraction(mPeakDb);
int peakSegment = mPeakDb > MINIMUM_DB ? (int)Math.min(segments - 1, Math.floor(peakFraction * segments)) : -1;
for(int x = 0; x < segments; x++)
{
double segmentFraction = (x + 0.5) / segments;
double segmentDb = MINIMUM_DB + segmentFraction * (MAXIMUM_DB - MINIMUM_DB);
boolean on = segmentFraction <= levelFraction || x == peakSegment;
if(segmentDb >= CLIP_DB)
{
gc.setFill(on ? CLIP_ON : CLIP_OFF);
}
else if(segmentDb >= WARNING_DB)
{
gc.setFill(on ? WARNING_ON : WARNING_OFF);
}
else
{
gc.setFill(on ? NORMAL_ON : NORMAL_OFF);
}
gc.fillRoundRect(x * step, 0, SEGMENT_WIDTH, height, 2, 2);
}
}
}

View File

@@ -0,0 +1,410 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.broadcast;
import io.github.dsheirer.audio.broadcast.AbstractAudioBroadcaster;
import io.github.dsheirer.audio.broadcast.BroadcastEvent;
import io.github.dsheirer.audio.broadcast.BroadcastModel;
import io.github.dsheirer.audio.broadcast.BroadcastServerType;
import io.github.dsheirer.audio.broadcast.BroadcastState;
import io.github.dsheirer.audio.broadcast.ConfiguredBroadcast;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.streaming.ViewStreamingRequest;
import io.github.dsheirer.gui.table.ColumnConfigurationButton;
import io.github.dsheirer.gui.table.TableColumnMonitor;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.preference.swing.SwingPreference;
import io.github.dsheirer.sample.Listener;
import java.net.URL;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.ToIntFunction;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconFontFX;
import jiconfont.javafx.IconNode;
/**
* Status of the configured audio streams: type, name, connection status and the streamed, queued, rejected, aged
* off and failed audio counts. The column selection, order and widths are kept across sessions.
*/
public class BroadcastStatusView extends VBox
{
static final String TABLE_KEY = "broadcast.status";
static final String SWING_TABLE_KEY = "application.broadcast.status.panel";
private final BroadcastModel mBroadcastModel;
private final ObservableList<ConfiguredBroadcast> mItems = FXCollections.observableArrayList();
private final TableView<ConfiguredBroadcast> mTableView = new TableView<>(mItems);
private final Label mSummaryLabel = new Label();
private final AtomicBoolean mUpdateScheduled = new AtomicBoolean();
private final Map<BroadcastServerType,Image> mServerTypeImages = new EnumMap<>(BroadcastServerType.class);
private final Listener<BroadcastEvent> mBroadcastEventListener = event -> scheduleUpdate();
private final ListChangeListener<ConfiguredBroadcast> mListChangeListener = change -> scheduleUpdate();
static
{
IconFontFX.register(FontAwesome.getIconFont());
}
/**
* Constructs an instance
* @param broadcastModel with the configured streams
* @param swingPreference with the column widths of the Swing version of this table, migrated once
*/
public BroadcastStatusView(BroadcastModel broadcastModel, SwingPreference swingPreference)
{
mBroadcastModel = broadcastModel;
getStyleClass().add("broadcast-status-view");
URL stylesheet = BroadcastStatusView.class.getResource("/broadcast_status.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
mTableView.getColumns().addAll(List.of(
createServerTypeColumn(),
createNameColumn(),
createStatusColumn(),
createCountColumn("queued", "Queued", AbstractAudioBroadcaster::getAudioQueueSize,
"Recordings waiting to be streamed or uploaded"),
createCountColumn("streamed", "Streamed/Uploaded", AbstractAudioBroadcaster::getStreamedAudioCount,
"Recordings streamed or uploaded"),
createCountColumn("duplicate", "Duplicate Rejected",
AbstractAudioBroadcaster::getDuplicateRejectedAudioCount, "Duplicate calls that were not streamed"),
createCountColumn("agedOff", "Aged Off", AbstractAudioBroadcaster::getAgedOffAudioCount,
"Recordings discarded because they waited too long to be streamed"),
createCountColumn("errors", "Upload Error", AbstractAudioBroadcaster::getAudioErrorCount,
"Recordings that failed to stream or upload")));
mTableView.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
mTableView.setTableMenuButtonVisible(false);
mTableView.setFixedCellSize(26);
Label placeholder = new Label("No streams are configured. Use Configure Streams to add a stream.");
placeholder.getStyleClass().add("broadcast-placeholder");
mTableView.setPlaceholder(placeholder);
VBox.setVgrow(mTableView, Priority.ALWAYS);
TableColumnMonitor<ConfiguredBroadcast> monitor = new TableColumnMonitor<>(mTableView, TABLE_KEY,
swingPreference, SWING_TABLE_KEY);
IconNode titleIcon = new IconNode(FontAwesome.PODCAST);
titleIcon.setIconSize(14);
titleIcon.getStyleClass().add("broadcast-title-icon");
Label title = new Label("Streaming", titleIcon);
title.getStyleClass().add("broadcast-title");
mSummaryLabel.getStyleClass().add("broadcast-summary");
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
IconNode configureIcon = new IconNode(FontAwesome.COG);
configureIcon.setIconSize(13);
Button configureButton = new Button("Configure Streams", configureIcon);
configureIcon.fillProperty().bind(configureButton.textFillProperty());
configureButton.setTooltip(new Tooltip("Add and edit streams in the playlist editor"));
configureButton.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewStreamingRequest()));
ColumnConfigurationButton columnsButton = new ColumnConfigurationButton(monitor, "Streaming Status Columns");
HBox toolbar = new HBox(10, title, mSummaryLabel, spacer, configureButton, columnsButton);
toolbar.getStyleClass().add("broadcast-toolbar");
toolbar.setAlignment(Pos.CENTER_LEFT);
getChildren().addAll(toolbar, mTableView);
mBroadcastModel.addListener(mBroadcastEventListener);
mBroadcastModel.getConfiguredBroadcasts().addListener(mListChangeListener);
update();
}
/**
* Deregisters from the broadcast model.
*/
public void dispose()
{
mBroadcastModel.removeListener(mBroadcastEventListener);
mBroadcastModel.getConfiguredBroadcasts().removeListener(mListChangeListener);
}
/**
* Table showing the streams.
*/
public TableView<ConfiguredBroadcast> getTableView()
{
return mTableView;
}
/**
* Schedules an update on the FX thread. Broadcasters report changes on their own threads, often several at a
* time, so the updates are coalesced.
*/
private void scheduleUpdate()
{
if(mUpdateScheduled.compareAndSet(false, true))
{
Platform.runLater(() -> {
mUpdateScheduled.set(false);
update();
});
}
}
/**
* Updates the table rows and summary from the model. FX thread only.
*/
private void update()
{
List<ConfiguredBroadcast> current = new ArrayList<>(mBroadcastModel.getConfiguredBroadcasts());
if(!current.equals(mItems))
{
mItems.setAll(current);
}
else
{
mTableView.refresh();
}
mSummaryLabel.setText(getSummary(current));
}
/**
* Summary of the stream status counts, for example: 3 connected, 1 error.
*/
static String getSummary(List<ConfiguredBroadcast> broadcasts)
{
if(broadcasts.isEmpty())
{
return "";
}
int connected = 0;
int warning = 0;
int error = 0;
int disabled = 0;
for(ConfiguredBroadcast broadcast: broadcasts)
{
switch(getSeverity(broadcast.getStatus()))
{
case OK -> connected++;
case WARNING -> warning++;
case ERROR -> error++;
case DISABLED -> disabled++;
default -> {}
}
}
List<String> parts = new ArrayList<>();
parts.add(connected + " of " + broadcasts.size() + " connected");
if(error > 0)
{
parts.add(error + (error == 1 ? " error" : " errors"));
}
if(warning > 0)
{
parts.add(warning + (warning == 1 ? " warning" : " warnings"));
}
if(disabled > 0)
{
parts.add(disabled + " disabled");
}
return String.join(" · ", parts);
}
/**
* Status severity used to color the status.
*/
enum Severity {OK, NEUTRAL, WARNING, ERROR, DISABLED}
static Severity getSeverity(BroadcastState state)
{
if(state == null)
{
return Severity.NEUTRAL;
}
return switch(state)
{
case CONNECTED -> Severity.OK;
case DISABLED -> Severity.DISABLED;
case INVALID_SETTINGS, NETWORK_UNAVAILABLE -> Severity.WARNING;
default -> state.isWarningState() ? Severity.WARNING :
state.isErrorState() ? Severity.ERROR : Severity.NEUTRAL;
};
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createServerTypeColumn()
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn("type", "Stream Type", 170);
column.setCellFactory(param -> new TableCell<>()
{
private final ImageView mImageView = new ImageView();
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
BroadcastServerType type = empty || item == null ? null : item.getBroadcastServerType();
if(type == null)
{
setText(null);
setGraphic(null);
}
else
{
setText(type.toString());
mImageView.setImage(getImage(type));
mImageView.setFitHeight(14);
mImageView.setPreserveRatio(true);
setGraphic(mImageView.getImage() != null ? mImageView : null);
}
}
});
return column;
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createNameColumn()
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn("name", "Name", 220);
column.setCellFactory(param -> new TableCell<>()
{
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
setText(empty || item == null ? null : item.getBroadcastConfiguration().getName());
}
});
return column;
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createStatusColumn()
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn("status", "Status", 190);
column.setCellFactory(param -> new TableCell<>()
{
private final Label mChip = new Label();
{
mChip.getStyleClass().add("broadcast-status-chip");
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setAlignment(Pos.CENTER_LEFT);
}
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
if(empty || item == null)
{
setGraphic(null);
setTooltip(null);
return;
}
BroadcastState state = item.getStatus();
mChip.setText(state != null ? state.toString() : "Unknown");
mChip.getStyleClass().removeIf(styleClass -> styleClass.startsWith("broadcast-status-severity-"));
mChip.getStyleClass().add("broadcast-status-severity-" +
getSeverity(state).name().toLowerCase());
setGraphic(mChip);
BroadcastState lastBad = item.lastBadBroadcastStateProperty().get();
setTooltip(lastBad != null && lastBad != state ? new Tooltip("Last problem: " + lastBad) : null);
}
});
return column;
}
private TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createCountColumn(String id, String title,
ToIntFunction<AbstractAudioBroadcaster> count, String description)
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = createColumn(id, title, 130);
Label header = new Label(title);
header.setTooltip(new Tooltip(description));
column.setText(null);
column.setGraphic(header);
TableColumnMonitor.setName(column, title);
column.setCellFactory(param -> new TableCell<>()
{
{
setAlignment(Pos.CENTER_RIGHT);
getStyleClass().add("broadcast-count");
}
@Override
protected void updateItem(ConfiguredBroadcast item, boolean empty)
{
super.updateItem(item, empty);
AbstractAudioBroadcaster broadcaster = empty || item == null ? null : item.getAudioBroadcaster();
setText(broadcaster != null ? String.format("%,d", count.applyAsInt(broadcaster)) : null);
}
});
return column;
}
private static TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> createColumn(String id, String title,
double width)
{
TableColumn<ConfiguredBroadcast,ConfiguredBroadcast> column = new TableColumn<>(title);
column.setId(id);
column.setPrefWidth(width);
column.setSortable(false);
column.setCellValueFactory(param -> new javafx.beans.property.ReadOnlyObjectWrapper<>(param.getValue()));
return column;
}
private Image getImage(BroadcastServerType type)
{
return mServerTypeImages.computeIfAbsent(type, serverType -> {
String path = serverType.getIconPath();
return path != null ? new Icon(serverType.name(), path).getFxImage() : null;
});
}
}

View File

@@ -1,573 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.LoggingTunerErrorListener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import io.github.dsheirer.source.tuner.test.TestTuner;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ChannelizerViewer extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelizerViewer.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private static final int CHANNEL_FFT_FRAME_RATE = 20;
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private JPanel mControlPanel;
private JLabel mToneFrequencyLabel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelArrayPanel mChannelPanel;
private DiscreteIndexChannelArrayPanel mDiscreteIndexChannelPanel;
private int mChannelCount;
private int mChannelsPerRow;
private long mBaseFrequency = 100000000; //100 MHz
private DFTSize mMainPanelDFTSize = DFTSize.FFT32768;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT04096;
private TestTuner mTestTuner;
/**
* GUI Test utility for researching polyphase channelizers.
*
* @param channelsPerRow
*/
public ChannelizerViewer(int channelsPerRow)
{
mTestTuner = new TestTuner(new LoggingTunerErrorListener());
mChannelCount = (int)(mTestTuner.getTunerController().getBandwidth() / CHANNEL_BANDWIDTH);
mChannelsPerRow = channelsPerRow;
init();
}
private void init()
{
setTitle("Polyphase Channelizer Viewer");
setSize(1200, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][][grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "wrap");
mPrimaryPanel.add(getControlPanel(), "wrap");
mPrimaryPanel.add(getChannelArrayPanel(), "wrap");
mPrimaryPanel.add(getDiscreteIndexChannelPanel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager,
mTestTuner.getTunerController().getSampleRate());
mPrimarySpectrumPanel.setPreferredSize(new Dimension(1200, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
mTestTuner.getTunerController().addBufferListener(mPrimarySpectrumPanel);
}
return mPrimarySpectrumPanel;
}
private JPanel getControlPanel()
{
if(mControlPanel == null)
{
mControlPanel = new JPanel();
mControlPanel.setLayout(new MigLayout("insets 0 0 0 0", "", ""));
mControlPanel.add(new JLabel("Tone:"), "align left");
long minimumFrequency = -(long)mTestTuner.getTunerController().getSampleRate() / 2 + 1;
long maximumFrequency = (long)mTestTuner.getTunerController().getSampleRate() / 2 - 1;
long toneFrequency = 0;
SpinnerNumberModel model = new SpinnerNumberModel(toneFrequency, minimumFrequency, maximumFrequency,
100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mTestTuner.getTunerController().setToneFrequency(toneFrequency);
mToneFrequencyLabel.setText(String.valueOf(getToneFrequency()));
}
});
JSpinner spinner = new JSpinner(model);
mControlPanel.add(spinner);
mControlPanel.add(new JLabel("Hz"));
mControlPanel.add(new JLabel("Frequency:"), "push,align right");
mToneFrequencyLabel = new JLabel(String.valueOf(getToneFrequency()));
mControlPanel.add(mToneFrequencyLabel, "push,align left");
mControlPanel.add(new JLabel("Channels: " + mChannelCount), "push,align right");
}
return mControlPanel;
}
private long getToneFrequency()
{
return mTestTuner.getTunerController().getFrequency() + mTestTuner.getTunerController().getToneFrequency();
}
private ChannelArrayPanel getChannelArrayPanel()
{
if(mChannelPanel == null)
{
mChannelPanel = new ChannelArrayPanel();
}
return mChannelPanel;
}
private DiscreteIndexChannelArrayPanel getDiscreteIndexChannelPanel()
{
if(mDiscreteIndexChannelPanel == null)
{
mDiscreteIndexChannelPanel = new DiscreteIndexChannelArrayPanel();
}
return mDiscreteIndexChannelPanel;
}
public class ChannelArrayPanel extends JPanel
{
private final Logger mLog = LoggerFactory.getLogger(ChannelArrayPanel.class);
public ChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
double spectralBandwidth = mTestTuner.getTunerController().getSampleRate();
double halfSpectralBandwidth = spectralBandwidth / 2.0;
int channelToLog = -1;
long baseFrequency = mBaseFrequency + (CHANNEL_BANDWIDTH / 2);
for(int x = 0; x < mChannelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
mLog.debug("Channel " + x + "/" + mChannelCount + " Frequency: " + frequency);
ChannelPanel channelPanel = new ChannelPanel(mSettingsManager, CHANNEL_BANDWIDTH * 2, frequency, CHANNEL_BANDWIDTH, (x == channelToLog));
channelPanel.setDFTSize(mChannelPanelDFTSize);
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
public class DiscreteIndexChannelArrayPanel extends JPanel
{
public DiscreteIndexChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
for(int x = 0; x < mChannelCount; x++)
{
TunerChannel tunerChannel = new TunerChannel(100000000, 12500);
TunerChannelSource source = mTestTuner.getChannelSourceManager().getSource(tunerChannel, null, "test");
DiscreteChannelPanel channelPanel = new DiscreteChannelPanel(mSettingsManager, source, x);
channelPanel.setDFTSize(mChannelPanelDFTSize);
mLog.debug("Testing Channel [" + x + "] is set to [" + source.getTunerChannel().getFrequency() + "]");
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
/**
* Returns a list of tuner channels that will fit within the tuner's bandwidth, minus a half channel each at the
* lower and upper ends of the spectrum.
*
* @param tuner to create channels for
* @return list of contiguous channels filling the tuner bandwidth
*/
public static List<TunerChannel> getTunerChannels(Tuner tuner)
{
List<TunerChannel> tunerChannels = new ArrayList<>();
long baseFrequency = tuner.getTunerController().getFrequency();
baseFrequency -= tuner.getTunerController().getSampleRate() / 2;
baseFrequency += (CHANNEL_BANDWIDTH / 2);
int channelCount = (int)(tuner.getTunerController().getSampleRate() / CHANNEL_BANDWIDTH) - 1;
for(int x = 0; x < channelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
tunerChannels.add(tunerChannel);
}
return tunerChannels;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager, double sampleRate)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(28);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class ChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public ChannelPanel(SettingsManager settingsManager, double sampleRate, long frequency, int bandwidth, boolean enableLogging)
{
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
TunerChannel tunerChannel = new TunerChannel(frequency, bandwidth);
mSource = mTestTuner.getChannelSourceManager().getSource(tunerChannel, null, "test");
if(mSource != null)
{
mSource.setListener(complexSamples -> mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved())));
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for frequency: " + frequency);
}
if(mSource != null)
{
add(new JLabel("Center:" + frequency));
}
else
{
add(new JLabel("NO SRC:" + frequency));
}
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class DiscreteChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private final Logger mLog = LoggerFactory.getLogger(DiscreteChannelPanel.class);
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public DiscreteChannelPanel(SettingsManager settingsManager, TunerChannelSource source, int index)
{
mSource = source;
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
add(new JLabel("Index:" + index));
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
if(mSource != null)
{
mSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
if(mLoggingEnabled)
{
mLog.debug("Samples:" + Arrays.toString(complexSamples.toInterleaved().samples()));
}
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
});
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for index: " + index);
}
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public static void main(String[] args)
{
boolean useGUI = true;
if(useGUI)
{
int channelsPerRow = 16;
final ChannelizerViewer frame = new ChannelizerViewer(channelsPerRow);
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
frame.setVisible(true);
}
});
}
else
{
TestTuner tuner = new TestTuner(new LoggingTunerErrorListener());
List<TunerChannel> tunerChannels = getTunerChannels(tuner);
List<TunerChannelSource> sources = new ArrayList<>();
int maxSourceCount = 30;
int sourceCount = 0;
for(TunerChannel tunerChannel : tunerChannels)
{
if(sourceCount < maxSourceCount)
{
TunerChannelSource source = tuner.getChannelSourceManager().getSource(tunerChannel, null, "test");
if(source != null)
{
sources.add(source);
sourceCount++;
}
else
{
mLog.debug("Couldn't get source for: " + tunerChannel);
}
}
}
mLog.debug("Starting [" + sources.size() + "] tuner channel sources");
for(TunerChannelSource tunerChannelSource : sources)
{
tunerChannelSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
}
});
tunerChannelSource.start();
}
while(true)
{
;
}
}
}
}

View File

@@ -1,472 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.dsp.filter.channelizer.PolyphaseChannelSource;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.LoggingTunerErrorListener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.channel.ChannelSpecification;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import io.github.dsheirer.source.tuner.test.TestTuner;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ChannelizerViewer2 extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelizerViewer2.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private JPanel mControlPanel;
private JButton mTopFrameAddChannelButton;
private JButton mBottomFrameAddChannelButton;
private JLabel mToneFrequencyLabel;
private JLabel mCenterFrequencyLabel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelArrayPanel mTopChannelArrayPanel;
private ChannelArrayPanel mBottomChannelArrayPanel;
private DFTSize mMainPanelDFTSize = DFTSize.FFT32768;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT04096;
private TestTuner mTestTuner = new TestTuner(new LoggingTunerErrorListener());
/**
* GUI Test utility for researching polyphase channelizers.
*/
public ChannelizerViewer2()
{
init();
}
private void init()
{
setTitle("Polyphase Channelizer Viewer");
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][][grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "wrap");
mPrimaryPanel.add(getControlPanel(), "wrap");
mPrimaryPanel.add(getTopChannelArrayPanel(), "wrap");
mPrimaryPanel.add(getBottomChannelArrayPanel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager,
mTestTuner.getTunerController().getSampleRate());
mPrimarySpectrumPanel.setPreferredSize(new Dimension(1200, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
mTestTuner.getTunerController().addBufferListener(mPrimarySpectrumPanel);
}
return mPrimarySpectrumPanel;
}
private JPanel getControlPanel()
{
if(mControlPanel == null)
{
mControlPanel = new JPanel();
mControlPanel.setLayout(new MigLayout("insets 0 0 0 0", "", ""));
mControlPanel.add(new JLabel("Tone:"), "align left");
long minimumFrequency = -(long)mTestTuner.getTunerController().getSampleRate() / 2 + 1;
long maximumFrequency = (long)mTestTuner.getTunerController().getSampleRate() / 2 - 1;
long toneFrequency = 0;
SpinnerNumberModel model = new SpinnerNumberModel(toneFrequency, minimumFrequency, maximumFrequency,
100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mTestTuner.getTunerController().setToneFrequency(toneFrequency);
mToneFrequencyLabel.setText(String.valueOf(getToneFrequency()));
mCenterFrequencyLabel.setText(String.valueOf(getCenterFrequency()));
}
});
JSpinner spinner = new JSpinner(model);
mControlPanel.add(spinner);
mControlPanel.add(new JLabel("Hz"));
mControlPanel.add(new JLabel("Tone Frequency:"), "push,align right");
mToneFrequencyLabel = new JLabel(String.valueOf(getToneFrequency()));
mControlPanel.add(mToneFrequencyLabel, "push,align left");
mControlPanel.add(new JLabel("Center Frequency:"), "push,align right");
mCenterFrequencyLabel = new JLabel(String.valueOf(getCenterFrequency()));
mControlPanel.add(mCenterFrequencyLabel, "push,align left");
mControlPanel.add(getBottomFrameAddChannelButton(), "push,align right");
mControlPanel.add(getTopFrameAddChannelButton(), "push,align right");
}
return mControlPanel;
}
private JButton getTopFrameAddChannelButton()
{
if(mTopFrameAddChannelButton == null)
{
mTopFrameAddChannelButton = new JButton("Top - Add Channel");
mTopFrameAddChannelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String value = JOptionPane.showInputDialog(ChannelizerViewer2.this, "Frequency?");
if(value != null && !value.isEmpty())
{
try
{
int frequency = Integer.parseInt(value);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
getTopChannelArrayPanel().addChannel(tunerChannel);
}
catch(Exception e1)
{
mLog.error("Can't parse frequency from value: " + value, e1);
}
}
}
});
}
return mTopFrameAddChannelButton;
}
private JButton getBottomFrameAddChannelButton()
{
if(mBottomFrameAddChannelButton == null)
{
mBottomFrameAddChannelButton = new JButton("Bottom - Add Channel");
mBottomFrameAddChannelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String value = JOptionPane.showInputDialog(ChannelizerViewer2.this, "Frequency?");
if(value != null && !value.isEmpty())
{
try
{
int frequency = Integer.parseInt(value);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
getBottomChannelArrayPanel().addChannel(tunerChannel);
}
catch(Exception e1)
{
mLog.error("Can't parse frequency from value: " + value, e1);
}
}
}
});
}
return mBottomFrameAddChannelButton;
}
private long getToneFrequency()
{
return mTestTuner.getTunerController().getFrequency() + mTestTuner.getTunerController().getToneFrequency();
}
private long getCenterFrequency()
{
return mTestTuner.getTunerController().getFrequency();
}
private ChannelArrayPanel getTopChannelArrayPanel()
{
if(mTopChannelArrayPanel == null)
{
mTopChannelArrayPanel = new ChannelArrayPanel();
}
return mTopChannelArrayPanel;
}
private ChannelArrayPanel getBottomChannelArrayPanel()
{
if(mBottomChannelArrayPanel == null)
{
mBottomChannelArrayPanel = new ChannelArrayPanel();
}
return mBottomChannelArrayPanel;
}
public class ChannelArrayPanel extends JPanel
{
public ChannelArrayPanel()
{
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
}
public void addChannel(TunerChannel tunerChannel)
{
ChannelPanel channelPanel = new ChannelPanel(mSettingsManager, CHANNEL_BANDWIDTH * 2,
tunerChannel.getFrequency(), CHANNEL_BANDWIDTH);
channelPanel.setDFTSize(mChannelPanelDFTSize);
add(channelPanel, "grow,push");
validate();
repaint();
}
}
/**
* Returns a list of tuner channels that will fit within the tuner's bandwidth, minus a half channel each at the
* lower and upper ends of the spectrum.
*
* @param tuner to create channels for
* @return list of contiguous channels filling the tuner bandwidth
*/
public static List<TunerChannel> getTunerChannels(Tuner tuner)
{
List<TunerChannel> tunerChannels = new ArrayList<>();
long baseFrequency = tuner.getTunerController().getFrequency();
baseFrequency -= tuner.getTunerController().getSampleRate() / 2;
baseFrequency += (CHANNEL_BANDWIDTH / 2);
int channelCount = (int)(tuner.getTunerController().getSampleRate() / CHANNEL_BANDWIDTH) - 1;
for(int x = 0; x < channelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
tunerChannels.add(tunerChannel);
}
return tunerChannels;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager, double sampleRate)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class ChannelPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public ChannelPanel(SettingsManager settingsManager, double sampleRate, long frequency, int bandwidth)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill][grow,fill][grow,fill]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel, "span");
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
TunerChannel tunerChannel = new TunerChannel(frequency, bandwidth);
mSource = mTestTuner.getChannelSourceManager().getSource(tunerChannel,
new ChannelSpecification(50000, 12500, 6000, 7000), "test");
if(mSource != null)
{
mLog.debug("Channel: " + mSource.getTunerChannel() + " Rate:" + mSource.getSampleRate());
mSource.setListener((Listener<ComplexSamples>) complexSamples ->
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
});
if(mSource instanceof PolyphaseChannelSource pcs)
{ List<Integer> indexes = pcs.getOutputProcessorIndexes();
double sRate = pcs.getSampleRate();
long indexCenterFrequency = pcs.getIndexCenterFrequency();
long appliedFrequencyOffset = pcs.getFrequencyOffset();
long requestedCenterFrequency = pcs.getFrequency();
StringBuilder sb = new StringBuilder();
sb.append("Polyphase Channel - Bandwidth: ").append(sRate);
sb.append(" Channel/Requested/Offset: ").append(indexCenterFrequency);
sb.append("/").append(requestedCenterFrequency);
sb.append("/").append(appliedFrequencyOffset);
sb.append(" Indexes: ").append(indexes);
sb.append(" Tuner SR:").append(pcs.getTunerSampleRate());
sb.append(" Tuner CF:").append(pcs.getTunerCenterFrequency());
mLog.info(sb.toString());
}
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for frequency: " + frequency);
}
if(mSource != null)
{
int half = (int)(sampleRate / 2.0f);
add(new JLabel("Min:" + (frequency - half)), "align left");
add(new JLabel("Center:" + frequency));
add(new JLabel("Max:" + (frequency + half)), "align right");
}
else
{
add(new JLabel("NO SRC:" + frequency));
}
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(e -> mLoggingEnabled = mLoggingButton.isSelected());
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public static void main(String[] args)
{
final ChannelizerViewer2 frame = new ChannelizerViewer2();
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
frame.setVisible(true);
}
});
}
}

View File

@@ -1,573 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.LoggingTunerErrorListener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.channel.ChannelSpecification;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import io.github.dsheirer.source.tuner.test.TestTuner;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class HeterodyneChannelizerViewer extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(HeterodyneChannelizerViewer.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private static final int CHANNEL_FFT_FRAME_RATE = 20;
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private JPanel mControlPanel;
private JLabel mToneFrequencyLabel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelArrayPanel mChannelPanel;
private DiscreteIndexChannelArrayPanel mDiscreteIndexChannelPanel;
private int mChannelCount;
private int mChannelsPerRow;
private long mBaseFrequency = 100000000; //100 MHz
private DFTSize mMainPanelDFTSize = DFTSize.FFT04096;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT04096;
private TestTuner mTestTuner;
/**
* GUI Test utility for researching channelizers.
*/
public HeterodyneChannelizerViewer()
{
mTestTuner = new TestTuner(new LoggingTunerErrorListener());
mChannelCount = 5;
mChannelsPerRow = 5;
init();
}
private void init()
{
setTitle("Heterodyne Channelizer Viewer");
setSize(1200, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][][grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "wrap");
mPrimaryPanel.add(getControlPanel(), "wrap");
mPrimaryPanel.add(getChannelArrayPanel(), "wrap");
// mPrimaryPanel.add(getDiscreteIndexChannelPanel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager,
mTestTuner.getTunerController().getSampleRate());
mPrimarySpectrumPanel.setPreferredSize(new Dimension(1200, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
mTestTuner.getTunerController().addBufferListener(mPrimarySpectrumPanel);
}
return mPrimarySpectrumPanel;
}
private JPanel getControlPanel()
{
if(mControlPanel == null)
{
mControlPanel = new JPanel();
mControlPanel.setLayout(new MigLayout("insets 0 0 0 0", "", ""));
mControlPanel.add(new JLabel("Tone:"), "align left");
long minimumFrequency = -(long)mTestTuner.getTunerController().getSampleRate() / 2 + 1;
long maximumFrequency = (long)mTestTuner.getTunerController().getSampleRate() / 2 - 1;
long toneFrequency = 0;
SpinnerNumberModel model = new SpinnerNumberModel(toneFrequency, minimumFrequency, maximumFrequency,
100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mTestTuner.getTunerController().setToneFrequency(toneFrequency);
mToneFrequencyLabel.setText(String.valueOf(getToneFrequency()));
}
});
JSpinner spinner = new JSpinner(model);
mControlPanel.add(spinner);
mControlPanel.add(new JLabel("Hz"));
mControlPanel.add(new JLabel("Frequency:"), "push,align right");
mToneFrequencyLabel = new JLabel(String.valueOf(getToneFrequency()));
mControlPanel.add(mToneFrequencyLabel, "push,align left");
mControlPanel.add(new JLabel("Channels: " + mChannelCount), "push,align right");
}
return mControlPanel;
}
private long getToneFrequency()
{
return mTestTuner.getTunerController().getFrequency() + mTestTuner.getTunerController().getToneFrequency();
}
private ChannelArrayPanel getChannelArrayPanel()
{
if(mChannelPanel == null)
{
mChannelPanel = new ChannelArrayPanel();
}
return mChannelPanel;
}
private DiscreteIndexChannelArrayPanel getDiscreteIndexChannelPanel()
{
if(mDiscreteIndexChannelPanel == null)
{
mDiscreteIndexChannelPanel = new DiscreteIndexChannelArrayPanel();
}
return mDiscreteIndexChannelPanel;
}
public class ChannelArrayPanel extends JPanel
{
private final Logger mLog = LoggerFactory.getLogger(ChannelArrayPanel.class);
public ChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
double spectralBandwidth = mTestTuner.getTunerController().getSampleRate();
double halfSpectralBandwidth = spectralBandwidth / 2.0;
int channelToLog = -1;
long baseFrequency = mBaseFrequency + (CHANNEL_BANDWIDTH / 2);
for(int x = 0; x < mChannelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
mLog.debug("Channel " + x + "/" + mChannelCount + " Frequency: " + frequency);
ChannelPanel channelPanel = new ChannelPanel(mSettingsManager, CHANNEL_BANDWIDTH * 2, frequency, CHANNEL_BANDWIDTH, (x == channelToLog));
channelPanel.setDFTSize(mChannelPanelDFTSize);
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
public class DiscreteIndexChannelArrayPanel extends JPanel
{
public DiscreteIndexChannelArrayPanel()
{
int bufferSize = CHANNEL_BANDWIDTH / CHANNEL_FFT_FRAME_RATE;
if(bufferSize % 2 == 1)
{
bufferSize++;
}
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "fill", "fill"));
ChannelSpecification channelSpecification = new ChannelSpecification(25000.0, 12500, 6000.0, 6250.0);
for(int x = 0; x < mChannelCount; x++)
{
TunerChannel tunerChannel = new TunerChannel(100000000, 12500);
TunerChannelSource source = mTestTuner.getChannelSourceManager().getSource(tunerChannel,
channelSpecification, "test");
DiscreteChannelPanel channelPanel = new DiscreteChannelPanel(mSettingsManager, source, x);
channelPanel.setDFTSize(mChannelPanelDFTSize);
mLog.debug("Testing Channel [" + x + "] is set to [" + source.getTunerChannel().getFrequency() + "]");
if(x % mChannelsPerRow == mChannelsPerRow - 1)
{
add(channelPanel, "grow,push,wrap 2px");
}
else
{
add(channelPanel, "grow,push");
}
}
}
}
/**
* Returns a list of tuner channels that will fit within the tuner's bandwidth, minus a half channel each at the
* lower and upper ends of the spectrum.
*
* @param tuner to create channels for
* @return list of contiguous channels filling the tuner bandwidth
*/
public static List<TunerChannel> getTunerChannels(Tuner tuner)
{
List<TunerChannel> tunerChannels = new ArrayList<>();
long baseFrequency = tuner.getTunerController().getFrequency();
baseFrequency -= tuner.getTunerController().getSampleRate() / 2;
baseFrequency += (CHANNEL_BANDWIDTH / 2);
int channelCount = (int)(tuner.getTunerController().getSampleRate() / CHANNEL_BANDWIDTH) - 1;
for(int x = 0; x < channelCount; x++)
{
long frequency = baseFrequency + (x * CHANNEL_BANDWIDTH);
TunerChannel tunerChannel = new TunerChannel(frequency, CHANNEL_BANDWIDTH);
tunerChannels.add(tunerChannel);
}
return tunerChannels;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>, ISourceEventProcessor
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager, double sampleRate)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(28);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class ChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public ChannelPanel(SettingsManager settingsManager, double sampleRate, long frequency, int bandwidth, boolean enableLogging)
{
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
TunerChannel tunerChannel = new TunerChannel(frequency, bandwidth);
ChannelSpecification channelSpecification = new ChannelSpecification(25000.0, 12500, 6000.0, 6250.0);
mSource = mTestTuner.getChannelSourceManager().getSource(tunerChannel, channelSpecification, "test");
if(mSource != null)
{
mSource.setListener(complexSamples -> mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved())));
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for frequency: " + frequency);
}
if(mSource != null)
{
add(new JLabel("Center:" + frequency));
}
else
{
add(new JLabel("NO SRC:" + frequency));
}
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public class DiscreteChannelPanel extends JPanel implements Listener<ComplexSamples>, ISourceEventProcessor
{
private final Logger mLog = LoggerFactory.getLogger(DiscreteChannelPanel.class);
private TunerChannelSource mSource;
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private JToggleButton mLoggingButton;
private boolean mLoggingEnabled;
public DiscreteChannelPanel(SettingsManager settingsManager, TunerChannelSource source, int index)
{
mSource = source;
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow,fill][]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(32);
add(mSpectrumPanel, "span");
add(new JLabel("Index:" + index));
mLoggingButton = new JToggleButton("Logging");
mLoggingButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
mLoggingEnabled = mLoggingButton.isSelected();
}
});
// add(mLoggingButton);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDecibelConverter.addListener(mSpectrumPanel);
if(mSource != null)
{
mSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
if(mLoggingEnabled)
{
mLog.debug("Samples:" + Arrays.toString(complexSamples.toInterleaved().samples()));
}
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
});
mSource.start();
}
else
{
mLog.error("Couldn't get a source from the tuner for index: " + index);
}
}
public TunerChannelSource getSource()
{
return mSource;
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(ComplexSamples complexSamples)
{
mComplexDftProcessor.receive(new FloatNativeBuffer(complexSamples.toInterleaved()));
}
@Override
public void process(SourceEvent event) throws SourceException
{
mLog.debug("Source Event! Add handler support for this to channelizer viewer");
}
}
public static void main(String[] args)
{
boolean useGUI = true;
if(useGUI)
{
final HeterodyneChannelizerViewer frame = new HeterodyneChannelizerViewer();
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
frame.setVisible(true);
}
});
}
else
{
TestTuner tuner = new TestTuner(new LoggingTunerErrorListener());
List<TunerChannel> tunerChannels = getTunerChannels(tuner);
List<TunerChannelSource> sources = new ArrayList<>();
int maxSourceCount = 30;
int sourceCount = 0;
for(TunerChannel tunerChannel : tunerChannels)
{
if(sourceCount < maxSourceCount)
{
TunerChannelSource source = tuner.getChannelSourceManager().getSource(tunerChannel,
null, "test");
if(source != null)
{
sources.add(source);
sourceCount++;
}
else
{
mLog.debug("Couldn't get source for: " + tunerChannel);
}
}
}
mLog.debug("Starting [" + sources.size() + "] tuner channel sources");
for(TunerChannelSource tunerChannelSource : sources)
{
tunerChannelSource.setListener(new Listener<ComplexSamples>()
{
@Override
public void receive(ComplexSamples complexSamples)
{
}
});
tunerChannelSource.start();
}
while(true)
{
;
}
}
}
}

View File

@@ -1,322 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.channelizer;
import io.github.dsheirer.buffer.FloatNativeBuffer;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.dsp.filter.FilterFactory;
import io.github.dsheirer.dsp.filter.channelizer.TwoChannelSynthesizerM2;
import io.github.dsheirer.dsp.filter.design.FilterDesignException;
import io.github.dsheirer.dsp.oscillator.FS4DownConverter;
import io.github.dsheirer.dsp.oscillator.IComplexOscillator;
import io.github.dsheirer.dsp.oscillator.OscillatorFactory;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import io.github.dsheirer.util.ThreadPool;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.concurrent.TimeUnit;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SynthesizerViewer extends JFrame
{
private final static Logger mLog = LoggerFactory.getLogger(SynthesizerViewer.class);
private static final int CHANNEL_BANDWIDTH = 12500;
private static final int CHANNEL_SAMPLE_RATE = 25000;
private static final int CHANNEL_FFT_FRAME_RATE = 20; //frames per second
private static final int DATA_GENERATOR_FRAME_RATE = 50; //frames per second
private SettingsManager mSettingsManager = new SettingsManager();
private JPanel mPrimaryPanel;
private PrimarySpectrumPanel mPrimarySpectrumPanel;
private ChannelPanel mChannel1Panel;
private ChannelPanel mChannel2Panel;
private ChannelControlPanel mChannel1ControlPanel;
private ChannelControlPanel mChannel2ControlPanel;
private DFTSize mMainPanelDFTSize = DFTSize.FFT08192;
private DFTSize mChannelPanelDFTSize = DFTSize.FFT08192;
/**
* GUI Test utility for researching polyphase synthesizers.
*/
public SynthesizerViewer()
{
init();
}
public void start()
{
ThreadPool.SCHEDULED.scheduleAtFixedRate(new DataGenerationManager(), 0, 1000 / DATA_GENERATOR_FRAME_RATE, TimeUnit.MILLISECONDS);
}
private void init()
{
setTitle("Polyphase Synthesizer Viewer");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
setLocationRelativeTo(null);
add(getPrimaryPanel());
}
private JPanel getPrimaryPanel()
{
if(mPrimaryPanel == null)
{
mPrimaryPanel = new JPanel();
mPrimaryPanel.setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill][grow,fill]", "[grow,fill][grow,fill]"));
mPrimaryPanel.add(getSpectrumPanel(), "span");
mPrimaryPanel.add(getChannel1Panel());
mPrimaryPanel.add(getChannel2Panel());
}
return mPrimaryPanel;
}
private PrimarySpectrumPanel getSpectrumPanel()
{
if(mPrimarySpectrumPanel == null)
{
mPrimarySpectrumPanel = new PrimarySpectrumPanel(mSettingsManager);
mPrimarySpectrumPanel.setPreferredSize(new Dimension(500, 200));
mPrimarySpectrumPanel.setDFTSize(mMainPanelDFTSize);
}
return mPrimarySpectrumPanel;
}
private ChannelPanel getChannel1Panel()
{
if(mChannel1Panel == null)
{
mChannel1Panel = new ChannelPanel(mSettingsManager, getChannel1ControlPanel());
mChannel1Panel.setPreferredSize(new Dimension(250, 200));
mChannel1Panel.setDFTSize(mChannelPanelDFTSize);
}
return mChannel1Panel;
}
private ChannelPanel getChannel2Panel()
{
if(mChannel2Panel == null)
{
mChannel2Panel = new ChannelPanel(mSettingsManager, getChannel2ControlPanel());
mChannel2Panel.setPreferredSize(new Dimension(250, 200));
mChannel2Panel.setDFTSize(mChannelPanelDFTSize);
}
return mChannel2Panel;
}
public class PrimarySpectrumPanel extends JPanel implements Listener<INativeBuffer>
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
public PrimarySpectrumPanel(SettingsManager settingsManager)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDftProcessor.setFrameRate(CHANNEL_FFT_FRAME_RATE);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
}
public class ChannelPanel extends JPanel implements Listener<INativeBuffer>
{
private ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private ComplexDecibelConverter mComplexDecibelConverter = new ComplexDecibelConverter();
private SpectrumPanel mSpectrumPanel;
private boolean mLoggingEnabled = false;
public ChannelPanel(SettingsManager settingsManager, ChannelControlPanel channelControlPanel)
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill][]"));
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(16);
add(mSpectrumPanel, "wrap");
add(channelControlPanel);
mComplexDftProcessor.addConverter(mComplexDecibelConverter);
mComplexDftProcessor.setFrameRate(CHANNEL_FFT_FRAME_RATE);
mComplexDecibelConverter.addListener(mSpectrumPanel);
}
public void setDFTSize(DFTSize dftSize)
{
mComplexDftProcessor.setDFTSize(dftSize);
}
@Override
public void receive(INativeBuffer nativeBuffer)
{
mComplexDftProcessor.receive(nativeBuffer);
}
}
private ChannelControlPanel getChannel1ControlPanel()
{
if(mChannel1ControlPanel == null)
{
mChannel1ControlPanel = new ChannelControlPanel();
}
return mChannel1ControlPanel;
}
private ChannelControlPanel getChannel2ControlPanel()
{
if(mChannel2ControlPanel == null)
{
mChannel2ControlPanel = new ChannelControlPanel();
}
return mChannel2ControlPanel;
}
public class ChannelControlPanel extends JPanel
{
private static final int MIN_FREQUENCY = -6250;
private static final int MAX_FREQUENCY = 6250;
private static final int DEFAULT_FREQUENCY = 50;
private IComplexOscillator mOscillator = OscillatorFactory.getComplexOscillator(DEFAULT_FREQUENCY, CHANNEL_SAMPLE_RATE);
public ChannelControlPanel()
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
add(new JLabel("Tone:"), "align right");
SpinnerNumberModel model = new SpinnerNumberModel(DEFAULT_FREQUENCY, MIN_FREQUENCY, MAX_FREQUENCY, 100);
model.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
long toneFrequency = model.getNumber().longValue();
mOscillator.setFrequency(toneFrequency);
}
});
JSpinner spinner = new JSpinner(model);
add(spinner);
add(new JLabel("Hz"));
}
public IComplexOscillator getOscillator()
{
return mOscillator;
}
}
public class DataGenerationManager implements Runnable
{
private TwoChannelSynthesizerM2 mSynthesizer;
private FS4DownConverter mFS4DownConverter = new FS4DownConverter();
private int mSamplesPerCycle = CHANNEL_SAMPLE_RATE / DATA_GENERATOR_FRAME_RATE;
private boolean mOddSample = false;
public DataGenerationManager()
{
try
{
float[] taps = FilterFactory.getSincM2Synthesizer( 25000.0, 12500.0, 2, 24);
mSynthesizer = new TwoChannelSynthesizerM2(taps);
}
catch(FilterDesignException fde)
{
mLog.error("Filter design error", fde);
}
}
@Override
public void run()
{
ComplexSamples channel1Buffer = getChannel1ControlPanel().getOscillator().generateComplexSamples(mSamplesPerCycle, 0l);
ComplexSamples channel2Buffer = getChannel2ControlPanel().getOscillator().generateComplexSamples(mSamplesPerCycle, 0l);
//Translate channel 2 by FS/2 so that it sits adjacent to channel 1 for synthesis
float[] i2 = channel2Buffer.i().clone();
float[] q2 = channel2Buffer.q().clone();
for(int x = 0; x < i2.length; x++)
{
if(mOddSample)
{
i2[x] = -i2[x];
q2[x] = -q2[x];
}
mOddSample = !mOddSample;
}
ComplexSamples synthesizedBuffer = mSynthesizer.process(channel1Buffer,
new ComplexSamples(i2, q2, channel2Buffer.timestamp()));
getChannel1Panel().receive(new FloatNativeBuffer(channel1Buffer));
getChannel2Panel().receive(new FloatNativeBuffer(channel2Buffer));
getSpectrumPanel().receive(new FloatNativeBuffer(synthesizedBuffer));
}
}
public static void main(String[] args)
{
final SynthesizerViewer frame = new SynthesizerViewer();
EventQueue.invokeLater(() -> {
frame.setVisible(true);
frame.start();
});
}
}

View File

@@ -1,179 +0,0 @@
package io.github.dsheirer.gui.control;
import io.github.dsheirer.buffer.CircularBuffer;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.Complex;
import org.apache.commons.math3.util.FastMath;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.util.List;
public class ConstellationViewer extends JPanel implements Listener<Complex>
{
private static final long serialVersionUID = 1L;
private int mSampleRate;
private int mSymbolRate;
private float mSamplesPerSymbol;
private float mCounter = 0;
private float mOffset = 0;
private CircularBuffer<Complex> mBuffer =
new CircularBuffer<Complex>( 5000 );
private Complex mPrevious = new Complex( 1, 1 );
public ConstellationViewer( int sampleRate, int symbolRate )
{
mSampleRate = sampleRate;
mSymbolRate = symbolRate;
mSamplesPerSymbol = (float)mSampleRate / (float)mSymbolRate;
initGui();
}
private void initGui()
{
setPreferredSize( new Dimension( 200,200 ) );
addMouseListener( new MouseListener()
{
@Override
public void mouseClicked( MouseEvent e )
{
if( SwingUtilities.isRightMouseButton( e ) )
{
JPopupMenu menu = new JPopupMenu();
menu.add( new TimingOffsetItem( (int)( mSamplesPerSymbol * 10 ), (int)( mOffset * 10 ) ) );
menu.show( ConstellationViewer.this, e.getX(), e.getY() );
}
}
public void mouseReleased( MouseEvent e ) {}
public void mousePressed( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mouseEntered( MouseEvent e ) {}
} );
}
@Override
public void receive( Complex sample )
{
mBuffer.receive( sample );
Complex angle = Complex.multiply( sample, mPrevious.conjugate() );
repaint();
}
/**
* Sets the timing offset ( 0 <> SamplesPerSymbol ) for selecting which
* sample to plot, within the symbol timeframe. Values greater than the
* samples per symbol value will simply wrap or delay into the next symbol
* period.
*
* @param offset
*/
public void setOffset( float offset )
{
mOffset = offset;
repaint();
}
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D graphics = (Graphics2D) g;
graphics.setColor( Color.BLUE );
List<Complex> samples = mBuffer.getElements();
double centerX = (double)getHeight() / 2.0d;
double centerY = (double)getWidth() / 2.0d;
double scale = 0.5d;
mCounter = 0;
for( Complex sample: samples )
{
if( mCounter > ( mOffset + mSamplesPerSymbol ) )
{
/**
* Multiply the current sample against the complex conjugate of the
* previous sample to derive the phase delta between the two samples
*
* Negating the previous sample quadrature produces the conjugate
*/
double i = ( sample.inphase() * mPrevious.inphase() ) -
( sample.quadrature() * -mPrevious.quadrature() );
double q = ( sample.quadrature() * mPrevious.inphase() ) +
( sample.inphase() * -mPrevious.quadrature() );
double angle;
//Check for divide by zero
if( i == 0 )
{
angle = 0.0;
}
else
{
/**
* Use the arcus tangent of imaginary (q) divided by real (i) to
* get the phase angle (+/-) which was directly manipulated by the
* original message waveform during the modulation. This value now
* serves as the instantaneous amplitude of the demodulated signal
*/
double denominator = 1.0d / i;
angle = FastMath.atan( (double)q * denominator );
}
Ellipse2D.Double ellipse =
new Ellipse2D.Double( centerX - ( i * scale ),
centerY - ( q * scale ), 4, 4 );
graphics.draw( ellipse );
mCounter -= mSamplesPerSymbol;
}
mCounter++;
}
}
public class TimingOffsetItem extends JSlider implements ChangeListener
{
private static final long serialVersionUID = 1L;
public TimingOffsetItem( int maxValue, int currentValue )
{
super( JSlider.HORIZONTAL, 0, maxValue, currentValue );
setMajorTickSpacing( 10 );
setMinorTickSpacing( 5 );
setPaintTicks( true );
setPaintLabels( true );
addChangeListener( this );
}
@Override
public void stateChanged( ChangeEvent event )
{
int value = ((JSlider)event.getSource()).getValue();
setOffset( (float)value / 10.0f );
}
}
}

View File

@@ -1,148 +0,0 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2017 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/
package io.github.dsheirer.gui.editor;
import javax.swing.*;
/**
* Generic editor with change detection, save and reset functions.
*
* This editor supports hierarchical nesting of sub-component editors where changes are detected
* at the lowest editor in the tree and percolated up to the top-level editor for managing the
* configuration set as a whole.
*
* To configure this editor as a collective, register each parent editor as a saveRequestListener
* on each child editor. If no save request listener is registered, the editor will simply invoke
* save when a change is detected and the user opts to save the contents.
*
* The top-level editor can override the saveRequest() method to perform custom save operations
* and validation.
*/
public abstract class Editor<T> extends JPanel
{
private static final long serialVersionUID = 1L;
protected T mItem;
protected boolean mModified = false;
protected Editor<?> mSaveRequestListener;
public Editor()
{
}
/**
* Requests to save the contents of this editor.
*
* If a save request listener is registered, the listener is notified that a save is requested,
* otherwise the save is request is processed by the instance.
*
* This allows for a save event to be percolated up the hierarchical set of editors so that
* a top-level editor can invoke custom operations such as configuration validation.
*/
protected void saveRequest()
{
if(mSaveRequestListener != null)
{
mSaveRequestListener.saveRequest();
}
else
{
save();
}
}
/**
* Registers the editor to be notified when this editor contents have been saved.
*/
public void setSaveRequestListener(Editor<?> listener)
{
mSaveRequestListener = listener;
}
/**
* Sets the object to be edited. If the contents from the previous object have changed, this
* prompts the user to save these changes. A saveRequest() is issued and either this editor
* or the parent editor will respond to the save request and invoke the save() method.
*/
public void setItem(T item)
{
if(isModified())
{
int option = JOptionPane.showConfirmDialog(
Editor.this,
"This item has changed. Do you want to save these changes?",
"Save Changes?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.YES_OPTION)
{
saveRequest();
}
setModified(false);
}
mItem = item;
}
/**
* Current editing item
*/
public T getItem()
{
return mItem;
}
public boolean hasItem()
{
return mItem != null;
}
/**
* Sets the contents modified flag
*/
public void setModified(boolean modified)
{
mModified = modified;
}
/**
* Indicates if this editor contents have been modified
*/
public boolean isModified()
{
return mModified;
}
/**
* Save the contents of the editor
*/
public abstract void save();
/**
* Reset the contents of the editor without saving any changes
*/
public void reset()
{
mModified = false;
setItem(mItem);
}
}

View File

@@ -1,59 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.service.radioreference.RadioReferenceFrequencyIndex;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
/**
* Swing panel that holds the JavaFX map view for the main application window. The JavaFX view is created on the
* JavaFX application thread after construction.
*/
public class MapPanel extends JFXPanel
{
/**
* Constructs an instance
* @param mapService for the entities to plot
* @param iconModel for alias icons
* @param userPreferences for the map view and the user's location
* @param frequencyIndex of the radio reference frequencies near the user, for the trunked system sites, or null
* @param playlistActions to add sites to the playlist or enable their channels, or null
*/
public MapPanel(MapService mapService, IconModel iconModel, UserPreferences userPreferences,
RadioReferenceFrequencyIndex frequencyIndex, RadioReferencePlaylistActions playlistActions)
{
Platform.setImplicitExit(false);
ThemeManager.getInstance().registerSwing(this);
Platform.runLater(() -> {
MapView view = new MapView(mapService, iconModel, userPreferences, frequencyIndex, playlistActions, true);
Scene scene = new Scene(view);
ThemeManager.getInstance().register(scene);
setScene(scene);
});
}
}

View File

@@ -78,7 +78,7 @@ public class DecodeEventView extends HistoryTableView<IDecodeEvent,IDecodeEvent>
userPreferences.getSwingPreference(), SWING_TABLE_KEY, "Event Filter Editor", "Event Columns");
mTimestampFormatter = timestampFormatter;
getHistoryControls().setFilterSet(mFilterSet);
//Filter changes come from the Swing filter editor
//Filter changes come from the filter editor
mFilterSet.register(() -> Platform.runLater(this::refilter));
MyEventBus.getGlobalEventBus().register(this);
}

View File

@@ -22,7 +22,6 @@ import io.github.dsheirer.filter.FilterEditor;
import io.github.dsheirer.filter.FilterSet;
import io.github.dsheirer.gui.table.ColumnConfigurationButton;
import io.github.dsheirer.gui.table.TableColumnMonitor;
import java.awt.EventQueue;
import java.util.function.IntConsumer;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
@@ -52,7 +51,6 @@ public class HistoryControls<T> extends HBox
private final Label mHistoryLabel = new Label("History:");
private final Slider mHistorySlider = new Slider(0, MAXIMUM_HISTORY_SIZE, DEFAULT_HISTORY_SIZE);
private final Label mHistoryValueLabel = new Label(String.valueOf(DEFAULT_HISTORY_SIZE));
//Swing filter editor, accessed on the Swing event thread
private FilterEditor<T> mFilterEditor;
private FilterSet<T> mFilterSet;
@@ -122,16 +120,14 @@ public class HistoryControls<T> extends HBox
{
mFilterSet = filterSet;
EventQueue.invokeLater(() -> {
if(mFilterEditor != null && filterSet != null)
{
mFilterEditor.updateFilterSet(filterSet);
}
});
if(mFilterEditor != null && filterSet != null)
{
mFilterEditor.updateFilterSet(filterSet);
}
}
/**
* Shows the filter editor. The filter editor is a Swing window.
* Shows the filter editor.
*/
private void showFilterEditor()
{
@@ -139,15 +135,13 @@ public class HistoryControls<T> extends HBox
if(filterSet != null)
{
EventQueue.invokeLater(() -> {
if(mFilterEditor == null)
{
mFilterEditor = new FilterEditor<>(mFilterEditorTitle, null, filterSet);
}
if(mFilterEditor == null)
{
mFilterEditor = new FilterEditor<>(mFilterEditorTitle,
getScene() != null ? getScene().getWindow() : null, filterSet);
}
mFilterEditor.setVisible(true);
mFilterEditor.toFront();
});
mFilterEditor.show();
}
}
}

View File

@@ -94,7 +94,7 @@ public class MessageActivityView extends HistoryTableView<MessageItem,IMessage>
MessageHistory history = processingChain.getMessageHistory();
FilterSet<IMessage> filterSet = DecoderFactory.getMessageFilters(processingChain.getModules());
mMessageFilterSet = filterSet;
//Filter changes come from the Swing filter editor
//Filter changes come from the filter editor
filterSet.register(() -> Platform.runLater(() -> {
if(mMessageFilterSet == filterSet)
{

View File

@@ -31,7 +31,6 @@ import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import javax.swing.UIManager;
/**
* Table column and cell helpers for the Now Playing tables.
@@ -125,9 +124,8 @@ public final class NowPlayingCells
setGraphic(icon != null && icon.getFxImage() != null ? new ImageView(icon.getFxImage()) : null);
java.awt.Color color = new java.awt.Color(item.color());
java.awt.Color background = UIManager.getColor("Table.background");
java.awt.Color readable = background != null ?
ThemeManager.getInstance().getReadableColor(color, background) : color;
java.awt.Color readable = ThemeManager.getInstance().getReadableColor(color,
ThemeManager.getInstance().getInnerBackground());
String fill = toWebColor(readable.getRGB());
//An inline style, since the themed table row style otherwise replaces the text fill
setStyle("-fx-text-fill: " + fill + ";");

View File

@@ -1,81 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.nowplaying;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
/**
* Swing panel that holds the JavaFX Now Playing view for the main application window. The JavaFX view is created
* on the JavaFX application thread after construction.
*/
public class NowPlayingPanel extends JFXPanel
{
private NowPlayingView mNowPlayingView;
private boolean mDetailTabsVisible;
/**
* Constructs an instance
* @param playlistManager for the channels
* @param iconModel for alias icons
* @param userPreferences for display formats and column settings
* @param detailTabsVisible to show the channel detail tabs
*/
public NowPlayingPanel(PlaylistManager playlistManager, IconModel iconModel, UserPreferences userPreferences,
boolean detailTabsVisible)
{
mDetailTabsVisible = detailTabsVisible;
Platform.setImplicitExit(false);
ThemeManager.getInstance().registerSwing(this);
Platform.runLater(() -> {
NowPlayingView view;
synchronized(NowPlayingPanel.this)
{
view = new NowPlayingView(playlistManager, iconModel, userPreferences, mDetailTabsVisible);
mNowPlayingView = view;
}
Scene scene = new Scene(view);
ThemeManager.getInstance().register(scene);
setScene(scene);
});
}
/**
* Changes the visibility of the channel details tabs. Can be called from any thread.
* @param visible true to show or false to hide.
*/
public synchronized void setDetailTabsVisible(boolean visible)
{
mDetailTabsVisible = visible;
if(mNowPlayingView != null)
{
NowPlayingView view = mNowPlayingView;
Platform.runLater(() -> view.setDetailTabsVisible(visible));
}
}
}

View File

@@ -37,7 +37,6 @@ import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.util.ThreadPool;
import io.github.dsheirer.util.TimeStamp;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
@@ -131,6 +130,9 @@ public class PlaylistEditor extends BorderPane
getRadioReferenceEditor().view(viewRequest);
}
break;
case STREAM:
getTabPane().getSelectionModel().select(getStreamingTab());
break;
case PLAYLIST:
//Ignore - this is a request to simply show te playlist editor
break;
@@ -182,7 +184,7 @@ public class PlaylistEditor extends BorderPane
screenShot.setOnShown(event -> menuItem.fire());
menuItem.setOnAction(event -> {
WritableImage image = getMenuBar().getScene().snapshot(null);
final BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
final BufferedImage bufferedImage = io.github.dsheirer.gui.FxToolkit.toBufferedImage(image);
String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png";
final Path captureFile = mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture().resolve(filename);

View File

@@ -20,7 +20,7 @@
package io.github.dsheirer.gui.playlist;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.gui.JavaFxWindowManager;
import io.github.dsheirer.gui.WindowManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.module.log.EventLogManager;
import io.github.dsheirer.playlist.PlaylistManager;
@@ -41,7 +41,7 @@ public class PlaylistEditorApplication extends Application
private TunerManager mTunerManager;
private UserPreferences mUserPreferences = new UserPreferences();
private PlaylistManager mPlaylistManager;
private JavaFxWindowManager mJavaFxWindowManager;
private WindowManager mWindowManager;
public PlaylistEditorApplication()
{
@@ -52,7 +52,7 @@ public class PlaylistEditorApplication extends Application
mPlaylistManager = new PlaylistManager(mUserPreferences, mTunerManager, aliasModel, eventLogManager, new IconModel());
mPlaylistManager.init();
mJavaFxWindowManager = new JavaFxWindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
mWindowManager = new WindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
}
@Override

View File

@@ -79,7 +79,6 @@ import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import javax.swing.UIManager;
import jiconfont.IconCode;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconNode;
@@ -950,7 +949,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
rectangle.setVisible(true);
java.awt.Color color = alias.getDisplayColor();
java.awt.Color readable = ThemeManager.getInstance().getReadableColor(color,
UIManager.getColor("TextField.background"));
ThemeManager.getInstance().getInnerBackground());
rectangle.setFill(ColorUtil.fromInteger(readable.equals(color) ? alias.getColor() :
readable.getRGB()));
setAccessibleText(String.format("#%06X", alias.getColor() & 0xFFFFFF));

View File

@@ -164,7 +164,7 @@ public abstract class AbstractBroadcastEditor<T extends BroadcastConfiguration>
}
}
//TODO: remove this after we get rid of Swing tables so that we don't have to announce these changes.
//Restarts the stream's broadcaster with the updated configuration and notifies the model's listeners
mPlaylistManager.getBroadcastModel().process(new BroadcastEvent(configuration,
BroadcastEvent.Event.CONFIGURATION_CHANGE));
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,27 +17,18 @@
* ****************************************************************************
*/
package io.github.dsheirer.util;
package io.github.dsheirer.gui.playlist.streaming;
import java.awt.EventQueue;
import io.github.dsheirer.gui.playlist.PlaylistEditorRequest;
/**
* Swing utilities
* Request to show the playlist editor with the Streaming tab selected.
*/
public class SwingUtils
public class ViewStreamingRequest extends PlaylistEditorRequest
{
/**
* Runs the runnable on the swing dispatch thread
*/
public static void run(Runnable r)
@Override
public TabName getTabName()
{
if(EventQueue.isDispatchThread())
{
r.run();
}
else
{
EventQueue.invokeLater(r);
}
return TabName.STREAM;
}
}

View File

@@ -38,8 +38,8 @@ import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Appearance preferences - selects the active UI {@link Theme} and the global GUI zoom factor for
* both the Swing main window and the JavaFX panels.
* Appearance preferences - selects the active UI {@link Theme} and the global GUI zoom factor for the
* application windows.
*/
public class AppearancePreferenceEditor extends HBox
{

View File

@@ -146,6 +146,17 @@ public abstract class DftSpectralDisplay extends StackPane
setMinSize(0, 0);
}
private final ObjectProperty<Runnable> mHideHandler = new SimpleObjectProperty<>();
/**
* Optional handler that hides this display, for example by collapsing the main window's spectrum pane. When set,
* the configuration panel shows a hide button. JavaFX thread only.
*/
public ObjectProperty<Runnable> hideHandlerProperty()
{
return mHideHandler;
}
/**
* Creates the configuration panel. Subclasses call this at the end of their constructor, after their own
* settings are loaded, since the panel reads the subclass's controls.

View File

@@ -0,0 +1,282 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.ui.DiscoveredTunerModel;
import io.github.dsheirer.controller.NamingThreadFactory;
import io.github.dsheirer.util.ThreadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.scene.layout.StackPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main window spectrum and waterfall display for the selected tuner.
*
* The display can be hidden. A hidden display is disposed: it stops the DFT processing, disconnects from the tuner's
* sample stream and releases the waterfall images, so it uses no processing or memory. The selected tuner is kept
* and a new display shows it again when the display is shown.
*
* Showing a tuner can block while the tuner starts its sample stream, so tuner changes run in order on a dedicated
* thread and the methods can be called from any thread.
*/
public class MainSpectralDisplay extends StackPane
{
private static final Logger mLog = LoggerFactory.getLogger(MainSpectralDisplay.class);
private final PlaylistManager mPlaylistManager;
private final DiscoveredTunerModel mDiscoveredTunerModel;
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor(
new NamingThreadFactory("sdrtrunk main spectral display"));
private final ReadOnlyBooleanWrapper mDisplayVisible = new ReadOnlyBooleanWrapper(true);
private TunerSpectralDisplay mDisplay;
private Tuner mTuner;
private Runnable mHideRequestHandler;
private boolean mDisposed;
/**
* Constructs an instance. JavaFX thread only.
* @param playlistManager for the channels
* @param discoveredTunerModel for the list of tuners
* @param visible true to create the display now, or false to start hidden
*/
public MainSpectralDisplay(PlaylistManager playlistManager, DiscoveredTunerModel discoveredTunerModel,
boolean visible)
{
mPlaylistManager = playlistManager;
mDiscoveredTunerModel = discoveredTunerModel;
getStyleClass().add("main-spectral-display");
setMinSize(0, 0);
mDisplayVisible.set(visible);
if(visible)
{
createDisplay();
}
}
/**
* Indicates if the display is showing (true) or hidden and disposed (false).
*/
public ReadOnlyBooleanProperty displayVisibleProperty()
{
return mDisplayVisible.getReadOnlyProperty();
}
/**
* Sets the handler that the display's hide button invokes, so that the main window can collapse its pane and
* update its menu. The handler is expected to call {@link #setDisplayVisible(boolean)}.
*/
public void setHideRequestHandler(Runnable handler)
{
mHideRequestHandler = handler;
TunerSpectralDisplay display = mDisplay;
if(display != null)
{
display.hideHandlerProperty().set(handler);
}
}
/**
* Shows or hides the display. Hiding disposes the display so that it uses no processing or memory. Showing
* creates a new display for the selected tuner. JavaFX thread only.
*/
public void setDisplayVisible(boolean visible)
{
if(visible == mDisplayVisible.get() || mDisposed)
{
return;
}
mDisplayVisible.set(visible);
if(visible)
{
createDisplay();
}
else
{
TunerSpectralDisplay display;
synchronized(this)
{
display = mDisplay;
mDisplay = null;
}
getChildren().clear();
if(display != null)
{
//Disconnecting from the tuner can block, so dispose on the display thread
mExecutor.submit(() -> dispose(display));
}
}
}
/**
* Creates the display and shows the selected tuner. JavaFX thread only.
*/
private void createDisplay()
{
TunerSpectralDisplay display = new TunerSpectralDisplay(mPlaylistManager, mDiscoveredTunerModel, true);
display.setTunerSelectionHandler(this::tunerSelected);
display.hideHandlerProperty().set(mHideRequestHandler);
getChildren().setAll(display);
Tuner tuner;
synchronized(this)
{
mDisplay = display;
tuner = mTuner;
}
if(tuner != null)
{
mExecutor.submit(() -> {
synchronized(MainSpectralDisplay.this)
{
//Skip when the display was hidden or the tuner changed before this ran
if(mDisplay != display || mTuner != tuner)
{
return;
}
}
display.showTuner(tuner);
});
}
}
/**
* Handles a tuner selection in the configuration panel. Selecting a tuner turns the main spectral display on and
* selecting no tuner turns it off, the same as the View menu.
*/
private void tunerSelected(Tuner tuner)
{
Tuner current = getTuner();
ThreadPool.CACHED.submit(() -> {
if(tuner != null)
{
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true);
mDiscoveredTunerModel.broadcast(new TunerEvent(tuner, TunerEvent.Event.REQUEST_MAIN_SPECTRAL_DISPLAY));
}
else
{
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, false);
mDiscoveredTunerModel.broadcast(new TunerEvent(current,
TunerEvent.Event.REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY));
}
});
}
/**
* Selects the tuner to show. When the display is hidden, the tuner is shown when the display is shown again.
* Can be called from any thread and doesn't block.
*/
public void showTuner(Tuner tuner)
{
synchronized(this)
{
mTuner = tuner;
}
mExecutor.submit(() -> {
TunerSpectralDisplay display;
synchronized(MainSpectralDisplay.this)
{
if(mTuner != tuner)
{
return;
}
display = mDisplay;
}
if(display != null)
{
display.showTuner(tuner);
}
});
}
/**
* Stops showing the selected tuner. Can be called from any thread and doesn't block.
*/
public void clearTuner()
{
showTuner(null);
}
/**
* Selected tuner, or null. The tuner is kept while the display is hidden.
*/
public synchronized Tuner getTuner()
{
return mTuner;
}
/**
* Disposes the display and stops the display thread. Blocks until the display has disconnected from the tuner.
*/
public void dispose()
{
TunerSpectralDisplay display;
synchronized(this)
{
mDisposed = true;
display = mDisplay;
mDisplay = null;
mTuner = null;
}
mExecutor.shutdownNow();
if(display != null)
{
dispose(display);
}
}
private static void dispose(TunerSpectralDisplay display)
{
try
{
display.dispose();
}
catch(Exception e)
{
mLog.error("Error disposing the spectral display", e);
}
}
}

View File

@@ -34,6 +34,7 @@ import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
@@ -233,7 +234,25 @@ public class SpectralDisplayConfigPanel extends VBox
pinButton.getStyleClass().add("spectral-config-pin");
pinButton.selectedProperty().bindBidirectional(mPinned);
pinButton.setTooltip(new Tooltip("Keep the settings panel open"));
HBox header = new HBox(6, headerIcon, title, spacer, pinButton);
IconNode hideIcon = new IconNode(FontAwesome.EYE_SLASH);
hideIcon.setIconSize(12);
hideIcon.getStyleClass().add("spectral-config-icon");
Button hideButton = new Button(null, hideIcon);
hideButton.getStyleClass().add("spectral-config-pin");
hideButton.setTooltip(new Tooltip("Hide the spectrum and waterfall. A hidden display uses no processing " +
"or memory. Show it again from the View menu or the bar at the top of the window."));
hideButton.setAccessibleText("Hide spectrum and waterfall");
hideButton.visibleProperty().bind(mHost.hideHandlerProperty().isNotNull());
hideButton.managedProperty().bind(hideButton.visibleProperty());
hideButton.setOnAction(event -> {
Runnable handler = mHost.hideHandlerProperty().get();
if(handler != null)
{
handler.run();
}
});
HBox header = new HBox(6, headerIcon, title, spacer, hideButton, pinButton);
header.setAlignment(Pos.CENTER_LEFT);
header.setPadding(new Insets(2, 2, 4, 4));

View File

@@ -1,190 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.ui.DiscoveredTunerModel;
import io.github.dsheirer.util.ThreadPool;
import java.awt.EventQueue;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
/**
* Swing panel that holds the JavaFX tuner spectral display for the main application window.
*
* The JavaFX display is created on the JavaFX application thread after construction. A tuner requested before the
* display exists is shown once the display is ready.
*/
public class SpectralDisplayPanel extends JFXPanel
{
private final DiscoveredTunerModel mDiscoveredTunerModel;
private TunerSpectralDisplay mTunerSpectralDisplay;
private Tuner mPendingTuner;
private boolean mDisposed;
/**
* Constructs an instance.
* @param playlistManager for the channels
* @param discoveredTunerModel for the list of tuners
*/
public SpectralDisplayPanel(PlaylistManager playlistManager, DiscoveredTunerModel discoveredTunerModel)
{
mDiscoveredTunerModel = discoveredTunerModel;
Platform.setImplicitExit(false);
Platform.runLater(() -> {
TunerSpectralDisplay display = new TunerSpectralDisplay(playlistManager, discoveredTunerModel, true);
display.setTunerSelectionHandler(this::tunerSelected);
Scene scene = new Scene(display);
ThemeManager.getInstance().register(scene);
setScene(scene);
Tuner pending;
synchronized(SpectralDisplayPanel.this)
{
if(mDisposed)
{
ThreadPool.CACHED.submit(display::dispose);
return;
}
mTunerSpectralDisplay = display;
pending = mPendingTuner;
mPendingTuner = null;
}
if(pending != null)
{
ThreadPool.CACHED.submit(() -> display.showTuner(pending));
}
});
}
/**
* Handles a tuner selection in the configuration panel. Selecting a tuner turns the main spectral display on and
* selecting no tuner turns it off, the same as the View menu.
*/
private void tunerSelected(Tuner tuner)
{
//Broadcast on the Swing event thread, the same as the Swing tuner menu items, since listeners update Swing
EventQueue.invokeLater(() -> {
if(tuner != null)
{
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true);
mDiscoveredTunerModel.broadcast(new TunerEvent(tuner, TunerEvent.Event.REQUEST_MAIN_SPECTRAL_DISPLAY));
}
else
{
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, false);
mDiscoveredTunerModel.broadcast(new TunerEvent(getTuner(),
TunerEvent.Event.REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY));
}
});
}
/**
* Shows the tuner in the display. Can block while the tuner starts its sample stream.
*/
public void showTuner(Tuner tuner)
{
TunerSpectralDisplay display;
synchronized(this)
{
if(mTunerSpectralDisplay == null)
{
mPendingTuner = tuner;
return;
}
display = mTunerSpectralDisplay;
}
display.showTuner(tuner);
}
/**
* Stops showing the current tuner.
*/
public void clearTuner()
{
TunerSpectralDisplay display;
synchronized(this)
{
if(mTunerSpectralDisplay == null)
{
mPendingTuner = null;
return;
}
display = mTunerSpectralDisplay;
}
display.clearTuner();
}
/**
* Currently displayed tuner, or null.
*/
public Tuner getTuner()
{
TunerSpectralDisplay display;
synchronized(this)
{
if(mTunerSpectralDisplay == null)
{
return mPendingTuner;
}
display = mTunerSpectralDisplay;
}
return display.getTuner();
}
/**
* Stops showing the tuner and releases resources.
*/
public void dispose()
{
TunerSpectralDisplay display;
synchronized(this)
{
mDisposed = true;
display = mTunerSpectralDisplay;
mTunerSpectralDisplay = null;
mPendingTuner = null;
}
if(display != null)
{
display.dispose();
}
}
}

View File

@@ -38,7 +38,7 @@ public class NoiseSquelchTestApplication extends Application
@Override
public void start(Stage primaryStage)
{
//Register FontAwesome so we can use the fonts in Swing windows
//Register FontAwesome so the views can use its icons
IconFontFX.register(FontAwesome.getIconFont());
NoiseSquelchView view = new NoiseSquelchView(null);

View File

@@ -20,34 +20,54 @@
package io.github.dsheirer.gui.theme;
/**
* Curated preset themes for the application.
*
* <p>Each theme pairs a FlatLaf Swing look-and-feel class with a flag indicating whether the
* palette is dark. The dark flag drives whether the dark JavaFX stylesheet is applied to
* registered Scenes. Other per-theme values (colours used to seed JIDE-specific UIManager
* keys) are read at runtime from {@link javax.swing.UIManager} after the LAF installs, so each
* theme automatically contributes its own palette to JIDE components.
* Application color themes. Each theme has a palette that the theme manager applies to the JavaFX scenes, and a
* dark flag that adds the dark stylesheet. The palettes are the colors of the FlatLaf themes that sdrtrunk used for
* its Swing windows, so the themes look the same after the move to JavaFX.
*/
public enum Theme
{
LIGHT("Light", "com.formdev.flatlaf.FlatLightLaf", false),
DARK("Dark", "com.formdev.flatlaf.FlatDarkLaf", true),
NORD("Nord", "com.formdev.flatlaf.intellijthemes.FlatNordIJTheme", true),
DRACULA("Dracula", "com.formdev.flatlaf.intellijthemes.FlatDraculaIJTheme", true),
SOLARIZED_LIGHT("Solarized Light", "com.formdev.flatlaf.intellijthemes.FlatSolarizedLightIJTheme", false),
SOLARIZED_DARK("Solarized Dark", "com.formdev.flatlaf.intellijthemes.FlatSolarizedDarkIJTheme", true),
MATERIAL_DEEP_OCEAN("Material Deep Ocean", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMTMaterialDeepOceanIJTheme", true),
ARC_DARK("Arc Dark", "com.formdev.flatlaf.intellijthemes.FlatArcDarkIJTheme", true);
LIGHT("Light", false,
new Palette(0xf2f2f2, 0xffffff, 0xfafafa, 0x2675bf, 0x2675bf, 0xffffff, 0x000000, 0xc2c2c2)),
DARK("Dark", true,
new Palette(0x3c3f41, 0x46494b, 0x353739, 0x4b6eaf, 0x4b6eaf, 0xeeeeee, 0xdddddd, 0x616365)),
NORD("Nord", true,
new Palette(0x2e3440, 0x3b4252, 0x353739, 0x88c0d0, 0x88c0d0, 0x2e3440, 0xeceff4, 0x3b4252)),
DRACULA("Dracula", true,
new Palette(0x414450, 0x3a3d4c, 0x353739, 0xff79c6, 0x6272a4, 0xf8f8f2, 0xdddddd, 0x6272a4)),
SOLARIZED_LIGHT("Solarized Light", false,
new Palette(0xeee8d5, 0xfdf6e3, 0xfafafa, 0x3d7ec0, 0x3570cd, 0xffffeb, 0x2e4e58, 0xbac0b8)),
SOLARIZED_DARK("Solarized Dark", true,
new Palette(0x0e3c4a, 0x1b4854, 0x353739, 0x3985c7, 0x1c62c9, 0xc2c5bc, 0xa9b3ae, 0x49636b)),
MATERIAL_DEEP_OCEAN("Material Deep Ocean", true,
new Palette(0x0f111a, 0x090b10, 0x353739, 0x84ffff, 0x3d4669, 0xffffff, 0x8f93a2, 0x1f2233)),
ARC_DARK("Arc Dark", true,
new Palette(0x383c4a, 0x474c5b, 0x353739, 0x2679db, 0x2679db, 0xffffff, 0xd3dae3, 0x2b2e39));
/**
* Theme colors as 0xRRGGBB values.
* @param background of windows and panels
* @param inner background of text fields, tables and lists
* @param innerAlternate background of alternate table rows
* @param accent for focus, default buttons and highlights
* @param selectionBackground of selected rows
* @param selectionText of selected rows
* @param text color
* @param border of controls and scroll bar thumbs
*/
public record Palette(int background, int inner, int innerAlternate, int accent, int selectionBackground,
int selectionText, int text, int border)
{
}
private final String mDisplayName;
private final String mLafClassName;
private final boolean mDark;
private final Palette mPalette;
Theme(String displayName, String lafClassName, boolean dark)
Theme(String displayName, boolean dark, Palette palette)
{
mDisplayName = displayName;
mLafClassName = lafClassName;
mDark = dark;
mPalette = palette;
}
/**
@@ -58,14 +78,6 @@ public enum Theme
return mDisplayName;
}
/**
* @return fully qualified FlatLaf class name to instantiate via reflection.
*/
public String getLafClassName()
{
return mLafClassName;
}
/**
* @return true if this theme is a dark palette - the JavaFX dark stylesheet is applied for
* dark themes and removed for light themes.
@@ -75,6 +87,14 @@ public enum Theme
return mDark;
}
/**
* Theme colors
*/
public Palette getPalette()
{
return mPalette;
}
/**
* Resolve a theme by its enum name, returning {@link #LIGHT} as a safe default if {@code name}
* is null or unrecognised.

View File

@@ -19,15 +19,11 @@
package io.github.dsheirer.gui.theme;
import com.formdev.flatlaf.FlatLightLaf;
import com.google.common.eventbus.Subscribe;
import com.jidesoft.plaf.LookAndFeelFactory;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Window;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedHashSet;
@@ -35,33 +31,16 @@ import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.application.Platform;
import javafx.scene.Scene;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalLookAndFeel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Centralized theme manager that drives both Swing and JavaFX appearance from the user
* preference selection.
* Applies the user's theme and GUI scale to every JavaFX scene.
*
* <p>Each {@link Theme} pairs a FlatLaf look-and-feel class with a dark/light flag. When a
* theme is applied:
* <ul>
* <li>The Swing LAF is installed (reflected from {@link Theme#getLafClassName()}).</li>
* <li>JIDE's LAF extension is reinstalled with an explicit Metal LAF for type detection so
* JIDE's compile-time {@code WindowsLookAndFeel} {@code instanceof} checks do not hit
* the missing-class branch on Linux/macOS JDKs.</li>
* <li>FlatLaf's standard defaults are re-applied on top of JIDE's clobber, and a set of
* JIDE-specific colour keys (JideTabbedPane.*, JideSplitPane.*, JideButton.*) are seeded
* from FlatLaf's just-installed values so each theme's palette propagates to JIDE widgets
* automatically.</li>
* <li>The dark JavaFX stylesheet is applied to (or removed from) every registered Scene
* depending on the theme's dark flag.</li>
* </ul>
* <p>Each {@link Theme} has a palette and a dark/light flag. The palette becomes a small stylesheet that sets
* Modena's looked-up colors and the scaled root font size. Dark themes also get the dark stylesheet. Registered
* scenes, and every JavaFX window that opens (including ad-hoc alerts and dialogs), are updated when the theme
* changes.</p>
*/
public class ThemeManager
{
@@ -71,7 +50,6 @@ public class ThemeManager
private final Set<WeakReference<Scene>> mScenes = new LinkedHashSet<>();
private final AtomicBoolean mWindowListenerAttached = new AtomicBoolean();
private final Set<WeakReference<java.awt.Component>> mSwingRoots = new LinkedHashSet<>();
private final String mDarkStylesheetUrl;
private volatile UserPreferences mUserPreferences;
private volatile Theme mCurrentTheme = Theme.LIGHT;
@@ -87,7 +65,7 @@ public class ThemeManager
if(mDarkStylesheetUrl == null)
{
mLog.warn("Dark stylesheet [{}] not found on classpath - dark themes will only affect Swing.",
mLog.warn("Dark stylesheet [{}] not found on classpath - dark themes won't be applied.",
DARK_STYLESHEET);
}
}
@@ -120,10 +98,8 @@ public class ThemeManager
attachJavaFxWindowListener();
}
//applyAll installs the Swing LAF *and* computes the per-theme accent stylesheet URL so it
//is ready before any Scene.register call. At init time the FX-side scene walk is a no-op
//because nothing has registered yet, but mAccentStylesheetUrl gets populated for later
//register(...) calls.
//Compute the per-theme accent stylesheet URL so it is ready before any Scene.register call. At init
//time the scene walk is a no-op because nothing has registered yet.
applyAll(mCurrentTheme);
}
@@ -190,7 +166,7 @@ public class ThemeManager
catch(IllegalStateException ignored)
{
//FX toolkit not started yet, which is the case when initialize() runs at application
//startup, before the first JFXPanel. register() attaches the listener once the
//startup, before the toolkit starts. register() attaches the listener once the
//first JavaFX scene is registered, which happens after the toolkit starts.
}
}
@@ -268,35 +244,6 @@ public class ThemeManager
applyToScene(scene, isDarkMode());
}
/**
* Register a Swing component that may be temporarily detached from any Window's component tree
* (e.g. swappable right-pane components in the Channel tab). Registered components get
* {@link SwingUtilities#updateComponentTreeUI(java.awt.Component)} called on them whenever the
* theme is applied, so they pick up the current palette even if they weren't attached when the
* user toggled.
*/
public void registerSwing(java.awt.Component component)
{
if(component == null)
{
return;
}
synchronized(mSwingRoots)
{
Iterator<WeakReference<java.awt.Component>> it = mSwingRoots.iterator();
while(it.hasNext())
{
java.awt.Component existing = it.next().get();
if(existing == null || existing == component)
{
it.remove();
}
}
mSwingRoots.add(new WeakReference<>(component));
}
}
@Subscribe
public void onPreferenceUpdated(PreferenceType type)
{
@@ -309,18 +256,7 @@ public class ThemeManager
double updatedScale = mUserPreferences.getApplicationPreference().getGuiScale();
boolean updatedComplementary = mUserPreferences.getApplicationPreference().isComplementaryAliasColors();
if(updatedComplementary != mComplementaryAliasColors)
{
mComplementaryAliasColors = updatedComplementary;
//The Swing table renderers look up the alias color each time they paint.
EventQueue.invokeLater(() -> {
for(Window window: Window.getWindows())
{
window.repaint();
}
});
}
mComplementaryAliasColors = updatedComplementary;
if(updated == mCurrentTheme && Math.abs(updatedScale - mCurrentGuiScale) < 1e-6)
{
@@ -334,8 +270,6 @@ public class ThemeManager
private void applyAll(Theme theme)
{
applySwingLookAndFeel(theme);
//Compute the per-theme accent stylesheet on the calling thread so the data URL is ready
//before the FX apply runs. Capture the previous URL so we can remove it from each Scene.
String previousAccentUrl = mAccentStylesheetUrl;
@@ -444,20 +378,15 @@ public class ThemeManager
{
try
{
UIDefaults laf = UIManager.getLookAndFeelDefaults();
boolean dark = theme.isDark();
String base = hex(laf.getColor("Panel.background"), dark ? 0x2b2b2b : 0xf2f2f2);
String inner = hex(laf.getColor("TextField.background"), dark ? 0x313335 : 0xffffff);
String innerAlt = hex(laf.getColor("Table.alternateRowColor"), dark ? 0x353739 : 0xfafafa);
String accent = hex(laf.getColor("Component.accentColor"),
hexInt(laf.getColor("List.selectionBackground"), dark ? 0x4a90d9 : 0x2675bf));
String selectionBg = hex(laf.getColor("List.selectionBackground"),
dark ? 0x214283 : 0x2675bf);
String selectionFg = hex(laf.getColor("List.selectionForeground"), 0xffffff);
String text = hex(laf.getColor("Label.foreground"), dark ? 0xe6e6e6 : 0x1e1e1e);
String border = hex(laf.getColor("Component.borderColor"),
dark ? 0x4f5356 : 0xc4c4c4);
Theme.Palette palette = theme.getPalette();
String base = hex(palette.background());
String inner = hex(palette.inner());
String innerAlt = hex(palette.innerAlternate());
String accent = hex(palette.accent());
String selectionBg = hex(palette.selectionBackground());
String selectionFg = hex(palette.selectionText());
String text = hex(palette.text());
String border = hex(palette.border());
//JavaFX side of the GUI scale: setting -fx-font-size on .root cascades through
//Modena because most sizes are em-relative. Modena's default is 12px; multiplying
@@ -514,305 +443,18 @@ public class ThemeManager
}
}
private static String hex(Color c, int fallbackRgb)
private static String hex(int rgb)
{
int rgb = (c != null) ? (c.getRGB() & 0xFFFFFF) : (fallbackRgb & 0xFFFFFF);
return String.format("#%06x", rgb);
}
private static int hexInt(Color c, int fallbackRgb)
{
return (c != null) ? (c.getRGB() & 0xFFFFFF) : (fallbackRgb & 0xFFFFFF);
}
private void applySwingLookAndFeel(Theme theme)
{
//FlatLaf reads the flatlaf.uiScale system property when its LAF instance is initialised.
//Set it before constructing the LAF so this theme apply picks up the user's zoom factor.
//We also clear any previous UIManager-stored override so the system property takes effect.
System.setProperty("flatlaf.uiScale", String.valueOf(mCurrentGuiScale));
UIManager.put("flatlaf.uiScale", null);
//Install the LAF synchronously on the calling thread so any Swing components constructed
//immediately afterwards (in particular the main JFrame) find a fully populated UIDefaults
//set. UIManager.setLookAndFeel is safe to call before the EDT is running.
LookAndFeel newLaf = instantiate(theme);
try
{
UIManager.setLookAndFeel(newLaf);
}
catch(Exception e)
{
mLog.error("Unable to apply Swing look-and-feel for theme = " + theme, e);
return;
}
try
{
//JIDE 3.6.18 has compile-time `instanceof WindowsLookAndFeel` checks throughout
//LookAndFeelFactory. The 3-arg overload lets us hand JIDE an explicit Metal LAF
//instance for type detection while leaving the real (FlatLaf) defaults table in place;
//JIDE's Metal branch matches first.
LookAndFeelFactory.installJideExtension(UIManager.getLookAndFeelDefaults(),
new MetalLookAndFeel(), LookAndFeelFactory.VSNET_STYLE);
}
catch(Throwable t)
{
mLog.warn("Unable to install JIDE LAF extension after theme change", t);
}
//JIDE's Metal-flavored extension overwrites FlatLaf's color/font/border defaults for
//standard Swing component keys. Re-apply FlatLaf's defaults on top of JIDE's install so
//the inner panels pick up the right colours. JIDE's UI delegate registrations live under
//Jide-prefixed keys that FlatLaf does not define, so they survive untouched.
try
{
UIDefaults flatFresh = instantiate(theme).getDefaults();
UIDefaults active = UIManager.getLookAndFeelDefaults();
for(java.util.Map.Entry<Object, Object> entry: flatFresh.entrySet())
{
Object key = entry.getKey();
Object value = entry.getValue();
String keyName = String.valueOf(key);
if(keyName.startsWith("Jide") || keyName.contains(".Jide"))
{
continue;
}
if(value != null)
{
active.put(key, value);
}
}
}
catch(Throwable t)
{
mLog.warn("Unable to re-apply FlatLaf defaults after JIDE install", t);
}
//Brute-force the standard component colour keys via UIManager.put which writes to the
//user-defaults layer that takes precedence over the LAF defaults. Colours are read from
//the FlatLaf-installed defaults so each theme contributes its own palette.
applyExplicitOverrides(theme);
//Re-rendering already-realized Swing windows must happen on the EDT. Also walk any Swing
//components explicitly registered via registerSwing(...) - they may be detached from any
//Window's tree at toggle time (e.g. swappable channel-tab right components).
Runnable updateRealized = () -> {
for(Window window: Window.getWindows())
{
SwingUtilities.updateComponentTreeUI(window);
}
synchronized(mSwingRoots)
{
Iterator<WeakReference<java.awt.Component>> it = mSwingRoots.iterator();
while(it.hasNext())
{
java.awt.Component c = it.next().get();
if(c == null)
{
it.remove();
}
else
{
SwingUtilities.updateComponentTreeUI(c);
}
}
}
};
if(EventQueue.isDispatchThread())
{
updateRealized.run();
}
else
{
EventQueue.invokeLater(updateRealized);
}
return String.format("#%06x", rgb & 0xFFFFFF);
}
/**
* Reflectively instantiate the FlatLaf class for the given theme. Falls back to
* {@link FlatLightLaf} if the class is missing - that should not happen in a normal build but
* keeps the app usable if a theme jar is removed.
* Background color of text fields, tables and lists in the current theme, for checking the contrast of user
* selected colors such as alias colors.
*/
private LookAndFeel instantiate(Theme theme)
public Color getInnerBackground()
{
try
{
Class<?> cls = Class.forName(theme.getLafClassName());
return (LookAndFeel) cls.getDeclaredConstructor().newInstance();
}
catch(Throwable t)
{
mLog.error("Unable to instantiate LAF [{}] for theme {} - falling back to FlatLightLaf",
theme.getLafClassName(), theme, t);
return new FlatLightLaf();
}
}
private void applyExplicitOverrides(Theme theme)
{
boolean darkMode = theme.isDark();
//CRITICAL: read from UIManager.getLookAndFeelDefaults() (LAF layer only) rather than
//UIManager.getColor() / UIManager.getDefaults() (which is the merged view). The merged
//view returns user-defaults entries from earlier applyExplicitOverrides calls instead of
//the fresh LAF values, which means a second theme switch picks up the previous theme's
//palette and the toggle appears broken after the first change.
UIDefaults laf = UIManager.getLookAndFeelDefaults();
ColorUIResource bgPanel = uir(laf.getColor("Panel.background"),
darkMode ? 0x2b2b2b : 0xf2f2f2);
ColorUIResource bgRaised = uir(laf.getColor("Button.background"),
darkMode ? 0x3c3f41 : 0xffffff);
ColorUIResource bgInput = uir(laf.getColor("TextField.background"),
darkMode ? 0x313335 : 0xffffff);
ColorUIResource bgSelection = uir(laf.getColor("List.selectionBackground"),
darkMode ? 0x214283 : 0x2675bf);
ColorUIResource fgPrimary = uir(laf.getColor("Label.foreground"),
darkMode ? 0xe6e6e6 : 0x1e1e1e);
ColorUIResource fgSelection = uir(laf.getColor("List.selectionForeground"),
0xffffff);
ColorUIResource fgDisabled = uir(laf.getColor("Label.disabledForeground"),
darkMode ? 0x6a6a6a : 0x8c8c8c);
ColorUIResource border = uir(laf.getColor("Component.borderColor"),
darkMode ? 0x4f5356 : 0xc4c4c4);
ColorUIResource altRow = uir(laf.getColor("Table.alternateRowColor"),
darkMode ? 0x353739 : 0xfafafa);
//Use a slightly brighter foreground than FlatLaf's default in dark mode so text reads
//sharper on the JIDE-flavoured surfaces. Light themes keep their own contrast.
if(darkMode && fgPrimary.getRed() < 0xd0)
{
fgPrimary = new ColorUIResource(0xe6e6e6);
}
String[] simpleComponents = {
"Button", "ToggleButton", "CheckBox", "RadioButton",
"Label", "Menu", "MenuItem", "CheckBoxMenuItem", "RadioButtonMenuItem",
"MenuBar", "PopupMenu", "Panel", "Viewport", "ScrollPane",
"Separator", "ToolBar", "ToolTip", "FormattedTextField",
"TitledBorder", "TabbedPane", "OptionPane", "ProgressBar",
"Spinner", "Slider", "ComboBox", "EditorPane", "PasswordField"
};
for(String c: simpleComponents)
{
UIManager.put(c + ".background", bgPanel);
UIManager.put(c + ".foreground", fgPrimary);
UIManager.put(c + ".disabledForeground", fgDisabled);
UIManager.put(c + ".disabledText", fgDisabled);
}
for(String c: new String[]{"Button", "ToggleButton", "ComboBox", "Spinner"})
{
UIManager.put(c + ".background", bgRaised);
}
for(String c: new String[]{"TextField", "TextArea", "TextPane", "EditorPane",
"FormattedTextField", "PasswordField"})
{
UIManager.put(c + ".background", bgInput);
UIManager.put(c + ".foreground", fgPrimary);
UIManager.put(c + ".caretForeground", fgPrimary);
UIManager.put(c + ".inactiveForeground", fgDisabled);
UIManager.put(c + ".selectionBackground", bgSelection);
UIManager.put(c + ".selectionForeground", fgSelection);
}
for(String c: new String[]{"Table", "Tree", "List"})
{
UIManager.put(c + ".background", bgInput);
UIManager.put(c + ".foreground", fgPrimary);
UIManager.put(c + ".selectionBackground", bgSelection);
UIManager.put(c + ".selectionForeground", fgSelection);
}
UIManager.put("Table.gridColor", border);
UIManager.put("Table.alternateRowColor", altRow);
UIManager.put("TableHeader.background", bgRaised);
UIManager.put("TableHeader.foreground", fgPrimary);
UIManager.put("TableHeader.cellBorder",
javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 1, border));
//Tab labels: selected tabs sit on the raised surface (which is white in light themes),
//not on the blue selection background, so the selected-tab text is the primary
//foreground - not the white selection foreground that is right for row selections.
UIManager.put("TabbedPane.foreground", fgPrimary);
UIManager.put("TabbedPane.background", bgPanel);
UIManager.put("TabbedPane.selectedForeground", fgPrimary);
UIManager.put("TabbedPane.selected", bgRaised);
UIManager.put("TabbedPane.contentAreaColor", bgPanel);
UIManager.put("TabbedPane.darkShadow", border);
UIManager.put("TabbedPane.shadow", border);
UIManager.put("MenuItem.selectionBackground", bgSelection);
UIManager.put("MenuItem.selectionForeground", fgSelection);
UIManager.put("Menu.selectionBackground", bgSelection);
UIManager.put("Menu.selectionForeground", fgSelection);
UIManager.put("SplitPane.background", bgPanel);
UIManager.put("SplitPane.dividerFocusColor", bgSelection);
UIManager.put("SplitPaneDivider.draggingColor", bgSelection);
UIManager.put("Component.borderColor", border);
UIManager.put("Component.disabledBorderColor", border);
UIManager.put("Separator.foreground", border);
UIManager.put("Separator.background", bgPanel);
UIManager.put("ToolTip.background", bgRaised);
UIManager.put("ToolTip.foreground", fgPrimary);
//JIDE components read their colours from JIDE-specific UIManager keys, not the standard
//Swing keys. Seed those from the same palette so JIDE widgets follow the theme.
UIManager.put("JideTabbedPane.background", bgPanel);
UIManager.put("JideTabbedPane.foreground", fgPrimary);
UIManager.put("JideTabbedPane.tabAreaBackground", bgPanel);
UIManager.put("JideTabbedPane.selectedTabBackground", bgRaised);
UIManager.put("JideTabbedPane.activeTabBackground", bgRaised);
UIManager.put("JideTabbedPane.tabListBackground", bgRaised);
UIManager.put("JideTabbedPane.selectedTabTextForeground", fgPrimary);
UIManager.put("JideTabbedPane.unselectedTabTextForeground", fgPrimary);
UIManager.put("JideTabbedPane.activeTabTextForeground", fgPrimary);
UIManager.put("JideTabbedPane.shadow", border);
UIManager.put("JideTabbedPane.darkShadow", border);
UIManager.put("JideTabbedPane.light", bgRaised);
UIManager.put("JideTabbedPane.highlight", bgRaised);
UIManager.put("JideSplitPane.background", bgPanel);
UIManager.put("JideSplitPaneDivider.background", bgPanel);
UIManager.put("JideSplitPane.dividerColor", border);
UIManager.put("JideButton.background", bgRaised);
UIManager.put("JideButton.foreground", fgPrimary);
UIManager.put("JideButton.selectedBackground", bgSelection);
UIManager.put("JideButton.selectedForeground", fgSelection);
UIManager.put("JideButton.shadow", border);
UIManager.put("JideButton.darkShadow", border);
UIManager.put("JideButton.light", bgRaised);
UIManager.put("JideButton.highlight", bgRaised);
UIManager.put("JideLabel.background", bgPanel);
UIManager.put("JideLabel.foreground", fgPrimary);
}
/**
* Convert a {@link Color} to a {@link ColorUIResource}, falling back to {@code fallbackRgb} if
* the input is null. Existing UIResource colours are returned as-is.
*/
private static ColorUIResource uir(Color c, int fallbackRgb)
{
if(c == null)
{
return new ColorUIResource(fallbackRgb);
}
if(c instanceof ColorUIResource cuir)
{
return cuir;
}
return new ColorUIResource(c);
return new Color(mCurrentTheme.getPalette().inner());
}
private void pruneDeadReferencesAndCheckPresent(Scene scene)

View File

@@ -1,178 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.theme;
import com.formdev.flatlaf.FlatLaf;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import jiconfont.IconCode;
import jiconfont.swing.IconFontSwing;
/**
* Swing font-glyph icon whose colour follows the active theme.
*
* <p>{@link IconFontSwing#buildIcon(IconCode, float)} bakes a fixed colour (black by default) into
* the rendered image, so those icons never change when the user switches themes and disappear on
* dark palettes. This icon resolves its colour from {@link UIManager} each time it is painted and
* only re-renders the glyph when that colour changes, so it automatically tracks theme changes
* applied by {@link ThemeManager}.
*
* <p>Colour resolution:
* <ul>
* <li>Disabled component: {@code Label.disabledForeground}</li>
* <li>Armed/selected menu item: {@code MenuItem.selectionForeground}</li>
* <li>Otherwise: the configured foreground key (default {@code Label.foreground})</li>
* </ul>
*/
public class ThemedFontIcon implements Icon, FlatLaf.DisabledIconProvider
{
private static final String DEFAULT_FOREGROUND_KEY = "Label.foreground";
private static final String DISABLED_FOREGROUND_KEY = "Label.disabledForeground";
private static final String SELECTION_FOREGROUND_KEY = "MenuItem.selectionForeground";
private final IconCode mIconCode;
private final float mSize;
private final String mForegroundKey;
private final boolean mForceDisabled;
private Color mCachedColor;
private Icon mCachedIcon;
private ThemedFontIcon mDisabledIcon;
/**
* Constructs a theme-aware glyph icon using the standard label foreground colour.
* @param iconCode glyph to render
* @param size in points
*/
public ThemedFontIcon(IconCode iconCode, float size)
{
this(iconCode, size, DEFAULT_FOREGROUND_KEY);
}
/**
* Constructs a theme-aware glyph icon using the specified UIManager colour key.
* @param iconCode glyph to render
* @param size in points
* @param foregroundKey UIManager colour key used for the normal (enabled) state
*/
public ThemedFontIcon(IconCode iconCode, float size, String foregroundKey)
{
this(iconCode, size, foregroundKey, false);
}
private ThemedFontIcon(IconCode iconCode, float size, String foregroundKey, boolean forceDisabled)
{
mIconCode = iconCode;
mSize = size;
mForegroundKey = foregroundKey;
mForceDisabled = forceDisabled;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
getIcon(resolveColor(c)).paintIcon(c, g, x, y);
}
//Glyph dimensions do not depend on colour, so size queries reuse whatever is cached rather than
//forcing a re-render in a different colour between paints.
@Override
public int getIconWidth()
{
return getSizingIcon().getIconWidth();
}
@Override
public int getIconHeight()
{
return getSizingIcon().getIconHeight();
}
private synchronized Icon getSizingIcon()
{
return mCachedIcon != null ? mCachedIcon : getIcon(resolveColor(null));
}
/**
* Disabled variant used by FlatLaf when the owning component is disabled.
*/
@Override
public Icon getDisabledIcon()
{
if(mDisabledIcon == null)
{
mDisabledIcon = new ThemedFontIcon(mIconCode, mSize, mForegroundKey, true);
}
return mDisabledIcon;
}
/**
* Determines the colour to paint with from the current theme and component state.
*/
private Color resolveColor(Component c)
{
if(mForceDisabled || (c != null && !c.isEnabled()))
{
return color(DISABLED_FOREGROUND_KEY, Color.GRAY);
}
//Menu items render their text in the selection foreground while armed (hovered) - match it
//so the glyph stays legible against the selection background. Top-level menus on the menu
//bar report as 'selected' while their popup is open.
if(c instanceof JMenuItem menuItem)
{
ButtonModel model = menuItem.getModel();
boolean highlighted = model.isArmed() || (menuItem instanceof JMenu && model.isSelected());
if(highlighted)
{
return color(SELECTION_FOREGROUND_KEY, color(mForegroundKey, Color.BLACK));
}
}
return color(mForegroundKey, Color.BLACK);
}
private static Color color(String key, Color fallback)
{
Color color = UIManager.getColor(key);
return color != null ? color : fallback;
}
/**
* Returns the glyph rendered in the requested colour, re-rendering only when the colour changes.
*/
private synchronized Icon getIcon(Color color)
{
if(mCachedIcon == null || !color.equals(mCachedColor))
{
mCachedIcon = IconFontSwing.buildIcon(mIconCode, mSize, color);
mCachedColor = color;
}
return mCachedIcon;
}
}

View File

@@ -19,15 +19,14 @@
package io.github.dsheirer.gui.viewer.symbol;
import io.github.dsheirer.util.SwingUtils;
import java.util.concurrent.CountDownLatch;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
import javafx.scene.Scene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
/**
* Utility for viewing sync detection results
@@ -59,7 +58,7 @@ public class SymbolViewerFX implements ISymbolResultsListener
{
CountDownLatch latch = new CountDownLatch(1);
final JFXPanel fxPanel = new JFXPanel();
FxToolkit.ensureStarted();
Platform.runLater(() -> {
Platform.setImplicitExit(false);
SymbolViewPanel viewer = new SymbolViewPanel();
@@ -77,19 +76,13 @@ public class SymbolViewerFX implements ISymbolResultsListener
// LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
// }
fxPanel.setScene(scene);
fxPanel.setVisible(true);
JFrame frame = new JFrame();
frame.setTitle("Symbol Results Viewer");
frame.setContentPane(fxPanel);
frame.setSize(1400, 1400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
SwingUtils.run(() -> {
frame.setVisible(true);
latch.countDown();
});
Stage stage = new Stage();
stage.setTitle("Symbol Results Viewer");
stage.setScene(scene);
//Closing the viewer exits the application, the same as the Swing viewer did
stage.setOnCloseRequest(event -> System.exit(0));
stage.show();
latch.countDown();
});
try

View File

@@ -19,15 +19,14 @@
package io.github.dsheirer.gui.viewer.sync;
import io.github.dsheirer.util.SwingUtils;
import java.util.concurrent.CountDownLatch;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
import javafx.scene.Scene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
/**
* Utility for viewing sync detection results
@@ -77,7 +76,7 @@ public class FMSyncResultsViewer implements ISyncResultsListener
{
CountDownLatch latch = new CountDownLatch(1);
final JFXPanel fxPanel = new JFXPanel();
FxToolkit.ensureStarted();
Platform.runLater(() -> {
Platform.setImplicitExit(false);
FMSyncVisualizer syncVisualizer = new FMSyncVisualizer();
@@ -96,19 +95,13 @@ public class FMSyncResultsViewer implements ISyncResultsListener
// LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
// }
fxPanel.setScene(scene);
fxPanel.setVisible(true);
JFrame frame = new JFrame();
frame.setTitle("Sync Results Viewer");
frame.setContentPane(fxPanel);
frame.setSize(1400, 1400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
SwingUtils.run(() -> {
frame.setVisible(true);
latch.countDown();
});
Stage stage = new Stage();
stage.setTitle("Sync Results Viewer");
stage.setScene(scene);
//Closing the viewer exits the application, the same as the Swing viewer did
stage.setOnCloseRequest(event -> System.exit(0));
stage.show();
latch.countDown();
});
try

View File

@@ -19,15 +19,14 @@
package io.github.dsheirer.gui.viewer.sync;
import io.github.dsheirer.util.SwingUtils;
import java.util.concurrent.CountDownLatch;
import io.github.dsheirer.gui.FxToolkit;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;
import javafx.scene.Scene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
/**
* Utility for viewing sync detection results
@@ -77,7 +76,7 @@ public class SyncResultsViewer implements ISyncResultsListener
{
CountDownLatch latch = new CountDownLatch(1);
final JFXPanel fxPanel = new JFXPanel();
FxToolkit.ensureStarted();
Platform.runLater(() -> {
Platform.setImplicitExit(false);
SyncVisualizer syncVisualizer = new SyncVisualizer();
@@ -96,19 +95,13 @@ public class SyncResultsViewer implements ISyncResultsListener
// LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
// }
fxPanel.setScene(scene);
fxPanel.setVisible(true);
JFrame frame = new JFrame();
frame.setTitle("Sync Results Viewer");
frame.setContentPane(fxPanel);
frame.setSize(1400, 1400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
SwingUtils.run(() -> {
frame.setVisible(true);
latch.countDown();
});
Stage stage = new Stage();
stage.setTitle("Sync Results Viewer");
stage.setScene(scene);
//Closing the viewer exits the application, the same as the Swing viewer did
stage.setOnCloseRequest(event -> System.exit(0));
stage.show();
latch.countDown();
});
try

View File

@@ -32,8 +32,6 @@ import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
import java.net.URL;
import java.nio.file.Path;
import java.util.Objects;
@@ -46,7 +44,6 @@ public class Icon implements Comparable<Icon>
private StringProperty mPath = new SimpleStringProperty();
private BooleanProperty mDefaultIcon = new SimpleBooleanProperty();
private BooleanProperty mStandardIcon = new SimpleBooleanProperty();
private ImageIcon mImageIcon;
private Image mFxImage;
private boolean mFxImageLoaded = false;
@@ -168,40 +165,6 @@ public class Icon implements Comparable<Icon>
mPath.set(path);
}
@JsonIgnore
public ImageIcon getIcon()
{
if(mImageIcon == null && mPath != null)
{
try
{
if(!getPath().startsWith("images"))
{
mImageIcon = new ImageIcon(getPath());
}
else
{
URL imageURL = Icon.class.getResource(getPath());
if(imageURL == null && !getPath().startsWith("/"))
{
imageURL = (Icon.class.getResource("/" + getPath()));
}
if(imageURL != null)
{
mImageIcon = new ImageIcon(imageURL);
}
}
}
catch(Exception e)
{
mLog.error("Error loading Icon [" + getPath() + "]", e);
}
}
return mImageIcon;
}
/**
* Lazy loads an FX image for the icon and retains it in memory.

View File

@@ -24,7 +24,6 @@ import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.util.ThreadPool;
import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -32,8 +31,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.beans.property.SimpleStringProperty;
@@ -44,7 +41,6 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
public class IconModel
{
@@ -60,7 +56,6 @@ public class IconModel
private AtomicBoolean mSavingIcons = new AtomicBoolean();
private ObservableList<Icon> mIcons = FXCollections.observableArrayList(Icon.extractor());
private StringProperty mDefaultIconName = new SimpleStringProperty();
private Map<String,ImageIcon> mResizedIcons = new HashMap<>();
private Icon mDefaultIcon;
private IconSet mStandardIcons;
@@ -173,81 +168,8 @@ public class IconModel
return mDefaultIcon;
}
/**
* Returns named icon scaled to the specified height. Utilizes an internal map to retain scaled icons so that they
* are only scaled/generated once.
*
* @param name - name of icon
* @param height - height of icon in pixels
* @return - scaled named icon (if it exists) or a scaled version of the default icon
*/
public ImageIcon getIcon(String name, int height)
{
if(name == null)
{
name = getDefaultIcon().getName();
}
String scaledIconName = name + height;
ImageIcon mapValue = mResizedIcons.get(scaledIconName);
if (mapValue != null)
{
return mapValue;
}
Icon icon = getIcon(name);
ImageIcon scaledIcon = getScaledIcon(icon.getIcon(), height);
if(scaledIcon != null)
{
mResizedIcons.put(scaledIconName, scaledIcon);
}
return scaledIcon;
}
/**
* Scales the icon to the new pixel height value
*
* @param original image icon
* @param height new height to scale the image (width will be scaled accordingly)
* @return
*/
public static ImageIcon getScaledIcon(ImageIcon original, int height)
{
if(original != null)
{
double scale = (double) original.getIconHeight() / (double) height;
int scaledWidth = (int) ((double) original.getIconWidth() / scale);
Image scaledImage = original.getImage().getScaledInstance(scaledWidth,
height, java.awt.Image.SCALE_SMOOTH);
return new ImageIcon(scaledImage);
}
return null;
}
/**
* Constructs an icon and scales it to the specified height
* @param path
* @param height
* @return
*/
public static ImageIcon getScaledIcon(String path, int height)
{
if(path != null)
{
Icon icon = new Icon("", path);
return getScaledIcon(icon.getIcon(), height);
}
return null;
}
/**
* Folder where icon, backup and lock files are stored

View File

@@ -22,20 +22,12 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.settings.Setting;
import io.github.dsheirer.settings.SettingType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
import java.awt.Image;
import java.net.URL;
public class MapIcon extends Setting implements Comparable<MapIcon>
{
private final static Logger mLog = LoggerFactory.getLogger(MapIcon.class);
private static final int sMAX_IMAGE_DIMENSION = 48;
private String mPath;
private ImageIcon mImageIcon;
@JacksonXmlProperty(isAttribute = true, localName = "type", namespace = "http://www.w3.org/2001/XMLSchema-instance")
@Override
@@ -103,65 +95,6 @@ public class MapIcon extends Setting implements Comparable<MapIcon>
mDefaultIcon = isDefault;
}
@JsonIgnore
public ImageIcon getImageIcon()
{
if(mImageIcon == null && mPath != null)
{
try
{
URL imageURL = Icon.class.getResource(mPath);
if(imageURL == null && !mPath.startsWith("/"))
{
imageURL = (Icon.class.getResource("/" + mPath));
}
if(imageURL != null)
{
mImageIcon = new ImageIcon(imageURL);
/**
* If the image is too big, scale it down to max pixel size squared
*/
if(mImageIcon.getIconWidth() > sMAX_IMAGE_DIMENSION ||
mImageIcon.getIconHeight() > sMAX_IMAGE_DIMENSION)
{
/**
* getScaled instance will correct any negative value to the
* correct value, maintaining original aspect ratio. So, we
* only scale the larger value, and allow the image class to
* determine the correct value for the other measurement
*/
int height = -1;
int width = -1;
/**
* Use the larger width or height value to determine the
* scaling factor
*/
if(mImageIcon.getIconHeight() > mImageIcon.getIconWidth())
{
height = sMAX_IMAGE_DIMENSION;
}
else
{
width = sMAX_IMAGE_DIMENSION;
}
mImageIcon = new ImageIcon(mImageIcon.getImage()
.getScaledInstance(width, height, Image.SCALE_SMOOTH));
}
}
}
catch(Exception e)
{
mLog.error("Error loading Icon [" + mPath + "]", e);
}
}
return mImageIcon;
}
@JacksonXmlProperty(isAttribute = true, localName = "path")
public String getPath()

View File

@@ -1,71 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.module.decode.event;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActivitySummaryFrame extends JFrame
{
private static final long serialVersionUID = 1L;
public ActivitySummaryFrame( String summary )
{
this( summary, null );
}
public ActivitySummaryFrame( String summary, Component displayOver )
{
setTitle( "Activity Summary" );
setLocationRelativeTo( displayOver );
setSize( 400, 400 );
setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
setLayout( new MigLayout( "", "[grow,fill]", "[grow,fill][]" ) );
JTextArea summaryText = new JTextArea( summary );
JScrollPane scroller = new JScrollPane( summaryText );
scroller.setViewportView( summaryText );
add( scroller, "wrap" );
JButton close = new JButton( "Close" );
close.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
dispose();
}
} );
add( close );
EventQueue.invokeLater( new Runnable()
{
public void run()
{
setVisible( true );
}
} );
}
}

View File

@@ -1,111 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.module.decode.event.filter;
import com.jidesoft.swing.JideSplitButton;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
public class EventClearButton extends JideSplitButton
{
private static final long serialVersionUID = 1L;
private EventClearHandler mEventClearHandler;
public EventClearButton(int maxHistoryCount)
{
super("Clear");
JPanel historyPanel = new JPanel();
historyPanel.add(new JLabel("History Size:"));
final JSlider historySlider = initializeHistorySlider();
JLabel valueLabel = new JLabel(String.valueOf(maxHistoryCount));
historySlider.setValue(maxHistoryCount);
historySlider.addChangeListener(arg0 -> {
if (mEventClearHandler != null)
{
mEventClearHandler.onHistoryLimitChanged(historySlider.getValue());
}
valueLabel.setText(String.valueOf(historySlider.getValue()));
});
historyPanel.add(historySlider);
historyPanel.add(valueLabel);
add(historyPanel);
/* This handles the click action on the main button. Clear messages */
addActionListener(e -> {
if (mEventClearHandler != null)
{
mEventClearHandler.onClearHistoryClicked();
}
});
}
public void setEventClearHandler(EventClearHandler eventClearHandler) {
this.mEventClearHandler = eventClearHandler;
}
private JSlider initializeHistorySlider()
{
final JSlider slider = new JSlider();
slider.setMinimum(0);
slider.setMaximum(2000);
slider.setMajorTickSpacing(500);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addMouseListener(new MouseListener()
{
@Override
public void mouseClicked(MouseEvent arg0)
{
if(SwingUtilities.isLeftMouseButton(arg0) && arg0.getClickCount() == 2)
{
slider.setValue(500); //default
}
}
public void mouseEntered(MouseEvent arg0)
{
}
public void mouseExited(MouseEvent arg0)
{
}
public void mousePressed(MouseEvent arg0)
{
}
public void mouseReleased(MouseEvent arg0)
{
}
});
return slider;
}
}

View File

@@ -1,103 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.module.decode.event.filter;
import com.jidesoft.swing.JideButton;
import io.github.dsheirer.filter.FilterEditorPanel;
import io.github.dsheirer.filter.FilterSet;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
/**
* Event filter button that includes split button functionality to allow user to select filter items.
*
* @param <T> type of filter.
*/
public class EventFilterButton<T> extends JideButton
{
private static final long serialVersionUID = 1L;
/**
* Constructs an instance
* @param dialogTitle for the dialog/panel that appears
* @param filterSet to include in the editor panel.
*/
public EventFilterButton(String dialogTitle, FilterSet<T> filterSet)
{
this("Filter", dialogTitle, filterSet);
}
/**
* Constructs an instance
* @param buttonLabel to use on the button
* @param dialogTitle for the dialog/panel that appears
* @param filterSet to include in the editor panel.
*/
public EventFilterButton(String buttonLabel, String dialogTitle, FilterSet<T> filterSet)
{
super(buttonLabel);
addActionListener(new EventFilterActionHandler(dialogTitle, filterSet));
}
/**
* Action handler for the button
*/
public class EventFilterActionHandler implements ActionListener
{
private String mTitle;
private FilterSet<T> mFilterSet;
/**
* Constructs an instance
* @param title for this panel
* @param filterSet to edit
*/
public EventFilterActionHandler(String title, FilterSet<T> filterSet)
{
mTitle = title;
mFilterSet = filterSet;
}
@Override
public void actionPerformed(ActionEvent e)
{
final JFrame editor = new JFrame();
editor.setTitle(mTitle);
editor.setLocationRelativeTo(EventFilterButton.this);
editor.setSize(600, 400);
editor.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
editor.setLayout(new MigLayout("", "[grow,fill]", "[grow,fill][][]"));
FilterEditorPanel<T> panel = new FilterEditorPanel<T>(mFilterSet);
JScrollPane scroller = new JScrollPane(panel);
scroller.setViewportView(panel);
editor.add(scroller, "wrap");
JButton close = new JButton("Close");
close.addActionListener(e1 -> editor.dispose());
editor.add(close);
EventQueue.invokeLater(() -> editor.setVisible(true));
}
}
}

View File

@@ -39,11 +39,12 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JOptionPane;
/**
* Utility class for monitoring system components and producing logging reports.
@@ -155,7 +156,12 @@ public class DiagnosticMonitor
"The application may degrade over time and eventually run out of memory.\n" +
"A diagnostic report was generated. Please open an issue on the GitHub\n" +
"website and attach this diagnostic report:\n\n" + reportPath.toString();
JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.ERROR, message);
alert.setTitle(title);
alert.setHeaderText("Thread deadlock detected");
alert.show();
});
}
}
}

View File

@@ -200,7 +200,8 @@ public class UserPreferences implements Listener<PreferenceType>
/**
* Swing window location/size user preferences
* Window locations and table column widths stored by the earlier Swing version of the application. Used only to
* migrate those settings to the JavaFX windows and tables.
*/
public SwingPreference getSwingPreference()
{

View File

@@ -61,6 +61,27 @@ public class JavaFxPreferences
mStageMonitors.add(new StageMonitor(stage, key));
}
/**
* Indicates if a size and location is stored for the stage key.
*/
public boolean hasStoredLocation(String key)
{
return mPreferences.get(PREFERENCE_STAGE_WIDTH_PREFIX + key, null) != null;
}
/**
* Stores a size and location for the stage key, for example to migrate a window's location from an older
* preference. Call before {@link #monitor(Stage, String)}.
*/
public void storeLocation(String key, double x, double y, double width, double height, boolean maximized)
{
mPreferences.putDouble(PREFERENCE_STAGE_X_PREFIX + key, x);
mPreferences.putDouble(PREFERENCE_STAGE_Y_PREFIX + key, y);
mPreferences.putDouble(PREFERENCE_STAGE_WIDTH_PREFIX + key, width);
mPreferences.putDouble(PREFERENCE_STAGE_HEIGHT_PREFIX + key, height);
mPreferences.putBoolean(PREFERENCE_STAGE_MAXIMIZED + key, maximized);
}
/**
* Removes monitoring for the specified stage
*/
@@ -116,10 +137,10 @@ public class JavaFxPreferences
//Position the stage before we add the coordinate monitoring
reposition(stage);
mX = new NumberMonitor(PREFERENCE_STAGE_X_PREFIX + key);
mY = new NumberMonitor(PREFERENCE_STAGE_Y_PREFIX + key);
mHeight = new NumberMonitor(PREFERENCE_STAGE_HEIGHT_PREFIX + key);
mWidth = new NumberMonitor(PREFERENCE_STAGE_WIDTH_PREFIX + key);
mX = new NumberMonitor(PREFERENCE_STAGE_X_PREFIX + key, stage);
mY = new NumberMonitor(PREFERENCE_STAGE_Y_PREFIX + key, stage);
mHeight = new NumberMonitor(PREFERENCE_STAGE_HEIGHT_PREFIX + key, stage);
mWidth = new NumberMonitor(PREFERENCE_STAGE_WIDTH_PREFIX + key, stage);
mMaximized = new BooleanMonitor(PREFERENCE_STAGE_MAXIMIZED + key);
mStage.xProperty().addListener(mX);
@@ -151,7 +172,7 @@ public class JavaFxPreferences
double y = mPreferences.getDouble(PREFERENCE_STAGE_Y_PREFIX + mKey, stage.getY());
double height = mPreferences.getDouble(PREFERENCE_STAGE_HEIGHT_PREFIX + mKey, stage.getHeight());
double width = mPreferences.getDouble(PREFERENCE_STAGE_WIDTH_PREFIX + mKey, stage.getWidth());
boolean maximized = mPreferences.getBoolean(PREFERENCE_STAGE_MAXIMIZED, stage.isMaximized());
boolean maximized = mPreferences.getBoolean(PREFERENCE_STAGE_MAXIMIZED + mKey, stage.isMaximized());
//If there is a screen (ie monitor) available to display the stage at these coordinates, then move the
// stage, otherwise let the stage display in the default coordinates
@@ -174,16 +195,24 @@ public class JavaFxPreferences
public class NumberMonitor implements ChangeListener<Number>
{
private String mKey;
private Stage mStage;
public NumberMonitor(String key)
/**
* Constructs an instance
* @param key for the stored value
* @param stage that is monitored. Values aren't stored while the stage is maximized, so that the stage
* returns to its normal size and location when the user restores it.
*/
public NumberMonitor(String key, Stage stage)
{
mKey = key;
mStage = stage;
}
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue)
{
if(newValue != null)
if(newValue != null && (mStage == null || !mStage.isMaximized()))
{
mPreferences.putDouble(mKey, newValue.doubleValue());
}

View File

@@ -1,160 +0,0 @@
/*
* ******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2019 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* *****************************************************************************
*/
package io.github.dsheirer.preference.swing;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.util.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.EventQueue;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumnModel;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Monitors a JTable column model and persists column width changes to the user preferences. Restores
* previous column width preferred sizes on application restart.
*/
public class JTableColumnWidthMonitor
{
private static final Logger mLog = LoggerFactory.getLogger(JTableColumnWidthMonitor.class);
private UserPreferences mUserPreferences;
private JTable mTable;
private String mKey;
private ColumnResizeListener mColumnResizeListener = new ColumnResizeListener();
private AtomicBoolean mSaveInProgress = new AtomicBoolean();
/**
* Constructs a column width monitor.
*
* @param userPreferences to store column widths
* @param table to monitor for column width changes
* @param key that uniquely identifies the table to monitor
*/
public JTableColumnWidthMonitor(UserPreferences userPreferences, JTable table, String key)
{
mUserPreferences = userPreferences;
mTable = table;
mKey = key;
mTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
// Wait until the UI is realized to set preferred column widths
EventQueue.invokeLater(this::restoreColumnWidths);
// Keep listening for drag-resizes so you can re-save new widths
mTable.getColumnModel().addColumnModelListener(mColumnResizeListener);
}
/**
* Prepares this monitor for disposal by unregistering as a listener to the table column model.
*/
public void dispose()
{
if(mTable != null && mColumnResizeListener != null)
{
mTable.getColumnModel().removeColumnModelListener(mColumnResizeListener);
}
mTable = null;
mUserPreferences = null;
}
/**
* Sets the preferred column widths on the table from persisted settings
*/
private void restoreColumnWidths()
{
TableColumnModel model = mTable.getColumnModel();
for(int x = 0; x < model.getColumnCount(); x++)
{
int width = mUserPreferences.getSwingPreference().getInt(getColumnKey(x), Integer.MAX_VALUE);
if(width != Integer.MAX_VALUE)
{
model.getColumn(x).setPreferredWidth(width);
}
}
}
/**
* Stores the current column widths to the user preferences
*/
private void storeColumnWidths()
{
TableColumnModel model = mTable.getColumnModel();
for(int x = 0; x < model.getColumnCount(); x++)
{
mUserPreferences.getSwingPreference().setInt(getColumnKey(x), model.getColumn(x).getWidth());
}
}
/**
* Constructs a preference key for the column number
*/
private String getColumnKey(int column)
{
return mKey + ".column." + column;
}
/**
* Table column model listener.
*/
class ColumnResizeListener implements TableColumnModelListener
{
@Override
public void columnMarginChanged(ChangeEvent e)
{
if(mSaveInProgress.compareAndSet(false, true))
{
ThreadPool.SCHEDULED.schedule(new ColumnWidthSaveTask(), 2, TimeUnit.SECONDS);
}
}
@Override
public void columnAdded(TableColumnModelEvent e){}
@Override
public void columnRemoved(TableColumnModelEvent e){}
@Override
public void columnMoved(TableColumnModelEvent e){}
@Override
public void columnSelectionChanged(ListSelectionEvent e){}
}
public class ColumnWidthSaveTask implements Runnable
{
@Override
public void run()
{
storeColumnWidths();
mSaveInProgress.set(false);
}
}
}

View File

@@ -1,69 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.settings;
import io.github.dsheirer.settings.ColorSetting.ColorSettingName;
import io.github.dsheirer.util.ColorIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* JMenuItem for selecting a color and automatically setting (saving) the
* color selection in the settings manager
*/
public class ColorSettingMenuItem extends JMenuItem
{
private static final long serialVersionUID = 1L;
private ColorSettingName mColorSettingName;
private SettingsManager mSettingsManager;
private Color mCurrentColor;
public ColorSettingMenuItem( SettingsManager settingsManager,
ColorSettingName colorSettingName )
{
super( colorSettingName.getLabel() );
mSettingsManager = settingsManager;
mColorSettingName = colorSettingName;
mCurrentColor = mSettingsManager
.getColorSetting( mColorSettingName ).getColor();
this.setIcon( new ColorIcon( mCurrentColor ) );
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
Color newColor = JColorChooser.showDialog( ColorSettingMenuItem.this,
mColorSettingName.getDialogTitle(),
mCurrentColor );
if( newColor != null )
{
mSettingsManager.setColorSetting( mColorSettingName, newColor );
}
}
} );
}
}

View File

@@ -1,52 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.settings;
import io.github.dsheirer.settings.ColorSetting.ColorSettingName;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* JMenuItem for selecting a color and automatically setting (saving) the
* color selection in the settings manager
*/
public class ColorSettingResetAllMenuItem extends JMenuItem
{
private static final long serialVersionUID = 1L;
private SettingsManager mSettingsManager;
public ColorSettingResetAllMenuItem( SettingsManager settingsManager,
ColorSettingName colorSettingName )
{
super( "Reset - " + colorSettingName.getLabel() );
mSettingsManager = settingsManager;
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mSettingsManager.resetAllColorSettings();
}
} );
}
}

View File

@@ -1,52 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.settings;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* JMenuItem for selecting a color and automatically setting (saving) the
* color selection in the settings manager
*/
public class ColorSettingResetMenuItem extends JMenuItem
{
private static final long serialVersionUID = 1L;
private ColorSetting.ColorSettingName mColorSettingName;
private SettingsManager mSettingsManager;
public ColorSettingResetMenuItem( SettingsManager settingsManager,
ColorSetting.ColorSettingName colorSettingName )
{
super( "Reset - " + colorSettingName.getLabel() );
mSettingsManager = settingsManager;
mColorSettingName = colorSettingName;
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mSettingsManager.resetColorSetting( mColorSettingName );
}
} );
}
}

View File

@@ -24,10 +24,9 @@ import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.gui.spectrum.SpectralDisplayPanel;
import io.github.dsheirer.gui.spectrum.MainSpectralDisplay;
import io.github.dsheirer.gui.spectrum.SpectralDisplayWindow;
import io.github.dsheirer.gui.spectrum.TunerSpectralDisplay;
import io.github.dsheirer.util.SwingUtils;
import io.github.dsheirer.util.ThreadPool;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -41,7 +40,7 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
{
private Logger mLog = LoggerFactory.getLogger(TunerSpectralDisplayManager.class);
private SpectralDisplayPanel mSpectralDisplayPanel;
private MainSpectralDisplay mMainSpectralDisplay;
private PlaylistManager mPlaylistManager;
private DiscoveredTunerModel mDiscoveredTunerModel;
@@ -51,10 +50,10 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
* @param playlistManager for channel updates
* @param discoveredTunerModel to access tuners
*/
public TunerSpectralDisplayManager(SpectralDisplayPanel panel, PlaylistManager playlistManager,
public TunerSpectralDisplayManager(MainSpectralDisplay panel, PlaylistManager playlistManager,
DiscoveredTunerModel discoveredTunerModel)
{
mSpectralDisplayPanel = panel;
mMainSpectralDisplay = panel;
mPlaylistManager = playlistManager;
mDiscoveredTunerModel = discoveredTunerModel;
}
@@ -65,7 +64,7 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
public Tuner showFirstTuner()
{
//Ensure spectral display is enabled before selecting first tuner
if(mSpectralDisplayPanel != null &&
if(mMainSpectralDisplay != null &&
SystemProperties.getInstance().get(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true))
{
List<DiscoveredTuner> availableTuners = mDiscoveredTunerModel.getAvailableTuners();
@@ -74,7 +73,7 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
{
if(discoveredTuner.hasTuner())
{
mSpectralDisplayPanel.showTuner(discoveredTuner.getTuner());
mMainSpectralDisplay.showTuner(discoveredTuner.getTuner());
return discoveredTuner.getTuner();
}
}
@@ -86,7 +85,7 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
@Override
public void receive(TunerEvent event)
{
if(mSpectralDisplayPanel == null)
if(mMainSpectralDisplay == null)
{
return;
}
@@ -94,12 +93,12 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
switch(event.getEvent())
{
case REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY:
SwingUtils.run(() -> mSpectralDisplayPanel.clearTuner());
mMainSpectralDisplay.clearTuner();
break;
case REQUEST_MAIN_SPECTRAL_DISPLAY:
if(SystemProperties.getInstance().get(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true))
{
SwingUtils.run(() -> mSpectralDisplayPanel.showTuner(event.getTuner()));
mMainSpectralDisplay.showTuner(event.getTuner());
}
break;
case REQUEST_NEW_SPECTRAL_DISPLAY:
@@ -107,17 +106,12 @@ public class TunerSpectralDisplayManager implements Listener<TunerEvent>
break;
case NOTIFICATION_ERROR_STATE:
case NOTIFICATION_SHUTTING_DOWN:
if(event.getTuner().equals(mSpectralDisplayPanel.getTuner()))
if(event.getTuner().equals(mMainSpectralDisplay.getTuner()))
{
SwingUtils.run(() ->
{
mSpectralDisplayPanel.clearTuner();
ThreadPool.SCHEDULED.schedule(() -> SwingUtils.run(() ->
{
showFirstTuner();
}), 1, TimeUnit.SECONDS);
});
mMainSpectralDisplay.clearTuner();
ThreadPool.SCHEDULED.schedule(this::showFirstTuner, 1, TimeUnit.SECONDS);
}
break;
default:
break;
}

View File

@@ -1,49 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
/**
* Swing host for the JavaFX Tuners tab.
*/
public class TunerViewPanel extends JFXPanel
{
/**
* Constructs an instance
* @param tunerManager for tuners
* @param userPreferences for making recordings in the tuner editor
*/
public TunerViewPanel(TunerManager tunerManager, UserPreferences userPreferences)
{
Platform.setImplicitExit(false);
ThemeManager.getInstance().registerSwing(this);
Platform.runLater(() -> {
Scene scene = new Scene(new TunerView(tunerManager, userPreferences));
ThemeManager.getInstance().register(scene);
setScene(scene);
});
}
}

View File

@@ -1,55 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
import io.github.dsheirer.gui.spectrum.SpectralDisplayPanel;
import io.github.dsheirer.gui.spectrum.TunerSpectralDisplay;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.util.ThreadPool;
import jiconfont.icons.font_awesome.FontAwesome;
import io.github.dsheirer.gui.theme.ThemedFontIcon;
import javax.swing.JMenuItem;
/**
* Menu item to disable the spectrum and waterfall and no longer monitor a tuner.
*/
public class DisableSpectrumWaterfallMenuItem extends JMenuItem
{
private SpectralDisplayPanel mSpectralDisplayPanel;
/**
* Construct an instance
* @param spectralDisplayPanel to disable.
*/
public DisableSpectrumWaterfallMenuItem(SpectralDisplayPanel spectralDisplayPanel)
{
super("Disable Spectrum & Waterfall");
setIcon(new ThemedFontIcon(FontAwesome.EYE_SLASH, 12));
mSpectralDisplayPanel = spectralDisplayPanel;
addActionListener(e -> {
SystemProperties properties = SystemProperties.getInstance();
properties.set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, false);
ThreadPool.CACHED.submit(() -> mSpectralDisplayPanel.clearTuner());
});
}
}

View File

@@ -1,240 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.sample.OverflowableTransferQueue;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.util.Iterator;
import java.util.LinkedList;
public class OverflowableBufferStream<T extends INativeBuffer> extends OverflowableTransferQueue<T>
{
private static final Logger mLog = LoggerFactory.getLogger(OverflowableBufferStream.class);
private int mFlushCount = 0;
private Iterator<InterleavedComplexSamples> mCurrentNativeBufferIterator;
private InterleavedComplexSamples mCurrentBuffer;
private int mCurrentBufferPointer = 0;
private FloatBuffer mFloatBuffer;
private LinkedList<T> mBufferList = new LinkedList<>();
private int mBufferFetchLimit;
/**
* Stream for receiving reusable buffers from a producer thread and providing access to a consumer thread to read
* the sample data. Extends the overflowable transfer queue to define maximum and reset thresholds to ensure the
* queue doesn't grow too large.
*
* This stream is designed for consistent sample size requests each time the get() samples method is invoked, such
* as might be needed for an FFT processor. It uses an internal float buffer that must be resized whenever the
* get(sample size) argument changes, so consider using another option if you anticipate that your sample size
* argument during get() operations will vary.
*
* @param maxSize of the internal buffer queue - defines the overflow threshold
* @param resetThreshold of the internal buffer queue - defines when the overflow state will be cleared once the
* queue size has reduced below this threshold
* @param arraySize of the anticipated samples to fetch using the get(x,y) method.
*/
public OverflowableBufferStream(int maxSize, int resetThreshold, int arraySize)
{
super(maxSize, resetThreshold);
mFloatBuffer = FloatBuffer.allocate(arraySize);
mBufferFetchLimit = maxSize - resetThreshold;
}
/**
* Retrieves the specified number of float samples from the stream. When a non-zero overlap is specified, a
* quantity of samples from the previous buffer are preloaded in the buffer and new samples are added to make a
* full array count.
*
* @param sampleCount of float samples to pull from the stream
* @param overlap to reuse part of the previous buffer's samples in this fetch - must be less than sample count
* @return an array of float samples from the stream
* @throws IOException if the buffer queue is/becomes empty and the samples cannot be provided
* @throws IllegalArgumentException if the overlap argument is not less than the sample count argument
*/
public float[] get(int sampleCount, int overlap) throws IOException
{
if(overlap >= sampleCount)
{
throw new IllegalArgumentException("Overlap must be less than the requested sample count");
}
if(mCurrentBuffer == null)
{
//This will throw an IO exception if the queue is empty
getNextBuffer();
}
//Resize the float buffer if the request size changes
if(mFloatBuffer.capacity() != sampleCount)
{
mFloatBuffer = FloatBuffer.allocate(sampleCount);
}
while(mFloatBuffer.hasRemaining())
{
int available = mCurrentBuffer.samples().length - mCurrentBufferPointer;
if(available <= 0)
{
getNextBuffer();
}
else
{
//Fill the buffer to capacity
int toCopy = mFloatBuffer.remaining();
if(available < toCopy)
{
toCopy = available;
}
if(toCopy > 0)
{
mFloatBuffer.put(mCurrentBuffer.samples(), mCurrentBufferPointer, toCopy);
mCurrentBufferPointer += toCopy;
}
}
}
//If we get to here, the float buffer is full. Get the samples and then refill with overlap if non-zero
mFloatBuffer.rewind();
float[] samples = new float[sampleCount];
mFloatBuffer.get(samples);
mFloatBuffer.clear();
if(overlap > 0)
{
mFloatBuffer.put(samples, samples.length - overlap, overlap);
}
try
{
performFlush();
}
catch(IOException ioe)
{
//Do nothing if we get an IO exception ... the buffer is empty
}
//Reset flush count to zero, even if we ran out of buffers
mFlushCount = 0;
return samples;
}
/**
* Throws away incoming sample data until mFlushCount is zeroized or the queue is empty.
*
* @throws IOException if the queue is emptied while performing flush.
*/
private void performFlush() throws IOException
{
//Flush sample data as requested
while(mFlushCount > 0)
{
int available = mCurrentBuffer.samples().length - mCurrentBufferPointer;
if(available <= mFlushCount)
{
mFlushCount -= available;
getNextBuffer();
}
else
{
mCurrentBufferPointer += mFlushCount;
mFlushCount = 0;
}
}
}
/**
* Flushes the specified number of samples from the incoming stream.
* @param sampleCount to throw away
*/
public void flush(int sampleCount)
{
mFlushCount += sampleCount;
}
/**
* Fetches the next buffer from the queue.
*
* @throws IOException if the queue is currently empty
*/
private void getNextBuffer() throws IOException
{
if(mCurrentNativeBufferIterator == null)
{
if(mBufferList.isEmpty())
{
drainTo(mBufferList, mBufferFetchLimit);
}
if(!mBufferList.isEmpty())
{
T buffer = mBufferList.poll();
if(buffer != null)
{
mCurrentNativeBufferIterator = buffer.iteratorInterleaved();
}
}
}
if(mCurrentNativeBufferIterator != null && !mCurrentNativeBufferIterator.hasNext())
{
mCurrentNativeBufferIterator = null;
getNextBuffer();
return;
}
if(mCurrentNativeBufferIterator != null && mCurrentNativeBufferIterator.hasNext())
{
mCurrentBuffer = mCurrentNativeBufferIterator.next();
mCurrentBufferPointer = 0;
}
else
{
mCurrentBuffer = null;
throw new IOException("Buffer queue is empty");
}
}
/**
* Clears all elements from the queue and resets the internal counter to 0
*/
@Override
public void clear()
{
synchronized(mQueue)
{
mQueue.clear();
mCounter.set(0);
mOverflow.set(false);
}
}
}

View File

@@ -1,61 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
import io.github.dsheirer.gui.spectrum.TunerSpectralDisplay;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
import io.github.dsheirer.source.tuner.ui.DiscoveredTunerModel;
import javax.swing.JMenuItem;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ShowTunerMenuItem extends JMenuItem
{
private DiscoveredTunerModel mDiscoveredTunerModel;
private Tuner mTuner;
public ShowTunerMenuItem(DiscoveredTunerModel discoveredTunerModel, Tuner tuner)
{
super(tuner != null ? "Show: " + tuner.getPreferredName() : "(empty)");
mDiscoveredTunerModel = discoveredTunerModel;
mTuner = tuner;
addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
SystemProperties properties = SystemProperties.getInstance();
properties.set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true);
mDiscoveredTunerModel.broadcast(new TunerEvent(mTuner, TunerEvent.Event.REQUEST_MAIN_SPECTRAL_DISPLAY));
}
});
}
});
}
}

View File

@@ -1,488 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
import io.github.dsheirer.dsp.filter.smoothing.GaussianSmoothingFilter;
import io.github.dsheirer.dsp.filter.smoothing.NoSmoothingFilter;
import io.github.dsheirer.dsp.filter.smoothing.RectangularSmoothingFilter;
import io.github.dsheirer.dsp.filter.smoothing.SmoothingFilter;
import io.github.dsheirer.dsp.filter.smoothing.SmoothingFilter.SmoothingType;
import io.github.dsheirer.dsp.filter.smoothing.TriangularSmoothingFilter;
import io.github.dsheirer.settings.ColorSetting;
import io.github.dsheirer.settings.ColorSetting.ColorSettingName;
import io.github.dsheirer.settings.Setting;
import io.github.dsheirer.settings.SettingChangeListener;
import io.github.dsheirer.settings.SettingsManager;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.util.Arrays;
import org.apache.commons.lang3.Validate;
import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JPanel;
public class SpectrumPanel extends JPanel implements DFTResultsListener, SettingChangeListener, SpectralDisplayAdjuster
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(SpectrumPanel.class);
private static final RenderingHints RENDERING_HINTS =
new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
static
{
RENDERING_HINTS.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
private Color mColorSpectrumBackground;
private Color mColorSpectrumGradientTop;
private Color mColorSpectrumGradientBottom;
private Color mColorSpectrumLine;
//Defines the panel inset along the bottom for frequency display
private float mSpectrumInset = 20.0f;
//Current DFT output bins in dB
private float[] mDisplayFFTBins = new float[1];
//Averaging across multiple DFT result sets
private int mAveraging = 4;
//Smoothing across bins in the same DFT result set
private SmoothingFilter mSmoothingFilter = new NoSmoothingFilter();
//Reference dB value set according to the source sample size
private float mDBScale;
private int mZoom = 0;
private int mZoomWindowOffset = 0;
private SettingsManager mSettingsManager;
public SpectrumPanel(SettingsManager settingsManager)
{
mSettingsManager = settingsManager;
if(mSettingsManager != null)
{
mSettingsManager.addListener(this);
}
setSampleSize(16.0);
mSmoothingFilter.setPointSize(SmoothingFilter.SMOOTHING_DEFAULT);
getColors();
setAveraging(mAveraging);
}
public void dispose()
{
if(mSettingsManager != null)
{
mSettingsManager.removeListener(this);
}
mSettingsManager = null;
}
/**
* DFTResultsListener interface for receiving the processed data
* to display
*/
public void receive(float[] currentFFTBins)
{
//Prevent arrays of NaN values from being rendered. The first few
//DFT result sets on startup will contain NaN values
if(Float.isInfinite(currentFFTBins[0]) || Float.isNaN(currentFFTBins[0]))
{
currentFFTBins = new float[currentFFTBins.length];
}
//Construct and/or resize our DFT results variables
if(mDisplayFFTBins == null ||
mDisplayFFTBins.length != currentFFTBins.length)
{
mDisplayFFTBins = currentFFTBins;
}
//Apply smoothing across the bins of the DFT results
float[] smoothedBins = mSmoothingFilter.filter(currentFFTBins);
//Apply averaging over multiple DFT output frames
if(mAveraging > 1)
{
float gain = 1.0f / (float)mAveraging;
for(int x = 0; x < mDisplayFFTBins.length; x++)
{
mDisplayFFTBins[x] +=
(smoothedBins[x] - mDisplayFFTBins[x]) * gain;
}
}
else
{
mDisplayFFTBins = smoothedBins;
}
repaint();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D graphics = (Graphics2D)g;
graphics.setBackground(mColorSpectrumBackground);
graphics.setRenderingHints(RENDERING_HINTS);
drawSpectrum(graphics);
}
/**
* Draws the current fft spectrum with a line and a gradient fill.
*/
private void drawSpectrum(Graphics2D graphics)
{
Dimension size = getSize();
//Draw the background
Rectangle background = new Rectangle(0, 0, size.width, size.height);
graphics.setColor(mColorSpectrumBackground);
graphics.draw(background);
graphics.fill(background);
//Define the gradient
GradientPaint gradient = new GradientPaint(0,
(getSize().height - mSpectrumInset) / 2,
mColorSpectrumGradientTop,
0,
getSize().height,
mColorSpectrumGradientBottom);
graphics.setBackground(mColorSpectrumBackground);
GeneralPath spectrumShape = new GeneralPath();
//Start at the lower right inset point
spectrumShape.moveTo(size.getWidth(),
size.getHeight() - mSpectrumInset);
//Draw to the lower left
spectrumShape.lineTo(0, size.getHeight() - mSpectrumInset);
float[] bins = getBins();
//If we have FFT data to display ...
if(bins != null)
{
float insideHeight = size.height - mSpectrumInset;
float scalor = insideHeight / -mDBScale;
/* Calculate based on bin size - 1, since bin 0 is rendered at zero
* and the last bin is rendered at the width */
float binSize = (float)size.width / ((float)(bins.length));
for(int x = 0; x < bins.length; x++)
{
float height;
height = bins[x] * scalor;
if(height > insideHeight)
{
height = insideHeight;
}
if(height < 0)
{
height = 0;
}
float xAxis = (float)x * binSize;
spectrumShape.lineTo(xAxis, height);
}
}
//Otherwise show an empty spectrum
else
{
//Draw Left Size
graphics.setPaint(gradient);
spectrumShape.lineTo(0, size.getHeight() - mSpectrumInset);
//Draw Middle
spectrumShape.lineTo(size.getWidth(),
size.getHeight() - mSpectrumInset);
}
//Draw Right Side
spectrumShape.lineTo(size.getWidth(),
size.getHeight() - mSpectrumInset);
graphics.setPaint(gradient);
graphics.draw(spectrumShape);
graphics.fill(spectrumShape);
graphics.setPaint(mColorSpectrumLine);
//Draw the bottom line under the spectrum
graphics.draw(new Line2D.Float(0,
size.height - mSpectrumInset,
size.width,
size.height - mSpectrumInset));
}
/**
* Sets the current zoom level
*
* 0 No Zoom
* 1 2x Zoom
* 2 4x Zoom
* 3 8x Zoom
* 4 16x Zoom
* 5 32x Zoom
* 6 64x Zoom
*
* @param zoom level, 0 - 6.
*/
public void setZoom(int zoom)
{
Validate.isTrue(0 <= zoom && zoom <= 6, "Unrecognized Zoom Level: " + zoom);
mZoom = zoom;
}
/**
* Sets the offset to define which subset of zoomed bins to display
*
* @param offset
*/
public void setZoomWindowOffset(int offset)
{
mZoomWindowOffset = offset;
}
/**
* Sets the source sample size in bits which defines the lowest dB value to
* display in the spectrum
*
* @param sampleSize in bits
*/
public void setSampleSize(double sampleSize)
{
Validate.isTrue(2.0 <= sampleSize && sampleSize <= 64.0);
mDBScale = (float)(20.0 * FastMath.log10(FastMath.pow(2.0, sampleSize - 1)));
}
/**
* Defines the number of DFT result sets to average across
*/
public void setAveraging(int size)
{
mAveraging = size;
}
/**
* DFT result sets averaging value
*/
public int getAveraging()
{
return mAveraging;
}
/**
* Clears the spectral display
*/
public void clearSpectrum()
{
Arrays.fill(mDisplayFFTBins, 0.0f);
repaint();
}
private void getColors()
{
mColorSpectrumBackground =
getColor(ColorSettingName.SPECTRUM_BACKGROUND);
mColorSpectrumGradientBottom =
getColor(ColorSettingName.SPECTRUM_GRADIENT_BOTTOM);
mColorSpectrumGradientTop =
getColor(ColorSettingName.SPECTRUM_GRADIENT_TOP);
mColorSpectrumLine = getColor(ColorSettingName.SPECTRUM_LINE);
}
/**
* Retrieves the current setting for the named color setting
*/
private Color getColor(ColorSettingName name)
{
ColorSetting setting = mSettingsManager.getColorSetting(name);
return setting.getColor();
}
/**
* Listener interface to receive setting change notifications
*/
@Override
public void settingChanged(Setting setting)
{
if(setting instanceof ColorSetting)
{
ColorSetting colorSetting = (ColorSetting)setting;
switch(((ColorSetting)setting).getColorSettingName())
{
case SPECTRUM_BACKGROUND:
mColorSpectrumBackground = colorSetting.getColor();
break;
case SPECTRUM_GRADIENT_BOTTOM:
mColorSpectrumGradientBottom = colorSetting.getColor();
break;
case SPECTRUM_GRADIENT_TOP:
mColorSpectrumGradientTop = colorSetting.getColor();
break;
case SPECTRUM_LINE:
mColorSpectrumLine = colorSetting.getColor();
break;
default:
break;
}
}
}
private int getZoomMultiplier()
{
return (int) FastMath.pow(2.0, mZoom);
}
/**
* Returns the DFT result bins, or a zoomed and offset version of the bins
* when the display is zoomed.
*/
private float[] getBins()
{
if(mZoom == 0)
{
return mDisplayFFTBins;
}
else
{
int length = mDisplayFFTBins.length / getZoomMultiplier();
int offset = mZoomWindowOffset;
if((offset + length) >= mDisplayFFTBins.length)
{
offset = mDisplayFFTBins.length - length;
}
if(offset < 0)
{
offset = 0;
}
return Arrays.copyOfRange(mDisplayFFTBins, offset, offset + length);
}
}
@Override
public void settingDeleted(Setting setting)
{ /* not implemented */ }
/**
* Returns the current inter-bin smoothing setting
*/
@Override
public int getSmoothing()
{
return mSmoothingFilter.getPointSize();
}
/**
* Sets the bin smoothing value to define how wide the smoothing window is
* when averaging across DFT bins
*/
@Override
public void setSmoothing(int smoothing)
{
mSmoothingFilter.setPointSize(smoothing);
}
/**
* Returns the current smoothing filter type
*/
@Override
public SmoothingType getSmoothingType()
{
return mSmoothingFilter.getSmoothingType();
}
/**
* Sets the smoothing filter type
*/
@Override
public void setSmoothingType(SmoothingType type)
{
if(mSmoothingFilter.getSmoothingType() != type)
{
int pointSize = getSmoothing();
synchronized(mSmoothingFilter)
{
switch(type)
{
case GAUSSIAN:
mSmoothingFilter = new GaussianSmoothingFilter();
break;
case RECTANGLE:
mSmoothingFilter = new RectangularSmoothingFilter();
break;
case TRIANGLE:
mSmoothingFilter = new TriangularSmoothingFilter();
break;
case NONE:
default:
mSmoothingFilter = new NoSmoothingFilter();
break;
}
}
setSmoothing(pointSize);
}
}
}

View File

@@ -1,42 +0,0 @@
package io.github.dsheirer.spectrum.converter;
import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RealDecibelConverter extends DFTResultsConverter
{
private static final Logger mLog = LoggerFactory.getLogger( RealDecibelConverter.class );
public RealDecibelConverter()
{
}
/**
* Converts the output of the JTransforms FloatFFT_1D.realForward()
* calculation into a normalized power spectrum in decibels, per description
* in Lyons, Understanding Digital Signal Processing, 3e, page 141.
*
* Note: this is only calculating the lower half of the spectrum
*/
@Override
public void receive( float[] results )
{
float dftBinSizeScalor = 1.0f / (float)results.length;
float[] processed = new float[ results.length / 4 ];
int index = 0;
for( int x = 0; x < processed.length; x ++ )
{
index = x * 2;
processed[ x ] = 20.0f * (float) FastMath.log10(
( ( results[ index ] * results[ index ] ) +
( results[ index + 1 ] * results[ index + 1 ] ) ) * dftBinSizeScalor );
}
dispatch( processed );
}
}

View File

@@ -1,57 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.util;
import javax.swing.*;
import java.awt.*;
public class ColorIcon implements Icon
{
private static final int sSIZE = 12;
private static final int sARC_SIZE = 3;
private Color mColor;
public ColorIcon( Color color )
{
mColor = color;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
Color temp = g.getColor();
g.setColor( mColor );
g.fillRoundRect( x, y, sSIZE, sSIZE, sARC_SIZE, sARC_SIZE );
g.setColor( temp );
}
@Override
public int getIconWidth()
{
return sSIZE;
}
@Override
public int getIconHeight()
{
return sSIZE;
}
}

View File

@@ -0,0 +1,359 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
/* Audio playback display. It is styled as an instrument display, dark in every application theme, so that the
call that is playing stands out from the rest of the application. -audio-accent is set per channel from the
alias color. The dark theme fills each label's .text node directly, so label colors are set on both the label
and its .text node, as in ChannelMenus. */
.audio-view
{
-audio-display: #0d1117;
-audio-panel: #161b22;
-audio-panel-active: #1b2430;
-audio-border: #2a313c;
-audio-text: #e6edf3;
-audio-text-secondary: #9aa6b4;
-audio-text-dim: #5f6b78;
-audio-live: #3ddc84;
-audio-muted: #ff5c5c;
-audio-accent: #3ddc84;
-fx-background-color: -audio-display;
-fx-padding: 8 10 8 10;
-fx-border-color: transparent transparent -audio-border transparent;
-fx-border-width: 0 0 1 0;
}
/* Master section */
.audio-view .audio-master
{
-fx-padding: 2 8 2 2;
-fx-alignment: top-left;
}
.audio-view .audio-master-title
{
-fx-text-fill: -audio-text-secondary;
-fx-font-size: 0.85em;
-fx-font-weight: bold;
}
.audio-view .audio-master-title .text
{
-fx-fill: -audio-text-secondary;
}
.audio-view .audio-device
{
-fx-text-fill: -audio-text-dim;
-fx-font-size: 0.85em;
}
.audio-view .audio-device .text
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-icon-button
{
-fx-background-color: -audio-panel;
-fx-background-radius: 6;
-fx-border-color: -audio-border;
-fx-border-radius: 6;
-fx-padding: 5 8 5 8;
-fx-cursor: hand;
}
.audio-view .audio-icon-button:hover
{
-fx-background-color: -audio-panel-active;
-fx-border-color: -audio-text-dim;
}
.audio-view .audio-icon-button:focus-visible
{
-fx-border-color: -audio-live;
}
.audio-view .audio-icon-button .audio-button-icon
{
-fx-fill: -audio-text;
}
.audio-view .audio-icon-button:selected
{
-fx-background-color: derive(-audio-muted, -60%);
-fx-border-color: -audio-muted;
}
.audio-view .audio-icon-button:selected .audio-button-icon
{
-fx-fill: -audio-muted;
}
.audio-view .audio-master-mute
{
-fx-padding: 6 12 6 12;
-fx-min-width: 48;
}
.audio-view .audio-volume .track
{
-fx-background-color: -audio-border;
-fx-background-radius: 3;
-fx-pref-height: 4;
}
.audio-view .audio-volume .thumb
{
-fx-background-color: -audio-text;
-fx-background-radius: 7;
-fx-padding: 6;
}
.audio-view .audio-volume:focus-visible .thumb
{
-fx-background-color: -audio-live;
}
/* Channel display */
.audio-view .audio-channel
{
-fx-background-color: -audio-panel;
-fx-background-radius: 8;
-fx-border-color: -audio-border;
-fx-border-radius: 8;
-fx-border-width: 1;
-fx-spacing: 10;
-fx-padding: 0 12 8 0;
}
.audio-view .audio-channel:active
{
-fx-background-color: -audio-panel-active;
-fx-border-color: -audio-accent;
}
.audio-view .audio-accent
{
-fx-background-color: transparent;
-fx-background-radius: 8 0 0 8;
}
.audio-view .audio-channel:active .audio-accent
{
-fx-background-color: -audio-accent;
}
.audio-view .audio-channel-content
{
-fx-padding: 6 0 0 0;
}
.audio-view .audio-icon-pane
{
-fx-background-color: -audio-display;
-fx-background-radius: 26;
-fx-border-color: -audio-border;
-fx-border-radius: 26;
}
.audio-view .audio-channel:active .audio-icon-pane
{
-fx-border-color: -audio-accent;
-fx-border-width: 2;
}
.audio-view .audio-placeholder-icon
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-channel:active .audio-placeholder-icon
{
-fx-fill: -audio-accent;
}
.audio-view .audio-channel-tag
{
-fx-text-fill: -audio-text-secondary;
-fx-background-color: -audio-display;
-fx-background-radius: 4;
-fx-padding: 1 6 1 6;
-fx-font-size: 0.8em;
-fx-font-weight: bold;
}
.audio-view .audio-channel-tag .text
{
-fx-fill: -audio-text-secondary;
}
.audio-view .audio-status
{
-fx-text-fill: -audio-text-dim;
-fx-font-size: 0.8em;
-fx-font-weight: bold;
}
.audio-view .audio-status .text
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-channel:active .audio-status
{
-fx-text-fill: -audio-live;
}
.audio-view .audio-channel:active .audio-status .text
{
-fx-fill: -audio-live;
}
.audio-view .audio-channel:muted .audio-status
{
-fx-text-fill: -audio-muted;
}
.audio-view .audio-channel:muted .audio-status .text
{
-fx-fill: -audio-muted;
}
.audio-view .audio-elapsed
{
-fx-text-fill: -audio-text-secondary;
-fx-font-family: monospace;
-fx-font-size: 1.05em;
}
.audio-view .audio-elapsed .text
{
-fx-fill: -audio-text-secondary;
}
.audio-view .audio-channel:active .audio-elapsed
{
-fx-text-fill: -audio-text;
}
.audio-view .audio-channel:active .audio-elapsed .text
{
-fx-fill: -audio-text;
}
.audio-view .audio-channel .audio-icon-button
{
-fx-padding: 3 7 3 7;
}
.audio-view .audio-to
{
-fx-text-fill: -audio-text-dim;
-fx-font-size: 1.9em;
-fx-font-weight: bold;
}
.audio-view .audio-to .text
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-channel:active .audio-to
{
-fx-text-fill: -audio-text;
}
.audio-view .audio-channel:active .audio-to .text
{
-fx-fill: -audio-text;
}
.audio-view .audio-to-detail
{
-fx-text-fill: -audio-text-dim;
-fx-font-family: monospace;
-fx-font-size: 1.05em;
}
.audio-view .audio-to-detail .text
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-channel:active .audio-to-detail
{
-fx-text-fill: -audio-accent;
}
.audio-view .audio-channel:active .audio-to-detail .text
{
-fx-fill: -audio-accent;
}
.audio-view .audio-detail
{
-fx-text-fill: -audio-text-dim;
-fx-font-size: 1.05em;
}
.audio-view .audio-detail .text
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-channel:active .audio-detail
{
-fx-text-fill: -audio-text-secondary;
}
.audio-view .audio-channel:active .audio-detail .text
{
-fx-fill: -audio-text-secondary;
}
.audio-view .audio-detail-icon
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-context
{
-fx-text-fill: -audio-text-dim;
-fx-font-size: 0.9em;
}
.audio-view .audio-context .text
{
-fx-fill: -audio-text-dim;
}
.audio-view .audio-channel:active .audio-context
{
-fx-text-fill: -audio-text-secondary;
}
.audio-view .audio-channel:active .audio-context .text
{
-fx-fill: -audio-text-secondary;
}

View File

@@ -0,0 +1,112 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
/* Streaming status panel. Colors follow the theme's looked-up colors except for the status chips, which use solid
colors with matching text so that they read the same in every theme. The dark theme fills each label's .text
node directly, so chip text colors are set on the .text node as well (see audio_panel.css). */
.broadcast-status-view
{
-fx-background-color: -fx-background;
}
.broadcast-status-view .broadcast-toolbar
{
-fx-padding: 4 8 4 8;
}
.broadcast-status-view .broadcast-title
{
-fx-font-weight: bold;
-fx-graphic-text-gap: 6;
}
.broadcast-status-view .broadcast-title-icon
{
-fx-fill: -fx-accent;
}
.broadcast-status-view .broadcast-summary
{
-fx-opacity: 0.75;
}
.broadcast-status-view .broadcast-placeholder
{
-fx-opacity: 0.7;
}
.broadcast-status-view .broadcast-count
{
-fx-font-family: monospace;
}
.broadcast-status-view .broadcast-status-chip
{
-fx-background-radius: 9;
-fx-padding: 1 9 1 9;
-fx-font-weight: bold;
-fx-font-size: 0.92em;
}
.broadcast-status-view .broadcast-status-severity-ok
{
-fx-background-color: #2e9e5b;
-fx-text-fill: #ffffff;
}
.broadcast-status-view .broadcast-status-severity-ok .text
{
-fx-fill: #ffffff;
}
.broadcast-status-view .broadcast-status-severity-warning
{
-fx-background-color: #e0a91f;
-fx-text-fill: #1d1d1d;
}
.broadcast-status-view .broadcast-status-severity-warning .text
{
-fx-fill: #1d1d1d;
}
.broadcast-status-view .broadcast-status-severity-error
{
-fx-background-color: #d64545;
-fx-text-fill: #ffffff;
}
.broadcast-status-view .broadcast-status-severity-error .text
{
-fx-fill: #ffffff;
}
.broadcast-status-view .broadcast-status-severity-neutral
{
-fx-background-color: transparent;
-fx-border-color: derive(-fx-text-base-color, -30%);
-fx-border-radius: 9;
}
.broadcast-status-view .broadcast-status-severity-disabled
{
-fx-background-color: transparent;
-fx-opacity: 0.6;
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,33 +17,31 @@
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
/* Main window. Colors are derived from the theme's looked-up colors so they follow every application theme. */
import io.github.dsheirer.dsp.filter.smoothing.SmoothingFilter.SmoothingType;
public interface SpectralDisplayAdjuster
.main-window
{
/**
* Gets the averaging value indicating the number of FFT results that are
* averaged to produce each FFT results output.
*
* @return averaging value ( 2 - 50 )
*/
public int getAveraging();
public void setAveraging( int averaging );
/**
* Sets the smoothing filter averaging window width.
*
* Valid values are odd in the range 3 - 29
*/
public int getSmoothing();
public void setSmoothing( int smoothing );
/**
* Sets the type of smoothing filter to use.
*/
public SmoothingType getSmoothingType();
public void setSmoothingType( SmoothingType type );
-fx-background-color: -fx-background;
}
.main-window .main-hidden-bar
{
-fx-padding: 4 8 4 10;
-fx-background-color: derive(-fx-background, -6%);
-fx-border-color: transparent transparent derive(-fx-background, -25%) transparent;
}
.main-window .main-hidden-bar-icon
{
-fx-fill: -fx-accent;
}
.main-window .main-hidden-bar-label
{
-fx-opacity: 0.8;
}
.main-window .main-playlist-tab-icon
{
-fx-fill: -fx-accent;
}

View File

@@ -468,3 +468,9 @@
{
-fx-background-color: #ffffff;
}
/* Main window menu icons (jiconfont IconNode text glyphs default to black) */
.main-menu-icon
{
-fx-fill: #ececec;
}

View File

@@ -0,0 +1,87 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.playback;
import io.github.dsheirer.preference.UserPreferences;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Peak level measurement used by the audio level meters.
*/
public class AudioChannelPeakLevelTest
{
private AudioChannel mChannel;
@BeforeEach
public void setup()
{
mChannel = new AudioChannel(new UserPreferences(), "TEST");
}
private static float[] interval(float... values)
{
float[] samples = new float[AudioChannel.SAMPLES_PER_INTERVAL];
System.arraycopy(values, 0, samples, 0, values.length);
return samples;
}
@Test
public void peakIsMaximumMagnitudeAndResets()
{
mChannel.playTest(interval(0.25f, -0.5f, 0.1f));
assertNotNull(mChannel.getAudio());
assertEquals(0.5f, mChannel.getAndResetPeakLevel(), 1e-6f);
assertEquals(0.0f, mChannel.getAndResetPeakLevel(), 0.0f, "peak resets after it is read");
}
@Test
public void peakAccumulatesAcrossIntervalsUntilRead()
{
mChannel.playTest(interval(0.3f));
mChannel.getAudio();
mChannel.playTest(interval(-0.7f));
mChannel.getAudio();
mChannel.playTest(interval(0.2f));
mChannel.getAudio();
assertEquals(0.7f, mChannel.getAndResetPeakLevel(), 1e-6f);
}
@Test
public void mutedChannelPlaysSilenceButMeasuresAudio()
{
mChannel.setMuted(true);
mChannel.playTest(interval(0.6f, -0.4f));
float[] audio = mChannel.getAudio();
assertArrayEquals(new float[AudioChannel.SAMPLES_PER_INTERVAL], audio, "muted channel plays silence");
assertEquals(0.6f, mChannel.getAndResetPeakLevel(), 1e-6f, "level is measured before muting");
}
@Test
public void noAudioLeavesPeakAtZero()
{
mChannel.getAudio();
assertEquals(0.0f, mChannel.getAndResetPeakLevel(), 0.0f);
}
}

View File

@@ -0,0 +1,77 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.audio;
import javafx.scene.paint.Color;
import javax.sound.sampled.FloatControl;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Audio display volume mapping and alias accent color.
*/
public class AudioViewTest
{
private static final FloatControl GAIN = new FloatControl(FloatControl.Type.MASTER_GAIN, -80.0f, 6.0f, 0.1f,
0, 0.0f, "dB") {};
@Test
public void volumeMidpointIsUnityGain()
{
assertEquals(0.0f, AudioView.toGain(GAIN, 50), 0.0f);
assertEquals(-80.0f, AudioView.toGain(GAIN, 0), 1e-4f);
assertEquals(6.0f, AudioView.toGain(GAIN, 100), 1e-4f);
assertEquals(-40.0f, AudioView.toGain(GAIN, 25), 1e-4f);
assertEquals(3.0f, AudioView.toGain(GAIN, 75), 1e-4f);
}
@Test
public void darkAliasColorIsLightenedForTheDisplay()
{
Color black = AudioChannelView.toReadable(0x000000);
Color navy = AudioChannelView.toReadable(0x1E3A8A);
assertTrue(contrast(black) >= 3.0, "black accent contrast " + contrast(black));
assertTrue(contrast(navy) >= 3.0, "navy accent contrast " + contrast(navy));
}
@Test
public void brightAliasColorIsUnchanged()
{
Color red = AudioChannelView.toReadable(0xD9381E);
assertEquals(Color.rgb(0xD9, 0x38, 0x1E), red);
}
private static double contrast(Color color)
{
return (luminance(color) + 0.05) / (luminance(Color.web("#161b22")) + 0.05);
}
private static double luminance(Color color)
{
return 0.2126 * linear(color.getRed()) + 0.7152 * linear(color.getGreen()) + 0.0722 * linear(color.getBlue());
}
private static double linear(double channel)
{
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
}
}

View File

@@ -0,0 +1,67 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.broadcast;
import io.github.dsheirer.audio.broadcast.BroadcastState;
import io.github.dsheirer.audio.broadcast.ConfiguredBroadcast;
import io.github.dsheirer.audio.broadcast.icecast.IcecastHTTPConfiguration;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Streaming status severity and summary.
*/
public class BroadcastStatusViewTest
{
@Test
public void severityMatchesTheSwingColors()
{
assertEquals(BroadcastStatusView.Severity.OK, BroadcastStatusView.getSeverity(BroadcastState.CONNECTED));
assertEquals(BroadcastStatusView.Severity.DISABLED, BroadcastStatusView.getSeverity(BroadcastState.DISABLED));
assertEquals(BroadcastStatusView.Severity.WARNING,
BroadcastStatusView.getSeverity(BroadcastState.INVALID_SETTINGS));
assertEquals(BroadcastStatusView.Severity.WARNING,
BroadcastStatusView.getSeverity(BroadcastState.NETWORK_UNAVAILABLE));
assertEquals(BroadcastStatusView.Severity.WARNING,
BroadcastStatusView.getSeverity(BroadcastState.MOUNT_POINT_IN_USE));
assertEquals(BroadcastStatusView.Severity.ERROR,
BroadcastStatusView.getSeverity(BroadcastState.INVALID_CREDENTIALS));
assertEquals(BroadcastStatusView.Severity.NEUTRAL, BroadcastStatusView.getSeverity(BroadcastState.CONNECTING));
assertEquals(BroadcastStatusView.Severity.NEUTRAL, BroadcastStatusView.getSeverity(null));
}
@Test
public void summaryCountsDisabledAndUnstartedStreams()
{
IcecastHTTPConfiguration disabled = new IcecastHTTPConfiguration();
disabled.setEnabled(false);
IcecastHTTPConfiguration enabled = new IcecastHTTPConfiguration();
enabled.setEnabled(true);
//An enabled stream without a broadcaster has invalid settings (warning) or failed to start (error)
String summary = BroadcastStatusView.getSummary(List.of(new ConfiguredBroadcast(disabled),
new ConfiguredBroadcast(enabled)));
assertEquals(true, summary.startsWith("0 of 2 connected"), summary);
assertEquals(true, summary.contains("1 disabled"), summary);
assertEquals("", BroadcastStatusView.getSummary(List.of()));
}
}