Compare commits

..

1 Commits

162 changed files with 17644 additions and 12263 deletions

View File

@@ -25,6 +25,24 @@ A cross-platform java application for decoding, monitoring, recording and stream
![sdrtrunk primary application window decoding a P25 trunked radio system](https://github.com/DSheirer/sdrtrunk/wiki/images/application_overview.png)
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
## MacOS Tahoe 26.1 Users - Attention
Changes to USB support in Tahoe version 26.x cause sdrtrunk to fail to launch. Do the following to install the latest libusb and create a symbolic link and then use the nightly build which includes an updated usb4java native library for Tahoe with ARM processor. There may still be issue(s) with MacOS accessing your USB SDR tuners.
```
brew install libusb --HEAD
cd /opt
sudo mkdir local
cd local
sudo mkdir lib
```
Next, find where brew installed the libusb library, for example: ```/opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib``` Note: the folder "HEAD-9ceaa52" is the version stamp for HEAD when you installed from it.
Finally, create a symbolic link from the installed library to the place where usb4java is expecting to find libusb (/opt/local/lib/libusb-1.0.0.dylib)
```
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.

View File

@@ -145,13 +145,18 @@ 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
@@ -190,6 +195,7 @@ 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
@@ -207,14 +213,6 @@ def jvmArgsLinux =
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
/**
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
*/
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
application {
mainClass = "io.github.dsheirer.gui.SDRTrunk"
@@ -226,16 +224,6 @@ application {
}
}
/**
* Adds the splash screen to the run task through an argument provider. Calling jvmArgs here would replace the
* applicationDefaultJvmArgs convention (--add-modules=jdk.incubator.vector, --enable-preview, etc.) instead of adding
* to it.
*/
tasks.named('run') {
def splashImage = file(splashResourceDir + '/' + splashImages[0]).absolutePath
jvmArgumentProviders.add({ ["-splash:${splashImage}".toString()] } as CommandLineArgumentProvider)
}
test {
if(os.isWindows()) {
jvmArgs = jvmArgsWindows
@@ -300,8 +288,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
* @return configured task.
*/
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
//Use the correct set of JVM arguments
rt.extension.launcherData.get().jvmArgs = jvmArgs
//Additional modules to include with auto-detected modules.
//jdk.charsets - NXDN BIG5 encoding support
@@ -309,9 +297,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.desktop, java.logging, java.net.http, java.prefs, javafx.controls - required by sdrtrunk (jdeps)
//java.base, java.logging, java.net.http, java.prefs, javafx.controls, javafx.swing - required by sdrtrunk (jdeps)
rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management',
'java.base', 'java.desktop', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls')
'java.base', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'javafx.swing')
//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
@@ -400,22 +388,6 @@ tasks.named('runtime') {rt ->
}
}
/**
* Copies the startup splash screen images into the lib folder of each runtime target image, where the launch scripts
* load them from (-splash:{{BIN_DIR}}/../lib/...).
*/
tasks.named('runtime') {rt ->
rt.doLast {
rt.targetPlatforms.get().keySet().each { target ->
def lib = new File(rt.imageDir.asFile, "${project.name}-${target}/lib")
splashImages.each { name ->
java.nio.file.Files.copy(file(splashResourceDir + '/' + name).toPath(), new File(lib, name).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
}
}
}
/**
* Verifies that each runtime target image contains every module that the sdrtrunk jar requires, as reported by jdeps.
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse

View File

@@ -0,0 +1,81 @@
/*
* *****************************************************************************
* 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

@@ -52,9 +52,7 @@ import org.slf4j.LoggerFactory;
* </ul>
*
* Only aliases whose only identifier is the radio are created or renamed. An alias that combines the radio with other
* identifiers (e.g. several radios or talkgroups) is left alone. The exception is a P25 radio's simple and fully
* qualified radio identifiers with the same radio ID: the second form decoded is added to the alias for the first
* form, including a user alias outside the managed group, instead of creating a second alias for the same radio.
* identifiers (e.g. several radios or talkgroups) is left alone.
*
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
* JavaFX application thread.
@@ -202,21 +200,6 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
Alias existing = findExactMatch(aliasList.getAliases(radio), aliasId);
if(existing == null)
{
existing = findCompanion(aliasList.aliases(), radio, aliasId);
if(existing != null)
{
//Add the radio to the alias for the same radio's other identifier form, then continue below to
//compare the talker alias with the alias name (only managed aliases are renamed).
existing.addAliasID(aliasId);
aliasList.updateAlias(existing);
mLog.info("Talker alias radio [" + aliasId + "] added to existing alias [" + existing.getName() +
"] in alias list [" + mAliasListName + "]");
}
}
if(existing == null)
{
Alias alias = new Alias(value);
@@ -425,114 +408,22 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
}
/**
* Finds the alias for the other identifier form of a P25 radio, so that a radio's simple and fully qualified
* identifiers share one alias instead of creating an alias for each. This includes user aliases outside the
* managed group, so that either identifier maps to the user's alias. The user alias is never renamed.
* <ul>
* <li>Fully qualified radio: the alias whose only identifier is the simple radio with the same radio
* ID. Only when the fully qualified radio isn't using a different local address (e.g. a roaming radio), since
* the radio ID then belongs to the home system and doesn't identify the radio on this system.</li>
* <li>Simple radio: the alias whose only identifier is a fully qualified radio with the same radio ID. None
* when more than one fully qualified radio alias matches.</li>
* </ul>
* @param aliases to search
* @param radio decoded radio identifier
* @param aliasId created from the decoded radio
* @return companion alias or null.
* Number of identifiers (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming.
*/
@VisibleForTesting
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
private static int getIdentityCount(Alias alias)
{
if(aliases == null || aliasId.getProtocol() != Protocol.APCO25)
{
return null;
}
boolean fullyQualified = aliasId instanceof P25FullyQualifiedRadio;
if(fullyQualified && !(radio instanceof FullyQualifiedRadioIdentifier fqri &&
fqri.getValue() != null && fqri.getValue() == fqri.getRadio()))
{
return null;
}
Alias match = null;
for(Alias alias: aliases)
{
if(getSoleIdentity(alias) instanceof Radio candidate &&
(candidate instanceof P25FullyQualifiedRadio) != fullyQualified &&
candidate.getProtocol() == Protocol.APCO25 && candidate.getValue() == aliasId.getValue())
{
if(match != null)
{
//Ambiguous - more than one candidate.
return null;
}
match = alias;
}
}
return match;
}
/**
* Identifier of an alias that has exactly one identifier, excluding audio settings.
* @return identifier or null if the alias has none or more than one.
*/
private static AliasID getSoleIdentity(Alias alias)
{
AliasID sole = null;
int count = 0;
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isAudioIdentifier())
{
if(sole != null)
{
return null;
}
sole = id;
count++;
}
}
return sole;
}
/**
* Number of identities (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming. A P25 radio's simple and fully qualified radio identifiers with the same radio ID count as one
* identity.
*/
private static int getIdentityCount(Alias alias)
{
List<AliasID> ids = alias.getAliasIdentifiers().stream().filter(id -> !id.isAudioIdentifier()).toList();
if(ids.size() == 2 && isRadioPair(ids.get(0), ids.get(1)))
{
return 1;
}
return ids.size();
}
/**
* Indicates if the identifiers are the simple and fully qualified forms of the same P25 radio ID.
*/
private static boolean isRadioPair(AliasID a, AliasID b)
{
if(a instanceof P25FullyQualifiedRadio)
{
AliasID swap = a;
a = b;
b = swap;
}
return a instanceof Radio simple && !(a instanceof P25FullyQualifiedRadio) &&
b instanceof P25FullyQualifiedRadio fqr && simple.getProtocol() == Protocol.APCO25 &&
simple.getValue() == fqr.getValue();
return count;
}
private static String getKey(Radio aliasId)

View File

@@ -19,16 +19,14 @@
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;
@@ -64,28 +62,23 @@ public abstract class RecurringAction extends AliasAction
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS);
String text = "Alias [" + alias.getName() + "] is active in message [" + message + "]";
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);
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();
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
});
}
else
{
dismissed.run();
}
break;
default:
}

View File

@@ -46,8 +46,9 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel;
public class BroadcastModel implements Listener<AudioRecording>
public class BroadcastModel extends AbstractTableModel implements Listener<AudioRecording>
{
private final static Logger mLog = LoggerFactory.getLogger(BroadcastModel.class);
@@ -56,6 +57,18 @@ public class BroadcastModel implements Listener<AudioRecording>
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<>();
@@ -158,6 +171,8 @@ public class BroadcastModel implements Listener<AudioRecording>
{
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;
}
@@ -259,6 +274,8 @@ public class BroadcastModel implements Listener<AudioRecording>
if(configuredBroadcast != null)
{
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
mConfiguredBroadcasts.remove(configuredBroadcast);
if(configuredBroadcast.hasAudioBroadcaster())
@@ -269,6 +286,8 @@ public class BroadcastModel implements Listener<AudioRecording>
}
process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE));
fireTableRowsDeleted(index, index);
}
}
@@ -335,6 +354,13 @@ public class BroadcastModel implements Listener<AudioRecording>
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());
}
@@ -357,6 +383,13 @@ public class BroadcastModel implements Listener<AudioRecording>
broadcaster.removeListener();
broadcaster.dispose();
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
if(index >= 0)
{
fireTableRowsUpdated(index, index);
}
broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE));
}
}
@@ -465,17 +498,186 @@ public class BroadcastModel implements Listener<AudioRecording>
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

@@ -0,0 +1,186 @@
/*
* *****************************************************************************
* 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,30 +151,6 @@ 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,7 +31,6 @@ 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;
@@ -59,7 +58,6 @@ 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;
@@ -176,66 +174,18 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
*/
public float[] getAudio()
{
float[] audio = getNextAudio();
if(audio != null)
if(mAudioBuffer.isFull())
{
updatePeakLevel(audio);
float[] audio = mAudioBuffer.get();
//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)
{
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)
@@ -299,6 +249,12 @@ 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

@@ -0,0 +1,373 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,98 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,305 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,120 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,105 @@
/*******************************************************************************
* 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

@@ -0,0 +1,242 @@
/*
* *****************************************************************************
* 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

@@ -1,215 +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.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,11 +30,13 @@ 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
public class ChannelMapModel extends AbstractListModel<ChannelMap>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(ChannelMapModel.class);
private ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor());
@@ -106,6 +108,17 @@ public class ChannelMapModel
*/
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);
}
@@ -129,6 +142,10 @@ public class ChannelMapModel
{
mChannelMaps.add(channelMap);
int index = mChannelMaps.indexOf(channelMap);
fireIntervalAdded(this, index, index);
broadcast(new ChannelMapEvent(channelMap, Event.ADD));
}
}
@@ -140,9 +157,36 @@ public class ChannelMapModel
{
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

@@ -0,0 +1,295 @@
/*
*
* * ******************************************************************************
* * 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,14 +1,16 @@
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()
{
FxToolkit.ensureStarted();
mJFXPanel = new JFXPanel();
Platform.runLater(() ->
{

View File

@@ -19,191 +19,54 @@
package io.github.dsheirer.filter;
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;
import java.awt.Component;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
/**
* 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
* Filter editor
* @param <T> item type for editing
*/
public class FilterEditor<T>
public class FilterEditor<T> extends JFrame
{
private final Stage mStage = new Stage();
private final TreeView<Object> mTreeView = new TreeView<>();
private FilterEditorPanel<T> mEditorPanel;
/**
* Constructs an instance. JavaFX thread only.
* @param title for the window
* @param owner window, or null
* @param filterSet to edit
* Constructor
* @param title for the editor window frame
* @param owner to register the popup location
* @param filterSet to use initially
*/
public FilterEditor(String title, Window owner, FilterSet<T> filterSet)
public FilterEditor(String title, Component owner, FilterSet<T> filterSet)
{
if(filterSet == null)
{
throw new IllegalArgumentException("Unable to construct FilterEditor - FilterSet cannot be null");
}
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);
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);
}
/**
* 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
* Updates this editor with the filterset.
* @param filterSet to use in this editor.
*/
public void updateFilterSet(FilterSet<T> 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;
}
mEditorPanel.updateFilterSet(filterSet);
}
}

View File

@@ -0,0 +1,444 @@
/*
* *****************************************************************************
* 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

@@ -1,231 +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;
import java.awt.Image;
import java.awt.Taskbar;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.stage.Stage;
import javafx.stage.Window;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* sdrtrunk application icon for JavaFX stages and the macOS Dock.
*
* 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
{
private static final Logger mLog = LoggerFactory.getLogger(ApplicationIcons.class);
private static final String RESOURCE_PATTERN = "/images/sdrtrunk/sdrtrunk-icon-%d.png";
private static final int[] SIZES = {16, 24, 32, 48, 64, 128, 256, 512};
private static final int TASKBAR_SIZE = 512;
private static List<Image> sAwtImages;
private static List<javafx.scene.image.Image> sFxImages;
private static boolean sTaskbarInstalled;
private static boolean sJavaFxInstalled;
private ApplicationIcons()
{
}
/**
* 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()
{
if(sAwtImages == null)
{
List<Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
Image image = ImageIO.read(in);
if(image != null)
{
images.add(image);
}
}
else
{
mLog.warn("Application icon resource not found [" + path + "]");
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sAwtImages = Collections.unmodifiableList(images);
}
return sAwtImages;
}
/**
* Application icon in each available size, smallest first, for JavaFX stages.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<javafx.scene.image.Image> getFxImages()
{
if(sFxImages == null)
{
List<javafx.scene.image.Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
javafx.scene.image.Image image = new javafx.scene.image.Image(in);
if(!image.isError())
{
images.add(image);
}
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sFxImages = Collections.unmodifiableList(images);
}
return sFxImages;
}
/**
* Sets the application icon on the JavaFX stage if it doesn't already have one. Call on the FX thread.
*/
public static void apply(Stage stage)
{
if(stage != null && stage.getIcons().isEmpty() && !getFxImages().isEmpty())
{
stage.getIcons().setAll(getFxImages());
}
}
/**
* 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 installTaskbarIcon()
{
if(sTaskbarInstalled || java.awt.GraphicsEnvironment.isHeadless())
{
return;
}
sTaskbarInstalled = true;
try
{
if(Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
{
List<Image> images = getAwtImages();
for(int x = 0; x < SIZES.length && x < images.size(); x++)
{
if(SIZES[x] == TASKBAR_SIZE)
{
Taskbar.getTaskbar().setIconImage(images.get(x));
}
}
}
}
catch(Exception e)
{
mLog.debug("Unable to set taskbar icon", e);
}
}
/**
* Gives each JavaFX stage that shows without an icon the application icon, and closes the startup splash screen
* if a JavaFX window opens before the main window does. Safe to call more than once. The JavaFX toolkit must
* already be running.
*/
public static synchronized void installJavaFx()
{
if(sJavaFxInstalled)
{
return;
}
sJavaFxInstalled = true;
installTaskbarIcon();
Platform.runLater(() -> {
for(Window window: Window.getWindows())
{
onFxWindowShown(window);
}
Window.getWindows().addListener((ListChangeListener<Window>)change -> {
while(change.next())
{
for(Window window: change.getAddedSubList())
{
onFxWindowShown(window);
}
}
});
});
}
/**
* Handles a JavaFX window that is showing.
*/
private static void onFxWindowShown(Window window)
{
//Only stages are top-level windows. Popups (menus, tooltips) are other Window types.
if(window instanceof Stage stage)
{
apply(stage);
//A JavaFX window (e.g. an error dialog) that shows before the main window would sit behind the splash.
Splash.close();
}
}
}

View File

@@ -1,131 +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;
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

@@ -20,25 +20,36 @@
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;
@@ -46,15 +57,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 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.
* Java FX window manager. Handles all secondary Java FX windows that are used within this primarily
* Swing application.
*/
public class WindowManager
public class JavaFxWindowManager extends Application
{
private final static Logger mLog = LoggerFactory.getLogger(WindowManager.class);
private final static Logger mLog = LoggerFactory.getLogger(JavaFxWindowManager.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";
@@ -63,6 +76,7 @@ public class WindowManager
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;
@@ -79,14 +93,12 @@ public class WindowManager
private Stage mPlaylistStage;
private Stage mUserPreferencesStage;
private Stage mRecordingViewerStage;
private JFXPanel mStatusPanel;
/**
* 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
* Constructs an instance. Note: this constructor is used for Swing applications.
*/
public WindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager)
public JavaFxWindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager)
{
mUserPreferences = userPreferences;
mTunerManager = tunerManager;
@@ -95,6 +107,43 @@ public class WindowManager
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
@@ -103,7 +152,7 @@ public class WindowManager
//Register JavaFX icon fonts
IconFontFX.register(jiconfont.icons.font_awesome.FontAwesome.getIconFont());
startToolkit();
createJFXPanel();
}
/**
@@ -111,7 +160,7 @@ public class WindowManager
*/
private void execute(Runnable runnable)
{
startToolkit();
createJFXPanel();
if(Platform.isFxApplicationThread())
{
@@ -124,11 +173,15 @@ public class WindowManager
}
/**
* Starts the JavaFX toolkit if it is not running
* Creates a JavaFX panel for Swing application compatibility
*/
private void startToolkit()
private void createJFXPanel()
{
FxToolkit.ensureStarted();
if(mJFXPanel == null)
{
mJFXPanel = new JFXPanel();
Platform.setImplicitExit(false);
}
}
/**
@@ -143,7 +196,7 @@ public class WindowManager
public CalibrationDialog getCalibrationDialog(UserPreferences userPreferences)
{
startToolkit();
createJFXPanel();
return new CalibrationDialog(userPreferences);
}
@@ -154,7 +207,7 @@ public class WindowManager
{
if(mRecordingViewerStage == null)
{
startToolkit();
createJFXPanel();
Scene scene = new Scene(getRecordingViewer(), 1100, 800);
ThemeManager.getInstance().register(scene);
mRecordingViewerStage = new Stage();
@@ -180,7 +233,7 @@ public class WindowManager
{
if(mIconManagerStage == null)
{
startToolkit();
createJFXPanel();
Scene scene = new Scene(getIconManager(), 500, 500);
ThemeManager.getInstance().register(scene);
mIconManagerStage = new Stage();
@@ -229,7 +282,7 @@ public class WindowManager
{
if(mJmbeEditorStage == null)
{
startToolkit();
createJFXPanel();
Scene scene = new Scene(getJmbeEditor(), 650, 650);
ThemeManager.getInstance().register(scene);
mJmbeEditorStage = new Stage();
@@ -271,7 +324,7 @@ public class WindowManager
{
if(mPlaylistStage == null)
{
startToolkit();
createJFXPanel();
Scene scene = new Scene(getPlaylistEditor(), 1000, 750);
ThemeManager.getInstance().register(scene);
mPlaylistStage = new Stage();
@@ -322,7 +375,7 @@ public class WindowManager
{
if(mUserPreferencesStage == null)
{
startToolkit();
createJFXPanel();
Scene scene = new Scene(getUserPreferencesEditor(), 900, 500);
ThemeManager.getInstance().register(scene);
mUserPreferencesStage = new Stage();
@@ -366,7 +419,7 @@ public class WindowManager
{
if(mChannelMapStage == null)
{
startToolkit();
createJFXPanel();
Scene scene = new Scene(getChannelMapEditor(), 500, 500);
ThemeManager.getInstance().register(scene);
mChannelMapStage = new Stage();
@@ -416,4 +469,75 @@ public class WindowManager
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

@@ -1,756 +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;
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,21 +18,28 @@
*/
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.ChannelAutoStartWindow;
import io.github.dsheirer.controller.channel.ChannelAutoStartFrame;
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;
@@ -48,12 +55,29 @@ 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;
@@ -61,52 +85,72 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.prefs.Preferences;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.embed.swing.JFXPanel;
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 MainWindow mMainWindow;
private WindowManager mWindowManager;
private SpectralDisplayPanel mSpectralPanel;
private JFrame mMainGui;
private JideSplitPane mSplitPane;
private JavaFxWindowManager mJavaFxWindowManager;
private UserPreferences mUserPreferences = new UserPreferences();
private TunerManager mTunerManager;
private ApplicationLog mApplicationLog;
private ResourceMonitor mResourceMonitor;
private JFXPanel mResourceStatusPanel;
private String mTitle;
public SDRTrunk()
{
try
{
initialize();
}
catch(Throwable t)
{
startupFailed(t);
}
}
/**
* Creates and starts the application components and shows the main window.
*/
private void initialize() throws Exception
{
if(!GraphicsEnvironment.isHeadless())
{
//Initialize the theme manager before any windows are created so that the chosen theme applies to the
//first window.
//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.
ThemeManager.getInstance().initialize(mUserPreferences);
mMainGui = new JFrame();
}
mApplicationLog = new ApplicationLog(mUserPreferences);
@@ -133,6 +177,8 @@ 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();
@@ -160,7 +206,7 @@ public class SDRTrunk implements Listener<TunerEvent>
if(!headless)
{
mWindowManager = new WindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
mJavaFxWindowManager = new JavaFxWindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
}
CalibrationManager calibrationManager = CalibrationManager.getInstance(mUserPreferences);
@@ -188,74 +234,68 @@ public class SDRTrunk implements Listener<TunerEvent>
MapService mapService = new MapService(aliasModel, mIconModel);
mPlaylistManager.getChannelProcessingManager().addDecodeEventListener(mapService);
if(!headless)
mNowPlayingDetailsVisible = mPreferences.getBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, true);
if(!GraphicsEnvironment.isHeadless())
{
mResourceMonitor.start();
mMainWindow = FxToolkit.callAndWait(() -> new MainWindow(mUserPreferences, mPlaylistManager,
mTunerManager, audioPlaybackManager, aliasModel, mIconModel, mapService, mResourceMonitor,
mDiagnosticMonitor, this::processShutdown));
mControllerPanel = new ControllerPanel(mPlaylistManager, audioPlaybackManager, mIconModel, mapService,
mSettingsManager, mTunerManager, mUserPreferences, mNowPlayingDetailsVisible);
}
TunerSpectralDisplayManager tunerSpectralDisplayManager = new TunerSpectralDisplayManager(
mMainWindow != null ? mMainWindow.getSpectralDisplay() : null, mPlaylistManager,
mTunerManager.getDiscoveredTunerModel());
if(!headless)
{
mSpectralPanel = new SpectralDisplayPanel(mPlaylistManager, mTunerManager.getDiscoveredTunerModel());
}
TunerSpectralDisplayManager tunerSpectralDisplayManager = new TunerSpectralDisplayManager(mSpectralPanel,
mPlaylistManager, mTunerManager.getDiscoveredTunerModel());
mTunerManager.getDiscoveredTunerModel().addListener(tunerSpectralDisplayManager);
mTunerManager.getDiscoveredTunerModel().addListener(this);
mPlaylistManager.init();
if(headless)
if(GraphicsEnvironment.isHeadless())
{
mLog.info("starting main application headless");
autoStartChannels();
return;
}
else
{
mLog.info("starting main application gui");
Platform.runLater(() -> {
//Initialize the GUI
initGUI();
}
//Start the gui
EventQueue.invokeLater(() -> {
try
{
mMainWindow.show();
//The JVM only closes the splash screen when the first AWT window shows, so close it here.
Splash.close();
if(!GraphicsEnvironment.isHeadless())
{
mMainGui.setVisible(true);
Tuner tuner = tunerSpectralDisplayManager.showFirstTuner();
if(tuner != null)
{
mMainWindow.updateTitle(tuner.getPreferredName());
updateTitle(tuner.getPreferredName());
}
if(!duplicateLibraries.isEmpty())
{
mMainWindow.showDuplicateLibraries(DuplicateLibraryDetector.describe(duplicateLibraries),
String.valueOf(DuplicateLibraryDetector.getFolder(duplicateLibraries)));
showDuplicateLibrariesDialog(duplicateLibraries);
}
}
catch(Exception e)
{
if(!mMainWindow.getStage().isShowing())
{
//The main window didn't open, so the user has no way to close the application.
ThreadPool.CACHED.submit(() -> startupFailed(e));
return;
}
mLog.error("Error while starting the application", e);
}
if(calibrating)
if(calibrating && !GraphicsEnvironment.isHeadless())
{
//Show the calibration dialog after the main window is showing
Platform.runLater(() -> {
CalibrationDialog calibrationDialog = mWindowManager.getCalibrationDialog(mUserPreferences);
Platform.runLater(() ->
{
CalibrationDialog calibrationDialog = mJavaFxWindowManager.getCalibrationDialog(mUserPreferences);
Optional<ButtonType> calibrate = calibrationDialog.showAndWait();
if(calibrate.isPresent() && calibrate.get().getText().equals("Calibrate"))
{
MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest(
PreferenceEditorType.VECTOR_CALIBRATION));
//Request focus and execute calibration
MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.VECTOR_CALIBRATION));
MyEventBus.getGlobalEventBus().post(new CalibrateRequest());
}
else
@@ -268,6 +308,11 @@ public class SDRTrunk implements Listener<TunerEvent>
{
autoStartChannels();
}
}
catch(Exception e)
{
e.printStackTrace();
}
});
}
@@ -299,12 +344,302 @@ public class SDRTrunk implements Listener<TunerEvent>
}
else
{
Platform.runLater(() -> new ChannelAutoStartWindow(mPlaylistManager.getChannelProcessingManager(),
channels, mUserPreferences, mMainWindow != null ? mMainWindow.getStage() : null).show());
new ChannelAutoStartFrame(mPlaylistManager.getChannelProcessingManager(), channels, mUserPreferences);
}
}
}
/**
* 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);
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
*/
@@ -312,18 +647,15 @@ 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 ...");
if(mMainWindow != null)
{
mMainWindow.dispose();
}
if(mWindowManager != null)
{
mWindowManager.shutdown();
}
mSpectralPanel.dispose();
mJavaFxWindowManager.shutdown();
mLog.info("Stopping channels ...");
mPlaylistManager.getChannelProcessingManager().shutdown();
mAudioRecordingManager.stop();
@@ -335,6 +667,93 @@ 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
@@ -401,129 +820,158 @@ public class SDRTrunk implements Listener<TunerEvent>
@Override
public void receive(TunerEvent event)
{
if(mMainWindow != null)
switch(event.getEvent())
{
mMainWindow.receive(event);
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;
}
}
/**
* 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
* application started before the error keep the JVM running with no main window and the splash screen showing.
* @param t error
* Updates the title bar with the tuner name. No-op when running headless (no main window).
* @param tunerName optional
*/
private void startupFailed(Throwable t)
private void updateTitle(String tunerName)
{
mLog.error("sdrtrunk failed to start", t);
if(mTunerManager != null)
if(mMainGui == null)
{
try
{
mTunerManager.stop();
return;
}
catch(Throwable t2)
if(tunerName != null)
{
mLog.error("Error stopping tuners after the startup error", t2);
mMainGui.setTitle(mTitle + " - " + tunerName);
}
else
{
mMainGui.setTitle(mTitle);
}
}
String logsDirectory = null;
try
public class ShutdownMonitor extends WindowAdapter
{
logsDirectory = mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog().toString();
}
catch(Throwable t2)
@Override
public void windowClosing(WindowEvent e)
{
//Not available - the dialog leaves out the log location
processShutdown();
}
if(mApplicationLog != null)
{
mApplicationLog.stop();
}
exitAfterStartupError(t, logsDirectory);
}
/**
* Closes the splash screen, shows the startup error to the user and exits the JVM with a non-zero status.
* @param t error
* @param logsDirectory where the application log is, or null if not known.
* Broadcast status panel visible toggle menu item
*/
private static void exitAfterStartupError(Throwable t, String logsDirectory)
public class BroadcastStatusVisibleMenuItem extends JCheckBoxMenuItem
{
//The application log may not be running yet, so also write the error to the console.
System.err.println("sdrtrunk failed to start");
t.printStackTrace();
Splash.close();
if(FxToolkit.isStarted())
public BroadcastStatusVisibleMenuItem()
{
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
{
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();
}
super("Show Streaming Status");
setSelected(mBroadcastStatusVisible);
addActionListener(e -> {
toggleBroadcastStatusPanelVisibility();
setSelected(mBroadcastStatusVisible);
});
latch.await();
}
catch(Throwable t2)
{
t2.printStackTrace();
}
}
System.exit(1);
/**
* 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);
}
/**
* Launch the application.
*/
public static void main(String[] args)
{
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();
}
catch(Throwable t)
{
//An error creating the SDRTrunk fields, before the constructor's own startup error handling runs.
exitAfterStartupError(t, null);
}
}
}

View File

@@ -1,117 +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;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.SplashScreen;
/**
* Startup splash screen.
*
* The JVM shows the splash image named by the -splash:path option (set by the launch scripts) before any application
* code runs, and closes it when the main window becomes visible. This class draws the version on the splash and lets
* the application close the splash early, for example when a dialog has to show before the main window.
*
* Headless operation: the java launcher doesn't show the splash when -Djava.awt.headless=true is on the command line
* (for example in JAVA_OPTS or SDR_TRUNK_OPTS), and there is nothing to show it on without a display. This class does
* nothing when headless.
*/
public final class Splash
{
//Splash image layout, in pixels of the 640 x 360 image. The version goes under the tagline.
private static final double IMAGE_WIDTH = 640.0;
private static final double VERSION_X = 214.0;
private static final double VERSION_Y = 232.0;
private static final double VERSION_FONT_SIZE = 13.0;
private static final Color VERSION_COLOR = new Color(0x2E, 0xE6, 0xA6);
private Splash()
{
}
/**
* Draws the version text on the splash screen, if a splash screen is showing.
* @param version to show, for example "v1.0.1", or null to leave the splash unchanged.
*/
public static void showVersion(String version)
{
if(version == null || version.isBlank() || GraphicsEnvironment.isHeadless())
{
return;
}
try
{
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash == null || !splash.isVisible())
{
return;
}
//Overlay coordinates are in the splash's size, which can differ from the image (HiDPI @2x image).
Dimension size = splash.getSize();
double scale = size.width / IMAGE_WIDTH;
Graphics2D g = splash.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(VERSION_COLOR);
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, (int)Math.round(VERSION_FONT_SIZE * scale)));
g.drawString(version, (float)(VERSION_X * scale), (float)(VERSION_Y * scale));
g.dispose();
splash.update();
}
catch(Exception e)
{
//The splash is cosmetic. Never let it stop the application from starting.
}
}
/**
* Closes the splash screen if it is still showing.
*/
public static void close()
{
if(GraphicsEnvironment.isHeadless())
{
return;
}
try
{
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash != null && splash.isVisible())
{
splash.close();
}
}
catch(Exception e)
{
//The splash is cosmetic. Never let it stop the application from starting.
}
}
}

View File

@@ -1,548 +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.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

@@ -1,392 +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.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

@@ -1,207 +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.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

@@ -1,410 +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.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

@@ -243,7 +243,8 @@ public class ChannelSpectrumView extends SplitPane implements Listener<Processin
if(source instanceof TunerChannelSource tcs)
{
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth);
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth,
tcs::getNoiseDensity);
}
}

View File

@@ -0,0 +1,573 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,472 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,573 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,322 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,179 @@
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,678 +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.control;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.LongConsumer;
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.AccessibleRole;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Duration;
/**
* Frequency display and tuning control that shows a frequency in MHz with six fractional digits (1 Hz).
*
* Mouse: hover over a digit to reveal its up/down halves. Click the upper half to increment the digit or the lower
* half to decrement it (hold the button to repeat), or use the scroll wheel over the digit. Steps carry into the
* higher digits and stop at the minimum/maximum frequency.
*
* Keyboard: left/right move the digit cursor, up/down (or +/-) step the digit under the cursor. Typing digits
* starts a calculator style entry (e.g. 851.0125) that is applied with Enter and cancelled with Escape. Shortcut-C
* and Shortcut-V copy and paste the frequency.
*
* The control only reports user requested frequencies to the listeners. {@link #setFrequency(long)} updates the
* display without notifying them, which is how the tuner reports its actual frequency back to the control.
*/
public class FrequencyControl extends HBox implements ISourceEventProcessor
{
private static final PseudoClass HOVER_UP = PseudoClass.getPseudoClass("hover-up");
private static final PseudoClass HOVER_DOWN = PseudoClass.getPseudoClass("hover-down");
private static final PseudoClass LEADING = PseudoClass.getPseudoClass("leading");
private static final PseudoClass CURSOR = PseudoClass.getPseudoClass("cursor");
private static final PseudoClass ENTRY = PseudoClass.getPseudoClass("entry");
private static final PseudoClass TYPED = PseudoClass.getPseudoClass("typed");
private static final PseudoClass INVALID = PseudoClass.getPseudoClass("invalid");
private static final Duration REPEAT_DELAY = Duration.millis(400);
private static final Duration REPEAT_INTERVAL = Duration.millis(70);
private final List<LongConsumer> mListeners = new CopyOnWriteArrayList<>();
private final Digit[] mDigits = new Digit[FrequencyEntry.DIGIT_COUNT];
private final FrequencyEntry.TypedEntry mTypedEntry = new FrequencyEntry.TypedEntry();
private final Text mProbe = new Text("0");
private final Label mUnitLabel = new Label("MHz");
private final Tooltip mTooltip = new Tooltip();
private final PauseTransition mInvalidFlash = new PauseTransition(Duration.millis(1200));
private final Timeline mRepeat = new Timeline();
private long mFrequency;
private long mMinimum = 1;
private long mMaximum = FrequencyEntry.MAXIMUM_DISPLAYABLE;
private int mCursorPosition = FrequencyEntry.FRACTION_DIGITS;
private double mScrollAccumulator;
/**
* Constructs an instance
*/
public FrequencyControl()
{
getStyleClass().add("frequency-control");
URL stylesheet = FrequencyControl.class.getResource("/frequency_control.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
setAlignment(Pos.CENTER_LEFT);
setFocusTraversable(true);
setAccessibleRole(AccessibleRole.SPINNER);
setMaxWidth(Region.USE_PREF_SIZE);
//Invisible probe text, styled like the digits, sizes every digit cell to the same width so that a
//proportional font doesn't make the display jitter as the digits change.
mProbe.getStyleClass().add("frequency-digit-text");
mProbe.setManaged(false);
mProbe.setVisible(false);
getChildren().add(mProbe);
for(int position = FrequencyEntry.DIGIT_COUNT - 1; position >= 0; position--)
{
Digit digit = new Digit(position);
mDigits[position] = digit;
getChildren().add(digit);
if(position == FrequencyEntry.FRACTION_DIGITS)
{
Text point = new Text(".");
point.getStyleClass().addAll("frequency-digit-text", "frequency-point");
getChildren().add(point);
}
else if(position % 3 == 0 && position > 0)
{
Region gap = new Region();
gap.getStyleClass().add("frequency-group-gap");
getChildren().add(gap);
}
}
mUnitLabel.getStyleClass().add("frequency-unit");
getChildren().add(mUnitLabel);
Tooltip.install(this, mTooltip);
updateTooltip();
mInvalidFlash.setOnFinished(e -> pseudoClassStateChanged(INVALID, false));
mRepeat.setCycleCount(Timeline.INDEFINITE);
addEventHandler(KeyEvent.KEY_PRESSED, this::keyPressed);
addEventHandler(KeyEvent.KEY_TYPED, this::keyTyped);
addEventHandler(MouseEvent.MOUSE_PRESSED, e -> requestFocus());
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
cancelEntry();
}
updateDigits();
});
disabledProperty().addListener((observable, wasDisabled, disabled) -> {
if(disabled)
{
stopRepeat();
cancelEntry();
}
});
setOnContextMenuRequested(e -> {
buildContextMenu().show(this, e.getScreenX(), e.getScreenY());
e.consume();
});
updateDigits();
}
/**
* Adds a listener to be notified of frequencies requested by the user. Listeners are invoked on the JavaFX
* application thread.
*/
public void addListener(LongConsumer listener)
{
if(listener != null && !mListeners.contains(listener))
{
mListeners.add(listener);
}
}
/**
* Removes the listener.
*/
public void removeListener(LongConsumer listener)
{
mListeners.remove(listener);
}
/**
* Removes all listeners.
*/
public void clearListeners()
{
mListeners.clear();
}
/**
* Current frequency in Hertz.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Sets the displayed frequency without notifying listeners. Safe to call from any thread.
* @param frequency in Hertz
*/
public void setFrequency(long frequency)
{
if(Platform.isFxApplicationThread())
{
mFrequency = Math.max(0, Math.min(FrequencyEntry.MAXIMUM_DISPLAYABLE, frequency));
updateDigits();
}
else
{
Platform.runLater(() -> setFrequency(frequency));
}
}
/**
* Sets the range of frequencies that the user can request.
* @param minimum frequency in Hertz
* @param maximum frequency in Hertz
*/
public void setRange(long minimum, long maximum)
{
mMinimum = Math.max(0, Math.min(minimum, maximum));
mMaximum = Math.min(FrequencyEntry.MAXIMUM_DISPLAYABLE, Math.max(minimum, maximum));
updateTooltip();
}
/**
* Minimum frequency that the user can request.
*/
public long getMinimum()
{
return mMinimum;
}
/**
* Maximum frequency that the user can request.
*/
public long getMaximum()
{
return mMaximum;
}
/**
* Receives tuner frequency change notifications and shows the new frequency. Requests are not re-broadcast.
*/
@Override
public void process(SourceEvent event)
{
if(event.getEvent() == SourceEvent.Event.NOTIFICATION_FREQUENCY_CHANGE && event.getValue() != null)
{
setFrequency(event.getValue().longValue());
}
}
/**
* Digit position under the keyboard cursor.
*/
public int getCursorPosition()
{
return mCursorPosition;
}
/**
* Steps the digit at the position and notifies listeners when the frequency changes.
* @param position of the digit (0 = 1 Hz)
* @param steps positive to increment, negative to decrement
*/
public void step(int position, int steps)
{
if(isDisabled() || steps == 0)
{
return;
}
cancelEntry();
long stepped = FrequencyEntry.step(mFrequency, position, steps, mMinimum, mMaximum);
request(stepped);
}
/**
* Requests the frequency on behalf of the user. An out of range frequency is rejected and flagged.
* @return true if the frequency was accepted.
*/
public boolean request(long frequency)
{
if(frequency < mMinimum || frequency > mMaximum)
{
flagInvalid();
return false;
}
if(frequency != mFrequency)
{
mFrequency = frequency;
updateDigits();
for(LongConsumer listener: mListeners)
{
listener.accept(frequency);
}
}
return true;
}
/**
* Indicates if a typed entry is in progress.
*/
public boolean isEntryActive()
{
return !mTypedEntry.isEmpty();
}
private void keyTyped(KeyEvent event)
{
if(isDisabled() || event.isShortcutDown() || event.isAltDown())
{
return;
}
String character = event.getCharacter();
if(character == null || character.length() != 1)
{
return;
}
char c = character.charAt(0);
if((c >= '0' && c <= '9') || c == '.' || c == ',')
{
mTypedEntry.type(c);
updateDigits();
event.consume();
}
else if(c == '+' || c == '=')
{
step(mCursorPosition, 1);
event.consume();
}
else if(c == '-')
{
step(mCursorPosition, -1);
event.consume();
}
}
private void keyPressed(KeyEvent event)
{
if(isDisabled())
{
return;
}
if(event.isShortcutDown())
{
if(event.getCode() == KeyCode.C)
{
copy();
event.consume();
}
else if(event.getCode() == KeyCode.V)
{
paste();
event.consume();
}
return;
}
switch(event.getCode())
{
case LEFT, KP_LEFT -> moveCursor(1);
case RIGHT, KP_RIGHT -> moveCursor(-1);
case HOME -> setCursorPosition(FrequencyEntry.DIGIT_COUNT - 1);
case END -> setCursorPosition(0);
case UP, KP_UP -> step(mCursorPosition, 1);
case DOWN, KP_DOWN -> step(mCursorPosition, -1);
case PAGE_UP -> step(mCursorPosition, 10);
case PAGE_DOWN -> step(mCursorPosition, -10);
case ENTER ->
{
if(!commitEntry())
{
return;
}
}
case ESCAPE ->
{
if(!isEntryActive())
{
return;
}
cancelEntry();
}
case BACK_SPACE ->
{
if(!isEntryActive())
{
return;
}
mTypedEntry.backspace();
updateDigits();
}
default ->
{
return;
}
}
event.consume();
}
/**
* Applies the typed entry.
* @return true if there was an entry to apply.
*/
private boolean commitEntry()
{
if(!isEntryActive())
{
return false;
}
long frequency = mTypedEntry.getFrequency();
mTypedEntry.clear();
if(!request(frequency))
{
updateDigits();
}
return true;
}
private void cancelEntry()
{
if(isEntryActive())
{
mTypedEntry.clear();
updateDigits();
}
}
private void moveCursor(int direction)
{
cancelEntry();
setCursorPosition(mCursorPosition + direction);
}
private void setCursorPosition(int position)
{
mCursorPosition = Math.max(0, Math.min(FrequencyEntry.DIGIT_COUNT - 1, position));
updateDigits();
}
private void copy()
{
ClipboardContent content = new ClipboardContent();
content.putString(FrequencyEntry.format(mFrequency));
Clipboard.getSystemClipboard().setContent(content);
}
private void paste()
{
Clipboard clipboard = Clipboard.getSystemClipboard();
if(clipboard.hasString())
{
Long frequency = FrequencyEntry.parse(clipboard.getString());
cancelEntry();
if(frequency != null)
{
request(frequency);
}
else
{
flagInvalid();
}
}
}
private ContextMenu buildContextMenu()
{
MenuItem copy = new MenuItem("Copy Frequency");
copy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
copy.setOnAction(e -> copy());
MenuItem paste = new MenuItem("Paste Frequency");
paste.setAccelerator(KeyCombination.keyCombination("Shortcut+V"));
paste.setDisable(isDisabled() || !Clipboard.getSystemClipboard().hasString());
paste.setOnAction(e -> paste());
MenuItem minimum = new MenuItem("Tune to Minimum (" + FrequencyEntry.format(mMinimum) + " MHz)");
minimum.setDisable(isDisabled());
minimum.setOnAction(e -> request(mMinimum));
MenuItem maximum = new MenuItem("Tune to Maximum (" + FrequencyEntry.format(mMaximum) + " MHz)");
maximum.setDisable(isDisabled());
maximum.setOnAction(e -> request(mMaximum));
return new ContextMenu(copy, paste, new SeparatorMenuItem(), minimum, maximum);
}
private void flagInvalid()
{
pseudoClassStateChanged(INVALID, true);
mInvalidFlash.playFromStart();
}
private void updateTooltip()
{
mTooltip.setText("Tuning range " + FrequencyEntry.format(mMinimum) + " - " +
FrequencyEntry.format(mMaximum) + " MHz\n\n" +
"Hover over a digit and use the scroll wheel, or click its upper or lower half, to step it.\n" +
"Or type a frequency in MHz (e.g. 851.0125) and press Enter. Escape cancels.\n" +
"Arrow keys move between digits and step the selected digit.");
}
/**
* Refreshes every digit's value and state.
*/
private void updateDigits()
{
boolean entry = isEntryActive();
long shown = entry ? mTypedEntry.getFrequency() : mFrequency;
boolean focused = isFocused();
pseudoClassStateChanged(ENTRY, entry);
for(Digit digit: mDigits)
{
int position = digit.getPosition();
digit.setValue(FrequencyEntry.getDigit(shown, position));
digit.pseudoClassStateChanged(LEADING, FrequencyEntry.isLeadingZero(shown, position));
digit.pseudoClassStateChanged(TYPED, entry && mTypedEntry.isTyped(position));
digit.pseudoClassStateChanged(CURSOR, focused && !entry && position == mCursorPosition);
}
setAccessibleText(FrequencyEntry.format(mFrequency) + " MHz");
}
private void stopRepeat()
{
mRepeat.stop();
mRepeat.getKeyFrames().clear();
}
/**
* A single digit with up and down halves.
*/
private class Digit extends VBox
{
private final int mPosition;
private final Text mText = new Text("0");
private final Region mUpHalf = new Region();
private final Region mDownHalf = new Region();
Digit(int position)
{
mPosition = position;
getStyleClass().add("frequency-digit");
setAlignment(Pos.CENTER);
Region upArrow = new Region();
upArrow.getStyleClass().addAll("frequency-arrow", "frequency-arrow-up");
Region downArrow = new Region();
downArrow.getStyleClass().addAll("frequency-arrow", "frequency-arrow-down");
mText.getStyleClass().add("frequency-digit-text");
mUpHalf.getStyleClass().addAll("frequency-half", "frequency-half-up");
mDownHalf.getStyleClass().addAll("frequency-half", "frequency-half-down");
StackPane cell = new StackPane(mUpHalf, mDownHalf, mText);
cell.getStyleClass().add("frequency-digit-cell");
StackPane.setAlignment(mUpHalf, Pos.TOP_CENTER);
StackPane.setAlignment(mDownHalf, Pos.BOTTOM_CENTER);
mUpHalf.maxHeightProperty().bind(cell.heightProperty().divide(2));
mDownHalf.maxHeightProperty().bind(cell.heightProperty().divide(2));
cell.minWidthProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getWidth() + 4));
cell.prefWidthProperty().bind(cell.minWidthProperty());
//Arrow size follows the digit font size, so it scales with the user's GUI scale
upArrow.prefWidthProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getWidth() * 0.6));
upArrow.prefHeightProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getHeight() * 0.18));
upArrow.maxWidthProperty().bind(upArrow.prefWidthProperty());
upArrow.maxHeightProperty().bind(upArrow.prefHeightProperty());
downArrow.prefWidthProperty().bind(upArrow.prefWidthProperty());
downArrow.prefHeightProperty().bind(upArrow.prefHeightProperty());
downArrow.maxWidthProperty().bind(upArrow.prefWidthProperty());
downArrow.maxHeightProperty().bind(upArrow.prefHeightProperty());
getChildren().addAll(upArrow, cell, downArrow);
addEventHandler(MouseEvent.MOUSE_MOVED, e -> setHalf(e.getY() < getHeight() / 2 ? 1 : -1));
addEventHandler(MouseEvent.MOUSE_ENTERED, e -> setHalf(e.getY() < getHeight() / 2 ? 1 : -1));
addEventHandler(MouseEvent.MOUSE_EXITED, e -> {
setHalf(0);
stopRepeat();
});
addEventHandler(MouseEvent.MOUSE_PRESSED, this::pressed);
addEventHandler(MouseEvent.MOUSE_RELEASED, e -> stopRepeat());
addEventHandler(ScrollEvent.SCROLL, this::scrolled);
}
int getPosition()
{
return mPosition;
}
void setValue(int value)
{
mText.setText(String.valueOf(value));
}
private void setHalf(int half)
{
pseudoClassStateChanged(HOVER_UP, half > 0);
pseudoClassStateChanged(HOVER_DOWN, half < 0);
}
private void pressed(MouseEvent event)
{
if(event.getButton() != MouseButton.PRIMARY || isDisabled())
{
return;
}
requestFocus();
mCursorPosition = mPosition;
int direction = event.getY() < getHeight() / 2 ? 1 : -1;
setHalf(direction);
step(mPosition, direction);
stopRepeat();
mRepeat.getKeyFrames().add(new KeyFrame(REPEAT_INTERVAL, e -> step(mPosition, direction)));
mRepeat.setDelay(REPEAT_DELAY);
mRepeat.playFromStart();
event.consume();
}
private void scrolled(ScrollEvent event)
{
if(isDisabled() || event.getDeltaY() == 0)
{
return;
}
//Accumulate so that high resolution (touchpad) scrolling steps once per wheel notch
double notch = event.getMultiplierY() > 1 ? event.getMultiplierY() : 40;
mScrollAccumulator += event.getDeltaY() / notch;
int steps = (int)mScrollAccumulator;
if(steps != 0)
{
mScrollAccumulator -= steps;
mCursorPosition = mPosition;
step(mPosition, steps);
}
event.consume();
}
}
}

View File

@@ -1,372 +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.control;
import java.math.BigDecimal;
/**
* Frequency arithmetic for the {@link FrequencyControl}, kept free of JavaFX so that it can be unit tested.
*
* The control shows a frequency in MHz as a fixed number of digits: {@link #INTEGER_DIGITS} MHz digits and
* {@link #FRACTION_DIGITS} fractional digits, so the least significant digit is 1 Hz. Digit positions are
* numbered by their power of ten in Hertz: position 0 is the 1 Hz digit and position 9 is the 1000 MHz digit.
*/
public final class FrequencyEntry
{
/**
* Number of MHz (integer) digits.
*/
public static final int INTEGER_DIGITS = 4;
/**
* Number of fractional MHz digits (precision to 1 Hz).
*/
public static final int FRACTION_DIGITS = 6;
/**
* Total number of displayed digits.
*/
public static final int DIGIT_COUNT = INTEGER_DIGITS + FRACTION_DIGITS;
/**
* Largest frequency that fits the display: 9999.999999 MHz.
*/
public static final long MAXIMUM_DISPLAYABLE = 9_999_999_999L;
private FrequencyEntry()
{
}
/**
* Value of the digit at the position.
* @param frequency in Hertz
* @param position power of ten (0 = 1 Hz)
* @return digit 0-9
*/
public static int getDigit(long frequency, int position)
{
return (int)((Math.abs(frequency) / pow10(position)) % 10);
}
/**
* Indicates if the digit at the position is a leading zero, which the control shows dimmed. The 1 MHz digit is
* never a leading zero.
*/
public static boolean isLeadingZero(long frequency, int position)
{
return position > FRACTION_DIGITS && Math.abs(frequency) < pow10(position);
}
/**
* Steps the frequency by a number of units of the digit position, carrying into the higher digits, and clamps
* the result to the range. A step that would leave the range lands on the range limit.
* @param frequency current value in Hertz
* @param position power of ten for the digit being stepped
* @param steps positive to increment, negative to decrement
* @param minimum allowed frequency
* @param maximum allowed frequency
* @return stepped and clamped frequency
*/
public static long step(long frequency, int position, int steps, long minimum, long maximum)
{
long stepped = frequency + (steps * pow10(position));
return clamp(stepped, minimum, maximum);
}
/**
* Replaces the digit at the position with a new value, without carry.
*/
public static long setDigit(long frequency, int position, int digit)
{
long unit = pow10(position);
int current = getDigit(frequency, position);
return frequency + ((long)(digit - current) * unit);
}
/**
* Clamps the frequency to the range.
*/
public static long clamp(long frequency, long minimum, long maximum)
{
return Math.max(minimum, Math.min(maximum, frequency));
}
/**
* Parses a typed or pasted frequency. A bare number is in MHz (e.g. 851.0125) unless it is too large to be MHz
* for the display, in which case it is read as Hertz (e.g. 851012500). An optional unit suffix of Hz, kHz, MHz
* or GHz (any case, with or without a space) overrides that. Thousands separators (comma, underscore or space)
* are ignored.
* @param text to parse
* @return frequency in Hertz, or null if the text isn't a frequency or has more precision than 1 Hz.
*/
public static Long parse(String text)
{
if(text == null)
{
return null;
}
String value = text.trim().toLowerCase().replace(",", "").replace("_", "").replace(" ", "");
if(value.isEmpty())
{
return null;
}
BigDecimal multiplier = null;
if(value.endsWith("ghz"))
{
multiplier = BigDecimal.valueOf(1_000_000_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("mhz"))
{
multiplier = BigDecimal.valueOf(1_000_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("khz"))
{
multiplier = BigDecimal.valueOf(1_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("hz"))
{
multiplier = BigDecimal.ONE;
value = value.substring(0, value.length() - 2);
}
BigDecimal number;
try
{
number = new BigDecimal(value);
}
catch(NumberFormatException nfe)
{
return null;
}
if(number.signum() < 0)
{
return null;
}
if(multiplier == null)
{
//A whole number too large to be MHz on the display is taken as Hertz
boolean whole = number.stripTrailingZeros().scale() <= 0;
multiplier = (whole && number.compareTo(BigDecimal.valueOf(10_000)) >= 0) ? BigDecimal.ONE :
BigDecimal.valueOf(1_000_000L);
}
BigDecimal hertz = number.multiply(multiplier).stripTrailingZeros();
if(hertz.scale() > 0)
{
return null;
}
try
{
return hertz.longValueExact();
}
catch(ArithmeticException ae)
{
return null;
}
}
/**
* Formats the frequency in MHz with all six fractional digits, e.g. 851.012500
*/
public static String format(long frequency)
{
return BigDecimal.valueOf(frequency, FRACTION_DIGITS).toPlainString();
}
/**
* Ten raised to the power.
*/
public static long pow10(int power)
{
long value = 1;
for(int x = 0; x < power; x++)
{
value *= 10;
}
return value;
}
/**
* Calculator style typed entry. Digits typed before the decimal point fill the MHz digits from the right and
* digits typed after it fill the fractional digits from the left, so typing 851.0125 shows 851.012500.
*/
public static class TypedEntry
{
private final StringBuilder mIntegerPart = new StringBuilder();
private final StringBuilder mFractionPart = new StringBuilder();
private boolean mDecimal = false;
/**
* Adds a typed character.
* @param c digit or decimal point
* @return true if the character was accepted
*/
public boolean type(char c)
{
if(c == '.' || c == ',')
{
if(mDecimal)
{
return false;
}
mDecimal = true;
return true;
}
if(c < '0' || c > '9')
{
return false;
}
if(mDecimal)
{
if(mFractionPart.length() >= FRACTION_DIGITS)
{
return false;
}
mFractionPart.append(c);
return true;
}
//Ignore leading zeros so they don't use up the MHz digits
if(mIntegerPart.isEmpty() && c == '0')
{
return true;
}
if(mIntegerPart.length() >= INTEGER_DIGITS)
{
return false;
}
mIntegerPart.append(c);
return true;
}
/**
* Removes the last typed character.
* @return true if there is still something typed after the removal.
*/
public boolean backspace()
{
if(!mFractionPart.isEmpty())
{
mFractionPart.setLength(mFractionPart.length() - 1);
}
else if(mDecimal)
{
mDecimal = false;
}
else if(!mIntegerPart.isEmpty())
{
mIntegerPart.setLength(mIntegerPart.length() - 1);
}
return !isEmpty();
}
/**
* Indicates if nothing has been typed.
*/
public boolean isEmpty()
{
return mIntegerPart.isEmpty() && mFractionPart.isEmpty() && !mDecimal;
}
/**
* Number of fractional digits typed so far.
*/
public int getFractionDigitsTyped()
{
return mFractionPart.length();
}
/**
* Indicates if the decimal point has been typed.
*/
public boolean hasDecimal()
{
return mDecimal;
}
/**
* Number of MHz digits typed so far.
*/
public int getIntegerDigitsTyped()
{
return mIntegerPart.length();
}
/**
* Frequency for what has been typed so far.
*/
public long getFrequency()
{
long mhz = mIntegerPart.isEmpty() ? 0 : Long.parseLong(mIntegerPart.toString());
long fraction = 0;
if(!mFractionPart.isEmpty())
{
fraction = Long.parseLong(mFractionPart.toString()) * pow10(FRACTION_DIGITS - mFractionPart.length());
}
return (mhz * 1_000_000L) + fraction;
}
/**
* Indicates if the digit at the position has been typed, as opposed to an implied trailing zero.
*/
public boolean isTyped(int position)
{
if(position >= FRACTION_DIGITS)
{
return position - FRACTION_DIGITS < mIntegerPart.length();
}
return (FRACTION_DIGITS - 1 - position) < mFractionPart.length();
}
/**
* Clears the typed entry.
*/
public void clear()
{
mIntegerPart.setLength(0);
mFractionPart.setLength(0);
mDecimal = false;
}
}
}

View File

@@ -1,111 +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.control;
import java.util.function.LongPredicate;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
/**
* Text field for a frequency in MHz (to 1 Hz). The value is committed when the user presses Enter or leaves the
* field. A commit handler can reject the new value, which restores the previous value. Escape reverts the text.
*/
public class FrequencyField extends TextField
{
private long mFrequency;
private LongPredicate mCommitHandler;
/**
* Constructs an instance
* @param frequency initial value in Hertz
*/
public FrequencyField(long frequency)
{
getStyleClass().add("frequency-field");
setPrefColumnCount(11);
setFrequency(frequency);
setOnAction(e -> commit());
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
commit();
}
});
setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ESCAPE)
{
setText(FrequencyEntry.format(mFrequency));
e.consume();
}
});
}
/**
* Sets the handler for committed values. The handler returns false to reject the value.
*/
public void setCommitHandler(LongPredicate handler)
{
mCommitHandler = handler;
}
/**
* Current frequency in Hertz.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Sets the frequency without invoking the commit handler.
*/
public void setFrequency(long frequency)
{
mFrequency = frequency;
setText(FrequencyEntry.format(frequency));
}
private void commit()
{
Long parsed = FrequencyEntry.parse(getText());
if(parsed == null)
{
setText(FrequencyEntry.format(mFrequency));
return;
}
if(parsed == mFrequency)
{
setText(FrequencyEntry.format(mFrequency));
return;
}
long previous = mFrequency;
mFrequency = parsed;
setText(FrequencyEntry.format(parsed));
if(mCommitHandler != null && !mCommitHandler.test(parsed))
{
setFrequency(previous);
}
}
}

View File

@@ -0,0 +1,195 @@
/*
* *****************************************************************************
* 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.control;
import java.awt.EventQueue;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
/**
* Swing text field control for entering frequency (MHz) values.
*/
public class FrequencyTextField extends JTextField
{
private static final Logger LOGGER = LoggerFactory.getLogger(FrequencyTextField.class);
//Value range: 0.000001 to 9999.999999
private static final String REGEX = "^[0-9]{0,4}[.]?[0-9]{0,6}$";
//This lets users start typing a really small number like 1 Hertz ... 0.00000
private static final String ZEROS_REGEX = "^0?([.]0{0,5})?$";
private double mMinimum;
private double mMaximum;
/**
* Constructs an instance
*
* @param minimum allowable frequency value in Hertz
* @param maximum allowable frequency value in Hertz
* @param current frequency value in Hertz
*/
public FrequencyTextField(long minimum, long maximum, long current)
{
super(8);
mMinimum = minimum / 1E6d;
mMaximum = maximum / 1E6d;
PlainDocument document = (PlainDocument)this.getDocument();
document.setDocumentFilter(new FrequencyFilter());
setFrequency(current);
}
/**
* Current frequency value
* @return frequency in Hertz
*/
public long getFrequency()
{
String value = getText();
if(value == null || value.isEmpty())
{
return 0;
}
try
{
return (long)(Double.parseDouble(getText()) * 1E6d);
}
catch(Exception e)
{
LOGGER.error("Unable to parse frequency value from text [" + value + "] " + e.getLocalizedMessage());
}
return 0;
}
/**
* Sets the current frequency value
* @param frequency in Hertz
*/
public void setFrequency(long frequency)
{
double frequencyMHz = frequency / 1E6d;
if(isValid(String.valueOf(frequencyMHz)))
{
setText(String.valueOf(frequencyMHz));
}
else
{
LOGGER.warn("Can't set frequency [" + frequency + "Hz / " + frequencyMHz + "MHz] with current minimum [" + mMinimum + "MHz] and maximum [" + mMaximum + "MHz] limits");
}
}
/**
* Indicates if the value is a valid double value that is between the minimum and maximum extents.
* @param value to test
* @return true if it is valid.
*/
private boolean isValid(String value)
{
if(value == null || value.isEmpty() || value.matches(ZEROS_REGEX))
{
return true;
}
if(value.matches(REGEX))
{
try
{
double frequency = Double.parseDouble(value);
return mMinimum <= frequency && frequency <= mMaximum;
}
catch(NumberFormatException e)
{
return false;
}
}
return false;
}
/**
* Input filter for user entered values.
*/
class FrequencyFilter extends DocumentFilter
{
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if(isValid(sb.toString()))
{
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if(isValid(sb.toString()))
{
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
if(isValid(sb.toString()))
{
super.remove(fb, offset, length);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Frequency Control Test");
frame.setSize(300, 200);
FrequencyTextField ftf = new FrequencyTextField(1, 9_999_999_999l, 101_100_000);
frame.setLayout(new MigLayout());
frame.add(ftf);
EventQueue.invokeLater(() -> frame.setVisible(true));
}
}

View File

@@ -0,0 +1,593 @@
/*
* *****************************************************************************
* 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.control;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.InvalidFrequencyException;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Custom frequency controller for displaying or editing frequency values in MHz.
*/
public class JFrequencyControl extends JPanel implements ISourceEventProcessor
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(JFrequencyControl.class);
private List<ISourceEventProcessor> mProcessors = new ArrayList<>();
private Color mHighlightColor = Color.YELLOW;
private long mFrequency;
private HashMap<Integer,Digit> mDigits = new HashMap<Integer,Digit>();
/**
* Constructor
*/
public JFrequencyControl()
{
init();
}
/**
* Initializes the control/layout.
*/
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[]0[]", ""));
Font font = new Font(Font.MONOSPACED, Font.BOLD, 30);
for(int x = 9; x >= 0; x--)
{
Digit digit = null;
try
{
digit = new Digit(x);
}
catch(ParseException e)
{
mLog.error("JFrequencyControl - parse exception constructing a digit - " + e);
}
if(digit != null)
{
mDigits.put(x, digit);
add(digit);
digit.setFont(font);
if(x == 6)
{
add(new JLabel(". "));
}
}
}
revalidate();
}
/**
* Enables or disables the control.
* @param enabled true if this component should be enabled, false otherwise
*/
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
for(Digit digit : mDigits.values())
{
digit.setEnabled(enabled);
}
}
/**
* Receives a frequency change event invoked by another control. We don't
* rebroadcast this event, just set the control to indicate the new frequency.
*/
@Override
public void process(SourceEvent event)
{
switch(event.getEvent())
{
case NOTIFICATION_FREQUENCY_CHANGE:
EventQueue.invokeLater(() -> setFrequency(event.getValue().longValue(), false));
break;
}
}
/**
* Loads the frequency into the display and optionally fires a change event
* to all registered listeners
*/
public void setFrequency(long frequency, boolean fireChangeEvent)
{
mFrequency = frequency;
for(Digit digit : mDigits.values())
{
digit.setFrequency(frequency, fireChangeEvent);
}
}
/**
* Current frequency value for the control.
* @return frequency
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Updates the frequency value according to the manually changed digit value.
*/
private void updateFrequency()
{
long frequency = 0;
for(Digit digit : mDigits.values())
{
frequency += digit.getFrequency();
}
mFrequency = frequency;
}
/**
* Fires a source changed event
* @throws SourceException of there's an error
*/
private void fireSourceChanged() throws SourceException
{
updateFrequency();
Iterator<ISourceEventProcessor> it = mProcessors.iterator();
SourceEvent event = SourceEvent.frequencyRequest(mFrequency);
while(it.hasNext())
{
it.next().process(event);
}
}
/**
* Adds the source event listener
* @param processor
*/
public void addListener(ISourceEventProcessor processor)
{
if(!mProcessors.contains(processor))
{
mProcessors.add(processor);
}
}
/**
* Remove all source event processors
*/
public void clearListeners()
{
mProcessors.clear();
}
/**
* Removes the source event processor
* @param processor
*/
public void removeListener(ISourceEventProcessor processor)
{
mProcessors.remove(processor);
}
/**
* Custom single digit value editor.
*/
public class Digit extends JTextField
{
private static final long serialVersionUID = 1L;
private int mPower = 0;
private long mValue = 0;
/**
* Constructor
* @param position of the digit where a position of 1 is the ones unit of MHz and a position of -1 is the tenths
* unit of MHz.
* @throws ParseException if there is an error
*/
private Digit(int position) throws ParseException
{
super("0");
setColumns(1);
mPower = position;
setToolTipText(getTooltip(mPower));
Listener listener = new Listener();
this.addKeyListener(listener);
this.addMouseListener(listener);
this.addMouseWheelListener(listener);
}
/**
* Generates a custom tooltip for the current hover-over digit.
* @param power of the digit in units of 10
* @return custom tooptip.
*/
private static String getTooltip(int power)
{
StringBuilder sb = new StringBuilder();
sb.append("Center frequency ");
switch(power)
{
case 0:
sb.append("1 Hertz");
break;
case 1:
sb.append("10 Hertz");
break;
case 2:
sb.append("100 Hertz");
break;
case 3:
sb.append("1 Kilohertz");
break;
case 4:
sb.append("10 Kilohertz");
break;
case 5:
sb.append("100 Kilohertz");
break;
case 6:
sb.append("1 Megahertz");
break;
case 7:
sb.append("10 Megahertz");
break;
case 8:
sb.append("100 Megahertz");
break;
case 9:
sb.append("1 Gigahertz");
break;
}
sb.append(" units. Type a number, use up/down arrows, or click the upper/lower digit control to adjust");
return sb.toString();
}
/**
* Sets this digit to the value of the column in frequency that corresponds
* to the power (ie column) set for this digit. Optionally, fires a
* value change event to all listeners.
*/
public void setFrequency(long frequency, boolean fireChangeEvent)
{
//Strip the digits higher than this one
long lower = frequency % (long)(FastMath.pow(10, mPower + 1));
//Set the value to int value of dividing by 10 to this power
long value = (long)(lower / (long)(FastMath.pow(10, mPower)));
set(value, fireChangeEvent);
}
/**
* Frequency value.
* @return frequency value.
*/
public long getFrequency()
{
return mValue * (long)FastMath.pow(10, mPower);
}
/**
* Increments the unit value and fires a change event
*/
public void increment()
{
increment(true);
}
/**
* Increments the unit value and fires a change event
* @param fireChangeEvent true to fire an event
*/
public void increment(boolean fireChangeEvent)
{
if(isEnabled())
{
set(mValue + 1, fireChangeEvent);
}
}
/**
* Decrements the unit value and fires a change event.
*/
public void decrement()
{
decrement(true);
}
/**
* Decrements the unit value and optionally fires a change event.
* @param fireChangeEvent set to true to fire an event
*/
public void decrement(boolean fireChangeEvent)
{
if(isEnabled())
{
set(mValue - 1, fireChangeEvent);
}
}
/**
* Convenience wrapper to change amount and fire change event
*/
private void set(long amount)
{
set(amount, true);
}
/**
* Changes the value and optionally fires change event to listeners
*/
private void set(long amount, boolean fireChangeEvent)
{
long previous = mValue;
boolean higherDigitIncremented = false;
boolean higherDigitDecremented = false;
mValue = amount;
while(mValue < 0)
{
mValue += 10;
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.decrement(false);
higherDigitDecremented = true;
}
}
while(mValue > 9)
{
mValue -= 10;
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.increment(false);
higherDigitIncremented = true;
}
}
if(fireChangeEvent)
{
try
{
fireSourceChanged();
}
catch(SourceException se)
{
mValue = previous;
if(higherDigitIncremented)
{
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.decrement(false);
}
}
if(higherDigitDecremented)
{
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.increment(false);
}
}
if(se instanceof InvalidFrequencyException ife)
{
JOptionPane.showMessageDialog(this, ife.getMessage() + " for this tuner.");
}
}
}
setText(String.valueOf(mValue));
repaint();
}
/**
* Multiple Listener interface implementation
*/
private class Listener implements KeyListener, MouseListener, MouseWheelListener
{
@Override
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
switch(key)
{
case KeyEvent.VK_0:
case KeyEvent.VK_NUMPAD0:
set(0);
Digit.this.transferFocus();
break;
case KeyEvent.VK_1:
case KeyEvent.VK_NUMPAD1:
set(1);
Digit.this.transferFocus();
break;
case KeyEvent.VK_2:
case KeyEvent.VK_NUMPAD2:
set(2);
Digit.this.transferFocus();
break;
case KeyEvent.VK_3:
case KeyEvent.VK_NUMPAD3:
set(3);
Digit.this.transferFocus();
break;
case KeyEvent.VK_4:
case KeyEvent.VK_NUMPAD4:
set(4);
Digit.this.transferFocus();
break;
case KeyEvent.VK_5:
case KeyEvent.VK_NUMPAD5:
set(5);
Digit.this.transferFocus();
break;
case KeyEvent.VK_6:
case KeyEvent.VK_NUMPAD6:
set(6);
Digit.this.transferFocus();
break;
case KeyEvent.VK_7:
case KeyEvent.VK_NUMPAD7:
set(7);
Digit.this.transferFocus();
break;
case KeyEvent.VK_8:
case KeyEvent.VK_NUMPAD8:
set(8);
Digit.this.transferFocus();
break;
case KeyEvent.VK_9:
case KeyEvent.VK_NUMPAD9:
set(9);
Digit.this.transferFocus();
break;
case KeyEvent.VK_LEFT:
Digit.this.transferFocusBackward();
break;
case KeyEvent.VK_RIGHT:
Digit.this.transferFocus();
break;
case KeyEvent.VK_UP:
increment();
break;
case KeyEvent.VK_DOWN:
decrement();
break;
case KeyEvent.VK_TAB:
break;
default:
set(mValue);
break;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void mouseClicked(MouseEvent e)
{
switch(e.getButton())
{
case MouseEvent.BUTTON1:
increment();
break;
case MouseEvent.BUTTON2:
break;
case MouseEvent.BUTTON3:
decrement();
break;
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e)
{
Color bg = UIManager.getColor("TextField.selectionBackground");
Color fg = UIManager.getColor("TextField.selectionForeground");
Digit.this.setBackground(bg != null ? bg : Color.YELLOW);
Digit.this.setForeground(fg != null ? fg : Color.BLACK);
repaint(); }
@Override
public void mouseExited(MouseEvent e)
{
Color bg = UIManager.getColor("TextField.background");
Color fg = UIManager.getColor("TextField.foreground");
Digit.this.setBackground(bg != null ? bg : Color.WHITE);
Digit.this.setForeground(fg != null ? fg : Color.BLACK);
repaint(); }
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
//Swing delivers mouse wheel events to disabled components, so check enabled state explicitly so that
//the wheel can't bypass the lock when the tuner is providing channels.
if(isEnabled())
{
set(mValue - e.getWheelRotation());
}
else if(getParent() != null)
{
//Pass the event up so that an enclosing scroll pane can still scroll while this control is locked
getParent().dispatchEvent(SwingUtilities.convertMouseEvent(Digit.this, e, getParent()));
}
}
}
}
}

View File

@@ -0,0 +1,148 @@
/*******************************************************************************
* 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

@@ -0,0 +1,59 @@
/*
* *****************************************************************************
* 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 filter editor
//Filter changes come from the Swing filter editor
mFilterSet.register(() -> Platform.runLater(this::refilter));
MyEventBus.getGlobalEventBus().register(this);
}

View File

@@ -22,6 +22,7 @@ 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;
@@ -51,6 +52,7 @@ 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;
@@ -120,14 +122,16 @@ public class HistoryControls<T> extends HBox
{
mFilterSet = filterSet;
EventQueue.invokeLater(() -> {
if(mFilterEditor != null && filterSet != null)
{
mFilterEditor.updateFilterSet(filterSet);
}
});
}
/**
* Shows the filter editor.
* Shows the filter editor. The filter editor is a Swing window.
*/
private void showFilterEditor()
{
@@ -135,13 +139,15 @@ public class HistoryControls<T> extends HBox
if(filterSet != null)
{
EventQueue.invokeLater(() -> {
if(mFilterEditor == null)
{
mFilterEditor = new FilterEditor<>(mFilterEditorTitle,
getScene() != null ? getScene().getWindow() : null, filterSet);
mFilterEditor = new FilterEditor<>(mFilterEditorTitle, null, filterSet);
}
mFilterEditor.show();
mFilterEditor.setVisible(true);
mFilterEditor.toFront();
});
}
}
}

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 filter editor
//Filter changes come from the Swing filter editor
filterSet.register(() -> Platform.runLater(() -> {
if(mMessageFilterSet == filterSet)
{

View File

@@ -31,6 +31,7 @@ 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.
@@ -124,8 +125,9 @@ 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 readable = ThemeManager.getInstance().getReadableColor(color,
ThemeManager.getInstance().getInnerBackground());
java.awt.Color background = UIManager.getColor("Table.background");
java.awt.Color readable = background != null ?
ThemeManager.getInstance().getReadableColor(color, background) : color;
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

@@ -0,0 +1,81 @@
/*
* *****************************************************************************
* 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,6 +37,7 @@ 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;
@@ -130,9 +131,6 @@ 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;
@@ -184,7 +182,7 @@ public class PlaylistEditor extends BorderPane
screenShot.setOnShown(event -> menuItem.fire());
menuItem.setOnAction(event -> {
WritableImage image = getMenuBar().getScene().snapshot(null);
final BufferedImage bufferedImage = io.github.dsheirer.gui.FxToolkit.toBufferedImage(image);
final BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
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.WindowManager;
import io.github.dsheirer.gui.JavaFxWindowManager;
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 WindowManager mWindowManager;
private JavaFxWindowManager mJavaFxWindowManager;
public PlaylistEditorApplication()
{
@@ -52,7 +52,7 @@ public class PlaylistEditorApplication extends Application
mPlaylistManager = new PlaylistManager(mUserPreferences, mTunerManager, aliasModel, eventLogManager, new IconModel());
mPlaylistManager.init();
mWindowManager = new WindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
mJavaFxWindowManager = new JavaFxWindowManager(mUserPreferences, mTunerManager, mPlaylistManager);
}
@Override

View File

@@ -79,6 +79,7 @@ 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;
@@ -659,7 +660,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
nameColumn.setPrefWidth(140);
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Category");
groupColumn.setText("Group");
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
groupColumn.setPrefWidth(140);
@@ -949,7 +950,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,
ThemeManager.getInstance().getInnerBackground());
UIManager.getColor("TextField.background"));
rectangle.setFill(ColorUtil.fromInteger(readable.equals(color) ? alias.getColor() :
readable.getRGB()));
setAccessibleText(String.format("#%06X", alias.getColor() & 0xFFFFFF));

View File

@@ -1094,7 +1094,7 @@ public class AliasItemEditor extends Editor<Alias>
GridPane.setConstraints(getColorPicker(), 7, row);
mTextFieldPane.getChildren().add(getColorPicker());
Label groupLabel = new Label("Category");
Label groupLabel = new Label("Group");
groupLabel.setLabelFor(getGroupField());
GridPane.setHalignment(groupLabel, HPos.RIGHT);
GridPane.setConstraints(groupLabel, 0, ++row);

View File

@@ -243,7 +243,7 @@ public class AliasViewByIdentifierEditor extends VBox
aliasColumn.setPrefWidth(200);
TableColumn<AliasAndIdentifier, String> groupColumn = new TableColumn<>();
groupColumn.setText("Category");
groupColumn.setText("Group");
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
groupColumn.setPrefWidth(200);

View File

@@ -241,7 +241,7 @@ public class AliasViewByRecordingEditor extends VBox
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Category");
groupColumn.setText("Group");
groupColumn.setPrefWidth(200);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
@@ -280,7 +280,7 @@ public class AliasViewByRecordingEditor extends VBox
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Category");
groupColumn.setText("Group");
groupColumn.setPrefWidth(200);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));

View File

@@ -694,8 +694,8 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases");
mAutoAddTalkerAliasesCheckBox.setDisable(true);
mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds decoded talker aliases as radio aliases in " +
"the Talker Alias category. Only radio aliases in that category are automatically renamed; existing " +
"radio aliases outside the category are left unchanged. Move an alias out of the Talker Alias category " +
"the Talker Alias group. Only radio aliases in that group are automatically renamed; existing " +
"radio aliases outside the group are left unchanged. Move an alias out of the Talker Alias group " +
"to preserve a custom name. Applies when the channel is (re)started."));
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
}

View File

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

View File

@@ -225,7 +225,7 @@ public class StreamAliasSelectionEditor extends VBox
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Category");
groupColumn.setText("Group");
groupColumn.setPrefWidth(150);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
@@ -270,7 +270,7 @@ public class StreamAliasSelectionEditor extends VBox
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Category");
groupColumn.setText("Group");
groupColumn.setPrefWidth(150);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));

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 the
* application windows.
* Appearance preferences - selects the active UI {@link Theme} and the global GUI zoom factor for
* both the Swing main window and the JavaFX panels.
*/
public class AppearancePreferenceEditor extends HBox
{

View File

@@ -23,6 +23,8 @@ import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.spectrum.ChannelSignalMeter;
import java.util.function.DoubleSupplier;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
@@ -46,9 +48,11 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
private final ChannelTuningLayer mTuningLayer;
private final EdgeSlider mNoiseFloorSlider;
private final ChannelSignalMeter mSignalMeter = new ChannelSignalMeter(this::showReading);
private final Object mLock = new Object();
private boolean mActive;
private boolean mHasChannel;
private volatile boolean mHasChannel;
private volatile boolean mHasNoiseDensity;
/**
* Constructs an instance.
@@ -65,7 +69,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
SpectralDisplayModel model = getSpectralDisplay().getModel();
getSpectralDisplay().messageProperty().set(MESSAGE_NO_CHANNEL);
//Noise floor slider for the spectrum
//Noise floor slider along the right edge, below the configuration panel tab
mNoiseFloorSlider = new EdgeSlider("Floor", "Noise floor: moves the bottom of the spectrum's dB range. " +
"Higher settings show a deeper range and move the noise floor up the display.",
MINIMUM_SAMPLE_SIZE, MAXIMUM_SAMPLE_SIZE, 1, this::formatPlotBottom);
@@ -82,14 +86,50 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
model.binCountProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
model.noiseBandwidthProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
mNoiseFloorSlider.refreshLabel();
//Along the right edge of the spectrum section, below the configuration panel tab
StackPane.setAlignment(mNoiseFloorSlider, Pos.CENTER_RIGHT);
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
getSpectralDisplay().addSectionOverlay(DisplaySection.SPECTRUM, mNoiseFloorSlider);
getChildren().add(mNoiseFloorSlider);
//Channel power and SNR, measured from the spectrum frames
mSignalMeter.setWindowNoiseBandwidth(model.noiseBandwidthProperty().get());
model.noiseBandwidthProperty().addListener((ob, ov, nv) ->
mSignalMeter.setWindowNoiseBandwidth(nv.doubleValue()));
addDecibelListener(mSignalMeter);
installConfigPanel();
}
/**
* Shows the channel signal reading in the tuning layer. Called on the DFT processor thread.
*/
private void showReading(ChannelSignalMeter.Reading reading)
{
String text = String.format("%.1f dBFS", reading.dbfs());
//Channels that aren't sourced by a tuner show the channel power without the SNR
if(mHasNoiseDensity)
{
if(!reading.hasSnr())
{
//Waiting for the tuner noise floor estimate, which restarts after a tuner frequency change
text += " SNR --";
}
else
{
text += Double.isFinite(reading.snr()) && reading.snr() >= 0.0 ?
String.format(" SNR %.1f dB", reading.snr()) : " SNR < 0 dB";
}
}
String readout = text;
runOnFxThread(() -> {
if(mHasChannel && isDftRunning())
{
mTuningLayer.signalReadoutProperty().set(readout);
}
});
}
/**
* Listener for the channel's complex sample buffers.
*/
@@ -105,10 +145,25 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
* @param bandwidth of the channel in Hertz, or zero to hide the passband markers
*/
public void setChannel(long frequency, int sampleRate, int bandwidth)
{
setChannel(frequency, sampleRate, bandwidth, null);
}
/**
* Sets the channel to display.
* @param frequency of the channel
* @param sampleRate of the channel samples, or 0 for no channel
* @param bandwidth of the channel in Hertz
* @param noiseDensity supplier of the tuner noise density near the channel, in full-scale units per Hertz, for the
* signal-to-noise ratio. Null, or a supplier that returns NaN, shows the channel power without the SNR.
*/
public void setChannel(long frequency, int sampleRate, int bandwidth, DoubleSupplier noiseDensity)
{
synchronized(mLock)
{
mHasChannel = sampleRate > 0;
mSignalMeter.setChannel(sampleRate, bandwidth, noiseDensity);
mHasNoiseDensity = noiseDensity != null;
updateProcessing();
}
@@ -119,6 +174,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
model.centerFrequencyProperty().set(frequency);
model.sampleRateProperty().set(sampleRate);
mTuningLayer.channelBandwidthProperty().set(bandwidth);
mTuningLayer.signalReadoutProperty().set(null);
mTuningLayer.carrierOffsetValidProperty().set(false);
mTuningLayer.carrierOffsetProperty().set(0);
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
@@ -196,6 +252,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
else
{
stopDft();
runOnFxThread(() -> mTuningLayer.signalReadoutProperty().set(null));
}
}

View File

@@ -24,6 +24,7 @@ import io.github.dsheirer.gui.spectrum.layer.DecibelLayer;
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTResultsListener;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
import javafx.application.Platform;
@@ -55,8 +56,6 @@ public abstract class DftSpectralDisplay extends StackPane
private static final String PEAK_HOLD = "peak.hold";
private static final String SPECTRUM_ENABLED = "spectrum.enabled";
private static final String WATERFALL_ENABLED = "waterfall.enabled";
private static final String WATERFALL_RANGE = "waterfall.range";
private static final String WATERFALL_AVERAGING = "waterfall.averaging";
private static final String DIVIDER_POSITION = "divider.position";
private static final String DECIBEL_SCALE = "decibel.scale";
private static final String CONFIG_PINNED = "config.pinned";
@@ -123,9 +122,6 @@ public abstract class DftSpectralDisplay extends StackPane
});
mSpectralDisplay.averagingProperty().addListener((ob, ov, nv) -> save(AVERAGING, nv.intValue()));
mSpectralDisplay.peakHoldProperty().addListener((ob, ov, nv) -> save(PEAK_HOLD, nv));
mSpectralDisplay.waterfallRangeProperty().addListener((ob, ov, nv) -> save(WATERFALL_RANGE, nv.intValue()));
mSpectralDisplay.waterfallAveragingProperty().addListener((ob, ov, nv) ->
save(WATERFALL_AVERAGING, nv.intValue()));
mSpectralDisplay.dividerPositionProperty().addListener((ob, ov, nv) ->
save(DIVIDER_POSITION, String.valueOf(nv.doubleValue())));
mDecibelLayer.visibleProperty().addListener((ob, ov, nv) -> save(DECIBEL_SCALE, nv));
@@ -146,17 +142,6 @@ 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.
@@ -221,12 +206,6 @@ public abstract class DftSpectralDisplay extends StackPane
mSpectralDisplay.averagingProperty().set(Math.max(SpectralDisplay.AVERAGING_MINIMUM,
Math.min(SpectralDisplay.AVERAGING_MAXIMUM, averaging)));
mSpectralDisplay.peakHoldProperty().set(properties.get(key(PEAK_HOLD), false));
mSpectralDisplay.waterfallRangeProperty().set(Math.max(WaterfallScaler.RANGE_MINIMUM,
Math.min(WaterfallScaler.RANGE_MAXIMUM, properties.get(key(WATERFALL_RANGE),
WaterfallScaler.RANGE_DEFAULT))));
mSpectralDisplay.waterfallAveragingProperty().set(Math.max(WaterfallScaler.AVERAGING_MINIMUM,
Math.min(WaterfallScaler.AVERAGING_MAXIMUM, properties.get(key(WATERFALL_AVERAGING),
WaterfallScaler.AVERAGING_DEFAULT))));
mDecibelLayer.visibleProperty().set(properties.get(key(DECIBEL_SCALE), true));
try
@@ -322,6 +301,14 @@ public abstract class DftSpectralDisplay extends StackPane
/**
* DFT processor. Register it with the sample source to feed the display.
*/
/**
* Adds a listener for the dBFS spectrum frames, lowest frequency first. Frames arrive on the DFT processor thread.
*/
protected void addDecibelListener(DFTResultsListener listener)
{
mDecibelConverter.addListener(listener);
}
protected ComplexDftProcessor getDftProcessor()
{
return mDftProcessor;

View File

@@ -1,282 +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.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

@@ -42,8 +42,6 @@ import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Orientation;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
@@ -106,10 +104,6 @@ public class SpectralDisplay extends StackPane
private final SplitPane mSplitPane = new SplitPane();
private final CanvasPane mSpectrumPane = new CanvasPane(DisplaySection.SPECTRUM);
private final CanvasPane mWaterfallPane = new CanvasPane(DisplaySection.WATERFALL);
//Each section's canvas with overlay controls stacked on top
private final StackPane mSpectrumSection = new StackPane(mSpectrumPane);
private final StackPane mWaterfallSection = new StackPane(mWaterfallPane);
private final EdgeSlider mWaterfallRangeSlider;
private final StackPane mDisabledPane = new StackPane();
private final BooleanProperty mSpectrumEnabled = new SimpleBooleanProperty(true);
@@ -118,8 +112,6 @@ public class SpectralDisplay extends StackPane
private final IntegerProperty mAveraging = new SimpleIntegerProperty(AVERAGING_DEFAULT);
private final BooleanProperty mPeakHold = new SimpleBooleanProperty(false);
private final DoubleProperty mDividerPosition = new SimpleDoubleProperty(0.5);
private final IntegerProperty mWaterfallRange = new SimpleIntegerProperty(WaterfallScaler.RANGE_DEFAULT);
private final IntegerProperty mWaterfallAveraging = new SimpleIntegerProperty(WaterfallScaler.AVERAGING_DEFAULT);
private final StringProperty mMessage = new SimpleStringProperty();
//Values read on the DFT results thread
@@ -127,7 +119,6 @@ public class SpectralDisplay extends StackPane
private volatile boolean mWaterfallActive = true;
private volatile boolean mWaterfallPausedFlag = false;
private final SpectrumAverager mAverager = new SpectrumAverager();
private final WaterfallScaler mWaterfallScaler = new WaterfallScaler();
//Hand off from the DFT results thread to the JavaFX thread
private final AtomicReference<SpectrumAverager.Frame> mLatestSpectrum = new AtomicReference<>();
@@ -142,10 +133,8 @@ public class SpectralDisplay extends StackPane
private WritableImage[] mWaterfallTiles;
private int mWaterfallWidth;
private int mWaterfallHeight;
private byte[] mWaterfallLevels;
private byte[] mWaterfallIndexes;
private int[] mWaterfallPixels;
//ARGB color for each waterfall level code, for the current theme and range. Null when it needs to be rebuilt.
private int[] mWaterfallColors;
private int mWaterfallWriteRow = 0;
private double[] mPolygonX = new double[0];
private double[] mPolygonY = new double[0];
@@ -178,37 +167,6 @@ public class SpectralDisplay extends StackPane
themeChanged(disabledLabel);
getChildren().addAll(mDisabledPane, mSplitPane);
setMinSize(0, 0);
mSpectrumSection.setMinSize(0, 0);
mWaterfallSection.setMinSize(0, 0);
//Waterfall gain slider along the right edge of the waterfall. The slider value is inverted so that moving it
//up narrows the dB range, which raises the contrast of weak signals.
int rangeSum = WaterfallScaler.RANGE_MINIMUM + WaterfallScaler.RANGE_MAXIMUM;
mWaterfallRangeSlider = new EdgeSlider("Gain", "Waterfall gain: dB range from the noise floor to the top " +
"of the color palette. Higher settings use a smaller range, which gives weak signals more contrast " +
"against the noise and saturates strong signals sooner.", WaterfallScaler.RANGE_MINIMUM,
WaterfallScaler.RANGE_MAXIMUM, 1, value -> (rangeSum - Math.round(value)) + " dB");
mWaterfallRangeSlider.valueProperty().set(rangeSum - mWaterfallRange.get());
mWaterfallRangeSlider.valueProperty().addListener((ob, ov, nv) ->
mWaterfallRange.set(rangeSum - (int)Math.round(nv.doubleValue())));
mWaterfallRange.addListener((ob, ov, nv) -> {
int range = Math.max(WaterfallScaler.RANGE_MINIMUM, Math.min(WaterfallScaler.RANGE_MAXIMUM,
nv.intValue()));
if(range != nv.intValue())
{
mWaterfallRange.set(range);
return;
}
mWaterfallRangeSlider.valueProperty().set(rangeSum - range);
mWaterfallColors = null;
repaintWaterfallImage();
});
StackPane.setAlignment(mWaterfallRangeSlider, Pos.CENTER_RIGHT);
mWaterfallSection.getChildren().add(mWaterfallRangeSlider);
mWaterfallAveraging.addListener((ob, ov, nv) -> mWaterfallScaler.setAveraging(nv.intValue()));
mSpectrumEnabled.addListener((ob, ov, nv) -> updateSections());
mWaterfallEnabled.addListener((ob, ov, nv) -> updateSections());
@@ -303,7 +261,6 @@ public class SpectralDisplay extends StackPane
SpectralDisplayTheme theme = getTheme();
mDisabledPane.setBackground(new Background(new BackgroundFill(theme.getBackground(), null, null)));
disabledLabel.setTextFill(theme.getLine());
mWaterfallColors = null;
repaintWaterfallImage();
requestRender();
}
@@ -400,42 +357,6 @@ public class SpectralDisplay extends StackPane
return mPeakHold;
}
/**
* Waterfall dB range from the noise floor to the top of the color palette, from WaterfallScaler.RANGE_MINIMUM to
* RANGE_MAXIMUM. Smaller ranges give weak signals more contrast. JavaFX thread only.
*/
public IntegerProperty waterfallRangeProperty()
{
return mWaterfallRange;
}
/**
* Number of DFT frames averaged into each waterfall row, from WaterfallScaler.AVERAGING_MINIMUM to
* AVERAGING_MAXIMUM. Averaging steadies the noise floor so weak signals stand out, but the waterfall scrolls
* more slowly.
*/
public IntegerProperty waterfallAveragingProperty()
{
return mWaterfallAveraging;
}
/**
* Waterfall gain slider along the right edge of the waterfall section.
*/
public EdgeSlider getWaterfallRangeSlider()
{
return mWaterfallRangeSlider;
}
/**
* Adds a control on top of the spectrum or the waterfall section, for example an EdgeSlider. Set its StackPane
* alignment and margin before adding it. The control is hidden with its section.
*/
public void addSectionOverlay(DisplaySection section, javafx.scene.Node node)
{
(section == DisplaySection.SPECTRUM ? mSpectrumSection : mWaterfallSection).getChildren().add(node);
}
/**
* Divider position (0 - 1.0) between the spectrum and the waterfall when both are showing.
*/
@@ -474,7 +395,6 @@ public class SpectralDisplay extends StackPane
public void clear()
{
mAverager.reset();
mWaterfallScaler.reset();
mLatestSpectrum.set(null);
mWaterfallRows.clear();
@@ -492,11 +412,10 @@ public class SpectralDisplay extends StackPane
return;
}
//The first DFT results on startup can be NaN or infinite - drop them. Replacing them with zeros would add
//full scale (0 dBFS) values to the spectrum averaging and the waterfall floor tracking.
//The first DFT results on startup can be NaN or infinite
if(Float.isNaN(bins[0]) || Float.isInfinite(bins[0]))
{
return;
bins = new float[bins.length];
}
if(mSpectrumActive)
@@ -506,11 +425,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallActive && !mWaterfallPausedFlag)
{
byte[] row = mWaterfallScaler.process(bins);
if(row != null)
{
mWaterfallRows.offer(row);
mWaterfallRows.offer(toWaterfallRow(bins));
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
{
@@ -518,7 +433,6 @@ public class SpectralDisplay extends StackPane
}
}
}
}
/**
* Stops rendering and releases the layers and listeners.
@@ -538,7 +452,33 @@ public class SpectralDisplay extends StackPane
mLatestSpectrum.set(null);
mWaterfallRows.clear();
mWaterfallTiles = null;
mWaterfallLevels = null;
mWaterfallIndexes = null;
}
/**
* Converts the DFT results to a row of waterfall intensity indexes (0 - 255). Each bin is scaled relative to the
* average bin value so the noise floor stays at the bottom of the palette regardless of tuner gain.
*/
private static byte[] toWaterfallRow(float[] bins)
{
double sum = 0.0;
for(float bin: bins)
{
sum += bin;
}
float average = (float)(sum / bins.length) - 1.0f;
float scale = 256.0f / average;
byte[] row = new byte[bins.length];
for(int x = 0; x < bins.length; x++)
{
int value = (int)((average - bins[x]) * scale);
row[x] = (byte)Math.max(0, Math.min(255, value));
}
return row;
}
/**
@@ -551,11 +491,11 @@ public class SpectralDisplay extends StackPane
mSpectrumActive = spectrum;
mWaterfallActive = waterfall;
List<StackPane> items = new ArrayList<>();
List<Pane> items = new ArrayList<>();
if(spectrum)
{
items.add(mSpectrumSection);
items.add(mSpectrumPane);
}
else
{
@@ -565,16 +505,13 @@ public class SpectralDisplay extends StackPane
if(waterfall)
{
items.add(mWaterfallSection);
items.add(mWaterfallPane);
}
else
{
mWaterfallRows.clear();
}
//Keep the waterfall slider below the configuration panel tab when the waterfall is at the top
StackPane.setMargin(mWaterfallRangeSlider, new Insets(spectrum ? 8 : 44, 0, 8, 0));
mSplitPane.getItems().setAll(items);
mSplitPane.setVisible(!items.isEmpty());
@@ -606,7 +543,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallTiles != null)
{
mWaterfallTiles = null;
mWaterfallLevels = null;
mWaterfallIndexes = null;
mWaterfallWriteRow = 0;
}
@@ -644,8 +581,8 @@ public class SpectralDisplay extends StackPane
/**
* Writes the row into the waterfall ring buffer. The newest row is at mWaterfallWriteRow and older rows follow
* it, wrapping around the end of the image. The level codes are kept alongside the image so the history
* can be recolored when the theme or the waterfall range changes.
* it, wrapping around the end of the image. The intensity indexes are kept alongside the image so the history
* can be recolored when the theme changes.
*/
private void writeWaterfallRow(byte[] row)
{
@@ -653,7 +590,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallTiles == null || mWaterfallWidth != row.length)
{
mWaterfallLevels = new byte[row.length * rows];
mWaterfallIndexes = new byte[row.length * rows];
createWaterfallTiles(row.length, rows);
mWaterfallWriteRow = 0;
repaintWaterfallImage();
@@ -665,7 +602,7 @@ public class SpectralDisplay extends StackPane
int width = row.length;
mWaterfallWriteRow = (mWaterfallWriteRow - 1 + mWaterfallHeight) % mWaterfallHeight;
System.arraycopy(row, 0, mWaterfallLevels, mWaterfallWriteRow * width, width);
System.arraycopy(row, 0, mWaterfallIndexes, mWaterfallWriteRow * width, width);
writeWaterfallPixels(mWaterfallWriteRow);
}
@@ -688,7 +625,7 @@ public class SpectralDisplay extends StackPane
}
/**
* Colors one row of the waterfall image tiles from the stored level codes.
* Colors one row of the waterfall image tiles from the stored intensity indexes.
*/
private void writeWaterfallPixels(int imageRow)
{
@@ -699,12 +636,12 @@ public class SpectralDisplay extends StackPane
mWaterfallPixels = new int[width];
}
int[] colors = getWaterfallColors();
SpectralDisplayTheme theme = getTheme();
int offset = imageRow * width;
for(int x = 0; x < width; x++)
{
mWaterfallPixels[x] = colors[mWaterfallLevels[offset + x] & 0xFF];
mWaterfallPixels[x] = theme.getWaterfallColor(mWaterfallIndexes[offset + x]);
}
for(int tile = 0; tile < mWaterfallTiles.length; tile++)
@@ -716,33 +653,11 @@ public class SpectralDisplay extends StackPane
}
/**
* ARGB color for each waterfall level code, for the current theme and range.
*/
private int[] getWaterfallColors()
{
if(mWaterfallColors == null)
{
SpectralDisplayTheme theme = getTheme();
int range = mWaterfallRange.get();
int[] colors = new int[256];
for(int level = 0; level < colors.length; level++)
{
colors[level] = theme.getWaterfallColor(WaterfallScaler.paletteIndex(level, range));
}
mWaterfallColors = colors;
}
return mWaterfallColors;
}
/**
* Recolors the whole waterfall image from the stored level codes using the current theme and range.
* Recolors the whole waterfall image from the stored intensity indexes using the current theme.
*/
private void repaintWaterfallImage()
{
if(mWaterfallTiles != null && mWaterfallLevels != null)
if(mWaterfallTiles != null && mWaterfallIndexes != null)
{
for(int y = 0; y < mWaterfallHeight; y++)
{
@@ -774,10 +689,10 @@ public class SpectralDisplay extends StackPane
for(int y = 0; y < previousHeight; y++)
{
int source = (mWaterfallWriteRow + y) % previousHeight;
System.arraycopy(mWaterfallLevels, source * width, indexes, y * width, width);
System.arraycopy(mWaterfallIndexes, source * width, indexes, y * width, width);
}
mWaterfallLevels = indexes;
mWaterfallIndexes = indexes;
createWaterfallTiles(width, rows);
mWaterfallWriteRow = 0;
repaintWaterfallImage();

View File

@@ -34,7 +34,6 @@ 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;
@@ -234,25 +233,7 @@ public class SpectralDisplayConfigPanel extends VBox
pinButton.getStyleClass().add("spectral-config-pin");
pinButton.selectedProperty().bindBidirectional(mPinned);
pinButton.setTooltip(new Tooltip("Keep the settings panel open"));
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);
HBox header = new HBox(6, headerIcon, title, spacer, pinButton);
header.setAlignment(Pos.CENTER_LEFT);
header.setPadding(new Insets(2, 2, 4, 4));
@@ -372,27 +353,6 @@ public class SpectralDisplayConfigPanel extends VBox
"falling slowly"));
row = addRow(grid, row, peakHold.label(), peakHold.control());
//Waterfall
grid.add(sectionLabel("Waterfall"), 0, row++, 2, 1);
ComboBox<Integer> waterfallAveraging = new ComboBox<>();
for(int frames = WaterfallScaler.AVERAGING_MINIMUM; frames <= WaterfallScaler.AVERAGING_MAXIMUM; frames++)
{
waterfallAveraging.getItems().add(frames);
}
waterfallAveraging.setMaxWidth(Double.MAX_VALUE);
waterfallAveraging.setConverter(converter(frames -> frames == 1 ? "Off" : frames + " frames"));
waterfallAveraging.setValue(mSpectralDisplay.waterfallAveragingProperty().get());
waterfallAveraging.valueProperty().addListener((ob, ov, nv) -> {
if(nv != null)
{
mSpectralDisplay.waterfallAveragingProperty().set(nv);
}
});
waterfallAveraging.setTooltip(new Tooltip("FFT frames averaged into each waterfall row. Averaging steadies " +
"the noise floor so weak signals stand out, but the waterfall scrolls more slowly."));
trackPopup(waterfallAveraging.showingProperty());
row = addRow(grid, row, "Averaging", waterfallAveraging);
//Layer settings
for(SpectralDisplayLayer layer: mSpectralDisplay.getLayers())
{

View File

@@ -0,0 +1,190 @@
/*
* *****************************************************************************
* 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

@@ -33,31 +33,44 @@ public class WaterfallPalette
}
/**
* Palette based on the original Swing waterfall colors: a dark to bright blue ramp, a blue to yellow ramp, yellow
* fading to orange, then red. The blue ramp covers the bottom quarter of the palette, where the waterfall places
* the noise floor, so the noise stays blue and weak signals stand out from it.
* Palette of the original Swing waterfall: dark blue noise floor, a blue to yellow ramp, yellow fading to orange,
* then red.
*/
public static int[] classic()
{
int[] palette = new int[SIZE];
for(int x = 0; x < 64; x++)
for(int x = 0; x < 16; x++)
{
palette[x] = argb(0, 0, blend(64, 191, x / 63.0));
palette[x] = argb(0, 0, 127);
}
for(int x = 64; x < 100; x++)
for(int x = 16; x < 32; x++)
{
double t = (x - 64) / 36.0;
palette[x] = argb(blend(0, 255, t), blend(0, 255, t), blend(191, 0, t));
palette[x] = argb(0, 0, 191);
}
for(int x = 100; x < 220; x++)
int r = 0;
int g = 0;
int b = 191;
for(int x = 32; x < 60; x++)
{
palette[x] = argb(255, blend(255, 0, (x - 100) / 120.0), 0);
palette[x] = argb(r, g, b);
r += 9;
g += 9;
b -= 6;
}
for(int x = 220; x < SIZE; x++)
g = 255;
for(int x = 60; x < 188; x++)
{
palette[x] = argb(255, g, 0);
g -= 2;
}
for(int x = 188; x < SIZE; x++)
{
palette[x] = argb(255, 0, 0);
}
@@ -65,11 +78,6 @@ public class WaterfallPalette
return palette;
}
private static int blend(int from, int to, double fraction)
{
return (int)Math.round(from + (to - from) * fraction);
}
/**
* Palette that blends linearly between evenly spaced colors.
* @param colors web color strings (for example #440154), lowest intensity first

View File

@@ -1,289 +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 java.util.Arrays;
/**
* Converts DFT results in dB to rows of waterfall level codes, and level codes to palette indexes.
*
* Optionally averages several DFT frames (in linear power) into each row. Averaging reduces the random variation of
* the noise bins (about 5.6 dB for a single frame), which is the only thing that makes weak signals statistically
* easier to see, at the cost of fewer rows per second.
*
* The noise floor reference is a low percentile of the bins, so signals that fill much of the span don't raise it,
* smoothed across rows so the waterfall background doesn't flicker.
*
* Each row stores a level code per bin: the bin level relative to the floor reference in LEVEL_STEP_DB steps. The
* level codes are mapped to palette indexes over a dB range above the floor (see paletteIndex()) when the row is
* colored, so the range can change and the waterfall history can be recolored without the original DFT results.
*
* Not thread safe: process() on the DFT results thread only. reset() and setAveraging() are safe from any thread.
*/
public class WaterfallScaler
{
public static final int RANGE_MINIMUM = 20;
public static final int RANGE_MAXIMUM = 80;
public static final int RANGE_DEFAULT = 45;
public static final int AVERAGING_MINIMUM = 1;
public static final int AVERAGING_MAXIMUM = 4;
public static final int AVERAGING_DEFAULT = 2;
//Percentile of the bins used as the noise floor reference. Robust to signals in up to 75% of the bins.
static final double FLOOR_PERCENTILE = 0.25;
//Smoothing applied to the floor reference each row: about 5 rows. The percentile barely varies from row to row,
//so this mostly limits jumps from bursts of signals while still following tuner gain changes quickly.
static final float FLOOR_SMOOTHING = 0.2f;
//Floor reference changes larger than this jump straight to the new level instead of smoothing, for example when
//the first samples arrive after DFT frames of an empty buffer (-196 dB), or after a tuner or gain change.
static final float FLOOR_JUMP_DB = 10.0f;
//Level code resolution and the level code of the floor reference: codes cover -8 dB to +94 dB from the floor,
//which covers the palette at the maximum range.
static final float LEVEL_STEP_DB = 0.4f;
static final int FLOOR_LEVEL = 20;
//Palette index for the floor reference. Noise bins spread above the 25th percentile, so this places the noise in
//the lower part of the palette as texture with only the weakest noise bins at the background color.
static final float FLOOR_INDEX = 16.0f;
private static final float DB_TO_LN_POWER = (float)(Math.log(10.0) / 10.0);
private float mFloor = Float.NaN;
private volatile boolean mResetRequested;
private volatile int mAveraging = AVERAGING_DEFAULT;
private float[] mScratch = new float[0];
private float[] mPowerSum = new float[0];
private float[] mAverage = new float[0];
private int mFrameCount;
/**
* Restarts floor tracking and frame averaging on the next frame, for example after the source changes. Safe to
* call from any thread.
*/
public void reset()
{
mResetRequested = true;
}
/**
* Sets the number of DFT frames averaged into each waterfall row. Safe to call from any thread.
* @param frames from AVERAGING_MINIMUM to AVERAGING_MAXIMUM
*/
public void setAveraging(int frames)
{
mAveraging = Math.max(AVERAGING_MINIMUM, Math.min(AVERAGING_MAXIMUM, frames));
}
/**
* Current noise floor reference in dB, or NaN before the first row.
*/
public float getFloor()
{
return mFloor;
}
/**
* Adds the DFT results to the current row.
* @param bins in dB
* @return the row of level codes (unsigned bytes) when the row is complete, otherwise null
*/
public byte[] process(float[] bins)
{
if(mResetRequested)
{
mResetRequested = false;
mFloor = Float.NaN;
mFrameCount = 0;
}
int frames = mAveraging;
if(frames <= 1 && mFrameCount == 0)
{
return levels(bins);
}
if(mPowerSum.length != bins.length)
{
mPowerSum = new float[bins.length];
mAverage = new float[bins.length];
mFrameCount = 0;
}
if(mFrameCount == 0)
{
Arrays.fill(mPowerSum, 0.0f);
}
for(int x = 0; x < bins.length; x++)
{
mPowerSum[x] += (float)Math.exp(bins[x] * DB_TO_LN_POWER);
}
mFrameCount++;
//The averaging can drop below the frames already summed - complete the row with what has been summed
if(mFrameCount < frames)
{
return null;
}
float scale = 1.0f / mFrameCount;
for(int x = 0; x < bins.length; x++)
{
mAverage[x] = (float)(10.0 * Math.log10(mPowerSum[x] * scale));
}
mFrameCount = 0;
return levels(mAverage);
}
/**
* Updates the floor reference and converts the bins to level codes.
*/
private byte[] levels(float[] bins)
{
float percentile = percentile(bins);
if(Float.isNaN(mFloor) || Float.isInfinite(mFloor) || Math.abs(percentile - mFloor) > FLOOR_JUMP_DB)
{
mFloor = percentile;
}
else
{
mFloor += (percentile - mFloor) * FLOOR_SMOOTHING;
}
byte[] row = new byte[bins.length];
float floor = mFloor;
for(int x = 0; x < bins.length; x++)
{
int level = Math.round((bins[x] - floor) / LEVEL_STEP_DB) + FLOOR_LEVEL;
row[x] = (byte)Math.max(0, Math.min(255, level));
}
return row;
}
/**
* Palette index for a level code.
* @param level code (0 - 255)
* @param range in dB from the noise floor reference to the top of the palette. Smaller ranges give weak signals
* more contrast against the noise and saturate strong signals sooner.
* @return palette index (0 - 255)
*/
public static int paletteIndex(int level, double range)
{
double db = (level - FLOOR_LEVEL) * LEVEL_STEP_DB;
long index = Math.round(db * (WaterfallPalette.SIZE - 1) / range + FLOOR_INDEX);
return (int)Math.max(0, Math.min(WaterfallPalette.SIZE - 1, index));
}
/**
* Floor reference percentile of the bins, using quickselect on a scratch copy.
*/
private float percentile(float[] bins)
{
if(mScratch.length != bins.length)
{
mScratch = new float[bins.length];
}
System.arraycopy(bins, 0, mScratch, 0, bins.length);
return select(mScratch, (int)(FLOOR_PERCENTILE * (bins.length - 1)));
}
/**
* Quickselect: the k-th smallest value, partially reordering the array.
*/
static float select(float[] values, int k)
{
int left = 0;
int right = values.length - 1;
while(left < right)
{
//Median of three pivot
int middle = (left + right) >>> 1;
if(values[middle] < values[left])
{
swap(values, middle, left);
}
if(values[right] < values[left])
{
swap(values, right, left);
}
if(values[right] < values[middle])
{
swap(values, right, middle);
}
float pivot = values[middle];
int i = left;
int j = right;
while(i <= j)
{
while(values[i] < pivot)
{
i++;
}
while(values[j] > pivot)
{
j--;
}
if(i <= j)
{
swap(values, i, j);
i++;
j--;
}
}
if(k <= j)
{
right = j;
}
else if(k >= i)
{
left = i;
}
else
{
return values[k];
}
}
return values[k];
}
private static void swap(float[] values, int a, int b)
{
float temp = values[a];
values[a] = values[b];
values[b] = temp;
}
}

View File

@@ -30,6 +30,8 @@ import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
@@ -52,6 +54,7 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
private final IntegerProperty mChannelBandwidth = new SimpleIntegerProperty(0);
private final LongProperty mCarrierOffset = new SimpleLongProperty(0);
private final BooleanProperty mCarrierOffsetValid = new SimpleBooleanProperty(false);
private final StringProperty mSignalReadout = new SimpleStringProperty();
private final Text mMeasure = new Text();
private final double mTextHeight;
@@ -66,6 +69,15 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
mChannelBandwidth.addListener((ob, ov, nv) -> requestRender());
mCarrierOffset.addListener((ob, ov, nv) -> requestRender());
mCarrierOffsetValid.addListener((ob, ov, nv) -> requestRender());
mSignalReadout.addListener((ob, ov, nv) -> requestRender());
}
/**
* Channel signal level readout shown below the channel bandwidth label, or null for none.
*/
public StringProperty signalReadoutProperty()
{
return mSignalReadout;
}
/**
@@ -163,6 +175,24 @@ public class ChannelTuningLayer extends SpectralDisplayLayer
gc.setTextAlign(TextAlignment.LEFT);
gc.fillText(label, x, y);
}
//Signal readout centered on the channel, on the row below the carrier (PLL) label. Drawn last so that the
//carrier line doesn't cross it.
String readout = mSignalReadout.get();
if(edges != null && readout != null && !readout.isEmpty())
{
mMeasure.setText(readout);
double width = mMeasure.getLayoutBounds().getWidth();
double x = Math.max(3, Math.min(area.width() - width - 3, (edges[0] + edges[1] - width) / 2.0));
double y = 2 * (mTextHeight + 6);
//Nearly opaque, since the readout is centered on the channel where the carrier line usually is
gc.setFill(theme.getBackground(0.95));
gc.fillRoundRect(x - 3, y - 1, width + 6, mTextHeight + 2, 4, 4);
gc.setFill(opaque(theme.getChannelProcessing()));
gc.setTextAlign(TextAlignment.LEFT);
gc.fillText(readout, x, y);
}
}
@Override

View File

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

View File

@@ -20,54 +20,34 @@
package io.github.dsheirer.gui.theme;
/**
* 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.
* 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.
*/
public enum Theme
{
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)
{
}
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);
private final String mDisplayName;
private final String mLafClassName;
private final boolean mDark;
private final Palette mPalette;
Theme(String displayName, boolean dark, Palette palette)
Theme(String displayName, String lafClassName, boolean dark)
{
mDisplayName = displayName;
mLafClassName = lafClassName;
mDark = dark;
mPalette = palette;
}
/**
@@ -78,6 +58,14 @@ 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.
@@ -87,14 +75,6 @@ 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,11 +19,15 @@
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;
@@ -31,16 +35,33 @@ 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;
/**
* Applies the user's theme and GUI scale to every JavaFX scene.
* Centralized theme manager that drives both Swing and JavaFX appearance from the user
* preference selection.
*
* <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>
* <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>
*/
public class ThemeManager
{
@@ -50,6 +71,7 @@ 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;
@@ -65,7 +87,7 @@ public class ThemeManager
if(mDarkStylesheetUrl == null)
{
mLog.warn("Dark stylesheet [{}] not found on classpath - dark themes won't be applied.",
mLog.warn("Dark stylesheet [{}] not found on classpath - dark themes will only affect Swing.",
DARK_STYLESHEET);
}
}
@@ -98,8 +120,10 @@ public class ThemeManager
attachJavaFxWindowListener();
}
//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 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.
applyAll(mCurrentTheme);
}
@@ -166,7 +190,7 @@ public class ThemeManager
catch(IllegalStateException ignored)
{
//FX toolkit not started yet, which is the case when initialize() runs at application
//startup, before the toolkit starts. register() attaches the listener once the
//startup, before the first JFXPanel. register() attaches the listener once the
//first JavaFX scene is registered, which happens after the toolkit starts.
}
}
@@ -244,6 +268,35 @@ 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)
{
@@ -256,8 +309,19 @@ 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();
}
});
}
if(updated == mCurrentTheme && Math.abs(updatedScale - mCurrentGuiScale) < 1e-6)
{
return;
@@ -270,6 +334,8 @@ 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;
@@ -378,15 +444,20 @@ public class ThemeManager
{
try
{
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());
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);
//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
@@ -443,18 +514,305 @@ public class ThemeManager
}
}
private static String hex(int rgb)
private static String hex(Color c, int fallbackRgb)
{
return String.format("#%06x", rgb & 0xFFFFFF);
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);
}
}
/**
* Background color of text fields, tables and lists in the current theme, for checking the contrast of user
* selected colors such as alias colors.
* 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.
*/
public Color getInnerBackground()
private LookAndFeel instantiate(Theme theme)
{
return new Color(mCurrentTheme.getPalette().inner());
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);
}
private void pruneDeadReferencesAndCheckPresent(Scene scene)

View File

@@ -0,0 +1,178 @@
/*
* *****************************************************************************
* 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,14 +19,15 @@
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.stage.Stage;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
/**
* Utility for viewing sync detection results
@@ -58,7 +59,7 @@ public class SymbolViewerFX implements ISymbolResultsListener
{
CountDownLatch latch = new CountDownLatch(1);
FxToolkit.ensureStarted();
final JFXPanel fxPanel = new JFXPanel();
Platform.runLater(() -> {
Platform.setImplicitExit(false);
SymbolViewPanel viewer = new SymbolViewPanel();
@@ -76,14 +77,20 @@ public class SymbolViewerFX implements ISymbolResultsListener
// LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
// }
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();
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();
});
});
try
{

View File

@@ -19,14 +19,15 @@
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.stage.Stage;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
/**
* Utility for viewing sync detection results
@@ -76,7 +77,7 @@ public class FMSyncResultsViewer implements ISyncResultsListener
{
CountDownLatch latch = new CountDownLatch(1);
FxToolkit.ensureStarted();
final JFXPanel fxPanel = new JFXPanel();
Platform.runLater(() -> {
Platform.setImplicitExit(false);
FMSyncVisualizer syncVisualizer = new FMSyncVisualizer();
@@ -95,14 +96,20 @@ public class FMSyncResultsViewer implements ISyncResultsListener
// LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
// }
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();
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();
});
});
try
{

View File

@@ -19,14 +19,15 @@
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.stage.Stage;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
/**
* Utility for viewing sync detection results
@@ -76,7 +77,7 @@ public class SyncResultsViewer implements ISyncResultsListener
{
CountDownLatch latch = new CountDownLatch(1);
FxToolkit.ensureStarted();
final JFXPanel fxPanel = new JFXPanel();
Platform.runLater(() -> {
Platform.setImplicitExit(false);
SyncVisualizer syncVisualizer = new SyncVisualizer();
@@ -95,14 +96,20 @@ public class SyncResultsViewer implements ISyncResultsListener
// LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
// }
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();
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();
});
});
try
{

View File

@@ -32,6 +32,8 @@ 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;
@@ -44,6 +46,7 @@ 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;
@@ -165,6 +168,40 @@ 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,6 +24,7 @@ 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;
@@ -31,6 +32,8 @@ 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;
@@ -41,6 +44,7 @@ import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.ImageIcon;
public class IconModel
{
@@ -56,6 +60,7 @@ 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;
@@ -168,8 +173,81 @@ 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,12 +22,20 @@ 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
@@ -95,6 +103,65 @@ 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

@@ -0,0 +1,71 @@
/*******************************************************************************
* 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

@@ -0,0 +1,111 @@
/*
* *****************************************************************************
* 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

@@ -0,0 +1,103 @@
/*
* *****************************************************************************
* 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,12 +39,11 @@ 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.
@@ -156,12 +155,7 @@ 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();
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.ERROR, message);
alert.setTitle(title);
alert.setHeaderText("Thread deadlock detected");
alert.show();
});
JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
}
}
}

View File

@@ -200,8 +200,7 @@ public class UserPreferences implements Listener<PreferenceType>
/**
* 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.
* Swing window location/size user preferences
*/
public SwingPreference getSwingPreference()
{

View File

@@ -61,27 +61,6 @@ 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
*/
@@ -137,10 +116,10 @@ public class JavaFxPreferences
//Position the stage before we add the coordinate monitoring
reposition(stage);
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);
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);
mMaximized = new BooleanMonitor(PREFERENCE_STAGE_MAXIMIZED + key);
mStage.xProperty().addListener(mX);
@@ -172,7 +151,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 + mKey, stage.isMaximized());
boolean maximized = mPreferences.getBoolean(PREFERENCE_STAGE_MAXIMIZED, 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
@@ -195,24 +174,16 @@ public class JavaFxPreferences
public class NumberMonitor implements ChangeListener<Number>
{
private String mKey;
private Stage mStage;
/**
* 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)
public NumberMonitor(String key)
{
mKey = key;
mStage = stage;
}
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue)
{
if(newValue != null && (mStage == null || !mStage.isMaximized()))
if(newValue != null)
{
mPreferences.putDouble(mKey, newValue.doubleValue());
}

View File

@@ -0,0 +1,160 @@
/*
* ******************************************************************************
* 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

@@ -0,0 +1,69 @@
/*******************************************************************************
* 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

@@ -0,0 +1,52 @@
/*******************************************************************************
* 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

@@ -0,0 +1,52 @@
/*******************************************************************************
* 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

@@ -54,6 +54,8 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
private ReentrantLock mBufferListenerLock = new ReentrantLock();
private ReentrantLock mLock = new ReentrantLock();
protected Broadcaster<INativeBuffer> mNativeBufferBroadcaster = new Broadcaster();
private final TunerNoiseFloorEstimator mNoiseFloorEstimator = new TunerNoiseFloorEstimator(this::getFrequency,
this::getSampleRate, this::getUsableBandwidth);
protected FrequencyController mFrequencyController;
private int mMiddleUnusableHalfBandwidth;
private int mMeasuredFrequencyError;
@@ -726,6 +728,15 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
//Note: unprotected access to the broadcaster ... the broadcaster uses thread-save internal list
mNativeBufferBroadcaster.broadcast(complexSamples);
mNoiseFloorEstimator.receive(complexSamples);
}
/**
* Noise floor estimator for this tuner, which measures on demand from the buffers that this controller delivers.
*/
public TunerNoiseFloorEstimator getNoiseFloorEstimator()
{
return mNoiseFloorEstimator;
}
/**

View File

@@ -0,0 +1,463 @@
/*
* *****************************************************************************
* 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;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.dsp.fft.MixedRadixComplexFFT;
import io.github.dsheirer.dsp.window.WindowFactory;
import io.github.dsheirer.dsp.window.WindowType;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
import io.github.dsheirer.util.ThreadPool;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Estimates a tuner's noise floor from the tuner's sample buffers, independent of the channelizer that sources the
* tuner's channels. A windowed FFT with bins of about 25 kHz measures the tuner bandwidth and each bin's mean power is
* converted to a noise power density once a second.
*
* A channel's noise floor is the median of the 40 usable bins nearest the channel (about +/- 500 kHz), excluding the
* channel's own bins and their immediate neighbors. Near a band edge, the search continues toward the band center so
* that channels anywhere in the tuner's usable bandwidth get an estimate. Usable bins are the tuner's usable
* bandwidth, which is where the channel source managers place channels, minus the DC spur. Most bins hold only noise, so the median is a robust noise estimate unless more than
* half of the neighborhood is occupied. The estimate is local because real tuner noise floors aren't flat: a
* HydraSDR airband recording tilts about 6 dB across 8 MHz, which put a tuner-wide median 2 dB above the noise at one
* end of the band.
*
* The noise density is in full-scale units per Hertz, where a complex tone with a magnitude of 1.0 has a power of 1.0
* (0 dBFS). The channelizers preserve the tuner's full scale, so the noise density applies directly to channel
* samples.
*
* Measurement is on demand. A noise density request turns it on and it turns itself off when there are no requests
* for a few seconds. While it's off, the tuner's buffer delivery thread only checks a flag. While it's on, the
* delivery thread keeps a reference to the latest buffer and a scheduled task measures a few FFT blocks from it 20
* times a second. The estimator never registers as a buffer listener, since that starts and stops tuner streaming.
*/
public class TunerNoiseFloorEstimator
{
private static final Logger LOGGER = LoggerFactory.getLogger(TunerNoiseFloorEstimator.class);
private static final double BIN_WIDTH = 25000.0;
//Minimum size so that low sample rate tuners have enough bins for a channel neighborhood, with narrower bins
private static final int MINIMUM_FFT_SIZE = 64;
//Window with low sidelobes so that strong signals don't leak into the noise bins
private static final WindowType WINDOW_TYPE = WindowType.BLACKMAN_HARRIS_7;
private static final long PROCESSING_INTERVAL_MS = 50;
private static final int BLOCKS_PER_INTERVAL = 8;
private static final long ESTIMATE_INTERVAL_MS = 1000;
private static final long REQUEST_TIMEOUT_MS = 3000;
//Fraction of the sample rate, centered on DC, that is used when the tuner's usable bandwidth isn't known. The
//tuner's anti-alias filter rolls off the edges.
private static final double DEFAULT_USABLE_BANDWIDTH_FRACTION = 0.8;
//Bins on each side of DC that are skipped to avoid the tuner's DC spur
private static final int DC_EXCLUSION_BINS = 1;
//Usable bins nearest the channel that form its noise neighborhood (+/- 500 kHz at 25 kHz bins)
private static final int NEIGHBORHOOD_BINS = 40;
//Bins on each side of a channel's own bins that are excluded since they can hold the channel's signal
private static final int GUARD_BINS = 1;
//Fewest neighborhood bins for an estimate
private static final int MINIMUM_NEIGHBORHOOD_BINS = 8;
/**
* Noise density of each bin, with the tuner frequency and sample rate that it was measured at. Bins are in FFT
* order: bin 0 is DC and bins above size / 2 are negative frequencies.
*/
private record Estimate(long frequency, double sampleRate, double[] density, boolean[] usable) {}
private final LongSupplier mFrequency;
private final DoubleSupplier mSampleRate;
private final IntSupplier mUsableBandwidth;
private final boolean mScheduled;
private final AtomicReference<INativeBuffer> mLatestBuffer = new AtomicReference<>();
private final Object mLock = new Object();
private volatile boolean mActive;
private volatile long mLastRequestTimestamp;
private volatile Estimate mEstimate;
private ScheduledFuture<?> mProcessingTask;
//Measurement state, accessed only by the processing task
private long mMeasurementFrequency;
private double mMeasurementSampleRate;
private MixedRadixComplexFFT mFFT;
private float[] mWindow;
private double mWindowPower;
private float[] mBlock;
private int mBlockPointer;
private double[] mBinPowerAccumulator;
private int mAccumulatedBlocks;
private long mMeasurementStart;
/**
* Constructs an instance
* @param frequency supplier for the tuner's center frequency
* @param sampleRate supplier for the tuner's sample rate
* @param usableBandwidth supplier for the tuner's usable bandwidth in Hertz, or 0 or less if unknown
*/
public TunerNoiseFloorEstimator(LongSupplier frequency, DoubleSupplier sampleRate, IntSupplier usableBandwidth)
{
this(frequency, sampleRate, usableBandwidth, true);
}
/**
* Constructs an instance
* @param frequency supplier for the tuner's center frequency
* @param sampleRate supplier for the tuner's sample rate
* @param usableBandwidth supplier for the tuner's usable bandwidth in Hertz, or 0 or less if unknown
* @param scheduled true to measure on a scheduled task, or false for tests that call process() directly
*/
TunerNoiseFloorEstimator(LongSupplier frequency, DoubleSupplier sampleRate, IntSupplier usableBandwidth,
boolean scheduled)
{
mFrequency = frequency;
mSampleRate = sampleRate;
mUsableBandwidth = usableBandwidth;
mScheduled = scheduled;
}
/**
* Receives each tuner buffer on the tuner's buffer delivery thread. Keeps the buffer only while measuring.
*/
public void receive(INativeBuffer buffer)
{
if(mActive)
{
mLatestBuffer.set(buffer);
}
}
/**
* Noise power density near a channel, in full-scale units per Hertz. Turns on the measurement. Thread safe.
* @param frequency of the channel
* @param bandwidth of the channel in Hertz
* @return noise density, or NaN when there isn't an estimate yet, the tuner frequency or sample rate changed since
* the estimate, or the channel isn't within the usable tuner bandwidth.
*/
public double getNoiseDensity(long frequency, int bandwidth)
{
mLastRequestTimestamp = System.currentTimeMillis();
if(!mActive)
{
start();
}
Estimate estimate = mEstimate;
if(estimate == null || estimate.frequency() != mFrequency.getAsLong() ||
estimate.sampleRate() != mSampleRate.getAsDouble())
{
return Double.NaN;
}
int size = estimate.density().length;
double binWidth = estimate.sampleRate() / size;
//Signed bin offsets from DC of the bins that the channel overlaps
int low = (int)Math.round((frequency - bandwidth / 2.0 - estimate.frequency()) / binWidth);
int high = (int)Math.round((frequency + bandwidth / 2.0 - estimate.frequency()) / binWidth);
int center = (int)Math.round((double)(frequency - estimate.frequency()) / binWidth);
if(Math.abs(center) >= size / 2)
{
return Double.NaN;
}
double[] values = new double[NEIGHBORHOOD_BINS];
int count = 0;
int below = low - GUARD_BINS - 1;
int above = high + GUARD_BINS + 1;
//Alternate outward on each side of the channel, so that a channel near a band edge continues toward the center
while(count < NEIGHBORHOOD_BINS && (below > -size / 2 || above < size / 2))
{
if(below > -size / 2)
{
int bin = below < 0 ? below + size : below;
if(estimate.usable()[bin])
{
values[count++] = estimate.density()[bin];
}
below--;
}
if(count < NEIGHBORHOOD_BINS && above < size / 2)
{
int bin = above < 0 ? above + size : above;
if(estimate.usable()[bin])
{
values[count++] = estimate.density()[bin];
}
above++;
}
}
return count >= MINIMUM_NEIGHBORHOOD_BINS ? median(values, count) : Double.NaN;
}
/**
* Turns on the measurement.
*/
private void start()
{
synchronized(mLock)
{
if(!mActive)
{
mActive = true;
if(mScheduled)
{
mProcessingTask = ThreadPool.SCHEDULED.scheduleAtFixedRate(this::processScheduled,
PROCESSING_INTERVAL_MS, PROCESSING_INTERVAL_MS, TimeUnit.MILLISECONDS);
}
}
}
}
/**
* Turns off the measurement and discards the estimate, so that a stale estimate isn't used when it turns back on.
*/
private void stop()
{
synchronized(mLock)
{
//A request can arrive between the timeout check and here
if(System.currentTimeMillis() - mLastRequestTimestamp <= REQUEST_TIMEOUT_MS)
{
return;
}
mActive = false;
if(mProcessingTask != null)
{
mProcessingTask.cancel(false);
mProcessingTask = null;
}
mLatestBuffer.set(null);
mEstimate = null;
mBinPowerAccumulator = null;
}
}
private void processScheduled()
{
try
{
if(System.currentTimeMillis() - mLastRequestTimestamp > REQUEST_TIMEOUT_MS)
{
stop();
return;
}
process(System.currentTimeMillis());
}
catch(Throwable t)
{
LOGGER.error("Error estimating tuner noise floor", t);
}
}
/**
* Measures a few FFT blocks from the latest buffer and updates the estimate once a second. Package private for
* tests, which call it directly instead of waiting for the scheduled task.
* @param now timestamp in milliseconds
*/
void process(long now)
{
INativeBuffer buffer = mLatestBuffer.getAndSet(null);
if(buffer == null)
{
return;
}
long frequency = mFrequency.getAsLong();
double sampleRate = mSampleRate.getAsDouble();
if(sampleRate <= 0)
{
return;
}
if(mBinPowerAccumulator == null || frequency != mMeasurementFrequency || sampleRate != mMeasurementSampleRate)
{
configure(frequency, sampleRate, now);
}
int blocks = 0;
int size = mWindow.length;
mBlockPointer = 0;
Iterator<InterleavedComplexSamples> iterator = buffer.iteratorInterleaved();
while(blocks < BLOCKS_PER_INTERVAL && iterator.hasNext())
{
float[] samples = iterator.next().samples();
int pointer = 0;
while(blocks < BLOCKS_PER_INTERVAL && pointer < samples.length)
{
int count = Math.min(samples.length - pointer, 2 * (size - mBlockPointer));
System.arraycopy(samples, pointer, mBlock, 2 * mBlockPointer, count);
pointer += count;
mBlockPointer += count / 2;
if(mBlockPointer == size)
{
measureBlock();
mBlockPointer = 0;
blocks++;
}
}
}
if(now - mMeasurementStart >= ESTIMATE_INTERVAL_MS && mAccumulatedBlocks > 0)
{
publish();
mMeasurementStart = now;
}
}
/**
* Sets up the FFT for the tuner's sample rate and restarts the measurement.
*/
private void configure(long frequency, double sampleRate, long now)
{
mMeasurementFrequency = frequency;
mMeasurementSampleRate = sampleRate;
mMeasurementStart = now;
mEstimate = null;
int size = getFftSize(sampleRate);
if(mWindow == null || mWindow.length != size)
{
mFFT = new MixedRadixComplexFFT(size);
mWindow = WindowFactory.getWindow(WINDOW_TYPE, size);
mBlock = new float[size * 2];
double sumSquares = 0.0;
for(float coefficient: mWindow)
{
sumSquares += coefficient * coefficient;
}
mWindowPower = sumSquares;
}
mBinPowerAccumulator = new double[size];
mAccumulatedBlocks = 0;
}
/**
* FFT size that gives bins of about 25 kHz, or narrower bins at low sample rates, using a size that the mixed
* radix FFT supports.
*/
static int getFftSize(double sampleRate)
{
int size = Math.max(MINIMUM_FFT_SIZE, (int)Math.round(sampleRate / BIN_WIDTH));
while(size > MINIMUM_FFT_SIZE && !MixedRadixComplexFFT.isSupported(size))
{
size--;
}
return size;
}
/**
* Windows the block, runs the FFT and accumulates each bin's power.
*/
private void measureBlock()
{
for(int x = 0; x < mWindow.length; x++)
{
mBlock[2 * x] *= mWindow[x];
mBlock[2 * x + 1] *= mWindow[x];
}
mFFT.forward(mBlock, 0);
for(int bin = 0; bin < mWindow.length; bin++)
{
float i = mBlock[2 * bin];
float q = mBlock[2 * bin + 1];
mBinPowerAccumulator[bin] += i * i + q * q;
}
mAccumulatedBlocks++;
}
/**
* Converts the accumulated bin powers to noise densities and publishes the estimate. For white noise with variance
* s^2 per complex sample, a windowed FFT bin has a mean power of s^2 * sum(w^2), and the noise density is s^2 / fs.
*/
private void publish()
{
int size = mBinPowerAccumulator.length;
double[] density = new double[size];
boolean[] usable = new boolean[size];
double scale = 1.0 / (mAccumulatedBlocks * mWindowPower * mMeasurementSampleRate);
int usableBandwidth = mUsableBandwidth != null ? mUsableBandwidth.getAsInt() : 0;
double usableFraction = usableBandwidth > 0 ? Math.min(1.0, usableBandwidth / mMeasurementSampleRate) :
DEFAULT_USABLE_BANDWIDTH_FRACTION;
double maximumOffset = size * usableFraction / 2.0;
for(int bin = 0; bin < size; bin++)
{
density[bin] = mBinPowerAccumulator[bin] * scale;
int offset = bin < (size + 1) / 2 ? bin : bin - size;
usable[bin] = Math.abs(offset) > DC_EXCLUSION_BINS && Math.abs(offset) <= maximumOffset;
}
mEstimate = new Estimate(mMeasurementFrequency, mMeasurementSampleRate, density, usable);
Arrays.fill(mBinPowerAccumulator, 0.0);
mAccumulatedBlocks = 0;
}
/**
* Median of the first count values. Sorts the values.
*/
private static double median(double[] values, int count)
{
Arrays.sort(values, 0, count);
int middle = count / 2;
return (count % 2 == 1) ? values[middle] : (values[middle - 1] + values[middle]) / 2.0;
}
/**
* Indicates if the measurement is turned on.
*/
public boolean isActive()
{
return mActive;
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
* 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
@@ -23,35 +23,50 @@ import io.github.dsheirer.source.tuner.airspy.AirspyTunerController.Gain;
import io.github.dsheirer.source.tuner.airspy.AirspyTunerController.GainMode;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Region;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Airspy tuner editor
* Airspy tuner editor/controller
*/
public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfiguration>
{
private ComboBox<AirspySampleRate> mSampleRateCombo;
private ComboBox<GainMode> mGainModeCombo;
private GainSlider mMasterGainSlider;
private Label mMasterGainLabel;
private GainSlider mIFGainSlider;
private Label mIFGainLabel;
private GainSlider mLNAGainSlider;
private Label mLNAGainLabel;
private GainSlider mMixerGainSlider;
private Label mMixerGainLabel;
private CheckBox mLNAAGCCheckBox;
private CheckBox mMixerAGCCheckBox;
private CheckBox mBiasTCheckBox;
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(AirspyTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<AirspySampleRate> mSampleRateCombo;
private JComboBox<GainMode> mGainModeCombo;
private JSlider mMasterGainSlider;
private JLabel mMasterGainLabel;
private JLabel mMasterGainValueLabel;
private JSlider mIFGainSlider;
private JLabel mIFGainLabel;
private JLabel mIFGainValueLabel;
private JSlider mLNAGainSlider;
private JLabel mLNAGainValueLabel;
private JSlider mMixerGainSlider;
private JLabel mMixerGainValueLabel;
private JCheckBox mLNAAGCCheckBox;
private JCheckBox mMixerAGCCheckBox;
private JCheckBox mBiasTCheckBox;
/**
* Constructs an instance
@@ -63,7 +78,7 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
@Override
@@ -78,218 +93,408 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return AirspyTunerController.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
TunerSection gain = addSection("Gain");
gain.addRow("Mode", getGainModeCombo());
mMasterGainLabel = gain.addRow("Master", getMasterGainSlider(), new Region());
mIFGainLabel = gain.addRow("IF", getIFGainSlider(), new Region());
mMixerGainLabel = gain.addRow("Mixer", getMixerGainSlider(), getMixerAGCCheckBox());
mLNAGainLabel = gain.addRow("LNA", getLNAGainSlider(), getLNAAGCCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
getBiasTCheckBox().setDisable(!hasTuner());
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getTunerInfoButton().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
getBiasTCheckBox().setSelected(hasTuner() && hasConfiguration() && getConfiguration().isBiasT());
updateGainComponents((hasTuner() && hasConfiguration()) ? getConfiguration().getGain() : null);
if(hasTuner())
{
List<AirspySampleRate> rates = getTuner().getController().getSampleRates();
getSampleRateCombo().getItems().setAll(rates);
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new AirspySampleRate[rates.size()])));
if(hasConfiguration())
{
getSampleRateCombo().setValue(getSampleRate(getConfiguration().getSampleRate()));
AirspySampleRate sampleRate = getSampleRate(getConfiguration().getSampleRate());
getSampleRateCombo().setSelectedItem(sampleRate);
}
}
else
{
getSampleRateCombo().getItems().clear();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
}
updateSampleRateToolTip();
setLoading(false);
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel(""));
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Mode:"));
add(getGainModeCombo(), "wrap");
add(getMasterGainLabel());
add(getMasterGainSlider());
add(getMasterGainValueLabel());
add(getIFGainLabel());
add(getIFGainSlider());
add(getIFGainValueLabel());
add(getMixerAGCCheckBox());
add(getMixerGainSlider());
add(getMixerGainValueLabel());
add(getLNAAGCCheckBox());
add(getLNAGainSlider());
add(getLNAGainValueLabel());
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private CheckBox getBiasTCheckBox()
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Bias-T", e1);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e1.getMessage());
}
}
});
}
return mBiasTCheckBox;
}
private CheckBox getLNAAGCCheckBox()
private JCheckBox getLNAAGCCheckBox()
{
if(mLNAAGCCheckBox == null)
{
mLNAAGCCheckBox = new CheckBox("AGC");
mLNAAGCCheckBox.setTooltip(new Tooltip("Automatic LNA gain control"));
mLNAAGCCheckBox.setDisable(true);
mLNAAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("LNA AGC",
() -> getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected())))
mLNAAGCCheckBox = new JCheckBox("AGC LNA:");
mLNAAGCCheckBox.setEnabled(false);
mLNAAGCCheckBox.addActionListener(e ->
{
getLNAGainSlider().setDisable(getLNAAGCCheckBox().isSelected());
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected());
getLNAGainSlider().setEnabled(!getLNAAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting LNA AGC Enabled");
}
}
});
}
return mLNAAGCCheckBox;
}
private CheckBox getMixerAGCCheckBox()
private JCheckBox getMixerAGCCheckBox()
{
if(mMixerAGCCheckBox == null)
{
mMixerAGCCheckBox = new CheckBox("AGC");
mMixerAGCCheckBox.setTooltip(new Tooltip("Automatic mixer gain control"));
mMixerAGCCheckBox.setDisable(true);
mMixerAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("mixer AGC",
() -> getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected())))
mMixerAGCCheckBox = new JCheckBox("AGC Mixer:");
mMixerAGCCheckBox.setEnabled(false);
mMixerAGCCheckBox.addActionListener(e ->
{
getMixerGainSlider().setDisable(getMixerAGCCheckBox().isSelected());
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected());
getMixerGainSlider().setEnabled(!getMixerAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Mixer AGC Enabled");
}
}
});
}
return mMixerAGCCheckBox;
}
private GainSlider getLNAGainSlider()
private JLabel getLNAGainValueLabel()
{
if(mLNAGainValueLabel == null)
{
mLNAGainValueLabel = new JLabel("0");
mLNAGainValueLabel.setEnabled(false);
}
return mLNAGainValueLabel;
}
private JSlider getLNAGainSlider()
{
if(mLNAGainSlider == null)
{
mLNAGainSlider = new GainSlider(AirspyTunerController.LNA_GAIN_MIN, AirspyTunerController.LNA_GAIN_MAX,
AirspyTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setDisable(true);
mLNAGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("LNA gain", () -> getTuner().getController().setLNAGain(gain)))
mLNAGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.LNA_GAIN_MIN,
AirspyTunerController.LNA_GAIN_MAX, AirspyTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setEnabled(false);
mLNAGainSlider.setMajorTickSpacing(1);
mLNAGainSlider.setPaintTicks(true);
mLNAGainSlider.addChangeListener(event ->
{
int gain = mLNAGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setLNAGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy LNA gain to:" + gain, e);
JOptionPane.showMessageDialog(mLNAGainSlider, "Couldn't set LNA gain value to " + gain);
}
}
getLNAGainValueLabel().setText(String.valueOf(gain));
});
}
return mLNAGainSlider;
}
private GainSlider getMixerGainSlider()
private JLabel getMixerGainValueLabel()
{
if(mMixerGainValueLabel == null)
{
mMixerGainValueLabel = new JLabel("0");
mMixerGainValueLabel.setEnabled(false);
}
return mMixerGainValueLabel;
}
private JSlider getMixerGainSlider()
{
if(mMixerGainSlider == null)
{
mMixerGainSlider = new GainSlider(AirspyTunerController.MIXER_GAIN_MIN,
mMixerGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.MIXER_GAIN_MIN,
AirspyTunerController.MIXER_GAIN_MAX, AirspyTunerController.MIXER_GAIN_MIN);
mMixerGainSlider.setDisable(true);
mMixerGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("mixer gain", () -> getTuner().getController().setMixerGain(gain)))
mMixerGainSlider.setEnabled(false);
mMixerGainSlider.setMajorTickSpacing(1);
mMixerGainSlider.setPaintTicks(true);
mMixerGainSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent event)
{
int gain = mMixerGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy Mixer gain to:" + gain, e);
JOptionPane.showMessageDialog(mMixerGainSlider, "Couldn't set Mixer gain value to " + gain);
}
}
getMixerGainValueLabel().setText(String.valueOf(gain));
}
});
}
return mMixerGainSlider;
}
private GainSlider getIFGainSlider()
private JLabel getIFGainLabel()
{
if(mIFGainLabel == null)
{
mIFGainLabel = new JLabel("IF:");
}
return mIFGainLabel;
}
private JLabel getIFGainValueLabel()
{
if(mIFGainValueLabel == null)
{
mIFGainValueLabel = new JLabel("0");
mIFGainValueLabel.setEnabled(false);
}
return mIFGainValueLabel;
}
private JSlider getIFGainSlider()
{
if(mIFGainSlider == null)
{
mIFGainSlider = new GainSlider(AirspyTunerController.IF_GAIN_MIN, AirspyTunerController.IF_GAIN_MAX,
AirspyTunerController.IF_GAIN_MIN);
mIFGainSlider.setDisable(true);
mIFGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("IF gain", () -> getTuner().getController().setIFGain(gain)))
mIFGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.IF_GAIN_MIN,
AirspyTunerController.IF_GAIN_MAX, AirspyTunerController.IF_GAIN_MIN);
mIFGainSlider.setEnabled(false);
mIFGainSlider.setMajorTickSpacing(1);
mIFGainSlider.setPaintTicks(true);
mIFGainSlider.addChangeListener(event ->
{
int gain = mIFGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setIFGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy IF gain to:" + gain, e);
JOptionPane.showMessageDialog(mIFGainSlider, "Couldn't set IF gain value to " + gain);
}
}
getIFGainValueLabel().setText(String.valueOf(gain));
});
}
return mIFGainSlider;
}
private GainSlider getMasterGainSlider()
private JLabel getMasterGainLabel()
{
if(mMasterGainLabel == null)
{
mMasterGainLabel = new JLabel("Master:");
}
return mMasterGainLabel;
}
private JLabel getMasterGainValueLabel()
{
if(mMasterGainValueLabel == null)
{
mMasterGainValueLabel = new JLabel("0");
mMasterGainValueLabel.setEnabled(false);
}
return mMasterGainValueLabel;
}
private JSlider getMasterGainSlider()
{
if(mMasterGainSlider == null)
{
mMasterGainSlider = new GainSlider(AirspyTunerController.GAIN_MIN, AirspyTunerController.GAIN_MAX,
AirspyTunerController.GAIN_MIN);
mMasterGainSlider.setDisable(true);
mMasterGainSlider.setOnChange(value -> {
Gain gain = Gain.getGain(getGainModeCombo().getValue(), value);
mMasterGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.GAIN_MIN,
AirspyTunerController.GAIN_MAX, AirspyTunerController.GAIN_MIN);
mMasterGainSlider.setEnabled(false);
mMasterGainSlider.setMajorTickSpacing(1);
mMasterGainSlider.setPaintTicks(true);
if(hasTuner() && !isLoading() && applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
mMasterGainSlider.addChangeListener(event ->
{
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = mMasterGainSlider.getValue();
Gain gain = Gain.getGain(mode, value);
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy gain to:" + gain.name(), e);
JOptionPane.showMessageDialog(mMasterGainSlider, "Couldn't set gain value to " +
gain.getValue());
}
}
getMasterGainValueLabel().setText(String.valueOf(value));
});
}
return mMasterGainSlider;
}
private ComboBox<GainMode> getGainModeCombo()
private JComboBox<GainMode> getGainModeCombo()
{
if(mGainModeCombo == null)
{
mGainModeCombo = new ComboBox<>(FXCollections.observableArrayList(GainMode.values()));
mGainModeCombo.setMaxWidth(Double.MAX_VALUE);
mGainModeCombo.setDisable(true);
mGainModeCombo.setTooltip(new Tooltip("Linearity and sensitivity modes set all gains from the master " +
"gain. Custom mode sets each gain separately."));
mGainModeCombo.setOnAction(e -> {
mGainModeCombo = new JComboBox<>(GainMode.values());
mGainModeCombo.setEnabled(false);
mGainModeCombo.addActionListener(e ->
{
if(hasTuner() && !isLoading())
{
Gain gain = Gain.getGain(mGainModeCombo.getValue(), getMasterGainSlider().getValue());
setLoading(true);
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = getMasterGainSlider().getValue();
Gain gain = Gain.getGain(mode, value);
updateGainComponents(gain);
setLoading(false);
applyToTuner("gain mode", () -> {
AirspyTunerController controller = getTuner().getController();
if(gain == Gain.CUSTOM)
{
controller.setMixerAGC(getMixerAGCCheckBox().isSelected());
controller.setLNAAGC(getLNAAGCCheckBox().isSelected());
controller.setIFGain(getIFGainSlider().getValue());
controller.setMixerGain(getMixerGainSlider().getValue());
controller.setLNAGain(getLNAGainSlider().getValue());
}
else
{
controller.setGain(gain);
}
});
save();
}
});
@@ -298,24 +503,38 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return mGainModeCombo;
}
private ComboBox<AirspySampleRate> getSampleRateCombo()
private JComboBox<AirspySampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
AirspySampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(rate)))
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(hasTuner() && !isLoading())
{
AirspySampleRate rate = (AirspySampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(AirspyTunerEditor.this,
"Couldn't set sample rate to " + rate.getLabel());
mLog.error("Error setting airspy sample rate", e1);
}
}
}
});
}
@@ -323,29 +542,48 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
}
/**
* Updates the enabled state of each of the gain controls according to the specified gain mode. The master gain
* control is enabled for linearity and sensitivity and the individual gain controls are disabled, and vice-versa
* for custom mode.
* Hyperlink button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(AirspyTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
/**
* Updates the enabled state of each of the gain controls according to the
* specified gain mode. The master gain control is enabled for linearity
* and sensitivity and the individual gain controls are disabled, and
* vice-versa for custom mode.
*/
private void updateGainComponents(Gain gain)
{
if(hasTuner() && gain != null)
{
boolean isCustom = gain.equals(Gain.CUSTOM);
getGainModeCombo().setDisable(false);
getGainModeCombo().setValue(gain.getGainMode());
mMasterGainLabel.setDisable(isCustom);
getMasterGainSlider().setDisable(isCustom);
getMasterGainSlider().setValue(gain.getValue());
mIFGainLabel.setDisable(!isCustom);
getIFGainSlider().setDisable(!isCustom);
mLNAGainLabel.setDisable(!isCustom);
getLNAAGCCheckBox().setDisable(!isCustom);
getLNAGainSlider().setDisable(!isCustom || getConfiguration().isLNAAGC());
mMixerGainLabel.setDisable(!isCustom);
getMixerAGCCheckBox().setDisable(!isCustom);
getMixerGainSlider().setDisable(!isCustom || getConfiguration().isMixerAGC());
getGainModeCombo().setEnabled(true);
getGainModeCombo().setSelectedItem(gain.getGainMode());
getMasterGainLabel().setEnabled(!isCustom);
getMasterGainSlider().setEnabled(!isCustom);
getMasterGainSlider().setValue(gain.getValue());
getMasterGainValueLabel().setEnabled(!isCustom);
getIFGainLabel().setEnabled(isCustom);
getIFGainSlider().setEnabled(isCustom);
getIFGainValueLabel().setEnabled(isCustom);
getLNAAGCCheckBox().setEnabled(isCustom);
getLNAGainSlider().setEnabled(isCustom && !getConfiguration().isLNAAGC());
getLNAGainValueLabel().setEnabled(isCustom);
getMixerAGCCheckBox().setEnabled(isCustom);
getMixerGainSlider().setEnabled(isCustom && !getConfiguration().isMixerAGC());
getMixerGainValueLabel().setEnabled(isCustom);
if(isCustom)
{
getIFGainSlider().setValue(getConfiguration().getIFGain());
@@ -365,23 +603,25 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
}
else
{
getGainModeCombo().setDisable(true);
mMasterGainLabel.setDisable(true);
getMasterGainSlider().setDisable(true);
getGainModeCombo().setEnabled(false);
getMasterGainLabel().setEnabled(false);
getMasterGainSlider().setEnabled(false);
getMasterGainSlider().setValue(0);
mIFGainLabel.setDisable(true);
getIFGainSlider().setDisable(true);
getMasterGainValueLabel().setEnabled(false);
getIFGainLabel().setEnabled(false);
getIFGainSlider().setEnabled(false);
getIFGainSlider().setValue(0);
mLNAGainLabel.setDisable(true);
getLNAAGCCheckBox().setDisable(true);
getIFGainValueLabel().setEnabled(false);
getLNAAGCCheckBox().setEnabled(false);
getLNAAGCCheckBox().setSelected(false);
getLNAGainSlider().setDisable(true);
getLNAGainSlider().setEnabled(false);
getLNAGainSlider().setValue(0);
mMixerGainLabel.setDisable(true);
getMixerAGCCheckBox().setDisable(true);
getLNAGainValueLabel().setEnabled(false);
getMixerAGCCheckBox().setEnabled(false);
getMixerAGCCheckBox().setSelected(false);
getMixerGainSlider().setDisable(true);
getMixerGainSlider().setEnabled(false);
getMixerGainSlider().setValue(0);
getMixerGainValueLabel().setEnabled(false);
}
}
@@ -390,21 +630,21 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
{
if(hasConfiguration() && !isLoading())
{
AirspyTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
if(getSampleRateCombo().getValue() != null)
{
config.setSampleRate(getSampleRateCombo().getValue().getRate());
}
config.setGain(Gain.getGain(getGainModeCombo().getValue(), getMasterGainSlider().getValue()));
config.setIFGain(getIFGainSlider().getValue());
config.setMixerGain(getMixerGainSlider().getValue());
config.setLNAGain(getLNAGainSlider().getValue());
config.setMixerAGC(getMixerAGCCheckBox().isSelected());
config.setLNAAGC(getLNAAGCCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate(((AirspySampleRate)getSampleRateCombo().getSelectedItem()).getRate());
Gain gain = Gain.getGain((GainMode)mGainModeCombo.getSelectedItem(), getMasterGainSlider().getValue());
getConfiguration().setGain(gain);
getConfiguration().setIFGain(getIFGainSlider().getValue());
getConfiguration().setMixerGain(getMixerGainSlider().getValue());
getConfiguration().setLNAGain(getLNAGainSlider().getValue());
getConfiguration().setMixerAGC(getMixerAGCCheckBox().isSelected());
getConfiguration().setLNAAGC(getLNAAGCCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
@@ -428,7 +668,7 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
}
}
if(!rates.isEmpty())
if(rates.size() > 0)
{
return rates.get(0);
}
@@ -444,32 +684,56 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
{
if(hasTuner() && getTuner().getController().isLockedSampleRate())
{
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else
{
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
}
@Override
protected void tunerLockStateUpdated(boolean locked)
public void setTunerLockState(boolean locked)
{
getSampleRateCombo().setDisable(!hasTuner() || locked);
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected String getTunerInfo()
private String getTunerInfo()
{
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
{
return getDiscoveredTuner().getErrorMessage();
}
if(hasTuner())
{
StringBuilder sb = new StringBuilder();
AirspyDeviceInformation info = getTuner().getController().getDeviceInfo();
sb.append("<html><h3>Airspy Tuner</h3>");
sb.append("<b>Serial: </b>").append(info.getSerialNumber()).append("<br>");
sb.append("<b>Serial: </b>");
sb.append(info.getSerialNumber());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
String[] firmware = info.getVersion().split(" ");
sb.append("<b>Firmware: </b>").append(firmware.length > 1 ? firmware[0] : info.getVersion()).append("<br>");
sb.append("<b>Part: </b>").append(info.getPartNumber()).append("<br>");
sb.append("<b>Board: </b>").append(info.getBoardName()).append("<br>");
sb.append(firmware.length > 1 ? firmware[0] : info.getVersion());
sb.append("<br>");
sb.append("<b>Part: </b>");
sb.append(info.getPartNumber());
sb.append("<br>");
sb.append("<b>Board: </b>");
sb.append(info.getBoardName());
sb.append("<br>");
return sb.toString();
}
return null;
}
}

View File

@@ -16,40 +16,50 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.airspy.hf;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
/**
* Airspy HF+ tuner editor
* Tuner editor for Airspy HF+/Discovery tuners
*/
public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTunerConfiguration>
{
private ComboBox<AirspyHfSampleRate> mSampleRateCombo;
private ComboBox<Attenuation> mAttenuationCombo;
private CheckBox mAgcCheckBox;
private CheckBox mLnaCheckBox;
private CheckBox mBiasTCheckBox;
private static final Logger mLog = LoggerFactory.getLogger(AirspyHfTunerEditor.class);
private JComboBox<AirspyHfSampleRate> mSampleRateCombo;
private JComboBox<Attenuation> mAttenuationCombo;
private JToggleButton mAgcToggleButton;
private JToggleButton mLnaToggleButton;
private JToggleButton mBiasTToggleButton;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
*
* @param userPreferences
* @param tunerManager for requesting configuration saves.
* @param discoveredTuner
*/
public AirspyHfTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
@Override
@@ -66,41 +76,61 @@ public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTuner
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][grow]"));
TunerSection gain = addSection("Gain");
gain.addRow("Attenuation", getAttenuationCombo(), getAgcCheckBox());
gain.addControl(getLnaCheckBox());
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
@Override
protected String getTunerInfo()
{
AirspyHfTunerController controller = getTuner().getController();
return "<html><h3>Airspy HF+ Tuner</h3>" +
"<b>Board: </b>" + controller.getBoardId() + "<br>" +
"<b>Serial: </b>" + controller.getSerialNumber() + "<br>" +
"<b>Firmware: </b>" + controller.getFirmwareVersion() + "<br>";
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JSeparator(), "span");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new MigLayout("insets 0", "[left]", ""));
buttonPanel.add(getAgcToggleButton());
buttonPanel.add(getLnaToggleButton());
buttonPanel.add(getBiasTToggleButton());
add(new JLabel(" "));
add(buttonPanel, "wrap");
add(new JLabel("Attenuation:"));
add(getAttenuationCombo(), "wrap");
}
@Override
protected void save()
{
if(hasConfiguration() && hasTuner() && !isLoading())
if(hasConfiguration() && !isLoading())
{
AirspyHfTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setSampleRate((int)getTuner().getController().getSampleRate());
config.setAttenuation(getAttenuationCombo().getValue());
config.setAgc(getAgcCheckBox().isSelected());
config.setLna(getLnaCheckBox().isSelected());
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((int)getTuner().getController().getSampleRate());
Attenuation attenuation = (Attenuation)getAttenuationCombo().getSelectedItem();
getConfiguration().setAttenuation(attenuation);
getConfiguration().setAgc(getAgcToggleButton().isSelected());
getConfiguration().setLna(getLnaToggleButton().isSelected());
//Only update bias-T when the device supports it, so the saved setting isn't lost on unsupported firmware.
if(getTuner().getController().isBiasTSupported())
{
config.setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTToggleButton().isSelected());
}
saveConfiguration();
@@ -110,171 +140,256 @@ public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTuner
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
if(hasTuner())
{
AirspyHfTunerController controller = getTuner().getController();
getSampleRateCombo().setDisable(controller.isLockedSampleRate());
getSampleRateCombo().getItems().setAll(controller.getAvailableSampleRates());
getSampleRateCombo().setValue(controller.getCurrentAirspySampleRate());
getAgcCheckBox().setDisable(false);
getAgcCheckBox().setSelected(controller.getAgc());
getLnaCheckBox().setDisable(false);
getLnaCheckBox().setSelected(controller.getLna());
boolean biasTSupported = controller.isBiasTSupported();
getBiasTCheckBox().setDisable(!biasTSupported);
getBiasTCheckBox().setSelected(biasTSupported && controller.getBiasT());
getBiasTCheckBox().setTooltip(new Tooltip(biasTSupported ? "Enable Bias-T power output for active " +
"antennas" : "Bias-T not supported by this device or firmware"));
getAttenuationCombo().setDisable(controller.getAgc());
getAttenuationCombo().setValue(controller.getAttenuation());
getTunerIdLabel().setText("Airspy " + getTuner().getController().getBoardId() + " SER# " +
getTuner().getController().getSerialNumber() + " FW " + getTuner().getController().getFirmwareVersion());
getSampleRateCombo().setEnabled(!getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().removeAllItems();
for(AirspyHfSampleRate sampleRate: getTuner().getController().getAvailableSampleRates())
{
getSampleRateCombo().addItem(sampleRate);
}
getAgcToggleButton().setEnabled(true);
getAgcToggleButton().setSelected(getTuner().getController().getAgc());
getLnaToggleButton().setEnabled(true);
getLnaToggleButton().setSelected(getTuner().getController().getLna());
boolean biasTSupported = getTuner().getController().isBiasTSupported();
getBiasTToggleButton().setEnabled(biasTSupported);
getBiasTToggleButton().setSelected(biasTSupported && getTuner().getController().getBiasT());
getBiasTToggleButton().setToolTipText(biasTSupported ? "Enable Bias-T power output for active antennas" :
"Bias-T not supported by this device or firmware");
getSampleRateCombo().setSelectedItem(getTuner().getController().getCurrentAirspySampleRate());
getAttenuationCombo().setEnabled(!getTuner().getController().getAgc());
getAttenuationCombo().setSelectedItem(getTuner().getController().getAttenuation());
}
else
{
getAgcCheckBox().setDisable(true);
getAgcCheckBox().setSelected(false);
getLnaCheckBox().setDisable(true);
getLnaCheckBox().setSelected(false);
getBiasTCheckBox().setDisable(true);
getBiasTCheckBox().setSelected(false);
getBiasTCheckBox().setTooltip(new Tooltip("No tuner available"));
getSampleRateCombo().setDisable(true);
getAttenuationCombo().setDisable(true);
getAttenuationCombo().setValue(Attenuation.A0);
getTunerIdLabel().setText("Airspy HF+");
getAgcToggleButton().setEnabled(false);
getAgcToggleButton().setSelected(false);
getLnaToggleButton().setEnabled(false);
getLnaToggleButton().setSelected(false);
getBiasTToggleButton().setEnabled(false);
getBiasTToggleButton().setSelected(false);
getBiasTToggleButton().setToolTipText("No tuner available");
getSampleRateCombo().setEnabled(false);
getAttenuationCombo().setEnabled(false);
getAttenuationCombo().setSelectedItem(Attenuation.A0);
}
updateSampleRateToolTip();
setLoading(false);
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setTooltip(new Tooltip("No tuner available"));
getSampleRateCombo().setToolTipText("No tuner available");
}
}
@Override
protected void tunerLockStateUpdated(boolean locked)
public void setTunerLockState(boolean locked)
{
getSampleRateCombo().setDisable(!hasTuner() || locked);
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
private ComboBox<AirspyHfSampleRate> getSampleRateCombo()
/**
* Sample rate combo for selecting among available sample rates.
* @return sample rate combo
*/
private JComboBox<AirspyHfSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
AirspyHfSampleRate sampleRate = mSampleRateCombo.getValue();
if(!isLoading() && hasTuner() && sampleRate != null &&
applyToTuner("sample rate [" + sampleRate + "]",
() -> getTuner().getController().setSampleRate(sampleRate)))
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e ->
{
if(!isLoading())
{
AirspyHfSampleRate sampleRate = (AirspyHfSampleRate)mSampleRateCombo.getSelectedItem();
if(sampleRate != null)
{
try
{
getTuner().getController().setSampleRate(sampleRate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(sampleRate.getSampleRate());
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy Hf Sample Rate [" + sampleRate + "]", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy Tuner Controller - couldn't apply the sample rate setting [" +
sampleRate + "] " + se.getLocalizedMessage());
}
}
}
});
}
return mSampleRateCombo;
}
private ComboBox<Attenuation> getAttenuationCombo()
/**
* Combobox with available attenuation items
* @return combo box
*/
private JComboBox<Attenuation> getAttenuationCombo()
{
if(mAttenuationCombo == null)
{
mAttenuationCombo = new ComboBox<>(FXCollections.observableArrayList(Attenuation.values()));
mAttenuationCombo.setMaxWidth(Double.MAX_VALUE);
mAttenuationCombo.setTooltip(new Tooltip("Attenuation applies when the AGC is off"));
mAttenuationCombo.setDisable(true);
mAttenuationCombo.setOnAction(e -> {
Attenuation selected = mAttenuationCombo.getValue();
if(!isLoading() && hasTuner() && selected != null &&
applyToTuner("attenuation [" + selected + "]",
() -> getTuner().getController().setAttenuation(selected)))
mAttenuationCombo = new JComboBox<>(Attenuation.values());
mAttenuationCombo.setToolTipText("Attenuation applies when the AGC is off");
mAttenuationCombo.setEnabled(false);
mAttenuationCombo.addActionListener(e -> {
if(!isLoading())
{
Attenuation selected = (Attenuation)mAttenuationCombo.getSelectedItem();
try
{
getTuner().getController().setAttenuation(selected);
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy Hf attenuation [" + selected + "]", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy Tuner Controller - couldn't apply attenuation setting [" +
selected + "] " + se.getLocalizedMessage());
}
}
});
}
return mAttenuationCombo;
}
private CheckBox getAgcCheckBox()
/**
* Automatic Gain Control (AGC) toggle button
*/
private JToggleButton getAgcToggleButton()
{
if(mAgcCheckBox == null)
if(mAgcToggleButton == null)
{
mAgcCheckBox = new CheckBox("AGC");
mAgcCheckBox.setTooltip(new Tooltip("Automatic gain control"));
mAgcCheckBox.setDisable(true);
mAgcCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() &&
applyToTuner("AGC", () -> getTuner().getController().setAgc(mAgcCheckBox.isSelected())))
mAgcToggleButton = new JToggleButton("AGC");
mAgcToggleButton.setToolTipText("Automatic Gain Control");
mAgcToggleButton.setEnabled(false);
mAgcToggleButton.addActionListener(e -> {
if(!isLoading())
{
getAttenuationCombo().setDisable(mAgcCheckBox.isSelected());
try
{
getTuner().getController().setAgc(mAgcToggleButton.isSelected());
getAttenuationCombo().setEnabled(!mAgcToggleButton.isSelected());
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy HF AGC", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy HF Tuner Controller - couldn't change AGC setting" + se.getLocalizedMessage());
}
}
});
}
return mAgcCheckBox;
return mAgcToggleButton;
}
private CheckBox getLnaCheckBox()
/**
* Low Noise Amplifier (LNA) toggle button
*/
private JToggleButton getLnaToggleButton()
{
if(mLnaCheckBox == null)
if(mLnaToggleButton == null)
{
mLnaCheckBox = new CheckBox("LNA (low noise amplifier)");
mLnaCheckBox.setTooltip(new Tooltip("Turn on the low noise amplifier"));
mLnaCheckBox.setDisable(true);
mLnaCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() &&
applyToTuner("LNA", () -> getTuner().getController().setLna(mLnaCheckBox.isSelected())))
mLnaToggleButton = new JToggleButton("LNA");
mLnaToggleButton.setToolTipText("Low Noise Amplifier");
mLnaToggleButton.setEnabled(false);
mLnaToggleButton.addActionListener(e -> {
if(!isLoading())
{
try
{
getTuner().getController().setLna(mLnaToggleButton.isSelected());
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy HF LNA", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy HF Tuner Controller - couldn't change LNA setting" + se.getLocalizedMessage());
}
}
});
}
return mLnaCheckBox;
return mLnaToggleButton;
}
private CheckBox getBiasTCheckBox()
/**
* Bias-T toggle button, enabled only when the device firmware supports a bias-T.
*/
private JToggleButton getBiasTToggleButton()
{
if(mBiasTCheckBox == null)
if(mBiasTToggleButton == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setOnAction(e -> {
mBiasTToggleButton = new JToggleButton("Bias-T");
mBiasTToggleButton.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTToggleButton.setEnabled(false);
mBiasTToggleButton.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
if(applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
try
{
getTuner().getController().setBiasT(mBiasTToggleButton.isSelected());
save();
}
else
catch(SourceException se)
{
mBiasTCheckBox.setSelected(getTuner().getController().getBiasT());
mLog.error("Error setting Airspy HF Bias-T", se);
mBiasTToggleButton.setSelected(getTuner().getController().getBiasT());
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy HF Tuner Controller - couldn't change Bias-T setting " + se.getLocalizedMessage());
}
}
});
}
return mBiasTCheckBox;
return mBiasTToggleButton;
}
}

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.bladerf;
import io.github.dsheirer.bladerf.GainMode;
@@ -24,26 +25,41 @@ import io.github.dsheirer.bladerf.Range;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.awt.Component;
import java.io.Serial;
import java.util.List;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.util.StringConverter;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
/**
* bladeRF tuner editor. sdrtrunk uses the RX1 connector as a single tuner.
* bladeRF tuner editor
*/
public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerConfiguration>
{
private ComboBox<BladeRfSampleRate> mSampleRateCombo;
private CheckBox mBiasTCheckBox;
private ComboBox<GainModeInfo> mGainModeCombo;
private GainSlider mGainSlider;
private Label mGainLabel;
@Serial
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(BladeRfTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<BladeRfSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JComboBox<GainModeInfo> mGainModeCombo;
private JSlider mGainSlider;
private JLabel mGainValueLabel;
/**
* Constructs an instance
@@ -55,7 +71,7 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
@Override
@@ -74,33 +90,78 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]", "[][][][][][][][][][][][grow]"));
TunerSection gain = addSection("Gain");
gain.addRow("Mode", getGainModeCombo());
mGainLabel = gain.addRow("Gain", getGainSlider());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Mode:"));
add(getGainModeCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainSlider());
add(getGainValueLabel());
//Empty row that takes all extra vertical space so that the controls stay stacked at the top of the editor.
add(new JLabel(), "span,pushy");
}
@Override
protected void tunerStatusUpdated()
{
if(hasStartedTuner())
setLoading(true);
boolean started = hasStartedTuner();
getTunerIdLabel().setText(started ? getTuner().getPreferredName() : getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(started);
if(started)
{
BladeRfTunerController controller = getTuner().getController();
List<BladeRfSampleRate> rates = controller.getSampleRates();
getSampleRateCombo().getItems().setAll(rates);
getSampleRateCombo().setValue(controller.getBladeRfSampleRate());
getSampleRateCombo().setDisable(controller.isLockedSampleRate());
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new BladeRfSampleRate[0])));
getSampleRateCombo().setSelectedItem(controller.getBladeRfSampleRate());
getSampleRateCombo().setEnabled(!controller.isLockedSampleRate());
getBiasTCheckBox().setVisible(controller.isBiasTSupported());
getBiasTCheckBox().setDisable(false);
getBiasTCheckBox().setEnabled(true);
List<GainModeInfo> modes = controller.getGainModes();
getGainModeCombo().getItems().setAll(modes);
getGainModeCombo().setDisable(false);
getGainModeCombo().setModel(new DefaultComboBoxModel<>(modes.toArray(new GainModeInfo[0])));
getGainModeCombo().setEnabled(true);
Range range = controller.getGainRange();
getGainSlider().setRange((int)range.min(), (int)range.max());
getGainSlider().setMinimum((int)range.min());
getGainSlider().setMaximum((int)range.max());
if(hasConfiguration())
{
@@ -111,7 +172,7 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
{
if(mode.mode() == getConfiguration().getGainMode())
{
getGainModeCombo().setValue(mode);
getGainModeCombo().setSelectedItem(mode);
}
}
}
@@ -120,173 +181,249 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
}
else
{
getSampleRateCombo().getItems().clear();
getSampleRateCombo().setDisable(true);
getBiasTCheckBox().setDisable(true);
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
getSampleRateCombo().setEnabled(false);
getBiasTCheckBox().setEnabled(false);
getBiasTCheckBox().setSelected(false);
getGainModeCombo().getItems().clear();
getGainModeCombo().setDisable(true);
getGainSlider().setDisable(true);
mGainLabel.setDisable(true);
getGainModeCombo().setModel(new DefaultComboBoxModel<>());
getGainModeCombo().setEnabled(false);
getGainSlider().setEnabled(false);
getGainValueLabel().setEnabled(false);
}
setLoading(false);
}
/**
* Indicates if the tuner is started, which is when the controller has the gain range.
* Indicates if the tuner has finished starting, since a status update can arrive while it's starting or restarting.
*/
private boolean hasStartedTuner()
{
return hasTuner() && getTuner().getController().getGainRange() != null;
}
/**
* Enables the gain slider when the gain mode is manual and refreshes the gain value label.
*/
private void updateGainControls()
{
GainModeInfo mode = getGainModeCombo().getValue();
GainModeInfo mode = (GainModeInfo)getGainModeCombo().getSelectedItem();
boolean manual = hasTuner() && mode != null && mode.mode() == GainMode.MANUAL;
getGainSlider().setDisable(!manual);
mGainLabel.setDisable(!manual);
getGainSlider().setFormatter(value -> manual ? value + " dB" : "AGC");
getGainSlider().setEnabled(manual);
getGainValueLabel().setEnabled(manual);
getGainValueLabel().setText(manual ? getGainSlider().getValue() + " dB" : "AGC");
}
private ComboBox<BladeRfSampleRate> getSampleRateCombo()
/**
* Button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(_ -> JOptionPane.showMessageDialog(BladeRfTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private JComboBox<BladeRfSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setTooltip(new Tooltip("Select a sample rate for the tuner"));
mSampleRateCombo.setOnAction(e -> {
BladeRfSampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate + "]", () -> getTuner().getController().setSampleRate(rate)))
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
BladeRfSampleRate rate = (BladeRfSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
mLog.error("Error setting bladeRF sample rate", e1);
JOptionPane.showMessageDialog(BladeRfTunerEditor.this, "Couldn't set sample rate to " + rate);
}
}
});
}
return mSampleRateCombo;
}
private CheckBox getBiasTCheckBox()
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas. Also powers the " +
"RX2 connector."));
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas. Also powers the RX2 connector.");
mBiasTCheckBox.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Bias-T", e1);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e1.getMessage());
}
}
});
}
return mBiasTCheckBox;
}
private ComboBox<GainModeInfo> getGainModeCombo()
private JComboBox<GainModeInfo> getGainModeCombo()
{
if(mGainModeCombo == null)
{
mGainModeCombo = new ComboBox<>();
mGainModeCombo.setMaxWidth(Double.MAX_VALUE);
mGainModeCombo.setDisable(true);
mGainModeCombo.setConverter(new StringConverter<>()
mGainModeCombo = new JComboBox<>();
mGainModeCombo.setEnabled(false);
mGainModeCombo.setRenderer(new DefaultListCellRenderer()
{
@Override
public String toString(GainModeInfo mode)
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean selected,
boolean focused)
{
return mode == null ? "" : mode.name();
}
@Override
public GainModeInfo fromString(String text)
{
return null;
Object label = value instanceof GainModeInfo mode ? mode.name() : value;
return super.getListCellRendererComponent(list, label, index, selected, focused);
}
});
mGainModeCombo.setOnAction(e -> {
GainModeInfo mode = mGainModeCombo.getValue();
if(hasTuner() && !isLoading() && mode != null &&
applyToTuner("gain mode [" + mode.name() + "]",
() -> getTuner().getController().setGainMode(mode.mode())))
mGainModeCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
GainModeInfo mode = (GainModeInfo)mGainModeCombo.getSelectedItem();
try
{
getTuner().getController().setGainMode(mode.mode());
updateGainControls();
save();
}
catch(Exception e1)
{
mLog.error("Error setting bladeRF gain mode", e1);
JOptionPane.showMessageDialog(mGainModeCombo, "Couldn't set gain mode to " + mode.name());
}
}
});
}
return mGainModeCombo;
}
private GainSlider getGainSlider()
private JSlider getGainSlider()
{
if(mGainSlider == null)
{
mGainSlider = new GainSlider(0, 60, BladeRfTunerController.GAIN_DEFAULT);
mGainSlider.setDisable(true);
mGainSlider.setFormatter(value -> value + " dB");
mGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
mGainSlider = new JSlider(JSlider.HORIZONTAL, 0, 60, BladeRfTunerController.GAIN_DEFAULT);
mGainSlider.setEnabled(false);
mGainSlider.setMajorTickSpacing(5);
mGainSlider.setPaintTicks(true);
mGainSlider.addChangeListener(_ ->
{
int gain = mGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set bladeRF gain to:" + gain, e);
JOptionPane.showMessageDialog(mGainSlider, "Couldn't set gain value to " + gain);
}
}
updateGainControls();
});
}
return mGainSlider;
}
private JLabel getGainValueLabel()
{
if(mGainValueLabel == null)
{
mGainValueLabel = new JLabel("0 dB");
mGainValueLabel.setEnabled(false);
}
return mGainValueLabel;
}
@Override
public void save()
{
if(hasConfiguration() && !isLoading())
{
BladeRfTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel)getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
if(getSampleRateCombo().getValue() instanceof BladeRfSampleRate rate)
if(getSampleRateCombo().getSelectedItem() instanceof BladeRfSampleRate rate)
{
config.setSampleRate(rate.getRate());
getConfiguration().setSampleRate(rate.getRate());
}
if(getGainModeCombo().getValue() instanceof GainModeInfo mode)
if(getGainModeCombo().getSelectedItem() instanceof GainModeInfo mode)
{
config.setGainMode(mode.mode());
getConfiguration().setGainMode(mode.mode());
}
config.setGain(getGainSlider().getValue());
config.setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setGain(getGainSlider().getValue());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
@Override
protected void tunerLockStateUpdated(boolean locked)
public void setTunerLockState(boolean locked)
{
getSampleRateCombo().setDisable(!hasStartedTuner() || locked);
getSampleRateCombo().setTooltip(new Tooltip(locked ? "Sample rate is locked. Disable decoding channels " +
"to unlock." : "Select a sample rate for the tuner"));
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setToolTipText(locked ? "Sample Rate is locked. Disable decoding channels to unlock." :
"Select a sample rate for the tuner");
}
@Override
protected String getTunerInfo()
private String getTunerInfo()
{
if(!hasStartedTuner())
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
{
return null;
return getDiscoveredTuner().getErrorMessage();
}
if(hasTuner())
{
BladeRfDeviceInformation info = getTuner().getController().getDeviceInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>bladeRF Tuner</h3>");
@@ -297,4 +434,7 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
sb.append("<b>USB Speed: </b>").append(info.speed()).append("<br>");
return sb.toString();
}
return null;
}
}

View File

@@ -84,6 +84,16 @@ public class MultiFrequencyTunerChannelSource extends TunerChannelSource
return source != null ? source.getTunerName() : null;
}
/**
* Noise density near the current frequency's tuner channel source.
*/
@Override
public double getNoiseDensity()
{
TunerChannelSource source = mTunerChannelSource;
return source != null ? source.getNoiseDensity() : Double.NaN;
}
/**
* Applies the channel decoder requested frequency correction.
* @param correction requested by the downstream processors.

View File

@@ -25,6 +25,7 @@ import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceEventListenerToProcessorAdapter;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.TunerNoiseFloorEstimator;
import io.github.dsheirer.source.tuner.frequency.ChannelFrequencyErrorManager;
import io.github.dsheirer.source.tuner.frequency.TunerFrequencyErrorManager;
import org.slf4j.Logger;
@@ -42,6 +43,7 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
private final ChannelFrequencyErrorManager mChannelFrequencyErrorManager;
private volatile long mStartTimestamp;
private volatile String mTunerName;
private volatile TunerNoiseFloorEstimator mNoiseFloorEstimator;
/**
* Tuner Channel Source is a Digital Drop Channel (DDC) abstract class that defines the minimum functionality
@@ -136,6 +138,28 @@ public abstract class TunerChannelSource extends ComplexSource implements ISourc
* sources where the producer incorporates a sample delay buffer.
* @param timestamp in milliseconds since epoch, or 0 to start with current samples.
*/
/**
* Tuner noise power density near this channel, in full-scale units per Hertz, where a complex tone with a
* magnitude of 1.0 at the tuner input has a power of 1.0 (0 dBFS). Requesting the noise density turns on the
* tuner's noise floor measurement, which turns itself back off a few seconds after the last request.
* @return noise density, or NaN if the tuner channel source doesn't measure it or it isn't measured yet.
*/
public double getNoiseDensity()
{
TunerNoiseFloorEstimator estimator = mNoiseFloorEstimator;
TunerChannel channel = getTunerChannel();
return estimator != null && channel != null ?
estimator.getNoiseDensity(channel.getFrequency(), channel.getBandwidth()) : Double.NaN;
}
/**
* Sets the noise floor estimator of the tuner that sources this channel.
*/
public void setNoiseFloorEstimator(TunerNoiseFloorEstimator noiseFloorEstimator)
{
mNoiseFloorEstimator = noiseFloorEstimator;
}
public void setStartTimestamp(long timestamp)
{
mStartTimestamp = timestamp;

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
* 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
@@ -19,6 +19,7 @@
package io.github.dsheirer.source.tuner.fcd.proV1;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.fcd.FCDTuner;
import io.github.dsheirer.source.tuner.fcd.proV1.FCD1TunerController.LNAEnhance;
import io.github.dsheirer.source.tuner.fcd.proV1.FCD1TunerController.LNAGain;
@@ -26,24 +27,34 @@ import io.github.dsheirer.source.tuner.fcd.proV1.FCD1TunerController.MixerGain;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.Tooltip;
import javafx.util.StringConverter;
import java.text.DecimalFormat;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
/**
* Funcube Dongle Pro tuner editor
*/
public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration>
{
private ComboBox<LNAGain> mLnaGainCombo;
private ComboBox<LNAEnhance> mLnaEnhanceCombo;
private ComboBox<MixerGain> mMixerGainCombo;
private CheckBox mBiasTCheckBox;
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(FCD1TunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<LNAGain> mLnaGainCombo;
private JComboBox<LNAEnhance> mLnaEnhanceCombo;
private JComboBox<MixerGain> mMixerGainCombo;
private JCheckBox mBiasTCheckBox;
private CorrectionSpinner mCorrectionDCI;
private CorrectionSpinner mCorrectionDCQ;
private CorrectionSpinner mGainCorrectionSpinner;
@@ -52,14 +63,14 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param tunerManager for saving tuner configuration
* @param discoveredTuner for the optionally usable tuner and controller
* @param tunerManager to save configuration
* @param discoveredTuner to control
*/
public FCD1TunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
private FCD1TunerController getController()
@@ -84,188 +95,318 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
return FCD1TunerController.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private void init()
{
TunerSection gain = addSection("Gain");
gain.addRow("LNA", getLnaGainCombo());
gain.addRow("LNA Enhance", getLnaEnhanceCombo());
gain.addRow("Mixer", getMixerGainCombo());
TunerSection correction = addSection("I/Q Correction");
correction.addRow("DC Inphase", getDcCorrectionSpinnerI());
correction.addRow("DC Quadrature", getDcCorrectionSpinnerQ());
correction.addRow("Gain", getGainCorrectionSpinner());
correction.addRow("Phase", getPhaseCorrectionSpinner());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(hasTuner());
if(hasTuner() && hasConfiguration())
{
FCD1TunerConfiguration config = getConfiguration();
getMixerGainCombo().setValue(config.getMixerGain());
getLnaEnhanceCombo().setValue(config.getLNAEnhance());
getLnaGainCombo().setValue(config.getLNAGain());
getBiasTCheckBox().setSelected(config.isBiasT());
getDcCorrectionSpinnerI().setCorrection(config.getInphaseDCCorrection());
getDcCorrectionSpinnerQ().setCorrection(config.getQuadratureDCCorrection());
getGainCorrectionSpinner().setCorrection(config.getGainCorrection());
getPhaseCorrectionSpinner().setCorrection(config.getPhaseCorrection());
getMixerGainCombo().setSelectedItem(getConfiguration().getMixerGain());
getLnaEnhanceCombo().setSelectedItem(getConfiguration().getLNAEnhance());
getLnaGainCombo().setSelectedItem(getConfiguration().getLNAGain());
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
getDcCorrectionSpinnerI().setValue(getConfiguration().getInphaseDCCorrection());
getDcCorrectionSpinnerQ().setValue(getConfiguration().getQuadratureDCCorrection());
getPhaseCorrectionSpinner().setValue(getConfiguration().getGainCorrection());
getGainCorrectionSpinner().setValue(getConfiguration().getPhaseCorrection());
}
getMixerGainCombo().setDisable(!hasTuner());
getLnaEnhanceCombo().setDisable(!hasTuner());
getLnaGainCombo().setDisable(!hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
getDcCorrectionSpinnerI().setDisable(!hasTuner());
getDcCorrectionSpinnerQ().setDisable(!hasTuner());
getPhaseCorrectionSpinner().setDisable(!hasTuner());
getGainCorrectionSpinner().setDisable(!hasTuner());
getMixerGainCombo().setEnabled(hasTuner());
getLnaEnhanceCombo().setEnabled(hasTuner());
getLnaGainCombo().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
getDcCorrectionSpinnerI().setEnabled(hasTuner());
getDcCorrectionSpinnerQ().setEnabled(hasTuner());
getPhaseCorrectionSpinner().setEnabled(hasTuner());
getGainCorrectionSpinner().setEnabled(hasTuner());
setLoading(false);
}
private ComboBox<LNAGain> getLnaGainCombo()
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain"), "span,align center");
add(new JLabel("LNA:"));
add(getLnaGainCombo(), "wrap");
add(new JLabel("Enhance:"));
add(getLnaEnhanceCombo(), "wrap");
add(new JLabel("Mixer:"));
add(getMixerGainCombo(), "wrap");
add(new JLabel(""));
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Correction"), "span,align center");
add(new JLabel("DC Inphase:"));
add(getDcCorrectionSpinnerI(), "wrap");
add(new JLabel("DC Quadrature:"));
add(getDcCorrectionSpinnerQ(), "wrap");
add(new JLabel("Gain:"));
add(getGainCorrectionSpinner(), "wrap");
add(new JLabel("Phase:"));
add(getPhaseCorrectionSpinner(), "wrap");
}
public JComboBox getLnaGainCombo()
{
if(mLnaGainCombo == null)
{
mLnaGainCombo = new ComboBox<>(FXCollections.observableArrayList(LNAGain.values()));
mLnaGainCombo.setMaxWidth(Double.MAX_VALUE);
mLnaGainCombo.setDisable(true);
mLnaGainCombo.setTooltip(new Tooltip("Adjust the low noise amplifier gain setting."));
mLnaGainCombo.setOnAction(e -> {
LNAGain gain = mLnaGainCombo.getValue();
if(!isLoading() && hasTuner() && gain != null &&
applyToTuner("LNA gain [" + gain + "]", () -> getController().setLNAGain(gain)))
mLnaGainCombo = new JComboBox<>(LNAGain.values());
mLnaGainCombo.setEnabled(false);
mLnaGainCombo.setToolTipText("Adjust the low noise amplifier gain setting.");
mLnaGainCombo.addActionListener(arg0 ->
{
if(!isLoading())
{
LNAGain gain = (LNAGain) mLnaGainCombo.getSelectedItem();
try
{
getController().setLNAGain(gain);
save();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCD Pro Tuner " +
"Controller - error setting LNA gain [" + gain + "]");
mLog.error("FuncubeDonglePro Controller - error setting gain [" + gain + "]", e);
}
}
});
}
return mLnaGainCombo;
}
private CheckBox getBiasTCheckBox()
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
public JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(event -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getController().setBiasT(mBiasTCheckBox.isSelected())))
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(event ->
{
if(hasTuner() && !isLoading())
{
try
{
getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set bias-T for FCD Pro", e);
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "Couldn't set Bias-T: " + e.getMessage());
}
}
});
}
return mBiasTCheckBox;
}
private ComboBox<LNAEnhance> getLnaEnhanceCombo()
public JComboBox getLnaEnhanceCombo()
{
if(mLnaEnhanceCombo == null)
{
mLnaEnhanceCombo = new ComboBox<>(FXCollections.observableArrayList(LNAEnhance.values()));
mLnaEnhanceCombo.setMaxWidth(Double.MAX_VALUE);
mLnaEnhanceCombo.setDisable(true);
mLnaEnhanceCombo.setTooltip(new Tooltip("Adjust the LNA enhance setting. Default value is OFF"));
mLnaEnhanceCombo.setOnAction(e -> {
LNAEnhance enhance = mLnaEnhanceCombo.getValue();
if(!isLoading() && hasTuner() && enhance != null &&
applyToTuner("LNA enhance [" + enhance + "]", () -> getController().setLNAEnhance(enhance)))
mLnaEnhanceCombo = new JComboBox<>(LNAEnhance.values());
mLnaEnhanceCombo.setEnabled(false);
mLnaEnhanceCombo.setToolTipText("Adjust the LNA enhance setting. Default value is OFF");
mLnaEnhanceCombo.addActionListener(arg0 ->
{
if(!isLoading())
{
LNAEnhance enhance = (LNAEnhance) mLnaEnhanceCombo.getSelectedItem();
try
{
getController().setLNAEnhance(enhance);
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCD Pro Tuner"
+ " error setting LNA enhance gain [" + enhance + "]");
mLog.error("FCDPro - error setting LNA enhance [" + enhance + "]", e1);
}
}
});
}
return mLnaEnhanceCombo;
}
private ComboBox<MixerGain> getMixerGainCombo()
public JComboBox getMixerGainCombo()
{
if(mMixerGainCombo == null)
{
mMixerGainCombo = new ComboBox<>(FXCollections.observableArrayList(MixerGain.values()));
mMixerGainCombo.setMaxWidth(Double.MAX_VALUE);
mMixerGainCombo.setDisable(true);
mMixerGainCombo.setTooltip(new Tooltip("Adjust mixer gain setting"));
mMixerGainCombo.setOnAction(e -> {
MixerGain gain = mMixerGainCombo.getValue();
if(!isLoading() && hasTuner() && gain != null &&
applyToTuner("mixer gain [" + gain + "]", () -> getController().setMixerGain(gain)))
mMixerGainCombo = new JComboBox<>(MixerGain.values());
mMixerGainCombo.setEnabled(false);
mMixerGainCombo.setToolTipText("Adjust mixer gain setting");
mMixerGainCombo.addActionListener(arg0 ->
{
if(!isLoading())
{
MixerGain gain = (MixerGain) mMixerGainCombo.getSelectedItem();
try
{
getController().setMixerGain(gain);
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCDPro - error setting"
+ " mixer gain [" + gain + "]");
mLog.error("FCDPro - error setting mixer gain [" + gain + "]", e1);
}
}
});
}
return mMixerGainCombo;
}
private CorrectionSpinner getDcCorrectionSpinnerQ()
public CorrectionSpinner getDcCorrectionSpinnerQ()
{
if(mCorrectionDCQ == null)
{
mCorrectionDCQ = new CorrectionSpinner(Correction.DC_QUADRATURE);
mCorrectionDCQ.setTooltip(new Tooltip("DC bias correction, quadrature component: -1.0 to 1.0 (default: 0.0)"));
mCorrectionDCQ = new CorrectionSpinner(Correction.DC_QUADRATURE, 0.0, 0.00001, 5);
mCorrectionDCQ.setEnabled(false);
mCorrectionDCQ.setToolTipText("DC Bias Correction/Quadrature Component: valid values are -1.0 to 1.0 (default: 0.0)");
}
return mCorrectionDCQ;
}
private CorrectionSpinner getDcCorrectionSpinnerI()
public CorrectionSpinner getDcCorrectionSpinnerI()
{
if(mCorrectionDCI == null)
{
mCorrectionDCI = new CorrectionSpinner(Correction.DC_INPHASE);
mCorrectionDCI.setTooltip(new Tooltip("DC bias correction, inphase component: -1.0 to 1.0 (default: 0.0)"));
mCorrectionDCI = new CorrectionSpinner(Correction.DC_INPHASE, 0.0, 0.00001, 5);
mCorrectionDCI.setEnabled(false);
mCorrectionDCI.setToolTipText("DC Bias Correction/Inphase Component: valid values are -1.0 to 1.0 (default: 0.0)");
}
return mCorrectionDCI;
}
private CorrectionSpinner getGainCorrectionSpinner()
public CorrectionSpinner getGainCorrectionSpinner()
{
if(mGainCorrectionSpinner == null)
{
mGainCorrectionSpinner = new CorrectionSpinner(Correction.GAIN);
mGainCorrectionSpinner.setTooltip(new Tooltip("Gain correction: -1.0 to 1.0 (default: 0.0)"));
mGainCorrectionSpinner = new CorrectionSpinner(Correction.GAIN, 0.0, 0.00001, 5);
mGainCorrectionSpinner.setEnabled(false);
mGainCorrectionSpinner.setToolTipText("Gain Correction: valid values are -1.0 to 1.0 (default: 0.0)");
}
return mGainCorrectionSpinner;
}
private CorrectionSpinner getPhaseCorrectionSpinner()
public CorrectionSpinner getPhaseCorrectionSpinner()
{
if(mPhaseCorrectionSpinner == null)
{
mPhaseCorrectionSpinner = new CorrectionSpinner(Correction.PHASE);
mPhaseCorrectionSpinner.setTooltip(new Tooltip("Phase correction: -1.0 to 1.0 (default: 0.0)"));
mPhaseCorrectionSpinner = new CorrectionSpinner(Correction.PHASE, 0.0, 0.00001, 5);
mPhaseCorrectionSpinner.setEnabled(false);
mPhaseCorrectionSpinner.setToolTipText("Phase Correction: valid values are -1.0 to 1.0 (default: 0.0)");
}
return mPhaseCorrectionSpinner;
}
@Override
protected String getTunerInfo()
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
}
public JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Tuner Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(FCD1TunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private String getTunerInfo()
{
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>Funcube Dongle Pro Tuner</h3>");
sb.append("<b>USB ID: </b>").append(getController().getUSBID()).append("<br>");
sb.append("<b>USB Address: </b>").append(getController().getUSBAddress()).append("<br>");
sb.append("<b>USB Speed: </b>").append(getController().getUSBSpeed()).append("<br>");
sb.append("<b>Cellular Band: </b>").append(getController().getConfiguration().getBandBlocking()).append("<br>");
sb.append("<b>Firmware: </b>").append(getController().getConfiguration().getFirmware()).append("<br>");
if(hasTuner())
{
sb.append("<b>USB ID: </b>");
sb.append(getController().getUSBID());
sb.append("<br>");
sb.append("<b>USB Address: </b>");
sb.append(getController().getUSBAddress());
sb.append("<br>");
sb.append("<b>USB Speed: </b>");
sb.append(getController().getUSBSpeed());
sb.append("<br>");
sb.append("<b>Cellular Band: </b>");
sb.append(getController().getConfiguration().getBandBlocking());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
sb.append(getController().getConfiguration().getFirmware());
sb.append("<br>");
}
return sb.toString();
}
@@ -274,95 +415,88 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
{
if(hasConfiguration() && !isLoading())
{
FCD1TunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setLNAEnhance(getLnaEnhanceCombo().getValue());
config.setLNAGain(getLnaGainCombo().getValue());
config.setMixerGain(getMixerGainCombo().getValue());
config.setBiasT(getBiasTCheckBox().isSelected());
config.setInphaseDCCorrection(getDcCorrectionSpinnerI().getCorrection());
config.setQuadratureDCCorrection(getDcCorrectionSpinnerQ().getCorrection());
config.setGainCorrection(getGainCorrectionSpinner().getCorrection());
config.setPhaseCorrection(getPhaseCorrectionSpinner().getCorrection());
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setLNAEnhance((LNAEnhance) mLnaEnhanceCombo.getSelectedItem());
getConfiguration().setLNAGain((LNAGain) mLnaGainCombo.getSelectedItem());
getConfiguration().setMixerGain((MixerGain) mMixerGainCombo.getSelectedItem());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
double dci = ((SpinnerNumberModel)mCorrectionDCI.getModel()).getNumber().doubleValue();
getConfiguration().setInphaseDCCorrection(dci);
double dcq = ((SpinnerNumberModel)mCorrectionDCQ.getModel()).getNumber().doubleValue();
getConfiguration().setQuadratureDCCorrection(dcq);
double gain = ((SpinnerNumberModel) mGainCorrectionSpinner.getModel()).getNumber().doubleValue();
getConfiguration().setGainCorrection(gain);
double phase = ((SpinnerNumberModel) mPhaseCorrectionSpinner.getModel()).getNumber().doubleValue();
getConfiguration().setPhaseCorrection(phase);
saveConfiguration();
}
}
public enum Correction {GAIN, PHASE, DC_INPHASE, DC_QUADRATURE}
public enum Correction {GAIN, PHASE, DC_INPHASE, DC_QUADRATURE};
/**
* Spinner for a correction value in the range -1.0 to 1.0 with five decimal places.
*/
public class CorrectionSpinner extends Spinner<Double>
public class CorrectionSpinner extends JSpinner
{
private static final long serialVersionUID = 1L;
private static final double MIN_VALUE = -1.0d;
private static final double MAX_VALUE = 1.0d;
private final Correction mCorrectionComponent;
public CorrectionSpinner(Correction component)
private Correction mCorrectionComponent;
public CorrectionSpinner(Correction component, double initialValue, double step, int decimalPlaces)
{
mCorrectionComponent = component;
SpinnerValueFactory.DoubleSpinnerValueFactory factory =
new SpinnerValueFactory.DoubleSpinnerValueFactory(MIN_VALUE, MAX_VALUE, 0.0, 0.00001);
factory.setConverter(new StringConverter<>()
{
@Override
public String toString(Double value)
{
return value == null ? "" : String.format("%.5f", value);
}
@Override
public Double fromString(String text)
SpinnerModel model = new SpinnerNumberModel(initialValue, MIN_VALUE, MAX_VALUE, step);
setModel(model);
JSpinner.NumberEditor editor = (JSpinner.NumberEditor)getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits(decimalPlaces);
editor.getTextField().setHorizontalAlignment(SwingConstants.CENTER);
addChangeListener(e ->
{
if(!isLoading())
{
double value = ((SpinnerNumberModel)getModel()).getNumber().doubleValue();
try
{
return Double.parseDouble(text.trim().replace(',', '.'));
}
catch(Exception e)
{
return factory.getValue();
}
}
});
setValueFactory(factory);
setEditable(true);
setDisable(true);
setMaxWidth(Double.MAX_VALUE);
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
increment(0);
}
});
valueProperty().addListener((observable, oldValue, value) -> {
if(!isLoading() && hasTuner() && value != null &&
applyToTuner(mCorrectionComponent + " correction [" + value + "]", () -> apply(value)))
{
save();
}
});
}
private void apply(double value) throws Exception
{
switch(mCorrectionComponent)
{
case DC_INPHASE -> getController().setDCCorrectionInPhase(value);
case DC_QUADRATURE -> getController().setDCCorrectionQuadrature(value);
case GAIN -> getController().setGainCorrection(value);
case PHASE -> getController().setPhaseCorrection(value);
}
case DC_INPHASE:
getController().setDCCorrectionInPhase(value);
break;
case DC_QUADRATURE:
getController().setDCCorrectionQuadrature(value);
break;
case GAIN:
getController().setGainCorrection(value);
break;
case PHASE:
getController().setPhaseCorrection(value);
break;
}
public void setCorrection(double value)
{
getValueFactory().setValue(value);
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCDPro - error "
+ "applying " + mCorrectionComponent.toString() + " correction value [" + value + "]");
public double getCorrection()
{
return getValue() != null ? getValue() : 0.0;
mLog.error("FCDPro - error applying " + mCorrectionComponent.toString() + " correction value [" +
value + "]", e1);
}
}
});
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
* 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
@@ -19,38 +19,46 @@
package io.github.dsheirer.source.tuner.fcd.proplusV2;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.fcd.FCDTuner;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tooltip;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
/**
* Funcube Dongle Pro Plus tuner editor
*/
public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguration>
{
private CheckBox mLnaGainCheckBox;
private CheckBox mMixerGainCheckBox;
private CheckBox mBiasTCheckBox;
private final static Logger mLog = LoggerFactory.getLogger(FCD2TunerEditor.class);
private static final long serialVersionUID = 1L;
private JButton mTunerInfoButton;
private JCheckBox mLnaGainCheckBox;
private JCheckBox mMixerGainCheckBox;
private JCheckBox mBiasTCheckBox;
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param tunerManager for saving tuner configuration
* @param discoveredTuner for the optionally usable tuner and controller
* @param tunerManager to save configuration
* @param discoveredTuner to control
*/
public FCD2TunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
TunerSection gain = addSection("Gain");
gain.addControl(getLnaGainCheckBox());
gain.addControl(getMixerGainCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
refresh();
init();
tunerStatusUpdated();
}
private FCD2TunerController getController()
@@ -78,9 +86,29 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
@Override
protected void tunerStatusUpdated()
{
getLnaGainCheckBox().setDisable(!hasTuner());
getMixerGainCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(hasTuner());
getLnaGainCheckBox().setEnabled(hasTuner());
getMixerGainCheckBox().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
if(hasTuner() && hasConfiguration())
{
@@ -88,57 +116,127 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
getMixerGainCheckBox().setSelected(getConfiguration().getGainMixer());
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
}
setLoading(false);
}
private CheckBox getLnaGainCheckBox()
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JSeparator(), "span,growx,push");
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new MigLayout("insets 0", "[left][left][left]", ""));
checkBoxPanel.add(getLnaGainCheckBox());
checkBoxPanel.add(getMixerGainCheckBox());
checkBoxPanel.add(getBiasTCheckBox());
add(checkBoxPanel, "span,align left");
}
public JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Tuner Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(FCD2TunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
public JCheckBox getLnaGainCheckBox()
{
if(mLnaGainCheckBox == null)
{
mLnaGainCheckBox = new CheckBox("LNA gain");
mLnaGainCheckBox.setDisable(true);
mLnaGainCheckBox.setOnAction(event -> {
if(!isLoading() && hasTuner() && applyToTuner("LNA gain",
() -> getController().setLNAGain(getLnaGainCheckBox().isSelected())))
mLnaGainCheckBox = new JCheckBox("LNA Gain");
mLnaGainCheckBox.setEnabled(false);
mLnaGainCheckBox.addActionListener(event ->
{
if(!isLoading())
{
try
{
getController().setLNAGain(getLnaGainCheckBox().isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set LNA gain for FCD2", e);
}
}
});
}
return mLnaGainCheckBox;
}
private CheckBox getMixerGainCheckBox()
public JCheckBox getMixerGainCheckBox()
{
if(mMixerGainCheckBox == null)
{
mMixerGainCheckBox = new CheckBox("Mixer gain");
mMixerGainCheckBox.setDisable(true);
mMixerGainCheckBox.setOnAction(event -> {
if(!isLoading() && hasTuner() && applyToTuner("mixer gain",
() -> getController().setMixerGain(getMixerGainCheckBox().isSelected())))
mMixerGainCheckBox = new JCheckBox("Mixer Gain");
mMixerGainCheckBox.setEnabled(false);
mMixerGainCheckBox.addActionListener(event ->
{
if(!isLoading())
{
try
{
getController().setMixerGain(getMixerGainCheckBox().isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set mixer gain for FCD2", e);
}
}
});
}
return mMixerGainCheckBox;
}
private CheckBox getBiasTCheckBox()
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
public JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(event -> {
if(hasTuner() && !isLoading() && applyToTuner("Bias-T",
() -> getController().setBiasT(getBiasTCheckBox().isSelected())))
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(event ->
{
if(hasTuner() && !isLoading())
{
try
{
getController().setBiasT(getBiasTCheckBox().isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set bias-T for FCD2", e);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e.getMessage());
}
}
});
}
@@ -146,15 +244,40 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
}
@Override
protected String getTunerInfo()
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
}
private String getTunerInfo()
{
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>Funcube Dongle Pro Plus Tuner</h3>");
sb.append("<b>USB ID: </b>").append(getController().getUSBID()).append("<br>");
sb.append("<b>USB Address: </b>").append(getController().getUSBAddress()).append("<br>");
sb.append("<b>USB Speed: </b>").append(getController().getUSBSpeed()).append("<br>");
sb.append("<b>Cellular Band: </b>").append(getController().getConfiguration().getBandBlocking()).append("<br>");
sb.append("<b>Firmware: </b>").append(getController().getConfiguration().getFirmware()).append("<br>");
if(hasTuner())
{
sb.append("<b>USB ID: </b>");
sb.append(getController().getUSBID());
sb.append("<br>");
sb.append("<b>USB Address: </b>");
sb.append(getController().getUSBAddress());
sb.append("<br>");
sb.append("<b>USB Speed: </b>");
sb.append(getController().getUSBSpeed());
sb.append("<br>");
sb.append("<b>Cellular Band: </b>");
sb.append(getController().getConfiguration().getBandBlocking());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
sb.append(getController().getConfiguration().getFirmware());
sb.append("<br>");
}
return sb.toString();
}
@@ -163,11 +286,15 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
{
if(hasConfiguration() && !isLoading())
{
FCD2TunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setGainLNA(getLnaGainCheckBox().isSelected());
config.setGainMixer(getMixerGainCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setGainLNA(getLnaGainCheckBox().isSelected());
getConfiguration().setGainMixer(getMixerGainCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}

View File

@@ -20,43 +20,50 @@ package io.github.dsheirer.source.tuner.hackrf;
import io.github.dsheirer.hackrf.HackRf;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.HackRFLNAGain;
import io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.HackRFSampleRate;
import io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.HackRFVGAGain;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
/**
* HackRF tuner editor
* HackRF Tuner Editor
*/
public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfiguration>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(HackRFTunerEditor.class);
private ComboBox<HackRFSampleRate> mSampleRateCombo;
private CheckBox mAmplifierCheckBox;
private CheckBox mBiasTCheckBox;
private ComboBox<HackRFLNAGain> mLnaGainCombo;
private ComboBox<HackRFVGAGain> mVgaGainCombo;
private JButton mTunerInfo;
private JComboBox<HackRFSampleRate> mSampleRateCombo;
private JToggleButton mAmplifier;
private JToggleButton mBiasT;
private JComboBox<HackRFLNAGain> mLnaGainCombo;
private JComboBox<HackRFVGAGain> mVgaGainCombo;
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param tunerManager for saving tuner configuration
* @param discoveredTuner for the optionally usable HackRF tuner and controller
* @param tunerManager to save configuration
* @param discoveredTuner to control
*/
public HackRFTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
@Override
@@ -73,55 +80,116 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][grow]"));
TunerSection gain = addSection("Gain");
gain.addRow("LNA", getLnaGainCombo());
gain.addRow("VGA", getVgaGainCombo());
gain.addControl(getAmplifierCheckBox());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"));
add(getAmplifierToggle(), "wrap");
add(new JLabel("LNA:"));
add(getLnaGainCombo(), "wrap");
add(new JLabel("VGA:"));
add(getVgaGainCombo(), "wrap");
add(new JLabel("Bias-T:"));
add(getBiasTToggle(), "wrap");
//Empty filler row that grows to take up the remaining vertical space
add(new JLabel(), "span,grow,push");
}
@Override
protected void tunerStatusUpdated()
{
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
updateSampleRateToolTip();
getAmplifierCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
getLnaGainCombo().setDisable(!hasTuner());
getVgaGainCombo().setDisable(!hasTuner());
getTunerInfoButton().setEnabled(hasTuner());
getAmplifierToggle().setEnabled(hasTuner());
getBiasTToggle().setEnabled(hasTuner());
getLnaGainCombo().setEnabled(hasTuner());
getVgaGainCombo().setEnabled(hasTuner());
if(hasConfiguration())
{
getSampleRateCombo().setValue(getConfiguration().getSampleRate());
getAmplifierCheckBox().setSelected(getConfiguration().getAmplifierEnabled());
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
getLnaGainCombo().setValue(getConfiguration().getLNAGain());
getVgaGainCombo().setValue(getConfiguration().getVGAGain());
}
getSampleRateCombo().setSelectedItem(getConfiguration().getSampleRate());
getAmplifierToggle().setSelected(getConfiguration().getAmplifierEnabled());
getBiasTToggle().setSelected(getConfiguration().isBiasT());
getLnaGainCombo().setSelectedItem(getConfiguration().getLNAGain());
getVgaGainCombo().setSelectedItem(getConfiguration().getVGAGain());
}
private ComboBox<HackRFVGAGain> getVgaGainCombo()
setLoading(false);
}
private JComboBox getVgaGainCombo()
{
if(mVgaGainCombo == null)
{
mVgaGainCombo = new ComboBox<>(FXCollections.observableArrayList(HackRFVGAGain.values()));
mVgaGainCombo.setMaxWidth(Double.MAX_VALUE);
mVgaGainCombo.setTooltip(new Tooltip("VGA gain. Adjust to set the baseband gain"));
mVgaGainCombo.setDisable(true);
mVgaGainCombo.setOnAction(e -> {
if(!isLoading() && hasTuner())
mVgaGainCombo = new JComboBox<HackRFVGAGain>(HackRFVGAGain.values());
mVgaGainCombo.setToolTipText("<html>VGA Gain. Adjust to set the baseband gain</html>");
mVgaGainCombo.setEnabled(false);
mVgaGainCombo.addActionListener(arg0 ->
{
HackRFVGAGain vgaGain = mVgaGainCombo.getValue() != null ? mVgaGainCombo.getValue() :
HackRFVGAGain.GAIN_16;
if(!isLoading())
{
try
{
HackRFVGAGain vgaGain = (HackRFVGAGain) mVgaGainCombo.getSelectedItem();
if(applyToTuner("VGA gain", () -> getTuner().getController().setVGAGain(vgaGain)))
if(vgaGain == null)
{
vgaGain = HackRFVGAGain.GAIN_16;
}
getTuner().getController().setVGAGain(vgaGain);
save();
}
catch(SourceException e)
{
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "HackRF Tuner Controller"
+ " - couldn't apply the VGA gain setting - " + e.getLocalizedMessage());
mLog.error("HackRF Tuner Controller - couldn't apply VGA gain setting", e);
}
}
});
}
@@ -129,24 +197,35 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return mVgaGainCombo;
}
private ComboBox<HackRFLNAGain> getLnaGainCombo()
private JComboBox getLnaGainCombo()
{
if(mLnaGainCombo == null)
{
mLnaGainCombo = new ComboBox<>(FXCollections.observableArrayList(HackRFLNAGain.values()));
mLnaGainCombo.setMaxWidth(Double.MAX_VALUE);
mLnaGainCombo.setTooltip(new Tooltip("LNA gain. Adjust to set the IF gain"));
mLnaGainCombo.setDisable(true);
mLnaGainCombo.setOnAction(e -> {
if(!isLoading() && hasTuner())
mLnaGainCombo = new JComboBox<HackRFLNAGain>(HackRFLNAGain.values());
mLnaGainCombo.setToolTipText("<html>LNA Gain. Adjust to set the IF gain</html>");
mLnaGainCombo.setEnabled(false);
mLnaGainCombo.addActionListener(arg0 ->
{
HackRFLNAGain lnaGain = mLnaGainCombo.getValue() != null ? mLnaGainCombo.getValue() :
HackRFLNAGain.GAIN_16;
if(!isLoading())
{
try
{
HackRFLNAGain lnaGain = (HackRFLNAGain) mLnaGainCombo.getSelectedItem();
if(applyToTuner("LNA gain", () -> getTuner().getController().setLNAGain(lnaGain)))
if(lnaGain == null)
{
lnaGain = HackRFLNAGain.GAIN_16;
}
getTuner().getController().setLNAGain(lnaGain);
save();
}
catch(SourceException e)
{
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "HackRF Tuner Controller"
+ " - couldn't apply the LNA gain setting - " + e.getLocalizedMessage());
mLog.error("HackRF Tuner Controller - couldn't apply LNA gain setting - ", e);
}
}
});
}
@@ -154,91 +233,145 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return mLnaGainCombo;
}
private CheckBox getAmplifierCheckBox()
private JToggleButton getAmplifierToggle()
{
if(mAmplifierCheckBox == null)
if(mAmplifier == null)
{
mAmplifierCheckBox = new CheckBox("RF amplifier");
mAmplifierCheckBox.setTooltip(new Tooltip("Enable or disable the RF gain amplifier"));
mAmplifierCheckBox.setDisable(true);
mAmplifierCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() && applyToTuner("amplifier",
() -> getTuner().getController().setAmplifierEnabled(mAmplifierCheckBox.isSelected())))
mAmplifier = new JToggleButton("Amplifier");
mAmplifier.setToolTipText("Enable or disable the gain amplifier");
mAmplifier.setEnabled(false);
mAmplifier.addActionListener(arg0 ->
{
if(!isLoading())
{
try
{
getTuner().getController().setAmplifierEnabled(mAmplifier.isSelected());
save();
}
catch(SourceException e)
{
mLog.error("couldn't enable/disable amplifier", e);
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "Couldn't change amplifier setting",
"Error changing amplifier setting", JOptionPane.ERROR_MESSAGE);
}
}
});
}
return mAmplifierCheckBox;
return mAmplifier;
}
private CheckBox getBiasTCheckBox()
private JToggleButton getBiasTToggle()
{
if(mBiasTCheckBox == null)
if(mBiasT == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setTooltip(new Tooltip("Enable or disable Bias-T power (3.3V) on the antenna port for " +
"active antennas or LNAs"));
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() && applyToTuner("Bias-T",
() -> getTuner().getController().setBiasTEnabled(mBiasTCheckBox.isSelected())))
mBiasT = new JToggleButton("Disabled");
mBiasT.setToolTipText("Enable or disable Bias-T power (3.3V) on the antenna port for active antennas or LNAs");
mBiasT.setEnabled(false);
//Item listener also fires for programmatic setSelected() when the configuration loads
mBiasT.addItemListener(e -> mBiasT.setText(mBiasT.isSelected() ? "Enabled" : "Disabled"));
mBiasT.addActionListener(arg0 ->
{
if(!isLoading())
{
try
{
getTuner().getController().setBiasTEnabled(mBiasT.isSelected());
save();
}
catch(SourceException e)
{
mLog.error("couldn't enable/disable bias-t", e);
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "Couldn't change Bias-T setting",
"Error changing Bias-T setting", JOptionPane.ERROR_MESSAGE);
}
}
});
}
return mBiasTCheckBox;
return mBiasT;
}
private ComboBox<HackRFSampleRate> getSampleRateCombo()
private JComboBox getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>(FXCollections.observableArrayList(HackRFSampleRate.VALID_SAMPLE_RATES));
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
HackRFSampleRate sampleRate = mSampleRateCombo.getValue();
if(!isLoading() && hasTuner() && sampleRate != null &&
applyToTuner("sample rate [" + sampleRate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(sampleRate)))
HackRFSampleRate[] validRates = HackRFSampleRate.VALID_SAMPLE_RATES.toArray(new HackRFSampleRate[0]);
mSampleRateCombo = new JComboBox<>(validRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e ->
{
if(!isLoading())
{
HackRFSampleRate sampleRate = (HackRFSampleRate)getSampleRateCombo().getSelectedItem();
try
{
getTuner().getController().setSampleRate(sampleRate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(sampleRate.getRate());
save();
}
catch(SourceException e2)
{
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "HackRF Tuner Controller"
+ " - couldn't apply the sample rate setting [" + sampleRate.getLabel() +
"] " + e2.getLocalizedMessage());
mLog.error("HackRF Tuner Controller - couldn't apply sample rate setting [" +
sampleRate.getLabel() + "]", e);
}
}
});
}
return mSampleRateCombo;
}
private JButton getTunerInfoButton()
{
if(mTunerInfo == null)
{
mTunerInfo = new JButton("Tuner Info");
mTunerInfo.setToolTipText("Provides details and information about the tuner");
mTunerInfo.setEnabled(false);
mTunerInfo.addActionListener(e -> JOptionPane.showMessageDialog(HackRFTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfo;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getController().isLockedSampleRate())
{
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
mSampleRateCombo.setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else
{
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
mSampleRateCombo.setToolTipText("Select a sample rate for the tuner");
}
}
@Override
protected void tunerLockStateUpdated(boolean locked)
public void setTunerLockState(boolean locked)
{
getSampleRateCombo().setDisable(!hasTuner() || locked);
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected String getTunerInfo()
private String getTunerInfo()
{
HackRFTunerController controller = hasTuner() ? getTuner().getController() : null;
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>HackRF Tuner</h3>");
appendInfo(sb, "Board", controller != null ? controller.getBoardName() : null);
@@ -258,6 +391,9 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return sb.toString();
}
/**
* Appends a labeled tuner info value, or Unknown when the value is not available.
*/
private static void appendInfo(StringBuilder sb, String label, String value)
{
sb.append("<b>").append(label).append(": </b>").append(value != null ? value : "Unknown").append("<br>");
@@ -268,13 +404,17 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
{
if(hasConfiguration() && !isLoading())
{
HackRFTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setSampleRate(getSampleRateCombo().getValue());
config.setAmplifierEnabled(getAmplifierCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
config.setLNAGain(getLnaGainCombo().getValue());
config.setVGAGain(getVgaGainCombo().getValue());
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((HackRFSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setAmplifierEnabled(getAmplifierToggle().isSelected());
getConfiguration().setBiasT(getBiasTToggle().isSelected());
getConfiguration().setLNAGain((HackRFLNAGain)getLnaGainCombo().getSelectedItem());
getConfiguration().setVGAGain((HackRFVGAGain)getVgaGainCombo().getSelectedItem());
saveConfiguration();
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
* 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
@@ -23,35 +23,50 @@ import io.github.dsheirer.source.tuner.hydrasdr.HydraSdrTunerController.Gain;
import io.github.dsheirer.source.tuner.hydrasdr.HydraSdrTunerController.GainMode;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Region;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* HydraSDR tuner editor
* HydraSDR tuner editor/controller
*/
public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTunerConfiguration>
{
private ComboBox<HydraSdrSampleRate> mSampleRateCombo;
private ComboBox<GainMode> mGainModeCombo;
private GainSlider mMasterGainSlider;
private Label mMasterGainLabel;
private GainSlider mIFGainSlider;
private Label mIFGainLabel;
private GainSlider mLNAGainSlider;
private Label mLNAGainLabel;
private GainSlider mMixerGainSlider;
private Label mMixerGainLabel;
private CheckBox mLNAAGCCheckBox;
private CheckBox mMixerAGCCheckBox;
private CheckBox mBiasTCheckBox;
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(HydraSdrTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<HydraSdrSampleRate> mSampleRateCombo;
private JComboBox<GainMode> mGainModeCombo;
private JSlider mMasterGainSlider;
private JLabel mMasterGainLabel;
private JLabel mMasterGainValueLabel;
private JSlider mIFGainSlider;
private JLabel mIFGainLabel;
private JLabel mIFGainValueLabel;
private JSlider mLNAGainSlider;
private JLabel mLNAGainValueLabel;
private JSlider mMixerGainSlider;
private JLabel mMixerGainValueLabel;
private JCheckBox mLNAAGCCheckBox;
private JCheckBox mMixerAGCCheckBox;
private JCheckBox mBiasTCheckBox;
/**
* Constructs an instance
@@ -63,7 +78,7 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
@Override
@@ -78,218 +93,411 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
return HydraSdrTunerController.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
TunerSection gain = addSection("Gain");
gain.addRow("Mode", getGainModeCombo());
mMasterGainLabel = gain.addRow("Master", getMasterGainSlider(), new Region());
mIFGainLabel = gain.addRow("IF", getIFGainSlider(), new Region());
mMixerGainLabel = gain.addRow("Mixer", getMixerGainSlider(), getMixerAGCCheckBox());
mLNAGainLabel = gain.addRow("LNA", getLNAGainSlider(), getLNAAGCCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
getBiasTCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setSelected(hasTuner() && hasConfiguration() && getConfiguration().isBiasT());
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getTunerInfoButton().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
if(hasTuner() && hasConfiguration())
{
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
}
updateGainComponents((hasTuner() && hasConfiguration()) ? getConfiguration().getGain() : null);
if(hasTuner())
{
List<HydraSdrSampleRate> rates = getTuner().getController().getSampleRates();
getSampleRateCombo().getItems().setAll(rates);
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new HydraSdrSampleRate[rates.size()])));
if(hasConfiguration())
{
getSampleRateCombo().setValue(getSampleRate(getConfiguration().getSampleRate()));
HydraSdrSampleRate sampleRate = getSampleRate(getConfiguration().getSampleRate());
getSampleRateCombo().setSelectedItem(sampleRate);
}
}
else
{
getSampleRateCombo().getItems().clear();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
}
updateSampleRateToolTip();
setLoading(false);
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private CheckBox getBiasTCheckBox()
private void init()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
{
save();
}
});
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Mode:"));
add(getGainModeCombo(), "wrap");
add(getMasterGainLabel());
add(getMasterGainSlider());
add(getMasterGainValueLabel());
add(getIFGainLabel());
add(getIFGainSlider());
add(getIFGainValueLabel());
add(getMixerAGCCheckBox());
add(getMixerGainSlider());
add(getMixerGainValueLabel());
add(getLNAAGCCheckBox());
add(getLNAGainSlider());
add(getLNAGainValueLabel());
}
return mBiasTCheckBox;
}
private CheckBox getLNAAGCCheckBox()
private JCheckBox getLNAAGCCheckBox()
{
if(mLNAAGCCheckBox == null)
{
mLNAAGCCheckBox = new CheckBox("AGC");
mLNAAGCCheckBox.setTooltip(new Tooltip("Automatic LNA gain control"));
mLNAAGCCheckBox.setDisable(true);
mLNAAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("LNA AGC",
() -> getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected())))
mLNAAGCCheckBox = new JCheckBox("AGC LNA:");
mLNAAGCCheckBox.setEnabled(false);
mLNAAGCCheckBox.addActionListener(e ->
{
getLNAGainSlider().setDisable(getLNAAGCCheckBox().isSelected());
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected());
getLNAGainSlider().setEnabled(!getLNAAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting LNA AGC Enabled");
}
}
});
}
return mLNAAGCCheckBox;
}
private CheckBox getMixerAGCCheckBox()
private JCheckBox getMixerAGCCheckBox()
{
if(mMixerAGCCheckBox == null)
{
mMixerAGCCheckBox = new CheckBox("AGC");
mMixerAGCCheckBox.setTooltip(new Tooltip("Automatic mixer gain control"));
mMixerAGCCheckBox.setDisable(true);
mMixerAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("mixer AGC",
() -> getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected())))
mMixerAGCCheckBox = new JCheckBox("AGC Mixer:");
mMixerAGCCheckBox.setEnabled(false);
mMixerAGCCheckBox.addActionListener(e ->
{
getMixerGainSlider().setDisable(getMixerAGCCheckBox().isSelected());
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected());
getMixerGainSlider().setEnabled(!getMixerAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Mixer AGC Enabled");
}
}
});
}
return mMixerAGCCheckBox;
}
private GainSlider getLNAGainSlider()
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Bias-T", e1);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e1.getMessage());
}
}
});
}
return mBiasTCheckBox;
}
private JLabel getLNAGainValueLabel()
{
if(mLNAGainValueLabel == null)
{
mLNAGainValueLabel = new JLabel("0");
mLNAGainValueLabel.setEnabled(false);
}
return mLNAGainValueLabel;
}
private JSlider getLNAGainSlider()
{
if(mLNAGainSlider == null)
{
mLNAGainSlider = new GainSlider(HydraSdrTunerController.LNA_GAIN_MIN, HydraSdrTunerController.LNA_GAIN_MAX,
HydraSdrTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setDisable(true);
mLNAGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("LNA gain", () -> getTuner().getController().setLNAGain(gain)))
mLNAGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.LNA_GAIN_MIN,
HydraSdrTunerController.LNA_GAIN_MAX, HydraSdrTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setEnabled(false);
mLNAGainSlider.setMajorTickSpacing(1);
mLNAGainSlider.setPaintTicks(true);
mLNAGainSlider.addChangeListener(event ->
{
int gain = mLNAGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setLNAGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR LNA gain to:" + gain, e);
JOptionPane.showMessageDialog(mLNAGainSlider, "Couldn't set LNA gain value to " + gain);
}
}
getLNAGainValueLabel().setText(String.valueOf(gain));
});
}
return mLNAGainSlider;
}
private GainSlider getMixerGainSlider()
private JLabel getMixerGainValueLabel()
{
if(mMixerGainValueLabel == null)
{
mMixerGainValueLabel = new JLabel("0");
mMixerGainValueLabel.setEnabled(false);
}
return mMixerGainValueLabel;
}
private JSlider getMixerGainSlider()
{
if(mMixerGainSlider == null)
{
mMixerGainSlider = new GainSlider(HydraSdrTunerController.MIXER_GAIN_MIN,
mMixerGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.MIXER_GAIN_MIN,
HydraSdrTunerController.MIXER_GAIN_MAX, HydraSdrTunerController.MIXER_GAIN_MIN);
mMixerGainSlider.setDisable(true);
mMixerGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("mixer gain", () -> getTuner().getController().setMixerGain(gain)))
mMixerGainSlider.setEnabled(false);
mMixerGainSlider.setMajorTickSpacing(1);
mMixerGainSlider.setPaintTicks(true);
mMixerGainSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent event)
{
int gain = mMixerGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR Mixer gain to:" + gain, e);
JOptionPane.showMessageDialog(mMixerGainSlider, "Couldn't set Mixer gain value to " + gain);
}
}
getMixerGainValueLabel().setText(String.valueOf(gain));
}
});
}
return mMixerGainSlider;
}
private GainSlider getIFGainSlider()
private JLabel getIFGainLabel()
{
if(mIFGainLabel == null)
{
mIFGainLabel = new JLabel("IF:");
}
return mIFGainLabel;
}
private JLabel getIFGainValueLabel()
{
if(mIFGainValueLabel == null)
{
mIFGainValueLabel = new JLabel("0");
mIFGainValueLabel.setEnabled(false);
}
return mIFGainValueLabel;
}
private JSlider getIFGainSlider()
{
if(mIFGainSlider == null)
{
mIFGainSlider = new GainSlider(HydraSdrTunerController.IF_GAIN_MIN, HydraSdrTunerController.IF_GAIN_MAX,
HydraSdrTunerController.IF_GAIN_MIN);
mIFGainSlider.setDisable(true);
mIFGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("IF gain", () -> getTuner().getController().setIFGain(gain)))
mIFGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.IF_GAIN_MIN,
HydraSdrTunerController.IF_GAIN_MAX, HydraSdrTunerController.IF_GAIN_MIN);
mIFGainSlider.setEnabled(false);
mIFGainSlider.setMajorTickSpacing(1);
mIFGainSlider.setPaintTicks(true);
mIFGainSlider.addChangeListener(event ->
{
int gain = mIFGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setIFGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR IF gain to:" + gain, e);
JOptionPane.showMessageDialog(mIFGainSlider, "Couldn't set IF gain value to " + gain);
}
}
getIFGainValueLabel().setText(String.valueOf(gain));
});
}
return mIFGainSlider;
}
private GainSlider getMasterGainSlider()
private JLabel getMasterGainLabel()
{
if(mMasterGainLabel == null)
{
mMasterGainLabel = new JLabel("Master:");
}
return mMasterGainLabel;
}
private JLabel getMasterGainValueLabel()
{
if(mMasterGainValueLabel == null)
{
mMasterGainValueLabel = new JLabel("0");
mMasterGainValueLabel.setEnabled(false);
}
return mMasterGainValueLabel;
}
private JSlider getMasterGainSlider()
{
if(mMasterGainSlider == null)
{
mMasterGainSlider = new GainSlider(HydraSdrTunerController.GAIN_MIN, HydraSdrTunerController.GAIN_MAX,
HydraSdrTunerController.GAIN_MIN);
mMasterGainSlider.setDisable(true);
mMasterGainSlider.setOnChange(value -> {
Gain gain = Gain.getGain(getGainModeCombo().getValue(), value);
mMasterGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.GAIN_MIN,
HydraSdrTunerController.GAIN_MAX, HydraSdrTunerController.GAIN_MIN);
mMasterGainSlider.setEnabled(false);
mMasterGainSlider.setMajorTickSpacing(1);
mMasterGainSlider.setPaintTicks(true);
if(hasTuner() && !isLoading() && applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
mMasterGainSlider.addChangeListener(event ->
{
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = mMasterGainSlider.getValue();
Gain gain = Gain.getGain(mode, value);
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR gain to:" + gain.name(), e);
JOptionPane.showMessageDialog(mMasterGainSlider, "Couldn't set gain value to " +
gain.getValue());
}
}
getMasterGainValueLabel().setText(String.valueOf(value));
});
}
return mMasterGainSlider;
}
private ComboBox<GainMode> getGainModeCombo()
private JComboBox<GainMode> getGainModeCombo()
{
if(mGainModeCombo == null)
{
mGainModeCombo = new ComboBox<>(FXCollections.observableArrayList(GainMode.values()));
mGainModeCombo.setMaxWidth(Double.MAX_VALUE);
mGainModeCombo.setDisable(true);
mGainModeCombo.setTooltip(new Tooltip("Linearity and sensitivity modes set all gains from the master " +
"gain. Custom mode sets each gain separately."));
mGainModeCombo.setOnAction(e -> {
mGainModeCombo = new JComboBox<>(GainMode.values());
mGainModeCombo.setEnabled(false);
mGainModeCombo.addActionListener(e ->
{
if(hasTuner() && !isLoading())
{
Gain gain = Gain.getGain(mGainModeCombo.getValue(), getMasterGainSlider().getValue());
setLoading(true);
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = getMasterGainSlider().getValue();
Gain gain = Gain.getGain(mode, value);
updateGainComponents(gain);
setLoading(false);
applyToTuner("gain mode", () -> {
HydraSdrTunerController controller = getTuner().getController();
if(gain == Gain.CUSTOM)
{
controller.setMixerAGC(getMixerAGCCheckBox().isSelected());
controller.setLNAAGC(getLNAAGCCheckBox().isSelected());
controller.setIFGain(getIFGainSlider().getValue());
controller.setMixerGain(getMixerGainSlider().getValue());
controller.setLNAGain(getLNAGainSlider().getValue());
}
else
{
controller.setGain(gain);
}
});
save();
}
});
@@ -298,24 +506,38 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
return mGainModeCombo;
}
private ComboBox<HydraSdrSampleRate> getSampleRateCombo()
private JComboBox<HydraSdrSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
HydraSdrSampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(rate)))
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(hasTuner() && !isLoading())
{
HydraSdrSampleRate rate = (HydraSdrSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(HydraSdrTunerEditor.this,
"Couldn't set sample rate to " + rate.getLabel());
mLog.error("Error setting HydraSDR sample rate", e1);
}
}
}
});
}
@@ -323,29 +545,48 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
}
/**
* Updates the enabled state of each of the gain controls according to the specified gain mode. The master gain
* control is enabled for linearity and sensitivity and the individual gain controls are disabled, and vice-versa
* for custom mode.
* Hyperlink button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(HydraSdrTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
/**
* Updates the enabled state of each of the gain controls according to the
* specified gain mode. The master gain control is enabled for linearity
* and sensitivity and the individual gain controls are disabled, and
* vice-versa for custom mode.
*/
private void updateGainComponents(Gain gain)
{
if(hasTuner() && gain != null)
{
boolean isCustom = gain.equals(Gain.CUSTOM);
getGainModeCombo().setDisable(false);
getGainModeCombo().setValue(gain.getGainMode());
mMasterGainLabel.setDisable(isCustom);
getMasterGainSlider().setDisable(isCustom);
getMasterGainSlider().setValue(gain.getValue());
mIFGainLabel.setDisable(!isCustom);
getIFGainSlider().setDisable(!isCustom);
mLNAGainLabel.setDisable(!isCustom);
getLNAAGCCheckBox().setDisable(!isCustom);
getLNAGainSlider().setDisable(!isCustom || getConfiguration().isLNAAGC());
mMixerGainLabel.setDisable(!isCustom);
getMixerAGCCheckBox().setDisable(!isCustom);
getMixerGainSlider().setDisable(!isCustom || getConfiguration().isMixerAGC());
getGainModeCombo().setEnabled(true);
getGainModeCombo().setSelectedItem(gain.getGainMode());
getMasterGainLabel().setEnabled(!isCustom);
getMasterGainSlider().setEnabled(!isCustom);
getMasterGainSlider().setValue(gain.getValue());
getMasterGainValueLabel().setEnabled(!isCustom);
getIFGainLabel().setEnabled(isCustom);
getIFGainSlider().setEnabled(isCustom);
getIFGainValueLabel().setEnabled(isCustom);
getLNAAGCCheckBox().setEnabled(isCustom);
getLNAGainSlider().setEnabled(isCustom && !getConfiguration().isLNAAGC());
getLNAGainValueLabel().setEnabled(isCustom);
getMixerAGCCheckBox().setEnabled(isCustom);
getMixerGainSlider().setEnabled(isCustom && !getConfiguration().isMixerAGC());
getMixerGainValueLabel().setEnabled(isCustom);
if(isCustom)
{
getIFGainSlider().setValue(getConfiguration().getIFGain());
@@ -365,23 +606,25 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
}
else
{
getGainModeCombo().setDisable(true);
mMasterGainLabel.setDisable(true);
getMasterGainSlider().setDisable(true);
getGainModeCombo().setEnabled(false);
getMasterGainLabel().setEnabled(false);
getMasterGainSlider().setEnabled(false);
getMasterGainSlider().setValue(0);
mIFGainLabel.setDisable(true);
getIFGainSlider().setDisable(true);
getMasterGainValueLabel().setEnabled(false);
getIFGainLabel().setEnabled(false);
getIFGainSlider().setEnabled(false);
getIFGainSlider().setValue(0);
mLNAGainLabel.setDisable(true);
getLNAAGCCheckBox().setDisable(true);
getIFGainValueLabel().setEnabled(false);
getLNAAGCCheckBox().setEnabled(false);
getLNAAGCCheckBox().setSelected(false);
getLNAGainSlider().setDisable(true);
getLNAGainSlider().setEnabled(false);
getLNAGainSlider().setValue(0);
mMixerGainLabel.setDisable(true);
getMixerAGCCheckBox().setDisable(true);
getLNAGainValueLabel().setEnabled(false);
getMixerAGCCheckBox().setEnabled(false);
getMixerAGCCheckBox().setSelected(false);
getMixerGainSlider().setDisable(true);
getMixerGainSlider().setEnabled(false);
getMixerGainSlider().setValue(0);
getMixerGainValueLabel().setEnabled(false);
}
}
@@ -390,21 +633,21 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
{
if(hasConfiguration() && !isLoading())
{
HydraSdrTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
if(getSampleRateCombo().getValue() != null)
{
config.setSampleRate(getSampleRateCombo().getValue().getRate());
}
config.setGain(Gain.getGain(getGainModeCombo().getValue(), getMasterGainSlider().getValue()));
config.setIFGain(getIFGainSlider().getValue());
config.setMixerGain(getMixerGainSlider().getValue());
config.setLNAGain(getLNAGainSlider().getValue());
config.setMixerAGC(getMixerAGCCheckBox().isSelected());
config.setLNAAGC(getLNAAGCCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate(((HydraSdrSampleRate)getSampleRateCombo().getSelectedItem()).getRate());
Gain gain = Gain.getGain((GainMode)mGainModeCombo.getSelectedItem(), getMasterGainSlider().getValue());
getConfiguration().setGain(gain);
getConfiguration().setIFGain(getIFGainSlider().getValue());
getConfiguration().setMixerGain(getMixerGainSlider().getValue());
getConfiguration().setLNAGain(getLNAGainSlider().getValue());
getConfiguration().setMixerAGC(getMixerAGCCheckBox().isSelected());
getConfiguration().setLNAAGC(getLNAAGCCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
@@ -428,7 +671,7 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
}
}
if(!rates.isEmpty())
if(rates.size() > 0)
{
return rates.get(0);
}
@@ -444,31 +687,55 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
{
if(hasTuner() && getTuner().getController().isLockedSampleRate())
{
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else
{
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
}
@Override
protected void tunerLockStateUpdated(boolean locked)
public void setTunerLockState(boolean locked)
{
getSampleRateCombo().setDisable(!hasTuner() || locked);
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected String getTunerInfo()
private String getTunerInfo()
{
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
{
return getDiscoveredTuner().getErrorMessage();
}
if(hasTuner())
{
StringBuilder sb = new StringBuilder();
HydraSdrDeviceInformation info = getTuner().getController().getDeviceInfo();
sb.append("<html><h3>HydraSDR Tuner</h3>");
sb.append("<b>Serial: </b>").append(info.getSerialNumber()).append("<br>");
sb.append("<b>Firmware: </b>").append(info.getVersion()).append("<br>");
sb.append("<b>Part: </b>").append(info.getPartNumber()).append("<br>");
sb.append("<b>Board: </b>").append(info.getBoardName()).append("<br>");
sb.append("<b>Serial: </b>");
sb.append(info.getSerialNumber());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
sb.append(info.getVersion());
sb.append("<br>");
sb.append("<b>Part: </b>");
sb.append(info.getPartNumber());
sb.append("<br>");
sb.append("<b>Board: </b>");
sb.append(info.getBoardName());
sb.append("<br>");
return sb.toString();
}
return null;
}
}

View File

@@ -16,25 +16,42 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.limesdr;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import java.io.Serial;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
/**
* LimeSDR tuner editor
*/
public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerConfiguration>
{
private ComboBox<LimeSdrSampleRate> mSampleRateCombo;
private ComboBox<String> mAntennaCombo;
private GainSlider mGainSlider;
@Serial
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(LimeSdrTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<LimeSdrSampleRate> mSampleRateCombo;
private JComboBox<String> mAntennaCombo;
private JSlider mGainSlider;
private JLabel mGainValueLabel;
/**
* Constructs an instance
@@ -46,7 +63,7 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
{
super(userPreferences, tunerManager, discoveredTuner);
init();
refresh();
tunerStatusUpdated();
}
@Override
@@ -65,150 +82,269 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
getTuningSection().addRow("Antenna", getAntennaCombo());
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]", "[][][][][][][][][][][grow]"));
TunerSection gain = addSection("Gain");
gain.addRow("Gain", getGainSlider());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Antenna:"));
add(getAntennaCombo(), "wrap");
add(new JSeparator(), "span,growx");
add(new JLabel("Gain:"));
add(getGainSlider());
add(getGainValueLabel());
//Empty row that takes all extra vertical space so that the controls stay stacked at the top of the editor.
add(new JLabel(), "span,pushy");
}
@Override
protected void tunerStatusUpdated()
{
if(hasStartedTuner())
setLoading(true);
boolean started = hasStartedTuner();
getTunerIdLabel().setText(started ? getTuner().getPreferredName() : getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(started);
if(started)
{
LimeSdrTunerController controller = getTuner().getController();
getSampleRateCombo().getItems().setAll(controller.getSampleRates());
getSampleRateCombo().setValue(controller.getLimeSdrSampleRate());
getSampleRateCombo().setDisable(controller.isLockedSampleRate());
getAntennaCombo().getItems().setAll(controller.getAntennas());
getAntennaCombo().setValue(controller.getAntenna());
getAntennaCombo().setDisable(false);
List<LimeSdrSampleRate> rates = controller.getSampleRates();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new LimeSdrSampleRate[0])));
getSampleRateCombo().setSelectedItem(controller.getLimeSdrSampleRate());
getSampleRateCombo().setEnabled(!controller.isLockedSampleRate());
List<String> antennas = controller.getAntennas();
getAntennaCombo().setModel(new DefaultComboBoxModel<>(antennas.toArray(new String[0])));
getAntennaCombo().setSelectedItem(controller.getAntenna());
getAntennaCombo().setEnabled(true);
getGainSlider().setValue(controller.getGain());
getGainSlider().setDisable(false);
getGainSlider().setEnabled(true);
getGainValueLabel().setEnabled(true);
}
else
{
getSampleRateCombo().getItems().clear();
getSampleRateCombo().setDisable(true);
getAntennaCombo().getItems().clear();
getAntennaCombo().setDisable(true);
getGainSlider().setDisable(true);
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
getSampleRateCombo().setEnabled(false);
getAntennaCombo().setModel(new DefaultComboBoxModel<>());
getAntennaCombo().setEnabled(false);
getGainSlider().setEnabled(false);
getGainValueLabel().setEnabled(false);
}
updateGainLabel();
setLoading(false);
}
/**
* Indicates if the tuner is started, which is when the controller knows the selected antenna.
* Indicates if the tuner has finished starting, since a status update can arrive while it's starting or restarting.
*/
private boolean hasStartedTuner()
{
return hasTuner() && getTuner().getController().getAntenna() != null;
}
private ComboBox<LimeSdrSampleRate> getSampleRateCombo()
private void updateGainLabel()
{
getGainValueLabel().setText(getGainSlider().getValue() + " dB");
}
/**
* Button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(_ -> JOptionPane.showMessageDialog(LimeSdrTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private JComboBox<LimeSdrSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setTooltip(new Tooltip("Select a sample rate for the tuner"));
mSampleRateCombo.setOnAction(e -> {
LimeSdrSampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate + "]", () -> getTuner().getController().setSampleRate(rate)))
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
LimeSdrSampleRate rate = (LimeSdrSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
mLog.error("Error setting LimeSDR sample rate", e1);
JOptionPane.showMessageDialog(LimeSdrTunerEditor.this, "Couldn't set sample rate to " + rate);
}
}
});
}
return mSampleRateCombo;
}
private ComboBox<String> getAntennaCombo()
private JComboBox<String> getAntennaCombo()
{
if(mAntennaCombo == null)
{
mAntennaCombo = new ComboBox<>();
mAntennaCombo.setMaxWidth(Double.MAX_VALUE);
mAntennaCombo.setDisable(true);
mAntennaCombo.setTooltip(new Tooltip("Receive port: LNAW wideband (default), LNAL low band, LNAH high band"));
mAntennaCombo.setOnAction(e -> {
String antenna = mAntennaCombo.getValue();
if(hasTuner() && !isLoading() && antenna != null &&
applyToTuner("antenna [" + antenna + "]", () -> getTuner().getController().setAntenna(antenna)))
mAntennaCombo = new JComboBox<>();
mAntennaCombo.setEnabled(false);
mAntennaCombo.setToolTipText("Receive port: LNAW wideband (default), LNAL low band, LNAH high band");
mAntennaCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
String antenna = (String)mAntennaCombo.getSelectedItem();
try
{
getTuner().getController().setAntenna(antenna);
save();
}
catch(Exception e1)
{
mLog.error("Error setting LimeSDR antenna", e1);
JOptionPane.showMessageDialog(mAntennaCombo, "Couldn't set antenna to " + antenna);
}
}
});
}
return mAntennaCombo;
}
private GainSlider getGainSlider()
private JSlider getGainSlider()
{
if(mGainSlider == null)
{
mGainSlider = new GainSlider(LimeSdrTunerController.GAIN_MINIMUM, LimeSdrTunerController.GAIN_MAXIMUM,
LimeSdrTunerController.GAIN_DEFAULT);
mGainSlider.setDisable(true);
mGainSlider.setFormatter(value -> value + " dB");
mGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
mGainSlider = new JSlider(JSlider.HORIZONTAL, LimeSdrTunerController.GAIN_MINIMUM,
LimeSdrTunerController.GAIN_MAXIMUM, LimeSdrTunerController.GAIN_DEFAULT);
mGainSlider.setEnabled(false);
mGainSlider.setMajorTickSpacing(5);
mGainSlider.setPaintTicks(true);
mGainSlider.addChangeListener(_ ->
{
int gain = mGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set LimeSDR gain to:" + gain, e);
JOptionPane.showMessageDialog(mGainSlider, "Couldn't set gain value to " + gain);
}
}
updateGainLabel();
});
}
return mGainSlider;
}
private JLabel getGainValueLabel()
{
if(mGainValueLabel == null)
{
mGainValueLabel = new JLabel("0 dB");
mGainValueLabel.setEnabled(false);
}
return mGainValueLabel;
}
@Override
public void save()
{
if(hasConfiguration() && !isLoading())
{
LimeSdrTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel)getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
if(getSampleRateCombo().getValue() instanceof LimeSdrSampleRate rate)
if(getSampleRateCombo().getSelectedItem() instanceof LimeSdrSampleRate rate)
{
config.setSampleRate(rate.getRate());
getConfiguration().setSampleRate(rate.getRate());
}
if(getAntennaCombo().getValue() instanceof String antenna)
if(getAntennaCombo().getSelectedItem() instanceof String antenna)
{
config.setAntenna(antenna);
getConfiguration().setAntenna(antenna);
}
config.setGain(getGainSlider().getValue());
getConfiguration().setGain(getGainSlider().getValue());
saveConfiguration();
}
}
@Override
protected void tunerLockStateUpdated(boolean locked)
public void setTunerLockState(boolean locked)
{
getSampleRateCombo().setDisable(!hasStartedTuner() || locked);
getSampleRateCombo().setTooltip(new Tooltip(locked ? "Sample rate is locked. Disable decoding channels " +
"to unlock." : "Select a sample rate for the tuner"));
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setToolTipText(locked ? "Sample Rate is locked. Disable decoding channels to unlock." :
"Select a sample rate for the tuner");
}
@Override
protected String getTunerInfo()
private String getTunerInfo()
{
if(!hasStartedTuner())
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
{
return null;
return getDiscoveredTuner().getErrorMessage();
}
if(hasTuner())
{
LimeSdrDeviceInformation info = getTuner().getController().getDeviceInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>LimeSDR Tuner</h3>");
@@ -221,4 +357,7 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
sb.append("<b>LimeSuiteNG: </b>").append(info.library()).append("<br>");
return sb.toString();
}
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More