Compare commits

..

1 Commits

Author SHA1 Message Date
denny
5e8837410f #315 Adds Tuner column to Now Playing channels view 2026-11-16 03:16:34 -05:00
311 changed files with 27584 additions and 22056 deletions

View File

@@ -4,7 +4,6 @@
[![Downloads](https://img.shields.io/github/downloads/DSheirer/sdrtrunk/total)](https://github.com/DSheirer/sdrtrunk/releases)
[![License](https://img.shields.io/github/license/DSheirer/sdrtrunk)](LICENSE)
[![Discord](https://img.shields.io/badge/chat-on%20Discord-5865F2?logo=discord&logoColor=white)](https://discord.gg/HJQaKYE)
[![support-google_groups-blue](https://img.shields.io/badge/support-google_groups-blue)](https://groups.google.com/g/sdrtrunk)
# sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
@@ -25,6 +24,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

@@ -1,269 +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.alias;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
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.util.Callback;
/**
* Persisted settings for an alias list. Alias lists are otherwise identified only by the list name that each alias
* carries, so settings that belong to the list itself, like tracking a Radio Reference system, are stored here and
* saved in the playlist.
*
* Radio Reference tracking uses two timestamps from the Radio Reference system's last updated value: the last updated
* value seen by the most recent check, and the last updated value that the aliases were synchronized to. When the
* seen value is newer than the synchronized value, the system changed on Radio Reference and the aliases haven't
* been updated yet.
*/
public class AliasListConfiguration
{
public static final int NO_SYSTEM = 0;
private StringProperty mName = new SimpleStringProperty();
private IntegerProperty mRadioReferenceSystemId = new SimpleIntegerProperty(NO_SYSTEM);
private StringProperty mRadioReferenceSystemName = new SimpleStringProperty();
private BooleanProperty mAutoUpdate = new SimpleBooleanProperty();
private LongProperty mRadioReferenceLastUpdated = new SimpleLongProperty();
private LongProperty mSynchronizedLastUpdated = new SimpleLongProperty();
private LongProperty mLastChecked = new SimpleLongProperty();
/**
* Jackson constructor
*/
public AliasListConfiguration()
{
}
/**
* Constructs an instance
* @param name of the alias list
*/
public AliasListConfiguration(String name)
{
setName(name);
}
/**
* Extractor so that observable lists of configurations report changes to the persisted properties.
*/
public static Callback<AliasListConfiguration,Observable[]> extractor()
{
return (AliasListConfiguration c) -> new Observable[] {c.mName, c.mRadioReferenceSystemId,
c.mRadioReferenceSystemName, c.mAutoUpdate, c.mRadioReferenceLastUpdated, c.mSynchronizedLastUpdated,
c.mLastChecked};
}
/**
* Alias list name
*/
@JacksonXmlProperty(isAttribute = true, localName = "name")
public String getName()
{
return mName.get();
}
public void setName(String name)
{
mName.set(name);
}
@JsonIgnore
public StringProperty nameProperty()
{
return mName;
}
/**
* Indicates if this alias list tracks a Radio Reference system.
*/
@JsonIgnore
public boolean isTrackingRadioReferenceSystem()
{
return getRadioReferenceSystemId() > NO_SYSTEM;
}
/**
* Indicates if this alias list tracks the specified Radio Reference system.
*/
public boolean isTracking(int systemId)
{
return systemId > NO_SYSTEM && getRadioReferenceSystemId() == systemId;
}
/**
* Radio Reference system ID tracked by this alias list, or NO_SYSTEM (0).
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_system_id")
public int getRadioReferenceSystemId()
{
return mRadioReferenceSystemId.get();
}
public void setRadioReferenceSystemId(int systemId)
{
mRadioReferenceSystemId.set(systemId);
}
@JsonIgnore
public IntegerProperty radioReferenceSystemIdProperty()
{
return mRadioReferenceSystemId;
}
/**
* Radio Reference system name, for display.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_system_name")
public String getRadioReferenceSystemName()
{
return mRadioReferenceSystemName.get();
}
public void setRadioReferenceSystemName(String name)
{
mRadioReferenceSystemName.set(name);
}
@JsonIgnore
public StringProperty radioReferenceSystemNameProperty()
{
return mRadioReferenceSystemName;
}
/**
* Indicates if talkgroups are automatically added or updated as aliases when the system changes on Radio Reference.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_auto_update")
public boolean isAutoUpdate()
{
return mAutoUpdate.get();
}
public void setAutoUpdate(boolean autoUpdate)
{
mAutoUpdate.set(autoUpdate);
}
@JsonIgnore
public BooleanProperty autoUpdateProperty()
{
return mAutoUpdate;
}
/**
* Radio Reference last updated timestamp (ms since epoch) for the system, as seen by the most recent check.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_last_updated")
public long getRadioReferenceLastUpdated()
{
return mRadioReferenceLastUpdated.get();
}
public void setRadioReferenceLastUpdated(long timestamp)
{
mRadioReferenceLastUpdated.set(timestamp);
}
@JsonIgnore
public LongProperty radioReferenceLastUpdatedProperty()
{
return mRadioReferenceLastUpdated;
}
/**
* Radio Reference last updated timestamp (ms since epoch) that the aliases were last synchronized to.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_synchronized")
public long getSynchronizedLastUpdated()
{
return mSynchronizedLastUpdated.get();
}
public void setSynchronizedLastUpdated(long timestamp)
{
mSynchronizedLastUpdated.set(timestamp);
}
@JsonIgnore
public LongProperty synchronizedLastUpdatedProperty()
{
return mSynchronizedLastUpdated;
}
/**
* Time (ms since epoch) of the most recent successful check of the system on Radio Reference.
*/
@JacksonXmlProperty(isAttribute = true, localName = "rr_last_checked")
public long getLastChecked()
{
return mLastChecked.get();
}
public void setLastChecked(long timestamp)
{
mLastChecked.set(timestamp);
}
@JsonIgnore
public LongProperty lastCheckedProperty()
{
return mLastChecked;
}
/**
* Indicates if the most recent check saw a system change on Radio Reference that the aliases don't include yet.
*/
@JsonIgnore
public boolean isUpdateAvailable()
{
return isTrackingRadioReferenceSystem() && getRadioReferenceLastUpdated() > getSynchronizedLastUpdated();
}
/**
* Starts tracking the Radio Reference system. Clears timestamps so that the next refresh synchronizes.
*/
public void track(int systemId, String systemName)
{
setRadioReferenceSystemId(systemId);
setRadioReferenceSystemName(systemName);
setRadioReferenceLastUpdated(0);
setSynchronizedLastUpdated(0);
setLastChecked(0);
}
/**
* Stops tracking any Radio Reference system.
*/
public void stopTracking()
{
track(NO_SYSTEM, null);
setAutoUpdate(false);
}
}

View File

@@ -46,8 +46,6 @@ public class AliasModel
private ObservableList<Alias> mAliases = FXCollections.observableArrayList(Alias.extractor());
private ObservableList<String> mAliasListNames = FXCollections.observableArrayList();
private Map<String,AliasList> mAliasListMap = new HashMap<>();
private ObservableList<AliasListConfiguration> mAliasListConfigurations =
FXCollections.observableArrayList(AliasListConfiguration.extractor());
public AliasModel()
{
@@ -65,99 +63,6 @@ public class AliasModel
return mAliasListNames;
}
/**
* Observable list of persisted alias list configurations. Only alias lists with settings, like Radio Reference
* system tracking, have a configuration.
*/
public ObservableList<AliasListConfiguration> aliasListConfigurations()
{
return mAliasListConfigurations;
}
/**
* Bulk loading of alias list configurations from a playlist. Ignores configurations without a name and
* duplicates of an earlier configuration's name.
*/
public void addAliasListConfigurations(List<AliasListConfiguration> configurations)
{
if(configurations != null)
{
for(AliasListConfiguration configuration: configurations)
{
String name = configuration.getName();
if(name != null && !name.isEmpty() && getAliasListConfiguration(name) == null)
{
mAliasListConfigurations.add(configuration);
addAliasList(name);
}
}
}
}
/**
* Configuration for the named alias list.
* @param aliasListName to find
* @return configuration or null if the alias list doesn't have one
*/
public AliasListConfiguration getAliasListConfiguration(String aliasListName)
{
if(aliasListName != null)
{
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(aliasListName.equals(configuration.getName()))
{
return configuration;
}
}
}
return null;
}
/**
* Configuration for the named alias list, created when the alias list doesn't have one.
* @param aliasListName for the configuration, not null or the (No Alias List) name
* @return configuration
*/
public AliasListConfiguration getOrCreateAliasListConfiguration(String aliasListName)
{
if(aliasListName == null || aliasListName.isEmpty() || aliasListName.equals(NO_ALIAS_LIST))
{
throw new IllegalArgumentException("Invalid alias list name [" + aliasListName + "]");
}
AliasListConfiguration configuration = getAliasListConfiguration(aliasListName);
if(configuration == null)
{
configuration = new AliasListConfiguration(aliasListName);
mAliasListConfigurations.add(configuration);
addAliasList(aliasListName);
}
return configuration;
}
/**
* Name of the first alias list that tracks the Radio Reference system.
* @param systemId of the Radio Reference system
* @return alias list name or null
*/
public String getAliasListNameTracking(int systemId)
{
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(configuration.isTracking(systemId))
{
return configuration.getName();
}
}
return null;
}
/**
* Clears and reloads the list of alias list names from the current set of aliases.
*/
@@ -174,15 +79,6 @@ public class AliasModel
mAliasListNames.add(aliasListName);
}
}
//Alias lists with a configuration exist even before they have any aliases
for(AliasListConfiguration configuration: mAliasListConfigurations)
{
if(!mAliasListNames.contains(configuration.getName()))
{
mAliasListNames.add(configuration.getName());
}
}
}
/**
@@ -197,22 +93,7 @@ public class AliasModel
return;
}
mAliases.stream().filter(alias -> oldName.equals(alias.getAliasListName())).forEach(alias -> alias.setAliasListName(newName));
AliasListConfiguration configuration = getAliasListConfiguration(oldName);
if(configuration != null)
{
//Merging into an existing list keeps that list's configuration
if(getAliasListConfiguration(newName) == null)
{
configuration.setName(newName);
}
else
{
mAliasListConfigurations.remove(configuration);
}
}
mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName));
}
/**
@@ -228,7 +109,6 @@ public class AliasModel
mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
mAliasListMap.remove(aliasListName);
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
}
/**
@@ -266,7 +146,6 @@ public class AliasModel
removeAlias(alias);
}
mAliasListConfigurations.clear();
mAliasListNames.clear();
}

View File

@@ -1,571 +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.alias;
import com.google.common.annotations.VisibleForTesting;
import io.github.dsheirer.alias.id.AliasID;
import io.github.dsheirer.alias.id.radio.NXDNTypeDRadio;
import io.github.dsheirer.alias.id.radio.P25FullyQualifiedRadio;
import io.github.dsheirer.alias.id.radio.Radio;
import io.github.dsheirer.identifier.alias.TalkerAliasIdentifier;
import io.github.dsheirer.identifier.radio.FullyQualifiedRadioIdentifier;
import io.github.dsheirer.identifier.radio.RadioIdentifier;
import io.github.dsheirer.module.decode.nxdn.identifier.NXDNRadioIdentifier;
import io.github.dsheirer.protocol.Protocol;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Automatically adds decoded talker aliases to an alias list as radio aliases, using the talker alias as the alias name,
* and renames a stored radio alias when the radio's talker alias changes.
*
* Talker aliases span up to 4 messages, so a decoded talker alias can be a fragment (the leading characters) of the
* full alias, even when the decoder reports it as complete. To avoid replacing a full alias with a fragment:
* <ul>
* <li>A decoded alias that is the start of the stored alias name is a fragment and never replaces it.</li>
* <li>A decoded alias that starts with the stored alias name is a longer version of a stored fragment and
* replaces it.</li>
* <li>Any other decoded alias that differs from the stored alias name replaces it only after it is decoded
* {@link #CONFIRMATIONS_REQUIRED} times in a row for the radio.</li>
* </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.
*
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
* JavaFX application thread.
*/
public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAliasIdentifier>
{
private static final Logger mLog = LoggerFactory.getLogger(TalkerAliasAutoAdder.class);
/**
* Group assigned to aliases created from talker aliases.
*/
public static final String ALIAS_GROUP = "Talker Alias";
/**
* Number of consecutive times a different talker alias must be decoded for a radio before it replaces the stored
* alias name.
*/
public static final int CONFIRMATIONS_REQUIRED = 2;
/**
* Interval for re-checking the stored alias for a talker alias that was already checked, so that a renamed or
* deleted alias is restored without checking the alias list for every decoded talker alias.
*/
private static final long RECHECK_INTERVAL_MS = 30_000;
/**
* Outcome of comparing a decoded talker alias with the stored alias name.
*/
public enum Decision
{
/**
* The stored alias name matches the talker alias.
*/
UNCHANGED,
/**
* The talker alias is a fragment of the stored alias name.
*/
FRAGMENT,
/**
* The talker alias differs from the stored alias name and is waiting for more decodes.
*/
AWAIT_CONFIRMATION,
/**
* The talker alias replaces the stored alias name.
*/
UPDATE
}
private final AliasModel mAliasModel;
private final String mAliasListName;
//Guarded by this
private final Map<String,Candidate> mCandidates = new HashMap<>();
private final Map<String,Checked> mChecked = new HashMap<>();
/**
* Constructs an instance
* @param aliasModel to add aliases to
* @param aliasListName of the alias list to add aliases to
*/
public TalkerAliasAutoAdder(AliasModel aliasModel, String aliasListName)
{
mAliasModel = aliasModel;
mAliasListName = aliasListName;
}
/**
* Name of the alias list that talker aliases are added to.
*/
public String getAliasListName()
{
return mAliasListName;
}
/**
* Processes a talker alias that is assigned to a radio.
* @param radio that the talker alias belongs to
* @param talkerAlias for the radio
*/
@Override
public void accept(RadioIdentifier radio, TalkerAliasIdentifier talkerAlias)
{
if(radio == null || talkerAlias == null || mAliasListName == null || mAliasListName.isEmpty())
{
return;
}
String value = normalize(talkerAlias.getValue());
Radio aliasId = createAliasId(radio);
if(value == null || aliasId == null || !aliasId.isValid())
{
return;
}
String key = getKey(aliasId);
long now = System.currentTimeMillis();
int confirmations;
synchronized(this)
{
Checked checked = mChecked.get(key);
if(checked != null && checked.value().equals(value) && (now - checked.timestamp()) < RECHECK_INTERVAL_MS)
{
return;
}
confirmations = confirm(key, value);
}
runOnFxThread(() -> apply(radio, aliasId, key, value, confirmations));
}
/**
* Counts the consecutive decodes of the talker alias for the radio. A fragment of the talker alias that is
* waiting for confirmation doesn't interrupt the count, because fragments are decoded while the full alias is
* assembled.
* @return number of consecutive decodes of the value, including this one.
*/
private int confirm(String key, String value)
{
Candidate candidate = mCandidates.get(key);
if(candidate != null && candidate.value().equals(value))
{
candidate = new Candidate(value, candidate.count() + 1);
mCandidates.put(key, candidate);
return candidate.count();
}
if(candidate != null && isFragment(value, candidate.value()))
{
return 1;
}
mCandidates.put(key, new Candidate(value, 1));
return 1;
}
/**
* Creates or updates the alias for the radio. Runs on the JavaFX application thread.
*/
private synchronized void apply(RadioIdentifier radio, Radio aliasId, String key, String value, int confirmations)
{
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);
alias.setAliasListName(mAliasListName);
alias.setGroup(ALIAS_GROUP);
alias.addAliasID(aliasId);
mAliasModel.addAlias(alias);
markChecked(key, value);
mLog.info("Talker alias [" + value + "] added for radio [" + aliasId + "] to alias list [" +
mAliasListName + "]");
return;
}
if(!ALIAS_GROUP.equals(existing.getGroup()))
{
//Only maintain aliases in the managed group. Existing user aliases must not be renamed or duplicated.
markChecked(key, value);
return;
}
if(getIdentityCount(existing) > 1)
{
//The alias also identifies other radios or talkgroups - leave it alone.
markChecked(key, value);
return;
}
String stored = normalize(existing.getName());
switch(decide(stored, value, confirmations))
{
case UPDATE:
existing.setName(value);
markChecked(key, value);
mLog.info("Talker alias for radio [" + aliasId + "] in alias list [" + mAliasListName +
"] changed from [" + stored + "] to [" + value + "]");
break;
case UNCHANGED:
case FRAGMENT:
markChecked(key, value);
break;
case AWAIT_CONFIRMATION:
default:
break;
}
}
private void markChecked(String key, String value)
{
mChecked.put(key, new Checked(value, System.currentTimeMillis()));
mCandidates.remove(key);
}
/**
* Compares the decoded talker alias with the stored alias name.
* @param stored alias name, normalized, or null
* @param decoded talker alias, normalized
* @param confirmations number of consecutive decodes of the talker alias
* @return decision
*/
@VisibleForTesting
static Decision decide(String stored, String decoded, int confirmations)
{
if(stored == null || stored.isEmpty())
{
return Decision.UPDATE;
}
if(stored.equals(decoded))
{
return Decision.UNCHANGED;
}
if(isFragment(decoded, stored))
{
return Decision.FRAGMENT;
}
//A longer version of a stored fragment.
if(isFragment(stored, decoded) && !hasUndecodableCharacters(decoded))
{
return Decision.UPDATE;
}
//A different alias that may be a corrupted or mis-assembled alias. It's replaced only once confirmed, and an
//alias that has undecodable characters (e.g. a partial multi-byte character) never replaces a stored alias.
if(confirmations >= CONFIRMATIONS_REQUIRED && !hasUndecodableCharacters(decoded))
{
return Decision.UPDATE;
}
return Decision.AWAIT_CONFIRMATION;
}
/**
* Indicates if the value is a fragment (the leading characters) of the full value.
*/
@VisibleForTesting
static boolean isFragment(String value, String full)
{
return value != null && full != null && value.length() < full.length() && full.startsWith(value);
}
private static boolean hasUndecodableCharacters(String value)
{
return value.indexOf('<27>') >= 0;
}
/**
* Removes padding, control characters and trailing undecodable characters (e.g. from a partial multi-byte
* character at the end of an alias fragment) from the talker alias.
* @param value to normalize
* @return normalized value or null if the value is empty.
*/
@VisibleForTesting
static String normalize(String value)
{
if(value == null)
{
return null;
}
StringBuilder sb = new StringBuilder(value.length());
for(int i = 0; i < value.length(); i++)
{
char c = value.charAt(i);
if(!Character.isISOControl(c))
{
sb.append(c);
}
}
int end = sb.length();
while(end > 0 && (sb.charAt(end - 1) == '<27>' || Character.isWhitespace(sb.charAt(end - 1))))
{
end--;
}
String normalized = sb.substring(0, end).trim();
return normalized.isEmpty() ? null : normalized;
}
/**
* Creates a radio alias identifier that exactly matches the radio.
* @param radio identifier
* @return alias identifier or null if the radio protocol isn't known.
*/
@VisibleForTesting
static Radio createAliasId(RadioIdentifier radio)
{
if(radio instanceof FullyQualifiedRadioIdentifier fqri && fqri.getProtocol() == Protocol.APCO25)
{
return new P25FullyQualifiedRadio(fqri.getWacn(), fqri.getSystem(), fqri.getRadio());
}
if(radio instanceof NXDNRadioIdentifier nxdn && nxdn.isTypeD())
{
return new NXDNTypeDRadio(nxdn.getTypeDHomeRepeater(), nxdn.getTypeDRadio());
}
Protocol protocol = radio.getProtocol();
if(protocol == null || protocol == Protocol.UNKNOWN || radio.getValue() == null)
{
return null;
}
return new Radio(protocol, radio.getValue());
}
/**
* Finds the alias that has an identifier that exactly matches the radio (i.e. not a radio range).
*/
@VisibleForTesting
static Alias findExactMatch(List<Alias> aliases, Radio aliasId)
{
if(aliases != null)
{
for(Alias alias: aliases)
{
for(AliasID id: alias.getAliasIdentifiers())
{
if(isExactMatch(id, aliasId))
{
return alias;
}
}
}
}
return null;
}
private static boolean isExactMatch(AliasID id, Radio aliasId)
{
if(aliasId instanceof P25FullyQualifiedRadio target)
{
return id instanceof P25FullyQualifiedRadio fqr && fqr.getHashKey().equals(target.getHashKey());
}
return id instanceof Radio radio && !(id instanceof P25FullyQualifiedRadio) &&
radio.getProtocol() == aliasId.getProtocol() && radio.getValue() == aliasId.getValue();
}
/**
* 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.
*/
@VisibleForTesting
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
{
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;
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isAudioIdentifier())
{
if(sole != null)
{
return null;
}
sole = id;
}
}
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();
}
private static String getKey(Radio aliasId)
{
if(aliasId instanceof P25FullyQualifiedRadio fqr)
{
return aliasId.getProtocol() + ":" + fqr.getHashKey();
}
return aliasId.getProtocol() + ":" + aliasId.getValue();
}
/**
* Runs on the FX thread, or on this thread when the FX toolkit isn't running (headless).
*/
private static void runOnFxThread(Runnable runnable)
{
if(Platform.isFxApplicationThread())
{
runnable.run();
return;
}
try
{
Platform.runLater(runnable);
}
catch(IllegalStateException ise)
{
runnable.run();
}
}
private record Candidate(String value, int count) {}
private record Checked(String value, long timestamp) {}
}

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

@@ -49,7 +49,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadata.class);
private AliasListConfigurationIdentifier mAliasListConfigurationIdentifier;
private SystemConfigurationIdentifier mSystemConfigurationIdentifier;
private SiteConfigurationIdentifier mSiteConfigurationIdentifier;
private ChannelNameConfigurationIdentifier mChannelNameConfigurationIdentifier;
@@ -129,19 +128,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
return this;
}
/**
* Alias list configuration identifier
*/
public AliasListConfigurationIdentifier getAliasListConfigurationIdentifier()
{
return mAliasListConfigurationIdentifier;
}
public boolean hasAliasListConfigurationIdentifier()
{
return mAliasListConfigurationIdentifier != null;
}
/**
* System configuration identifier
*/
@@ -337,15 +323,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
switch(identifier.getForm())
{
case ALIAS_LIST:
if(identifier instanceof AliasListConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))
{
mAliasListConfigurationIdentifier = (AliasListConfigurationIdentifier)identifier;
}
else
{
mAliasListConfigurationIdentifier = null;
}
if(update.isAdd())
{
mAliasList = mAliasModel.getAliasList((AliasListConfigurationIdentifier)identifier);
@@ -362,7 +339,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
}
}
}
broadcastUpdate(ChannelMetadataField.CONFIGURATION_ALIAS_LIST);
break;
case CHANNEL:
if(identifier instanceof ChannelNameConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))

View File

@@ -22,7 +22,6 @@ package io.github.dsheirer.channel.metadata;
public enum ChannelMetadataField
{
CONFIGURATION_ALIAS_LIST,
CONFIGURATION_CHANNEL,
CONFIGURATION_FREQUENCY,
CONFIGURATION_SITE,

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.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, playlistManager.getAliasModel(), 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

@@ -18,7 +18,6 @@
*/
package io.github.dsheirer.controller.channel;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@@ -84,8 +83,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
private BooleanProperty mProcessing = new SimpleBooleanProperty();
private BooleanProperty mAutoStart = new SimpleBooleanProperty();
//Enabled for new channels. Channels loaded from a playlist without the setting keep it disabled, see fromXml().
private BooleanProperty mAutoAddTalkerAliases = new SimpleBooleanProperty(true);
private IntegerProperty mAutoStartOrder = new SimpleIntegerProperty();
private boolean mSelected;
private List<TunerChannel> mTunerChannels = null;
@@ -126,19 +123,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
mChannelID = UNIQUE_ID++;
}
/**
* Creates a channel for deserialization from a playlist. Settings added after a channel was saved take their
* legacy (disabled) value when the playlist doesn't specify them, instead of the default for new channels, so that
* existing channels don't change behavior.
*/
@JsonCreator
private static Channel fromXml()
{
Channel channel = new Channel();
channel.setAutoAddTalkerAliases(false);
return channel;
}
/**
* Creates a (new) deep copy of this channel
*/
@@ -150,7 +134,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
channel.setAliasListName(mAliasListName.get());
channel.setAutoStart(mAutoStart.get());
channel.setAutoStartOrder(mAutoStartOrder.get());
channel.setAutoAddTalkerAliases(mAutoAddTalkerAliases.get());
AuxDecodeConfiguration auxCopy = new AuxDecodeConfiguration();
@@ -526,36 +509,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
mAutoStart.set(autoStart);
}
/**
* Auto-add talker aliases property
*/
public BooleanProperty autoAddTalkerAliasesProperty()
{
return mAutoAddTalkerAliases;
}
/**
* Indicates if decoded talker aliases are automatically added to the channel's alias list as radio aliases, using
* the talker alias as the alias name.
*
* @return true if talker aliases are automatically added to the alias list
*/
@JacksonXmlProperty(isAttribute = true, localName = "auto_add_talker_aliases")
public boolean isAutoAddTalkerAliases()
{
return mAutoAddTalkerAliases.get();
}
/**
* Sets automatically adding decoded talker aliases to the channel's alias list.
*
* @param autoAdd true to automatically add talker aliases to the alias list
*/
public void setAutoAddTalkerAliases(boolean autoAdd)
{
mAutoAddTalkerAliases.set(autoAdd);
}
/**
* Auto-start order. Specifies an optional ordering for channels so that when the application starts up,
* the channels can be started in a user-specified order.

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

@@ -42,7 +42,6 @@ public class ChannelDFTFactory
case VECTOR_SIMD_PREFERRED:
return new VectorChannelDFT(channelCount);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarChannelDFT(channelCount);
}

View File

@@ -79,11 +79,9 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
private static final int MAXIMUM_QUEUED_BATCHES = 50;
/**
* Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batch being filled and the batch
* being transformed. Channel output processors copy their channels from a batch instead of retaining it, so no
* other batches are held.
* Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batches queued for channel output.
*/
private static final int MAXIMUM_POOLED_BATCHES = MAXIMUM_QUEUED_BATCHES + 2;
private static final int MAXIMUM_POOLED_BATCHES = 2 * MAXIMUM_QUEUED_BATCHES;
//Sized to process 40 times per second
private IFFTProcessorDispatcher mIFFTProcessorDispatcher = new IFFTProcessorDispatcher(25);

View File

@@ -68,12 +68,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private final static Logger mLog = LoggerFactory.getLogger(PolyphaseChannelManager.class);
private static final double CHANNEL_OVERSAMPLING = 2.0;
private static final int POLYPHASE_CHANNELIZER_TAPS_PER_CHANNEL = 9;
/**
* Maximum duration of queued native buffers awaiting the channelizer. The queue is bounded by sample count instead
* of buffer count because tuner buffer sizes vary widely, for example about 1,000 samples per RSP buffer and 32,768
* samples per RTL-SDR buffer, so that each tuner can absorb a processing delay of the same duration.
*/
private static final double MAXIMUM_QUEUED_SECONDS = 1.0;
private static final int MAXIMUM_QUEUED_NATIVE_BUFFERS = 500;
private Broadcaster<SourceEvent> mSourceEventBroadcaster = new Broadcaster<>();
private TunerController mTunerController;
@@ -83,7 +78,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private ComplexPolyphaseChannelizerM2 mPolyphaseChannelizer;
private ChannelSourceEventListener mChannelSourceEventListener = new ChannelSourceEventListener();
private NativeBufferReceiver mNativeBufferReceiver = new NativeBufferReceiver();
private Dispatcher<INativeBuffer> mBufferDispatcher;
private Dispatcher mBufferDispatcher;
private boolean mRunning = true;
/**
@@ -104,21 +99,10 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
mChannelCalculator = new ChannelCalculator(tunerController.getSampleRate(), channelCount,
tunerController.getFrequency(), CHANNEL_OVERSAMPLING);
mBufferDispatcher = new Dispatcher<>("sdrtrunk polyphase buffer processor", 10, INativeBuffer::sampleCount,
getMaximumQueuedSamples(tunerController.getSampleRate()));
mBufferDispatcher = new Dispatcher("sdrtrunk polyphase buffer processor", 10, MAXIMUM_QUEUED_NATIVE_BUFFERS);
mBufferDispatcher.setListener(mNativeBufferReceiver);
}
/**
* Calculates the maximum number of queued samples for the buffer dispatcher.
* @param sampleRate of the tuner
* @return maximum queued samples, at least one
*/
private static long getMaximumQueuedSamples(double sampleRate)
{
return Math.max(1, (long)(sampleRate * MAXIMUM_QUEUED_SECONDS));
}
/**
* Provides a description of the state of this manager.
*/
@@ -294,7 +278,6 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
double sampleRate = sourceEvent.getValue().doubleValue();
int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate);
mChannelCalculator.setRates(sampleRate, channelCount);
mBufferDispatcher.setMaximumQueuedWeight(getMaximumQueuedSamples(sampleRate));
break;
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_LOCKED:
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_UNLOCKED:

View File

@@ -180,8 +180,7 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
/**
* Performs the output processor update. This method must be invoked on the channel results calling thread so that
* replacing the output processor doesn't overlap with delivery of channel results to it. The output processor
* applies channel index changes as it copies the next batch, and applies mixer and filter changes on its own
* dispatcher thread at that same batch.
* applies the configuration changes on its own dispatcher thread.
* @param channelCalculator for updates
* @param filterManager for updates
* @throws IllegalArgumentException if there's an issue.

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
@@ -24,7 +24,6 @@ import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import io.github.dsheirer.util.Dispatcher;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
@@ -35,20 +34,12 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
private final static Logger mLog = LoggerFactory.getLogger(ChannelOutputProcessor.class);
/**
* Maximum queued channel sample batches, about one second of samples. A full batch is dropped when this channel
* Maximum queued channel results batches, about one second of samples. A full batch is dropped when this channel
* falls behind, which preserves the even-sized batch block parity that two-channel synthesis relies on.
*/
private static final int MAXIMUM_QUEUED_BATCHES = 50;
/**
* Maximum channel sample arrays held for reuse: the queued batches plus the batch being processed and the batch
* being copied.
*/
private static final int MAXIMUM_POOLED_ARRAYS = MAXIMUM_QUEUED_BATCHES + 2;
private Dispatcher<QueuedChannelSamples> mChannelSamplesDispatcher;
private final Queue<float[]> mSamplePool = new ArrayBlockingQueue<>(MAXIMUM_POOLED_ARRAYS);
private volatile int[] mChannelOffsets = new int[0];
private Dispatcher<QueuedChannelResults> mChannelResultsDispatcher;
private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>();
private final AtomicLong mBatchSequence = new AtomicLong();
private HeartbeatManager mHeartbeatManager;
@@ -69,45 +60,25 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
mInputChannelCount = inputChannelCount;
//Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate)
mHeartbeatManager = heartbeatManager;
mChannelSamplesDispatcher = new Dispatcher<>(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelSamplesDispatcher.setListener(queued -> {
mChannelResultsDispatcher = new Dispatcher(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelResultsDispatcher.setListener(queued -> {
try
{
applyPendingUpdates(queued.sequence());
mCurrentSampleTimestamp = queued.timestamp();
process(queued.samples(), queued.blockCount());
mCurrentSampleTimestamp = queued.channelResults().getTimestamp();
process(queued.channelResults());
}
catch(Throwable t)
{
mLog.error("Error processing channel samples", t);
mLog.error("Error processing channel results", t);
}
finally
{
mSamplePool.offer(queued.samples());
queued.channelResults().release();
}
});
}
/**
* Sets the I/Q offsets within each channel results block for the polyphase channel(s) that this processor copies.
* The offsets take effect at the first channel results batch received after this method is invoked, the same as a
* change queued with enqueueUpdate(), so a change of offsets and of the mixer frequency apply to the same batch.
* This should only be invoked on the thread that delivers channel results, or before results are delivered.
* @param offsets for each polyphase channel, which is twice the channel index.
*/
protected void setChannelOffsets(int... offsets)
{
mChannelOffsets = offsets.clone();
}
/**
* Current I/Q offsets within each channel results block for the polyphase channel(s) that this processor copies.
*/
protected int[] getChannelOffsets()
{
return mChannelOffsets.clone();
}
/**
* Queues a configuration change to apply on the dispatcher thread, so that configuration changes don't overlap with
* sample processing. The change takes effect at the first channel results batch received after this method is
@@ -148,13 +119,13 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
@Override
public void start()
{
mChannelSamplesDispatcher.start();
mChannelResultsDispatcher.start();
}
@Override
public void stop()
{
mChannelSamplesDispatcher.stop();
mChannelResultsDispatcher.stop();
}
/**
@@ -176,66 +147,22 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
{
}
/**
* Copies this processor's polyphase channel(s) from the channel results batch and queues the copy for processing on
* the dispatcher thread. The copy is small (about 8 kB per polyphase channel for a 1024 block batch), so the batch
* isn't retained beyond this method and its large shared sample array returns to the channelizer's pool as soon as
* the channelizer has dispatched it to every channel. A slow channel then queues only its own samples.
*
* @param channelResults batch to copy from
*/
@Override
public void receiveChannelResults(ChannelResultsBatch channelResults)
{
long sequence = mBatchSequence.incrementAndGet();
channelResults.retain();
if(!mChannelSamplesDispatcher.isRunning())
if(!mChannelResultsDispatcher.offer(new QueuedChannelResults(channelResults, mBatchSequence.incrementAndGet())))
{
return;
}
int[] offsets = mChannelOffsets;
float[] source = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int blockCount = channelResults.getBlockCount();
float[] samples = getPooledArray(blockCount * offsets.length * 2);
int pointer = 0;
for(int block = 0; block < blockCount; block++)
{
int blockOffset = block * blockLength;
for(int offset : offsets)
{
samples[pointer++] = source[blockOffset + offset];
samples[pointer++] = source[blockOffset + offset + 1];
}
}
if(!mChannelSamplesDispatcher.offer(new QueuedChannelSamples(samples, blockCount, channelResults.getTimestamp(),
sequence)))
{
mSamplePool.offer(samples);
channelResults.release();
}
}
/**
* Provides a reused sample array of the requested length when one is available, or a new array.
* Sub-class implementation to process one polyphase channelizer results batch.
* @param channelResults to process
*/
private float[] getPooledArray(int length)
{
float[] samples = mSamplePool.poll();
return samples != null && samples.length == length ? samples : new float[length];
}
/**
* Sub-class implementation to process one batch of copied channel samples.
* @param samples for each block in order, with the I/Q pair of each polyphase channel in the order of the channel
* offsets, for example I1,Q1,I2,Q2 per block for two channels.
* @param blockCount number of blocks. Batches start on an even block index, so the index of a block within this
* batch has the same parity as its absolute block index.
*/
public abstract void process(float[] samples, int blockCount);
public abstract void process(ChannelResultsBatch channelResults);
@Override
public int getInputChannelCount()
@@ -244,10 +171,9 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
}
/**
* Copied channel samples with the timestamp of the batch they were copied from and the batch's position in the
* sequence of received batches.
* Channel results batch and its position in the sequence of received batches.
*/
private record QueuedChannelSamples(float[] samples, int blockCount, long timestamp, long sequence) {}
private record QueuedChannelResults(ChannelResultsBatch channelResults, long sequence) {}
/**
* Configuration change and the sequence number of the last batch received before the change was requested.

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
@@ -18,9 +18,9 @@
*/
package io.github.dsheirer.dsp.filter.channelizer.output;
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,6 +29,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{
private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class);
private final OneChannelMixerAssembler mMixerAssembler;
private int mChannelOffset;
/**
* Processor to extract a single channel from a polyphase channelizer and produce an output I/Q complex sample
@@ -54,7 +55,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{
StringBuilder sb = new StringBuilder();
sb.append("One Channel Output Processor");
sb.append("\n\tIndex (doubled) ").append(Arrays.toString(getChannelOffsets()));
sb.append("\n\tIndex (doubled) [").append(mChannelOffset).append("]");
sb.append("\n\tMixer Assembler: none");
return sb.toString();
}
@@ -80,7 +81,8 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
//Set the channelized output results offset to twice the channel index to account for each channel having
//an I/Q pair
setChannelOffsets(indexes.get(0) * 2);
int channelOffset = indexes.get(0) * 2;
enqueueUpdate(() -> mChannelOffset = channelOffset);
}
@Override
@@ -90,18 +92,19 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
}
/**
* Passes the copied channel samples to the assembler. The assembler will apply frequency translation and gain and
* indicate when a buffer is fully assembled.
* Extract the channel from the channel results array and pass to the assembler. The assembler will
* apply frequency translation and gain and indicate when a buffer is fully assembled.
*
* @param samples containing an I/Q pair for each block (I0,Q0,I1,Q1...In,Qn)
* @param blockCount number of blocks
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
*/
@Override
public void process(float[] samples, int blockCount)
public void process(ChannelResultsBatch channelResults)
{
int length = blockCount * 2;
float[] samples = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int channelOffset = mChannelOffset;
for(int index = 0; index < length; index += 2)
for(int index = channelOffset; index < samples.length; index += blockLength)
{
mMixerAssembler.receive(samples[index], samples[index + 1]);

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
@@ -18,9 +18,9 @@
*/
package io.github.dsheirer.dsp.filter.channelizer.output;
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
import io.github.dsheirer.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,6 +29,8 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{
private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class);
private TwoChannelMixerAssembler mMixerAssembler;
private int mChannelOffset1;
private int mChannelOffset2;
/**
* Processor to extract two channels from a polyphase channelizer, synthesize/recombine the channels, apply
@@ -58,7 +60,7 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{
StringBuilder sb = new StringBuilder();
sb.append("Two Channel Output Processor");
sb.append("\n\tIndices (doubled) ").append(Arrays.toString(getChannelOffsets()));
sb.append("\n\tIndices (doubled) 1 [").append(mChannelOffset1).append("] 2 [").append(mChannelOffset2).append("]");
sb.append("\n\tMixer Assembler: ").append(mMixerAssembler.getStateDescription());
return sb.toString();
}
@@ -96,32 +98,45 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
//Set the channelized output results offsets to twice the channel index to account for each channel having
//an I/Q pair
setChannelOffsets(indexes.get(0) * 2, indexes.get(1) * 2);
int channelOffset1 = indexes.get(0) * 2;
int channelOffset2 = indexes.get(1) * 2;
enqueueUpdate(() -> {
mChannelOffset1 = channelOffset1;
mChannelOffset2 = channelOffset2;
});
}
/**
* Synthesizes the two copied channels, applies frequency translation, and delivers the frequency-corrected channel
* I/Q sample set to the complex sample listener.
* Extract the channel from the channel results array, apply frequency translation, and deliver the
* extracted frequency-corrected channel I/Q sample set to the complex sample listener.
*
* @param samples containing an I/Q pair for each of the two channels per block (I1,Q1,I2,Q2 ...)
* @param blockCount number of blocks
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
*/
@Override
public void process(float[] samples, int blockCount)
public void process(ChannelResultsBatch channelResults)
{
float[] samples = channelResults.getSamples();
int blockLength = channelResults.getBlockLength();
int blockCount = channelResults.getBlockCount();
int channelOffset1 = mChannelOffset1;
int channelOffset2 = mChannelOffset2;
//Translate channel 2 up by FS/2 (multiply by (-1)^n) so that it sits adjacent to channel 1 for synthesis. The
//channelizer dispatches even-sized batches, so the index within the batch carries the absolute block parity.
for(int x = 0; x < blockCount; x++)
{
int block = x * 4;
int block = x * blockLength;
if((x & 1) == 0)
{
mMixerAssembler.receive(samples[block], samples[block + 1], samples[block + 2], samples[block + 3]);
mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
samples[block + channelOffset2], samples[block + channelOffset2 + 1]);
}
else
{
mMixerAssembler.receive(samples[block], samples[block + 1], -samples[block + 2], -samples[block + 3]);
mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
-samples[block + channelOffset2], -samples[block + channelOffset2 + 1]);
}
if(mMixerAssembler.hasBuffer())

View File

@@ -42,7 +42,6 @@ public class DcRemovalFilterFactory
case VECTOR_SIMD_PREFERRED:
return new VectorDcRemovalFilter(gain);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarDcRemovalFilter(gain);
}

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

@@ -52,7 +52,6 @@ public class FmDemodulatorFactory
case VECTOR_SIMD_512:
return new VectorFMDemodulator512();
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarFMDemodulator();
}

View File

@@ -44,7 +44,6 @@ public class ComplexGainFactory
return new VectorComplexGainControl();
}
case SCALAR:
case UNCALIBRATED:
default:
return new ComplexGainControl();
}
@@ -65,7 +64,6 @@ public class ComplexGainFactory
return new VectorComplexGain(gain);
}
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexGain(gain);
}

View File

@@ -52,7 +52,6 @@ public class MagnitudeFactory
case VECTOR_SIMD_512:
return new VectorMagnitudeCalculator512();
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarMagnitudeCalculator();
}

View File

@@ -49,7 +49,6 @@ public class ComplexMixerFactory
return new VectorComplexMixer(frequency, sampleRate);
}
case SCALAR:
case UNCALIBRATED:
{
return new ScalarComplexMixer(frequency, sampleRate);
}

View File

@@ -49,7 +49,6 @@ public class OscillatorFactory
case VECTOR_SIMD_PREFERRED:
return new VectorRealOscillator(frequency, sampleRate);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarRealOscillator(frequency, sampleRate);
}
@@ -70,7 +69,6 @@ public class OscillatorFactory
case VECTOR_SIMD_PREFERRED:
return new VectorComplexOscillator(frequency, sampleRate);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexOscillator(frequency, sampleRate);
}

View File

@@ -45,8 +45,7 @@ public class DifferentialDemodulatorFactory
case VECTOR_SIMD_128 -> new DifferentialDemodulatorFloatVector128(sampleRate, symbolRate);
case VECTOR_SIMD_256 -> new DifferentialDemodulatorFloatVector256(sampleRate, symbolRate);
case VECTOR_SIMD_512 -> new DifferentialDemodulatorFloatVector512(sampleRate, symbolRate);
case SCALAR, UNCALIBRATED -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate); //Includes SCALAR case
};
}
}

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

@@ -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

@@ -1,35 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import javafx.scene.canvas.GraphicsContext;
/**
* Overlay drawn over the map tiles, in the order the layers were added to the {@link TileMapView}.
*/
public interface MapLayer
{
/**
* Draws the layer. Called on the JavaFX thread.
* @param gc of the map canvas, in screen pixels
* @param map for converting positions to screen pixels
*/
void draw(GraphicsContext gc, TileMapView map);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,203 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.map.GeoPosition;
import io.github.dsheirer.preference.map.MapPreference;
/**
* Part of the world in view: the center point, the tile zoom level and the size of the view in pixels, with the
* conversions between positions and screen pixels. The map repeats east and west, so it can be panned around the
* world, and it stops at the top and bottom of the projection. Not thread safe: use it on the JavaFX thread.
*/
public class MapViewport
{
private double mCenterX = Mercator.x(0);
private double mCenterY = Mercator.y(0);
private int mZoom = 2;
private double mWidth;
private double mHeight;
/**
* Constructs an instance
*/
public MapViewport()
{
}
/**
* Tile zoom level
*/
public int getZoom()
{
return mZoom;
}
/**
* Sets the tile zoom level, keeping the center point
* @param zoom level, clamped to the map preference's range
*/
public void setZoom(int zoom)
{
mZoom = Math.clamp(zoom, MapPreference.MINIMUM_TILE_ZOOM, MapPreference.MAXIMUM_TILE_ZOOM);
clamp();
}
/**
* Changes the zoom level, keeping the position under the screen point in place
* @param zoom level, clamped to the map preference's range
* @param x of the screen point
* @param y of the screen point
*/
public void zoomAt(int zoom, double x, double y)
{
double worldX = (getLeft() + x) / getWorldSize();
double worldY = (getTop() + y) / getWorldSize();
mZoom = Math.clamp(zoom, MapPreference.MINIMUM_TILE_ZOOM, MapPreference.MAXIMUM_TILE_ZOOM);
mCenterX = worldX - (x - mWidth / 2.0) / getWorldSize();
mCenterY = worldY - (y - mHeight / 2.0) / getWorldSize();
clamp();
}
public double getWidth()
{
return mWidth;
}
public double getHeight()
{
return mHeight;
}
/**
* Sets the size of the view, keeping the center point
*/
public void setSize(double width, double height)
{
mWidth = Math.max(0, width);
mHeight = Math.max(0, height);
clamp();
}
/**
* Center point of the view
*/
public GeoPosition getCenter()
{
return new GeoPosition(Mercator.latitude(mCenterY), Mercator.longitude(mCenterX));
}
/**
* Centers the view on the position
*/
public void setCenter(GeoPosition position)
{
mCenterX = Mercator.x(position.getLongitude());
mCenterY = Mercator.y(position.getLatitude());
clamp();
}
/**
* Moves the view by screen pixels, as when the map is dragged by the opposite amount
* @param dx pixels to move the view east
* @param dy pixels to move the view south
*/
public void pan(double dx, double dy)
{
mCenterX += dx / getWorldSize();
mCenterY += dy / getWorldSize();
clamp();
}
/**
* World width and height in pixels at the current zoom level
*/
public double getWorldSize()
{
return Mercator.worldSize(mZoom);
}
/**
* World pixel at the left edge of the view, which is whole so tiles line up with screen pixels. It can be
* negative or past the world width, since the map repeats east and west.
*/
public double getLeft()
{
return Math.round(mCenterX * getWorldSize() - mWidth / 2.0);
}
/**
* World pixel at the top edge of the view, which is whole so tiles line up with screen pixels
*/
public double getTop()
{
return Math.round(mCenterY * getWorldSize() - mHeight / 2.0);
}
/**
* Screen x of the longitude, for the copy of the world nearest the middle of the view
*/
public double getScreenX(double longitude)
{
double worldSize = getWorldSize();
double x = Mercator.x(longitude) * worldSize - getLeft();
double middle = mWidth / 2.0;
return x - Math.round((x - middle) / worldSize) * worldSize;
}
/**
* Screen y of the latitude
*/
public double getScreenY(double latitude)
{
return Mercator.y(latitude) * getWorldSize() - getTop();
}
/**
* Position at the screen point
*/
public GeoPosition getPosition(double x, double y)
{
double worldSize = getWorldSize();
return new GeoPosition(Mercator.latitude((getTop() + y) / worldSize),
Mercator.longitude((getLeft() + x) / worldSize));
}
/**
* Keeps the center within one copy of the world, and the top and bottom of the map at the edges of the view, or
* the map in the middle when it's shorter than the view
*/
private void clamp()
{
mCenterX = mCenterX - Math.floor(mCenterX);
double worldSize = getWorldSize();
double halfHeight = mHeight / 2.0 / worldSize;
if(halfHeight >= 0.5)
{
mCenterY = 0.5;
}
else
{
mCenterY = Math.clamp(mCenterY, halfHeight, 1.0 - halfHeight);
}
}
}

View File

@@ -1,100 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
/**
* Web (spherical) Mercator projection used by OpenStreetMap tiles. Positions are expressed as fractions of the world
* width and height (0 to 1), independent of the zoom level: x grows eastward from -180 degrees longitude and y grows
* southward from the top of the map at about 85.05 degrees north latitude.
*/
public final class Mercator
{
/**
* Pixel width and height of a map tile
*/
public static final int TILE_SIZE = 256;
/**
* Northern and southern limit of the projection, where the map is square
*/
public static final double MAX_LATITUDE = 85.05112878;
private Mercator()
{
}
/**
* World width and height in pixels at the zoom level
*/
public static double worldSize(int zoom)
{
return TILE_SIZE * (double)(1L << zoom);
}
/**
* Number of tiles across the world at the zoom level
*/
public static int tileCount(int zoom)
{
return 1 << zoom;
}
/**
* Longitude to a fraction of the world width
*/
public static double x(double longitude)
{
return (longitude + 180.0) / 360.0;
}
/**
* Latitude to a fraction of the world height, clamped to the projection's limits
*/
public static double y(double latitude)
{
double radians = Math.toRadians(Math.clamp(latitude, -MAX_LATITUDE, MAX_LATITUDE));
return (1.0 - Math.log(Math.tan(radians) + 1.0 / Math.cos(radians)) / Math.PI) / 2.0;
}
/**
* Fraction of the world width to a longitude, wrapped into -180 to 180 degrees
*/
public static double longitude(double x)
{
return normalizeLongitude(x * 360.0 - 180.0);
}
/**
* Fraction of the world height to a latitude
*/
public static double latitude(double y)
{
double n = Math.PI * (1.0 - 2.0 * Math.clamp(y, 0.0, 1.0));
return Math.toDegrees(Math.atan(Math.sinh(n)));
}
/**
* Wraps a longitude into -180 to 180 degrees, since the map can be panned past +/-180 degrees
*/
public static double normalizeLongitude(double longitude)
{
return ((longitude + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;
}
}

View File

@@ -1,220 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.preference.radioreference.RadioReferencePreference;
import io.github.dsheirer.rrapi.type.Coverage;
import io.github.dsheirer.service.radioreference.DistanceFormat;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
/**
* Card with the details of radio reference trunked system sites, shown when the mouse rests over a site's tower on the
* map: the system and protocol, the site, and the site's channels.
*/
public final class SiteCard
{
private static final int MAX_SITES = 3;
private static final int CHANNEL_COLUMNS = 3;
private static final int MAX_CHANNELS = 24;
private static final double MAX_TEXT_WIDTH = 380;
private static final String SEPARATOR = " · ";
private static final String STYLE = "-fx-background-color: -fx-control-inner-background; " +
"-fx-border-color: -fx-box-border; -fx-background-radius: 3; -fx-border-radius: 3; -fx-padding: 6; " +
"-fx-effect: dropshadow(gaussian, rgba(0,0,0,0.35), 6, 0, 1, 2);";
/**
* Channel frequency with a control channel marker: C for control, A for alternate control, or null
*/
public record Channel(String frequency, String marker) {}
/**
* Details of one site
* @param title system name
* @param lines protocol, site, identifiers
* @param channels of the site, up to the card's limit
* @param notes about the channels
*/
public record Entry(String title, List<String> lines, List<Channel> channels, List<String> notes) {}
/**
* Card content
* @param entries for the sites shown, nearest first
* @param moreSites count of the sites under the mouse that aren't shown
*/
public record Content(List<Entry> entries, int moreSites) {}
private SiteCard()
{
}
/**
* Content of the card for the sites
* @param sites under the mouse, nearest first
* @param location of the user, for the distances, or null
*/
public static Content content(List<SiteRecord> sites, RadioReferencePreference.Location location)
{
DecimalFormat frequencyFormat = new DecimalFormat("0.00000");
List<Entry> entries = new ArrayList<>();
int shown = Math.min(sites.size(), MAX_SITES);
for(int index = 0; index < shown; index++)
{
SiteRecord site = sites.get(index);
List<String> lines = new ArrayList<>();
addLine(lines, site.protocol(), site.voice());
String distance = location != null ? DistanceFormat.format(Coverage.distanceKilometers(
location.latitude(), location.longitude(), site.latitude(), site.longitude())) : null;
addLine(lines, "Site " + site.siteNumber(), site.description(), site.county(), distance);
addLine(lines, site.nac() != null ? "NAC " + site.nac() : null,
site.rfss() > 0 ? "RFSS " + site.rfss() : null, site.zone() > 0 ? "Zone " + site.zone() : null);
List<Channel> channels = new ArrayList<>();
List<String> notes = new ArrayList<>();
boolean control = false;
if(site.channels() != null)
{
for(SiteRecord.SiteChannel channel: site.channels().subList(0, Math.min(site.channels().size(),
MAX_CHANNELS)))
{
String marker = "Control".equals(channel.use()) ? "C" :
"Alternate control".equals(channel.use()) ? "A" : null;
control |= marker != null;
channels.add(new Channel(frequencyFormat.format(channel.frequencyHz() / 1E6), marker));
}
if(site.channels().size() > MAX_CHANNELS)
{
notes.add("+ " + (site.channels().size() - MAX_CHANNELS) + " more channels");
}
}
if(control)
{
notes.add("C control, A alternate control");
}
entries.add(new Entry(site.systemName() != null ? site.systemName() : "(unnamed system)", lines,
channels, notes.isEmpty() ? List.of() : List.of(String.join(SEPARATOR, notes))));
}
return new Content(entries, sites.size() - shown);
}
/**
* Card node for the content
*/
public static Region create(Content content)
{
VBox card = new VBox(2);
card.setStyle(STYLE);
card.setMaxWidth(Region.USE_PREF_SIZE);
card.setMaxHeight(Region.USE_PREF_SIZE);
Font font = Font.font(11);
Font bold = Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 11);
for(int index = 0; index < content.entries().size(); index++)
{
Entry entry = content.entries().get(index);
if(index > 0)
{
card.getChildren().add(new Separator());
}
card.getChildren().add(label(entry.title(), bold));
entry.lines().forEach(line -> card.getChildren().add(label(line, font)));
if(!entry.channels().isEmpty())
{
GridPane grid = new GridPane();
grid.setHgap(10);
for(int channelIndex = 0; channelIndex < entry.channels().size(); channelIndex++)
{
Channel channel = entry.channels().get(channelIndex);
HBox cell = new HBox(3, label(channel.frequency(), font));
if(channel.marker() != null)
{
cell.getChildren().add(label(channel.marker(), bold));
}
grid.add(cell, channelIndex % CHANNEL_COLUMNS, channelIndex / CHANNEL_COLUMNS);
}
card.getChildren().add(grid);
}
entry.notes().forEach(note -> card.getChildren().add(label(note, font)));
}
if(content.moreSites() > 0)
{
card.getChildren().add(new Separator());
card.getChildren().add(label("+ " + content.moreSites() + " more site" +
(content.moreSites() > 1 ? "s" : "") + " here", font));
}
return card;
}
private static Label label(String text, Font font)
{
Label label = new Label(text);
label.setFont(font);
label.setWrapText(true);
label.setMaxWidth(MAX_TEXT_WIDTH);
return label;
}
/**
* Adds a line with the non-empty values separated by dots, or nothing when all are empty
*/
private static void addLine(List<String> lines, String... values)
{
List<String> parts = new ArrayList<>();
for(String value: values)
{
if(value != null && !value.isBlank())
{
parts.add(value);
}
}
if(!parts.isEmpty())
{
lines.add(String.join(SEPARATOR, parts));
}
}
}

View File

@@ -1,156 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Supplier;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
/**
* Radio reference trunked system sites: a radio tower at each site, with the base of the tower at the site location.
* Use on the JavaFX thread.
*/
public class SiteLayer implements MapLayer
{
private static final Color TOWER = Color.rgb(240, 128, 32);
private static final Color OUTLINE = Color.rgb(40, 40, 40, 200 / 255.0);
private static final double TOWER_WIDTH = 1.6;
private static final double OUTLINE_WIDTH = 3.6;
private static final double HEIGHT = 16;
private static final double HALF_BASE = 5;
//Hit area around the tower, in pixels from the site location
private static final double HIT_LEFT = -10;
private static final double HIT_TOP = -24;
private static final double HIT_WIDTH = 20;
private static final double HIT_HEIGHT = 28;
private final Supplier<List<SiteRecord>> mSites;
private boolean mShowSites = true;
/**
* Constructs an instance
* @param sites to draw, read each time the map is drawn
*/
public SiteLayer(Supplier<List<SiteRecord>> sites)
{
mSites = sites;
}
/**
* Shows or hides the sites
*/
public void setShowSites(boolean show)
{
mShowSites = show;
}
public boolean isShowSites()
{
return mShowSites;
}
/**
* Sites whose tower is under the point, nearest first
* @param viewport of the map
* @param x of the point in the view
* @param y of the point in the view
* @return sites, or an empty list when the sites are hidden or none is under the point
*/
public List<SiteRecord> getSitesAt(MapViewport viewport, double x, double y)
{
if(!mShowSites)
{
return Collections.emptyList();
}
record Hit(SiteRecord site, double distance) {}
List<Hit> hits = new ArrayList<>();
for(SiteRecord site: mSites.get())
{
double dx = x - viewport.getScreenX(site.longitude());
double dy = y - viewport.getScreenY(site.latitude());
if(dx >= HIT_LEFT && dx < HIT_LEFT + HIT_WIDTH && dy >= HIT_TOP && dy < HIT_TOP + HIT_HEIGHT)
{
//Nearest to the middle of the tower first
hits.add(new Hit(site, Math.hypot(dx, dy + (HEIGHT / 2.0))));
}
}
//Stable, so sites at the same spot keep their order
hits.sort(Comparator.comparingDouble(Hit::distance));
return hits.stream().map(Hit::site).toList();
}
@Override
public void draw(GraphicsContext gc, TileMapView map)
{
if(!mShowSites)
{
return;
}
MapViewport viewport = map.getViewport();
double width = viewport.getWidth();
double height = viewport.getHeight();
gc.setLineCap(StrokeLineCap.ROUND);
gc.setLineJoin(StrokeLineJoin.ROUND);
for(SiteRecord site: mSites.get())
{
double x = viewport.getScreenX(site.longitude());
double y = viewport.getScreenY(site.latitude());
if(x >= -20 && x <= width + 20 && y >= -4 && y <= height + 30)
{
drawTower(gc, x, y, OUTLINE, OUTLINE_WIDTH);
drawTower(gc, x, y, TOWER, TOWER_WIDTH);
gc.setFill(TOWER);
gc.fillOval(x - 2, y - HEIGHT - 2, 4, 4);
}
}
}
/**
* Strokes a tower with its base at the point: an A-frame mast with a cross brace and radio waves at the top
*/
private static void drawTower(GraphicsContext gc, double x, double y, Color color, double lineWidth)
{
double top = y - HEIGHT;
gc.setStroke(color);
gc.setLineWidth(lineWidth);
gc.strokePolyline(new double[]{x - HALF_BASE, x, x + HALF_BASE}, new double[]{y, top, y}, 3);
gc.strokeLine(x - (HALF_BASE * 0.55), y - (HEIGHT * 0.45), x + (HALF_BASE * 0.55), y - (HEIGHT * 0.45));
gc.strokeArc(x - 5, top - 4, 10, 8, 135, 90, ArcType.OPEN);
gc.strokeArc(x - 5, top - 4, 10, 8, -45, 90, ArcType.OPEN);
gc.strokeArc(x - 9, top - 7, 18, 14, 135, 90, ArcType.OPEN);
gc.strokeArc(x - 9, top - 7, 18, 14, -45, 90, ArcType.OPEN);
}
}

View File

@@ -1,122 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Entry in the tile server chooser: a server with tiles that follow the theme, or always light or always dark tiles.
* Dark tiles come from the server's dark style, or are recolored light tiles when it has none.
* @param server tile server
* @param style of the tiles
*/
public record TileChoice(TileServer server, Style style)
{
/**
* Tile style. The name is stored in the map preference. Don't change it.
*/
public enum Style
{
THEME(" - Auto"),
LIGHT(" - Light"),
DARK(" - Dark");
private final String mSuffix;
Style(String suffix)
{
mSuffix = suffix;
}
}
/**
* Choices offered to the user, in menu order: each server following the theme, then light, then dark
*/
public static final List<TileChoice> CHOICES;
static
{
List<TileChoice> choices = new ArrayList<>();
for(TileServer server: TileServer.SERVERS)
{
for(Style style: Style.values())
{
choices.add(new TileChoice(server, style));
}
}
CHOICES = Collections.unmodifiableList(choices);
}
/**
* Choice with the server and style
* @param serverId from the map preference, or null
* @param style name from the map preference, or null
* @return choice, following the theme when the style is unknown, see {@link TileServer#get(String)}
*/
public static TileChoice get(String serverId, String style)
{
TileServer server = TileServer.get(serverId);
for(Style candidate: Style.values())
{
if(candidate.name().equals(style))
{
return new TileChoice(server, candidate);
}
}
return new TileChoice(server, Style.THEME);
}
/**
* Indicates if the tiles are dark
* @param darkTheme true when the application uses a dark theme
*/
public boolean isDark(boolean darkTheme)
{
return switch(style)
{
case THEME -> darkTheme;
case LIGHT -> false;
case DARK -> true;
};
}
/**
* Tiles to load
* @param darkTheme true when the application uses a dark theme
* @param key from the user, for a server that needs one, or null
*/
public TileSource getSource(boolean darkTheme, String key)
{
return server.getSource(isDark(darkTheme), key);
}
@Override
public String toString()
{
return server.name() + style.mSuffix;
}
}

View File

@@ -1,89 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import javafx.scene.image.Image;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
/**
* Recolors light map tiles for a dark theme: inverts each pixel's lightness while keeping its hue, so a light
* background turns dark, water stays blue and roads keep their colors. The lightness is kept within a range so
* the darkest areas aren't black and the lightest aren't white, and the colors are muted a little.
*/
public final class TileDarkener
{
//Lightness of a white pixel after recoloring, and of a black pixel
static final double DARKEST = 0.10;
static final double LIGHTEST = 0.85;
private static final double SATURATION = 0.80;
private TileDarkener()
{
}
/**
* Recolored copy of the image. Can be called on any thread.
*/
public static Image darken(Image image)
{
int width = (int)image.getWidth();
int height = (int)image.getHeight();
int[] pixels = new int[width * height];
image.getPixelReader().getPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
for(int index = 0; index < pixels.length; index++)
{
pixels[index] = darken(pixels[index]);
}
WritableImage darkened = new WritableImage(width, height);
darkened.getPixelWriter().setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
return darkened;
}
/**
* Recolors one ARGB pixel: the HSL lightness L becomes DARKEST + (LIGHTEST - DARKEST) * (1 - L), and the
* saturation is scaled by SATURATION, keeping the hue and alpha
*/
static int darken(int argb)
{
double r = ((argb >> 16) & 0xFF) / 255.0;
double g = ((argb >> 8) & 0xFF) / 255.0;
double b = (argb & 0xFF) / 255.0;
double max = Math.max(r, Math.max(g, b));
double min = Math.min(r, Math.min(g, b));
double lightness = (max + min) / 2.0;
double chroma = max - min;
double target = DARKEST + (LIGHTEST - DARKEST) * (1.0 - lightness);
//Chroma that keeps the saturation at the new lightness: saturation = chroma / (1 - |2L - 1|)
double room = 1.0 - Math.abs(2.0 * lightness - 1.0);
double scale = chroma > 0 && room > 0 ? SATURATION * (1.0 - Math.abs(2.0 * target - 1.0)) / room : 0;
return (argb & 0xFF000000) | (channel(target + (r - lightness) * scale) << 16) |
(channel(target + (g - lightness) * scale) << 8) | channel(target + (b - lightness) * scale);
}
private static int channel(double value)
{
return (int)Math.round(Math.clamp(value, 0.0, 1.0) * 255.0);
}
}

View File

@@ -1,39 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
/**
* Map tile address in the OpenStreetMap (slippy map) scheme
* @param zoom level, 0 for the whole world in one tile
* @param x tile column, 0 to 2^zoom - 1, west to east
* @param y tile row, 0 to 2^zoom - 1, north to south
*/
public record TileKey(int zoom, int x, int y)
{
/**
* Tile that covers this tile at a lower (farther) zoom level
* @param levels to go up, 1 or more
* @return covering tile
*/
public TileKey parent(int levels)
{
return new TileKey(zoom - levels, x >> levels, y >> levels);
}
}

View File

@@ -1,492 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javafx.scene.image.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads map tile images from a {@link TileSource} in the background, with a memory cache of recently drawn tiles and
* a disk cache that follows the tile server's caching headers. Follows the OpenStreetMap tile usage policy, which
* suits the other servers too: an identifying User-Agent, two download threads, and local caching. The newest
* requests load first and requests for tiles that scrolled out of view are dropped. Changing the source drops the
* loaded and requested tiles.
*/
public class TileLoader
{
private static final Logger mLog = LoggerFactory.getLogger(TileLoader.class);
private static final String USER_AGENT = "sdrtrunk (https://github.com/DSheirer/sdrtrunk)";
private static final int DOWNLOAD_THREADS = 2;
//256 tiles of 256x256 pixels is about 64 MB
private static final int MEMORY_CACHE_TILES = 256;
private static final Duration DEFAULT_EXPIRY = Duration.ofDays(7);
private static final Duration MINIMUM_EXPIRY = Duration.ofHours(1);
private static final Duration RETRY_DELAY = Duration.ofSeconds(60);
private static final long DISK_CACHE_LIMIT_BYTES = 512L * 1024 * 1024;
private static final long DISK_CACHE_TRIM_BYTES = 400L * 1024 * 1024;
private static final Pattern MAX_AGE = Pattern.compile("max-age=(\\d+)");
private final Path mCacheDirectory;
private final Consumer<TileKey> mLoadedListener;
private final HttpClient mHttpClient;
private final Map<TileKey,Image> mMemoryCache = new LinkedHashMap<>(MEMORY_CACHE_TILES, 0.75f, true)
{
@Override
protected boolean removeEldestEntry(Map.Entry<TileKey,Image> eldest)
{
return size() > MEMORY_CACHE_TILES;
}
};
private final LinkedBlockingDeque<TileKey> mQueue = new LinkedBlockingDeque<>();
private final Set<TileKey> mPending = ConcurrentHashMap.newKeySet();
private final Map<TileKey,Long> mFailures = new ConcurrentHashMap<>();
private volatile Set<TileKey> mWanted = Collections.emptySet();
private volatile TileSource mSource;
private final AtomicBoolean mTrimmed = new AtomicBoolean();
private final List<Thread> mThreads = new ArrayList<>();
private volatile boolean mRunning = true;
/**
* Constructs an instance and starts the download threads. Nothing loads until a source is set.
* @param cacheDirectory for the disk cache, with a folder for each source, or null for no disk cache
* @param loadedListener notified on a download thread when a requested tile is ready in {@link #get(TileKey)}
*/
public TileLoader(Path cacheDirectory, Consumer<TileKey> loadedListener)
{
mCacheDirectory = cacheDirectory;
mLoadedListener = loadedListener;
mHttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL).build();
for(int index = 0; index < DOWNLOAD_THREADS; index++)
{
Thread thread = Thread.ofPlatform().daemon().name("sdrtrunk map tile loader " + index)
.unstarted(this::run);
mThreads.add(thread);
thread.start();
}
}
/**
* Sets the tiles to load, dropping the loaded and requested tiles of the previous source. Call on the thread that
* requests tiles.
* @param source of the tiles, or null to load none
*/
public void setSource(TileSource source)
{
if(Objects.equals(source, mSource))
{
return;
}
mSource = source;
mQueue.clear();
mPending.clear();
mFailures.clear();
synchronized(mMemoryCache)
{
mMemoryCache.clear();
}
}
/**
* Tile image from the memory cache
* @param key of the tile
* @return image, or null when it isn't loaded
*/
public Image get(TileKey key)
{
synchronized(mMemoryCache)
{
return mMemoryCache.get(key);
}
}
/**
* Sets the tiles that are in view. Queued requests for other tiles are dropped when they come up.
*/
public void setWanted(Set<TileKey> wanted)
{
mWanted = Set.copyOf(wanted);
}
/**
* Requests a tile, unless it's loaded, already requested, or failed recently. The newest request loads first.
*/
public void request(TileKey key)
{
TileSource source = mSource;
if(source == null || !source.isAvailable() || get(key) != null)
{
return;
}
Long failed = mFailures.get(key);
if(failed != null && System.currentTimeMillis() < failed + RETRY_DELAY.toMillis())
{
return;
}
if(mPending.add(key))
{
mQueue.addLast(key);
}
else if(mQueue.remove(key))
{
//Requested again, so move it to the front of the line
mQueue.addLast(key);
}
}
/**
* Stops the download threads
*/
public void dispose()
{
mRunning = false;
mThreads.forEach(Thread::interrupt);
}
/**
* Download thread: takes the newest request, from the disk cache when it's fresh, else from the tile server
*/
private void run()
{
trimDiskCache();
while(mRunning)
{
TileKey key;
try
{
key = mQueue.takeLast();
}
catch(InterruptedException e)
{
return;
}
TileSource source = mSource;
try
{
if(source != null && source.isAvailable() && mWanted.contains(key))
{
Image image = load(key, source);
//Drop the tile when the source changed while it loaded
if(source == mSource)
{
if(image != null)
{
mFailures.remove(key);
synchronized(mMemoryCache)
{
mMemoryCache.put(key, image);
}
mLoadedListener.accept(key);
}
else
{
mFailures.put(key, System.currentTimeMillis());
}
}
}
}
catch(Exception e)
{
mLog.error("Error loading map tile " + (source != null ? source.cacheName() : "") + " " + key, e);
mFailures.put(key, System.currentTimeMillis());
}
finally
{
mPending.remove(key);
}
}
}
/**
* Loads a tile from the disk cache while it's fresh, else downloads it, falling back to a stale cached copy when the
* download fails. Recolors the tile when the source darkens its tiles.
* @return image, or null
*/
private Image load(TileKey key, TileSource source)
{
Path file = getCacheFile(key, source);
byte[] bytes = null;
boolean fresh = false;
if(file != null && Files.isRegularFile(file))
{
try
{
//The file's modified time is when it expires
fresh = Files.getLastModifiedTime(file).toMillis() > System.currentTimeMillis();
bytes = Files.readAllBytes(file);
}
catch(IOException e)
{
bytes = null;
}
}
if(!fresh)
{
byte[] downloaded = download(key, file, source);
if(downloaded != null)
{
bytes = downloaded;
}
}
if(bytes == null)
{
return null;
}
Image image = new Image(new ByteArrayInputStream(bytes));
if(image.isError())
{
return null;
}
return source.darken() ? TileDarkener.darken(image) : image;
}
/**
* Downloads the tile and stores it in the disk cache
* @param key of the tile
* @param file of the disk cache, or null
* @param source of the tile
* @return tile image bytes, or null when the download failed
*/
private byte[] download(TileKey key, Path file, TileSource source)
{
if(!mRunning)
{
return null;
}
URI uri = URI.create(source.getUrl(key));
//The URL can hold the user's key, so the log names the source and the tile instead
String tile = source.cacheName() + " " + key;
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(20))
.header("User-Agent", USER_AGENT).GET().build();
try
{
HttpResponse<byte[]> response = mHttpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
if(response.statusCode() != 200)
{
mLog.debug("Map tile " + tile + " response " + response.statusCode());
return null;
}
byte[] bytes = response.body();
if(file != null)
{
store(file, bytes, getExpiry(response));
}
return bytes;
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch(IOException e)
{
mLog.debug("Unable to download map tile " + tile + " - " + e.getMessage());
}
return null;
}
/**
* Time the tile expires: the Cache-Control max-age, else the Expires header, else a week, and at least an hour
*/
private static long getExpiry(HttpResponse<?> response)
{
long now = System.currentTimeMillis();
Duration expiry = DEFAULT_EXPIRY;
Optional<String> cacheControl = response.headers().firstValue("Cache-Control");
Optional<String> expires = response.headers().firstValue("Expires");
if(cacheControl.isPresent())
{
Matcher matcher = MAX_AGE.matcher(cacheControl.get());
if(matcher.find())
{
expiry = Duration.ofSeconds(Long.parseLong(matcher.group(1)));
}
}
else if(expires.isPresent())
{
try
{
long time = ZonedDateTime.parse(expires.get(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()
.toEpochMilli();
expiry = Duration.ofMillis(time - now);
}
catch(Exception e)
{
//Use the default
}
}
if(expiry.compareTo(MINIMUM_EXPIRY) < 0)
{
expiry = MINIMUM_EXPIRY;
}
return now + expiry.toMillis();
}
/**
* Writes the tile to the disk cache, with its modified time set to when it expires
*/
private static void store(Path file, byte[] bytes, long expiry)
{
try
{
Files.createDirectories(file.getParent());
Path temporary = Files.createTempFile(file.getParent(), "tile", ".tmp");
Files.write(temporary, bytes);
Files.setLastModifiedTime(temporary, FileTime.fromMillis(expiry));
Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
catch(IOException e)
{
mLog.debug("Unable to cache map tile " + file + " - " + e.getMessage());
}
}
private Path getCacheFile(TileKey key, TileSource source)
{
return mCacheDirectory != null ? mCacheDirectory.resolve(source.cacheName())
.resolve(String.valueOf(key.zoom())).resolve(String.valueOf(key.x())).resolve(key.y() + ".tile") : null;
}
/**
* Deletes the tiles that expire first when the disk cache grows past its limit. Runs once per instance.
*/
private void trimDiskCache()
{
if(mCacheDirectory == null || !Files.isDirectory(mCacheDirectory) || mTrimmed.getAndSet(true))
{
return;
}
record CachedTile(Path path, long size, long expiry) {}
List<CachedTile> tiles = new ArrayList<>();
try(Stream<Path> stream = Files.walk(mCacheDirectory))
{
stream.filter(Files::isRegularFile).forEach(path -> {
try
{
tiles.add(new CachedTile(path, Files.size(path), Files.getLastModifiedTime(path).toMillis()));
}
catch(IOException e)
{
//Skip it
}
});
}
catch(IOException e)
{
mLog.debug("Unable to read the map tile cache - " + e.getMessage());
return;
}
long total = tiles.stream().mapToLong(CachedTile::size).sum();
if(total <= DISK_CACHE_LIMIT_BYTES)
{
return;
}
tiles.sort(Comparator.comparingLong(CachedTile::expiry));
int deleted = 0;
for(CachedTile tile: tiles)
{
if(total <= DISK_CACHE_TRIM_BYTES)
{
break;
}
try
{
Files.deleteIfExists(tile.path());
total -= tile.size();
deleted++;
}
catch(IOException e)
{
//Skip it
}
}
mLog.info("Trimmed the map tile cache: deleted " + deleted + " tiles");
}
}

View File

@@ -1,546 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.map.GeoPosition;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.input.ZoomEvent;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
/**
* JavaFX slippy map: tiles from a {@link TileSource} drawn on a canvas, with {@link MapLayer} overlays. While a tile
* loads, the matching part of a loaded tile from a farther zoom level stands in for it. Past the source's highest
* zoom level, its closest tiles are enlarged.
*
* Mouse: drag with the primary button to pan, scroll to zoom at the mouse, double-click or middle-click to center and
* zoom in. Keys: arrows pan, plus and minus zoom. Use on the JavaFX thread.
*/
public class TileMapView extends Region
{
private static final Color BACKGROUND = Color.rgb(221, 221, 221);
private static final Color DARK_BACKGROUND = Color.rgb(38, 38, 38);
private static final Color ATTRIBUTION_BACKGROUND = Color.rgb(255, 255, 255, 0.75);
private static final Color DARK_ATTRIBUTION_BACKGROUND = Color.rgb(30, 30, 30, 0.75);
private static final Color ATTRIBUTION_TEXT = Color.rgb(40, 40, 40);
private static final Color DARK_ATTRIBUTION_TEXT = Color.rgb(210, 210, 210);
private static final Font ATTRIBUTION_FONT = Font.font(11);
private static final Font MESSAGE_FONT = Font.font(14);
private static final int FALLBACK_LEVELS = 5;
//Scroll distance for one zoom step: one mouse wheel notch, or several trackpad events
private static final double SCROLL_STEP = 40.0;
private static final double PINCH_STEP = 1.4;
private static final double KEY_PAN_PIXELS = 64.0;
private final Canvas mCanvas = new Canvas();
private final MapViewport mViewport = new MapViewport();
private final TileLoader mTileLoader;
private final List<MapLayer> mLayers = new ArrayList<>();
private final List<Runnable> mViewListeners = new CopyOnWriteArrayList<>();
private final ReadOnlyIntegerWrapper mZoom = new ReadOnlyIntegerWrapper(mViewport.getZoom());
private final Text mMeasure = new Text();
private TileSource mSource;
private boolean mRedrawPending;
private double mDragX = Double.NaN;
private double mDragY = Double.NaN;
private double mScrollAccumulator;
private double mPinchAccumulator = 1.0;
/**
* Constructs an instance
* @param cacheDirectory for the map tiles on disk, or null to not keep tiles on disk
* @param loadTiles true to download tiles, or false for a blank map (tests and off-screen rendering)
*/
public TileMapView(Path cacheDirectory, boolean loadTiles)
{
mTileLoader = loadTiles ? new TileLoader(cacheDirectory, key -> Platform.runLater(this::requestRedraw)) : null;
getChildren().add(mCanvas);
setFocusTraversable(true);
setMinSize(0, 0);
setPrefSize(600, 400);
addEventHandler(MouseEvent.MOUSE_PRESSED, this::mousePressed);
addEventHandler(MouseEvent.MOUSE_DRAGGED, this::mouseDragged);
addEventHandler(MouseEvent.MOUSE_RELEASED, this::mouseReleased);
addEventHandler(MouseEvent.MOUSE_CLICKED, this::mouseClicked);
addEventHandler(ScrollEvent.SCROLL, this::scrolled);
addEventHandler(ZoomEvent.ZOOM_STARTED, event -> mPinchAccumulator = 1.0);
addEventHandler(ZoomEvent.ZOOM, this::pinched);
addEventHandler(KeyEvent.KEY_PRESSED, this::keyPressed);
}
/**
* Viewport, for converting positions to screen pixels
*/
public MapViewport getViewport()
{
return mViewport;
}
/**
* Sets the tiles to show, dropping the tiles of the previous source
* @param source of the tiles, or null to show none
*/
public void setSource(TileSource source)
{
mSource = source;
if(mTileLoader != null)
{
mTileLoader.setSource(source);
}
requestRedraw();
}
/**
* Source of the tiles, or null
*/
public TileSource getSource()
{
return mSource;
}
/**
* Tile zoom level, updated when the map zooms
*/
public ReadOnlyIntegerProperty zoomProperty()
{
return mZoom.getReadOnlyProperty();
}
public int getZoom()
{
return mViewport.getZoom();
}
/**
* Sets the tile zoom level, keeping the center point
*/
public void setZoom(int zoom)
{
if(zoom != mViewport.getZoom())
{
mViewport.setZoom(zoom);
viewChanged();
}
}
/**
* Changes the zoom level, keeping the position under the screen point in place
*/
public void zoomAt(int zoom, double x, double y)
{
if(zoom != mViewport.getZoom())
{
mViewport.zoomAt(zoom, x, y);
viewChanged();
}
}
public GeoPosition getCenter()
{
return mViewport.getCenter();
}
/**
* Centers the map on the position
*/
public void setCenter(GeoPosition position)
{
if(position != null)
{
mViewport.setCenter(position);
viewChanged();
}
}
/**
* Adds a layer over the tiles and the layers added before it
*/
public void addLayer(MapLayer layer)
{
mLayers.add(layer);
requestRedraw();
}
/**
* Adds a listener that's notified on the JavaFX thread each time the map pans or zooms
*/
public void addViewListener(Runnable listener)
{
mViewListeners.add(listener);
}
/**
* Redraws the map on the next JavaFX pulse. Can be called often: the requests are combined.
*/
public void requestRedraw()
{
if(!mRedrawPending)
{
mRedrawPending = true;
Platform.runLater(() -> {
mRedrawPending = false;
draw();
});
}
}
/**
* Stops loading tiles
*/
public void dispose()
{
if(mTileLoader != null)
{
mTileLoader.dispose();
}
}
private void viewChanged()
{
mZoom.set(mViewport.getZoom());
requestRedraw();
mViewListeners.forEach(Runnable::run);
}
@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);
mViewport.setSize(width, height);
draw();
}
}
/**
* Draws the tiles and the layers now
*/
public void draw()
{
GraphicsContext gc = mCanvas.getGraphicsContext2D();
double width = mCanvas.getWidth();
double height = mCanvas.getHeight();
boolean dark = mSource != null && mSource.dark();
gc.setFill(dark ? DARK_BACKGROUND : BACKGROUND);
gc.fillRect(0, 0, width, height);
if(width <= 0 || height <= 0)
{
return;
}
if(mSource != null && mSource.isAvailable())
{
drawTiles(gc, width, height);
}
else if(mSource != null && mSource.unavailableReason() != null)
{
gc.setFill(dark ? DARK_ATTRIBUTION_TEXT : ATTRIBUTION_TEXT);
gc.setFont(MESSAGE_FONT);
gc.setTextAlign(TextAlignment.CENTER);
gc.setTextBaseline(VPos.CENTER);
gc.fillText(mSource.unavailableReason(), width / 2.0, height / 2.0);
}
for(MapLayer layer: mLayers)
{
gc.save();
layer.draw(gc, this);
gc.restore();
}
if(mSource != null)
{
drawAttribution(gc, mSource.attribution(), dark, width, height);
}
}
private void drawTiles(GraphicsContext gc, double width, double height)
{
int zoom = mViewport.getZoom();
int count = Mercator.tileCount(zoom);
double left = mViewport.getLeft();
double top = mViewport.getTop();
int firstColumn = (int)Math.floor(left / Mercator.TILE_SIZE);
int lastColumn = (int)Math.floor((left + width - 1) / Mercator.TILE_SIZE);
int firstRow = Math.max(0, (int)Math.floor(top / Mercator.TILE_SIZE));
int lastRow = Math.min(count - 1, (int)Math.floor((top + height - 1) / Mercator.TILE_SIZE));
//Past the source's highest zoom level, its closest tiles are enlarged
int enlarged = Math.max(0, zoom - mSource.maxZoom());
Set<TileKey> wanted = new HashSet<>();
List<TileKey> missing = new ArrayList<>();
for(int row = firstRow; row <= lastRow; row++)
{
for(int column = firstColumn; column <= lastColumn; column++)
{
TileKey key = new TileKey(zoom, Math.floorMod(column, count), row);
TileKey source = enlarged > 0 ? key.parent(enlarged) : key;
double x = column * (double)Mercator.TILE_SIZE - left;
double y = row * (double)Mercator.TILE_SIZE - top;
wanted.add(source);
Image image = mTileLoader != null ? mTileLoader.get(source) : null;
if(image != null)
{
drawPart(gc, image, key, enlarged, x, y);
}
else
{
drawFallback(gc, key, enlarged, x, y);
if(!missing.contains(source))
{
missing.add(source);
}
}
}
}
if(mTileLoader != null)
{
mTileLoader.setWanted(wanted);
//Request the tiles nearest the middle last, so they load first
double scale = 1 << enlarged;
int sourceCount = Mercator.tileCount(zoom - enlarged);
double middleColumn = ((left + width / 2.0) / Mercator.TILE_SIZE) / scale - 0.5;
double middleRow = ((top + height / 2.0) / Mercator.TILE_SIZE) / scale - 0.5;
missing.sort((a, b) -> Double.compare(distance(b, middleColumn, middleRow, sourceCount),
distance(a, middleColumn, middleRow, sourceCount)));
missing.forEach(mTileLoader::request);
}
}
/**
* Distance in tiles from the middle of the view, allowing for the world repeating east and west
*/
private static double distance(TileKey key, double column, double row, int count)
{
double dx = Math.abs(key.x() - Math.floorMod((long)Math.floor(column), count));
dx = Math.min(dx, count - dx);
return Math.hypot(dx, key.y() - row);
}
/**
* Draws the part of a tile from a farther zoom level that covers the tile, enlarged to the tile's size
* @param image of the tile from the farther zoom level
* @param key of the tile to cover
* @param levels between the tiles' zoom levels, 0 to draw the whole image
*/
private static void drawPart(GraphicsContext gc, Image image, TileKey key, int levels, double x, double y)
{
if(levels == 0)
{
gc.drawImage(image, x, y, Mercator.TILE_SIZE, Mercator.TILE_SIZE);
return;
}
TileKey parent = key.parent(levels);
double size = image.getWidth() / (1 << levels);
double sourceX = (key.x() - ((long)parent.x() << levels)) * size;
double sourceY = (key.y() - ((long)parent.y() << levels)) * size;
gc.drawImage(image, sourceX, sourceY, size, size, x, y, Mercator.TILE_SIZE, Mercator.TILE_SIZE);
}
/**
* Draws the part of a loaded tile from a farther zoom level than the requested tile that covers the tile
* @param enlarged levels between the tile and the requested tile
*/
private void drawFallback(GraphicsContext gc, TileKey key, int enlarged, double x, double y)
{
if(mTileLoader == null)
{
return;
}
for(int levels = enlarged + 1; levels <= enlarged + FALLBACK_LEVELS && key.zoom() - levels >= 0; levels++)
{
Image image = mTileLoader.get(key.parent(levels));
if(image != null)
{
drawPart(gc, image, key, levels, x, y);
return;
}
}
}
/**
* Attribution in the bottom right corner, required by the tile servers
*/
private void drawAttribution(GraphicsContext gc, String attribution, boolean dark, double width, double height)
{
mMeasure.setText(attribution);
mMeasure.setFont(ATTRIBUTION_FONT);
double boxWidth = mMeasure.getLayoutBounds().getWidth() + 8;
double boxHeight = 16;
gc.setFill(dark ? DARK_ATTRIBUTION_BACKGROUND : ATTRIBUTION_BACKGROUND);
gc.fillRect(width - boxWidth, height - boxHeight, boxWidth, boxHeight);
gc.setFill(dark ? DARK_ATTRIBUTION_TEXT : ATTRIBUTION_TEXT);
gc.setFont(ATTRIBUTION_FONT);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.CENTER);
gc.fillText(attribution, width - boxWidth + 4, height - boxHeight / 2.0);
}
private void mousePressed(MouseEvent event)
{
requestFocus();
if(event.getButton() == MouseButton.PRIMARY)
{
mDragX = event.getX();
mDragY = event.getY();
}
}
private void mouseDragged(MouseEvent event)
{
if(event.isPrimaryButtonDown() && !Double.isNaN(mDragX))
{
mViewport.pan(mDragX - event.getX(), mDragY - event.getY());
mDragX = event.getX();
mDragY = event.getY();
setCursor(Cursor.MOVE);
viewChanged();
}
}
private void mouseReleased(MouseEvent event)
{
if(event.getButton() == MouseButton.PRIMARY)
{
mDragX = Double.NaN;
mDragY = Double.NaN;
setCursor(Cursor.DEFAULT);
}
}
private void mouseClicked(MouseEvent event)
{
boolean doubleClick = event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2 &&
event.isStillSincePress();
if(doubleClick || event.getButton() == MouseButton.MIDDLE)
{
mViewport.setCenter(mViewport.getPosition(event.getX(), event.getY()));
mViewport.setZoom(mViewport.getZoom() + 1);
viewChanged();
}
}
private void scrolled(ScrollEvent event)
{
if(event.getDeltaY() == 0)
{
return;
}
//Restart when the direction changes
if(Math.signum(event.getDeltaY()) != Math.signum(mScrollAccumulator))
{
mScrollAccumulator = 0;
}
mScrollAccumulator += event.getDeltaY();
int steps = (int)(mScrollAccumulator / SCROLL_STEP);
if(steps != 0)
{
mScrollAccumulator -= steps * SCROLL_STEP;
zoomAt(mViewport.getZoom() + steps, event.getX(), event.getY());
}
event.consume();
}
private void pinched(ZoomEvent event)
{
mPinchAccumulator *= event.getZoomFactor();
if(mPinchAccumulator >= PINCH_STEP)
{
mPinchAccumulator = 1.0;
zoomAt(mViewport.getZoom() + 1, event.getX(), event.getY());
}
else if(mPinchAccumulator <= 1.0 / PINCH_STEP)
{
mPinchAccumulator = 1.0;
zoomAt(mViewport.getZoom() - 1, event.getX(), event.getY());
}
event.consume();
}
private void keyPressed(KeyEvent event)
{
switch(event.getCode())
{
case LEFT, KP_LEFT -> pan(-KEY_PAN_PIXELS, 0);
case RIGHT, KP_RIGHT -> pan(KEY_PAN_PIXELS, 0);
case UP, KP_UP -> pan(0, -KEY_PAN_PIXELS);
case DOWN, KP_DOWN -> pan(0, KEY_PAN_PIXELS);
case PLUS, EQUALS, ADD -> setZoom(getZoom() + 1);
case MINUS, SUBTRACT -> setZoom(getZoom() - 1);
default -> {
return;
}
}
event.consume();
}
private void pan(double dx, double dy)
{
mViewport.pan(dx, dy);
viewChanged();
}
}

View File

@@ -1,129 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* Free map tile server. A server with a dark style follows the theme; a server without one has its light tiles
* recolored in dark themes.
* @param id stored in the map preference. Don't change it.
* @param name shown to the user
* @param lightUrl template of the light style tiles, see {@link TileSource#urlTemplate()}, with a {key} placeholder
* when the server needs a key
* @param darkUrl template of the dark style tiles, or null when the server has no dark style
* @param subdomains for the {s} placeholder, or empty
* @param maxZoom highest zoom level the server provides
* @param attribution required by the server
* @param keyUrl web page where the user gets a free key, or null when the server doesn't need a key
*/
public record TileServer(String id, String name, String lightUrl, String darkUrl, List<String> subdomains,
int maxZoom, String attribution, String keyUrl)
{
private static final String OSM = "© OpenStreetMap contributors";
public static final TileServer OPEN_STREET_MAP = new TileServer("osm", "OpenStreetMap",
"https://tile.openstreetmap.org/{z}/{x}/{y}.png", null, List.of(), 19, OSM, null);
/**
* Positron (light) and Dark Matter (dark). Needs a free key since 25 September 2026: 5 million tiles per month
* for non-commercial use.
*/
public static final TileServer CARTO = new TileServer("carto", "CARTO",
"https://basemaps.cartocdn.com/rastertiles/light_all/{z}/{x}/{y}.png?key={key}",
"https://basemaps.cartocdn.com/rastertiles/dark_all/{z}/{x}/{y}.png?key={key}", List.of(), 18,
OSM + ", © CARTO", "https://carto.com/basemaps/apikey/");
public static final TileServer ESRI_GRAY = new TileServer("esri.gray", "Esri Gray Canvas",
"https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}",
"https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}",
List.of(), 16, "Tiles © Esri — Esri, HERE, Garmin, " + OSM, null);
public static final TileServer OPEN_TOPO_MAP = new TileServer("opentopomap", "OpenTopoMap",
"https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", null, List.of("a", "b", "c"), 17,
"Map data: " + OSM + ", SRTM | Map style: © OpenTopoMap (CC-BY-SA)", null);
/**
* Servers offered to the user, in menu order
*/
public static final List<TileServer> SERVERS = List.of(OPEN_STREET_MAP, CARTO, ESRI_GRAY, OPEN_TOPO_MAP);
/**
* Server with the id
* @param id from the map preference, or null
* @return server, or OpenStreetMap when there's no server with the id
*/
public static TileServer get(String id)
{
return SERVERS.stream().filter(server -> server.id().equals(id)).findFirst().orElse(OPEN_STREET_MAP);
}
/**
* Indicates if the server needs a key from the user
*/
public boolean requiresKey()
{
return keyUrl != null;
}
/**
* Indicates if the server has its own dark style
*/
public boolean hasDarkStyle()
{
return darkUrl != null;
}
/**
* Tiles to load for the theme
* @param dark true for a dark theme
* @param key from the user, for a server that needs one, or null
*/
public TileSource getSource(boolean dark, String key)
{
boolean darkStyle = dark && hasDarkStyle();
String template = darkStyle ? darkUrl : lightUrl;
String cacheName = id + (darkStyle ? "/dark" : "/light");
String unavailable = null;
if(requiresKey())
{
if(key == null || key.isBlank())
{
unavailable = name + " needs a free API key: enter it in the map's Settings tab";
}
else
{
template = template.replace("{key}", URLEncoder.encode(key.strip(), StandardCharsets.UTF_8));
}
}
return new TileSource(cacheName, template, subdomains, maxZoom, dark && !hasDarkStyle(), dark, attribution,
unavailable);
}
@Override
public String toString()
{
return name;
}
}

View File

@@ -1,57 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.util.List;
/**
* Tiles the map loads: one style of a {@link TileServer}, resolved for the theme and the user's key.
* @param cacheName folder of the tiles in the disk cache, e.g. osm/light
* @param urlTemplate with {s} subdomain, {z} zoom, {x} column and {y} row placeholders, or null when unavailable
* @param subdomains for the {s} placeholder, or empty
* @param maxZoom highest zoom level the server provides. Closer zoom levels enlarge these tiles.
* @param darken true to recolor the tiles for a dark theme, for a server without a dark style
* @param dark true when the tiles are dark, from a dark style or recolored
* @param attribution shown on the map, as the server requires
* @param unavailableReason shown instead of tiles when the source can't load tiles, or null
*/
public record TileSource(String cacheName, String urlTemplate, List<String> subdomains, int maxZoom, boolean darken,
boolean dark, String attribution, String unavailableReason)
{
/**
* Indicates if the source can load tiles
*/
public boolean isAvailable()
{
return urlTemplate != null && unavailableReason == null;
}
/**
* URL of the tile. Spreads the tiles over the subdomains by position, so each tile always comes from the same
* subdomain and stays in the server's and the browser-style caches.
*/
public String getUrl(TileKey key)
{
String subdomain = subdomains.isEmpty() ? "" :
subdomains.get(Math.floorMod(key.x() + key.y(), subdomains.size()));
return urlTemplate.replace("{s}", subdomain).replace("{z}", String.valueOf(key.zoom()))
.replace("{x}", String.valueOf(key.x())).replace("{y}", String.valueOf(key.y()));
}
}

View File

@@ -1,228 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.map.PlottableEntityHistory;
import io.github.dsheirer.map.PlottableEntityModel;
import io.github.dsheirer.map.TimestampedGeoPosition;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
/**
* Plotted tracks: for each entity, a two-tone trail through its most recent positions, its alias icon at the latest
* position and its alias name (or identifier) beside the icon, in the alias color. Use on the JavaFX thread.
*/
public class TrackLayer implements MapLayer
{
private static final Color DEFAULT_COLOR = Color.BLUE;
private static final Color TRAIL_BACKGROUND = Color.BLACK;
private static final Color LABEL_HALO = Color.rgb(255, 255, 255, 0.85);
private static final Font LABEL_FONT = Font.font(12);
//Map edge allowance for icons and labels that are partly in view
private static final double MARGIN = 200;
private final PlottableEntityModel mEntityModel;
private final IconModel mIconModel;
private final Set<PlottableEntityHistory> mEntities = new LinkedHashSet<>();
private int mTrackHistoryLength = 3;
/**
* Constructs an instance
* @param entityModel for the entities' aliases
* @param iconModel for the alias icons
*/
public TrackLayer(PlottableEntityModel entityModel, IconModel iconModel)
{
mEntityModel = entityModel;
mIconModel = iconModel;
}
/**
* Number of positions in each trail, including the latest position
*/
public int getTrackHistoryLength()
{
return mTrackHistoryLength;
}
public void setTrackHistoryLength(int length)
{
mTrackHistoryLength = length;
}
/**
* Shows the entity
* @return true if it wasn't shown
*/
public boolean add(PlottableEntityHistory entity)
{
return entity != null && mEntities.add(entity);
}
/**
* Shows the entities
* @return true if any wasn't shown
*/
public boolean addAll(Collection<PlottableEntityHistory> entities)
{
boolean added = false;
for(PlottableEntityHistory entity: entities)
{
added |= add(entity);
}
return added;
}
/**
* Stops showing the entities
*/
public void removeAll(Collection<PlottableEntityHistory> entities)
{
mEntities.removeAll(entities);
}
/**
* Stops showing all entities. They're shown again when they report a new position.
*/
public void clear()
{
mEntities.clear();
}
@Override
public void draw(GraphicsContext gc, TileMapView map)
{
MapViewport viewport = map.getViewport();
gc.setLineCap(StrokeLineCap.ROUND);
gc.setLineJoin(StrokeLineJoin.ROUND);
gc.setFont(LABEL_FONT);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.CENTER);
for(PlottableEntityHistory entity: mEntities)
{
List<TimestampedGeoPosition> history = entity.getTrackHistoryModel().getTrackHistory();
if(history.isEmpty() || !history.getFirst().isValid())
{
continue;
}
List<Alias> aliases = mEntityModel.getAliases(entity);
Alias alias = aliases.isEmpty() ? null : aliases.getFirst();
Color color = alias != null ? toColor(alias.getColor()) : DEFAULT_COLOR;
drawTrail(gc, viewport, history, color);
TimestampedGeoPosition latest = history.getFirst();
double x = viewport.getScreenX(latest.getLongitude());
double y = viewport.getScreenY(latest.getLatitude());
if(x < -MARGIN || x > viewport.getWidth() + MARGIN || y < -MARGIN || y > viewport.getHeight() + MARGIN)
{
continue;
}
double iconWidth = drawIcon(gc, alias, x, y);
String label = alias != null ? alias.getName() : String.valueOf(entity.getIdentifier());
double labelX = x + iconWidth / 2.0 + 3;
gc.setStroke(LABEL_HALO);
gc.setLineWidth(3);
gc.strokeText(label, labelX, y);
gc.setFill(color);
gc.fillText(label, labelX, y);
}
}
/**
* Trail through the most recent positions: a wide black line under a narrow line in the entity's color
*/
private void drawTrail(GraphicsContext gc, MapViewport viewport, List<TimestampedGeoPosition> history,
Color color)
{
int length = Math.min(history.size(), mTrackHistoryLength);
if(length < 2)
{
return;
}
double[] xs = new double[length];
double[] ys = new double[length];
double reference = viewport.getScreenX(history.getFirst().getLongitude());
double worldSize = viewport.getWorldSize();
for(int index = 0; index < length; index++)
{
TimestampedGeoPosition position = history.get(index);
double x = viewport.getScreenX(position.getLongitude());
//Keep the trail on the same copy of the world as the latest position
xs[index] = x - Math.round((x - reference) / worldSize) * worldSize;
ys[index] = viewport.getScreenY(position.getLatitude());
}
gc.setStroke(TRAIL_BACKGROUND);
gc.setLineWidth(3);
gc.strokePolyline(xs, ys, length);
gc.setStroke(color);
gc.setLineWidth(1);
gc.strokePolyline(xs, ys, length);
}
/**
* Draws the alias icon, or the default icon, centered on the point
* @return drawn icon width
*/
private double drawIcon(GraphicsContext gc, Alias alias, double x, double y)
{
Icon icon = mIconModel.getIcon(alias != null ? alias.getIconName() : null);
Image image = icon != null ? icon.getFxImage() : null;
if(image == null || image.getHeight() <= 0)
{
return 0;
}
double height = IconModel.DEFAULT_ICON_SIZE;
double width = image.getWidth() * height / image.getHeight();
gc.drawImage(image, x - width / 2.0, y - height / 2.0, width, height);
return width;
}
private static Color toColor(int rgb)
{
return Color.rgb((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);
}
}

View File

@@ -1,90 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.map.GeoPosition;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
/**
* Push-pin at the user's location, with the tip of the pin at the location. Use on the JavaFX thread.
*/
public class UserLocationLayer implements MapLayer
{
private static final Color NEEDLE = Color.rgb(90, 90, 90);
private static final Color HEAD = Color.rgb(220, 40, 40);
private static final Color HEAD_OUTLINE = Color.rgb(110, 0, 0);
private static final Color HIGHLIGHT = Color.rgb(255, 255, 255, 170 / 255.0);
private static final Color SHADOW = Color.rgb(0, 0, 0, 70 / 255.0);
private static final double NEEDLE_LENGTH = 14.0;
private static final double HEAD_RADIUS = 7.0;
private GeoPosition mPosition;
/**
* Sets the location to mark
* @param position of the user, or null to remove the pin
*/
public void setPosition(GeoPosition position)
{
mPosition = position;
}
/**
* Location that is marked, or null
*/
public GeoPosition getPosition()
{
return mPosition;
}
@Override
public void draw(GraphicsContext gc, TileMapView map)
{
if(mPosition == null)
{
return;
}
MapViewport viewport = map.getViewport();
double x = viewport.getScreenX(mPosition.getLongitude());
double y = viewport.getScreenY(mPosition.getLatitude());
double headY = y - NEEDLE_LENGTH - HEAD_RADIUS;
//Shadow where the needle enters the map, so the tip reads as the location
gc.setFill(SHADOW);
gc.fillOval(x - 4, y - 2, 8, 4);
gc.setStroke(NEEDLE);
gc.setLineWidth(2.0);
gc.setLineCap(StrokeLineCap.ROUND);
gc.strokeLine(x, y, x, headY);
gc.setFill(HEAD);
gc.fillOval(x - HEAD_RADIUS, headY - HEAD_RADIUS, HEAD_RADIUS * 2, HEAD_RADIUS * 2);
gc.setStroke(HEAD_OUTLINE);
gc.setLineWidth(1.0);
gc.strokeOval(x - HEAD_RADIUS, headY - HEAD_RADIUS, HEAD_RADIUS * 2, HEAD_RADIUS * 2);
gc.setFill(HIGHLIGHT);
gc.fillOval(x - HEAD_RADIUS / 2 - 1, headY - HEAD_RADIUS / 2 - 1, 4, 4);
}
}

View File

@@ -361,32 +361,16 @@ public class ChannelMetadataView extends VBox implements ChannelMetadataModel.Li
columns.add(NowPlayingCells.column("tuner", "Tuner", null, Pos.CENTER,
row -> getTunerName(row.getChannelMetadata()), Row::revisionProperty));
//System and site labels from the channel configuration, hidden by default
TableColumn<Row,String> system = NowPlayingCells.column("system", "System", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getSystemConfigurationIdentifier()), Row::revisionProperty);
system.setVisible(false);
columns.add(system);
TableColumn<Row,String> site = NowPlayingCells.column("site", "Site", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getSiteConfigurationIdentifier()), Row::revisionProperty);
site.setVisible(false);
columns.add(site);
columns.add(NowPlayingCells.column("channel.name", "Channel Name", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getChannelNameConfigurationIdentifier()), Row::revisionProperty));
//Alias list from the channel configuration
columns.add(NowPlayingCells.column("alias.list", "Alias List", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getAliasListConfigurationIdentifier()), Row::revisionProperty));
//The channel rows are in channel start order, the same as the Swing version of the table
for(TableColumn<Row,?> column: columns)
{
column.setSortable(false);
}
//Column numbers in the Swing version of the table, for its stored column widths. Talker, Tuner, System, Site and Alias
//List are new columns.
//Column numbers in the Swing version of the table, for its stored column widths. Talker and Tuner are new columns.
String[] swingColumns = {"status", "decoder", "from", "from.alias", "to", "to.alias", "channel", "frequency",
"channel.name"};

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

@@ -23,7 +23,6 @@ import io.github.dsheirer.preference.swing.SwingPreference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
@@ -31,14 +30,8 @@ import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
@@ -52,7 +45,6 @@ import javafx.scene.layout.VBox;
*/
public abstract class HistoryTableView<T,F> extends VBox
{
private static final KeyCombination COPY = new KeyCodeCombination(KeyCode.C, KeyCombination.SHORTCUT_DOWN);
private final ObservableList<Row<T>> mRows = FXCollections.observableArrayList();
private final FilteredList<Row<T>> mFilteredRows = new FilteredList<>(mRows);
private final Map<T,Row<T>> mRowMap = new HashMap<>();
@@ -79,16 +71,6 @@ public abstract class HistoryTableView<T,F> extends VBox
mTableView.setItems(sortedRows);
mTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_SUBSEQUENT_COLUMNS);
mTableView.setPlaceholder(new Label(""));
mTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
mTableView.setOnKeyPressed(event -> {
if(COPY.match(event))
{
ClipboardContent content = new ClipboardContent();
content.putString(getSelectedText());
Clipboard.getSystemClipboard().setContent(content);
event.consume();
}
});
mTableColumnMonitor = new TableColumnMonitor<>(mTableView, tableKey, swingPreference, swingTableKey);
mHistoryControls = new HistoryControls<>(filterEditorTitle, this::clear, this::setHistorySize,
mTableColumnMonitor, columnsTitle);
@@ -178,32 +160,6 @@ public abstract class HistoryTableView<T,F> extends VBox
mRows.forEach(Row::refresh);
}
/**
* Text of the selected rows, one line per row with the visible column values separated by tabs.
*/
private String getSelectedText()
{
StringJoiner text = new StringJoiner("\n");
for(int row = 0; row < mTableView.getItems().size(); row++)
{
if(mTableView.getSelectionModel().isSelected(row))
{
StringJoiner line = new StringJoiner("\t");
for(TableColumn<Row<T>,?> column: mTableView.getVisibleLeafColumns())
{
Object value = column.getCellData(row);
line.add(value == null ? "" : value.toString());
}
text.add(line.toString());
}
}
return text.toString();
}
private void setHistorySize(int historySize)
{
mHistorySize = historySize;

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

@@ -27,7 +27,6 @@ import io.github.dsheirer.gui.playlist.channel.ChannelEditor;
import io.github.dsheirer.gui.playlist.channel.ChannelTabRequest;
import io.github.dsheirer.gui.playlist.manager.PlaylistManagerEditor;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferenceEditor;
import io.github.dsheirer.gui.playlist.radioreference.ViewRadioReferenceRequest;
import io.github.dsheirer.gui.playlist.streaming.StreamingEditor;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
@@ -37,6 +36,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;
@@ -77,7 +77,6 @@ public class PlaylistEditor extends BorderPane
private Tab mStreamingTab;
private AliasEditor mAliasEditor;
private ChannelEditor mChannelEditor;
private RadioReferenceEditor mRadioReferenceEditor;
/**
* Constructs an instance
@@ -123,16 +122,6 @@ public class PlaylistEditor extends BorderPane
getChannelEditor().process((ChannelTabRequest)request);
}
break;
case RADIOREFERENCE:
if(request instanceof ViewRadioReferenceRequest viewRequest)
{
getTabPane().getSelectionModel().select(getRadioReferenceTab());
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 +173,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);
@@ -277,22 +266,12 @@ public class PlaylistEditor extends BorderPane
if(mRadioReferenceTab == null)
{
mRadioReferenceTab = new Tab("Radio Reference");
mRadioReferenceTab.setContent(getRadioReferenceEditor());
mRadioReferenceTab.setContent(new RadioReferenceEditor(mUserPreferences, mPlaylistManager));
}
return mRadioReferenceTab;
}
private RadioReferenceEditor getRadioReferenceEditor()
{
if(mRadioReferenceEditor == null)
{
mRadioReferenceEditor = new RadioReferenceEditor(mUserPreferences, mPlaylistManager);
}
return mRadioReferenceEditor;
}
private Tab getStreamingTab()
{
if(mStreamingTab == null)

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

@@ -23,7 +23,6 @@ import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasFactory;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasListConfiguration;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.control.MaxLengthUnaryOperator;
@@ -34,11 +33,6 @@ import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.service.radioreference.AliasListSynchronizer;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -55,7 +49,6 @@ import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
@@ -69,16 +62,15 @@ import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.PropertyValueFactory;
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 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;
@@ -114,13 +106,6 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
private FilteredList<Alias> mAliasFilteredList;
private SortedList<Alias> mAliasSortedList;
private AliasPredicate mAliasPredicate;
private VBox mRadioReferenceBox;
private Label mRadioReferenceSystemLabel;
private Label mRadioReferenceStatusLabel;
private CheckBox mAutoUpdateCheckBox;
private Button mRefreshAliasListButton;
private boolean mRefreshInProgress;
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
/**
* Constructs an instance
@@ -135,7 +120,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
VBox leftBox = new VBox();
VBox.setVgrow(getAliasTableView(), Priority.ALWAYS);
leftBox.getChildren().addAll(getSearchAndListSelectionBox(), getRadioReferenceBox(), getAliasTableView());
leftBox.getChildren().addAll(getSearchAndListSelectionBox(), getAliasTableView());
HBox topBox = new HBox();
HBox.setHgrow(leftBox, Priority.ALWAYS);
@@ -145,191 +130,9 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
mCurrentEditor = getAliasItemEditor();
getItems().addAll(topBox, getAliasItemEditor());
//Configuration changes (e.g. a background Radio Reference check) update the Radio Reference controls
mPlaylistManager.getAliasModel().aliasListConfigurations()
.addListener((ListChangeListener<AliasListConfiguration>)c -> updateRadioReferenceControls());
updateRadioReferenceControls();
MyEventBus.getGlobalEventBus().register(this);
}
/**
* Configuration for the alias list selected in the combo box, or null.
*/
private AliasListConfiguration getSelectedConfiguration()
{
String aliasListName = getAliasListNameComboBox().getSelectionModel().getSelectedItem();
return mPlaylistManager.getAliasModel().getAliasListConfiguration(aliasListName);
}
/**
* Radio Reference system tracking controls for the selected alias list. Disabled when the alias list doesn't
* track a Radio Reference system.
*/
private VBox getRadioReferenceBox()
{
if(mRadioReferenceBox == null)
{
//Two rows so that a long system name doesn't push the controls and status off the editor
Label label = new Label("Radio Reference:");
label.setLabelFor(getRadioReferenceSystemLabel());
label.setMinWidth(Region.USE_PREF_SIZE);
HBox systemRow = new HBox(10, label, getRadioReferenceSystemLabel());
systemRow.setAlignment(Pos.CENTER_LEFT);
HBox controlsRow = new HBox(10, getAutoUpdateCheckBox(), getRefreshAliasListButton(),
getRadioReferenceStatusLabel());
controlsRow.setAlignment(Pos.CENTER_LEFT);
mRadioReferenceBox = new VBox(5, systemRow, controlsRow);
mRadioReferenceBox.setPadding(new Insets(0, 0, 10, 10));
}
return mRadioReferenceBox;
}
private Label getRadioReferenceSystemLabel()
{
if(mRadioReferenceSystemLabel == null)
{
mRadioReferenceSystemLabel = new Label();
}
return mRadioReferenceSystemLabel;
}
private Label getRadioReferenceStatusLabel()
{
if(mRadioReferenceStatusLabel == null)
{
mRadioReferenceStatusLabel = new Label();
}
return mRadioReferenceStatusLabel;
}
private CheckBox getAutoUpdateCheckBox()
{
if(mAutoUpdateCheckBox == null)
{
mAutoUpdateCheckBox = new CheckBox("Auto-Update Talkgroups");
mAutoUpdateCheckBox.setTooltip(new Tooltip("Automatically add or update talkgroup aliases when the " +
"system changes on Radio Reference. Set how often to check in User Preferences > Radio Reference > Alias Lists."));
mAutoUpdateCheckBox.setOnAction(event -> {
AliasListConfiguration configuration = getSelectedConfiguration();
if(configuration != null && configuration.isTrackingRadioReferenceSystem())
{
configuration.setAutoUpdate(getAutoUpdateCheckBox().isSelected());
}
});
}
return mAutoUpdateCheckBox;
}
private Button getRefreshAliasListButton()
{
if(mRefreshAliasListButton == null)
{
mRefreshAliasListButton = new Button("Refresh Now");
mRefreshAliasListButton.setTooltip(new Tooltip("Add or update talkgroup aliases from Radio Reference now"));
mRefreshAliasListButton.setOnAction(event -> {
AliasListConfiguration configuration = getSelectedConfiguration();
if(configuration == null || !configuration.isTrackingRadioReferenceSystem())
{
return;
}
mRefreshInProgress = true;
updateRadioReferenceControls();
getRadioReferenceStatusLabel().setText("Refreshing from Radio Reference...");
mPlaylistManager.getAliasListSynchronizer().refresh(configuration)
.whenComplete((result, throwable) -> Platform.runLater(() -> {
mRefreshInProgress = false;
updateRadioReferenceControls();
if(throwable != null)
{
Alert alert = new Alert(Alert.AlertType.ERROR, "Unable to refresh alias list [" +
configuration.getName() + "] from Radio Reference.\n\n" +
AliasListSynchronizer.getMessage(throwable), ButtonType.OK);
alert.setTitle("Refresh Alias List");
alert.setHeaderText("Radio Reference Refresh Failed");
alert.initOwner(getRefreshAliasListButton().getScene().getWindow());
alert.show();
}
else if(result != null && result.applied() && configuration == getSelectedConfiguration())
{
getRadioReferenceStatusLabel().setText("Added " + result.added() + ", updated " +
result.updated() + " aliases. " + getStatusText(configuration));
}
}));
});
}
return mRefreshAliasListButton;
}
/**
* Updates the Radio Reference controls for the currently selected alias list.
*/
private void updateRadioReferenceControls()
{
AliasListConfiguration configuration = getSelectedConfiguration();
boolean tracking = configuration != null && configuration.isTrackingRadioReferenceSystem();
getAutoUpdateCheckBox().setDisable(!tracking);
getAutoUpdateCheckBox().setSelected(tracking && configuration.isAutoUpdate());
getRefreshAliasListButton().setDisable(!tracking || mRefreshInProgress);
if(tracking)
{
String name = configuration.getRadioReferenceSystemName();
getRadioReferenceSystemLabel().setText((name != null && !name.isEmpty() ? name : "System") + " [" +
configuration.getRadioReferenceSystemId() + "]");
if(!mRefreshInProgress)
{
getRadioReferenceStatusLabel().setText(getStatusText(configuration));
}
}
else
{
getRadioReferenceSystemLabel().setText("Not tracking a system");
getRadioReferenceStatusLabel().setText(null);
}
}
/**
* Status text for a tracked alias list: Radio Reference last updated and synchronized timestamps.
*/
private static String getStatusText(AliasListConfiguration configuration)
{
StringBuilder sb = new StringBuilder();
sb.append("Updated on Radio Reference: ").append(format(configuration.getRadioReferenceLastUpdated()));
sb.append(" Synchronized: ").append(format(configuration.getSynchronizedLastUpdated()));
if(configuration.isUpdateAvailable())
{
sb.append(" (Update Available)");
}
return sb.toString();
}
private static String format(long timestamp)
{
if(timestamp <= 0)
{
return "never";
}
return DATE_FORMATTER.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()));
}
/**
* Redraws the alias color swatches after a change to the application theme.
*/
@@ -528,7 +331,6 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
{
getNewAliasButton().setDisable(newValue == null || newValue.contentEquals(AliasModel.NO_ALIAS_LIST));
update();
updateRadioReferenceControls();
});
if(mAliasListNameComboBox.getItems().size() > 1)
@@ -659,7 +461,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 +751,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

@@ -96,7 +96,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
private TextField mNameField;
private ComboBox<String> mAliasListComboBox;
private Button mNewAliasListButton;
private CheckBox mAutoAddTalkerAliasesCheckBox;
private GridPane mTextFieldPane;
private Button mSaveButton;
private Button mResetButton;
@@ -188,7 +187,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
getNameField().setDisable(disable);
getAliasListComboBox().setDisable(disable);
getNewAliasListButton().setDisable(disable);
getAutoAddTalkerAliasesCheckBox().setDisable(disable);
getAutoStartSwitch().setDisable(disable);
if(channel != null)
@@ -212,7 +210,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
getAliasListComboBox().getSelectionModel().select(null);
}
getAutoAddTalkerAliasesCheckBox().setSelected(channel.isAutoAddTalkerAliases());
getAutoStartSwitch().selectedProperty().set(channel.isAutoStart());
getAutoStartOrderSpinner().setDisable(!channel.isAutoStart());
Integer order = channel.getAutoStartOrder();
@@ -254,7 +251,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
getSiteField().setText(null);
getNameField().setText(null);
getAliasListComboBox().getSelectionModel().select(null);
getAutoAddTalkerAliasesCheckBox().setSelected(false);
getAutoStartSwitch().selectedProperty().set(false);
getAutoStartOrderSpinner().setDisable(true);
getAutoStartOrderSpinner().getValueFactory().setValue(0);
@@ -281,12 +277,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
getItem().setName(" ");
getItem().setName(getNameField().getText());
getItem().setAliasListName(getAliasListComboBox().getSelectionModel().getSelectedItem());
if(providesTalkerAlias())
{
getItem().setAutoAddTalkerAliases(getAutoAddTalkerAliasesCheckBox().isSelected());
}
getItem().setAutoStart(getAutoStartSwitch().isSelected());
Integer order = getAutoStartOrderSpinner().getValue();
@@ -608,12 +598,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
GridPane.setConstraints(getNewAliasListButton(), 4, row);
mTextFieldPane.getChildren().add(getNewAliasListButton());
if(providesTalkerAlias())
{
GridPane.setConstraints(getAutoAddTalkerAliasesCheckBox(), 3, ++row, 2, 1);
mTextFieldPane.getChildren().add(getAutoAddTalkerAliasesCheckBox());
}
}
return mTextFieldPane;
@@ -676,33 +660,6 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
return mAliasListComboBox;
}
/**
* Indicates if the decoder for this editor produces talker aliases.
*/
private boolean providesTalkerAlias()
{
return getDecoderType() != null && getDecoderType().providesTalkerAlias();
}
/**
* Check box to automatically add decoded talker aliases to the selected alias list.
*/
private CheckBox getAutoAddTalkerAliasesCheckBox()
{
if(mAutoAddTalkerAliasesCheckBox == null)
{
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 " +
"to preserve a custom name. Applies when the channel is (re)started."));
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
}
return mAutoAddTalkerAliasesCheckBox;
}
private Button getNewAliasListButton()
{
if(mNewAliasListButton == null)

View File

@@ -55,8 +55,6 @@ public class AgencyEditor extends VBox
private ListView<Agency> mAgencyListView;
private AgencyFrequencyEditor mAgencyFrequencyEditor;
private IntegerProperty mAgencyCountProperty = new SimpleIntegerProperty();
private Integer mPendingAgencyId;
private AgencyFrequencyEditor.FrequencyTarget mPendingFrequency;
/**
* Constructs an instance
@@ -111,56 +109,6 @@ public class AgencyEditor extends VBox
}
}
/**
* Prepares to show the agency with the frequency selected when the agencies are next set
* @param agencyId of the agency, or the negative county id for a county's own frequencies
* @param frequency to select, or null
*/
public void prepareView(int agencyId, AgencyFrequencyEditor.FrequencyTarget frequency)
{
mUserPreferences.getRadioReferencePreference().setPreferredAgencyId(agencyId, mLevel);
mPendingAgencyId = agencyId;
mPendingFrequency = frequency;
}
/**
* Shows the agency with the frequency selected
* @param agencyId of the agency, or the negative county id for a county's own frequencies
* @param frequency to select, or null
* @return false when the editor doesn't list the agency
*/
public boolean view(int agencyId, AgencyFrequencyEditor.FrequencyTarget frequency)
{
prepareView(agencyId, frequency);
for(Agency agency: getAgencyListView().getItems())
{
if(agency.getAgencyId() == agencyId)
{
if(getAgencyListView().getSelectionModel().getSelectedItem() == agency)
{
//Already shown - select the frequency in the shown categories
mPendingAgencyId = null;
mPendingFrequency = null;
if(frequency != null)
{
getAgencyFrequencyEditor().viewFrequency(frequency);
}
}
else
{
getAgencyListView().getSelectionModel().select(agency);
}
getAgencyListView().scrollTo(agency);
return true;
}
}
return getAgencyListView().getItems().isEmpty();
}
public void clear()
{
getAgencyListView().getItems().clear();
@@ -207,17 +155,6 @@ public class AgencyEditor extends VBox
{
getAgencyFrequencyEditor().clearAndSetLoading();
if(mPendingAgencyId != null && mPendingAgencyId == agency.getAgencyId())
{
if(mPendingFrequency != null)
{
getAgencyFrequencyEditor().viewFrequency(mPendingFrequency);
}
mPendingAgencyId = null;
mPendingFrequency = null;
}
mUserPreferences.getRadioReferencePreference().setPreferredAgencyId(agency.getAgencyId(), mLevel);
ThreadPool.CACHED.submit(() -> {

View File

@@ -68,21 +68,6 @@ public class AgencyFrequencyEditor extends GridPane
private Level mLevel;
private ComboBox<Category> mCategoryComboBox;
private ComboBox<SubCategory> mSubCategoryComboBox;
private FrequencyTarget mPendingFrequency;
private boolean mLoadingFrequencies;
/**
* Frequency to select in the editor
* @param category name, or null
* @param subCategory name, or null
* @param frequencyHz downlink frequency
* @param description of the frequency, or null
* @param alphaTag of the frequency, or null
*/
public record FrequencyTarget(String category, String subCategory, long frequencyHz, String description,
String alphaTag)
{
}
private TableView<Frequency> mFrequencyTableView;
private Label mPlaceholderLabel;
private ProgressIndicator mProgressIndicator;
@@ -180,127 +165,14 @@ public class AgencyFrequencyEditor extends GridPane
sorted.add(0, ALL_CATEGORIES);
}
getCategoryComboBox().getItems().addAll(sorted);
if(mPendingFrequency == null || !selectPendingFrequency())
{
getCategoryComboBox().getSelectionModel().select(sorted.get(0));
}
}
else
{
setLoading(false);
}
}
/**
* Selects the frequency in its category and subcategory, now or once the categories are set
*/
public void viewFrequency(FrequencyTarget target)
{
mPendingFrequency = target;
if(!getCategoryComboBox().getItems().isEmpty())
{
selectPendingFrequency();
}
}
/**
* Selects the pending frequency's category and subcategory, which loads the frequencies, or selects the frequency
* when they're already shown.
* @return false when the categories don't include the frequency's category
*/
private boolean selectPendingFrequency()
{
FrequencyTarget target = mPendingFrequency;
Category category = null;
for(Category candidate: getCategoryComboBox().getItems())
{
if(candidate != ALL_CATEGORIES && candidate.getName() != null &&
candidate.getName().equals(target.category()))
{
category = candidate;
}
}
if(category == null)
{
mPendingFrequency = null;
return false;
}
if(getCategoryComboBox().getValue() != category)
{
getCategoryComboBox().getSelectionModel().select(category);
}
SubCategory subCategory = null;
for(SubCategory candidate: getSubCategoryComboBox().getItems())
{
if(candidate != ALL_SUB_CATEGORIES && candidate.getName() != null &&
candidate.getName().equals(target.subCategory()))
{
subCategory = candidate;
}
}
if(subCategory != null && getSubCategoryComboBox().getValue() != subCategory)
{
//Loading the subcategory frequencies selects the frequency
getSubCategoryComboBox().getSelectionModel().select(subCategory);
}
else if(!mLoadingFrequencies)
{
selectFrequency();
}
return true;
}
/**
* Selects the pending frequency in the frequencies table: the one with the same description or alpha tag, or else
* the first one with the same frequency
*/
private void selectFrequency()
{
FrequencyTarget target = mPendingFrequency;
mPendingFrequency = null;
if(target == null)
{
return;
}
Frequency match = null;
for(Frequency frequency: getFrequencyTableView().getItems())
{
if(frequency.getDownlinkHz() == target.frequencyHz())
{
boolean same = (target.description() != null && target.description().equals(frequency.getDescription())) ||
(target.alphaTag() != null && target.alphaTag().equals(frequency.getAlphaTag()));
if(same)
{
match = frequency;
break;
}
else if(match == null)
{
match = frequency;
}
}
}
if(match != null)
{
getFrequencyTableView().getSelectionModel().select(match);
getFrequencyTableView().scrollTo(match);
}
}
private FrequencyEditor getFrequencyEditor()
{
if(mFrequencyEditor == null)
@@ -528,7 +400,6 @@ public class AgencyFrequencyEditor extends GridPane
getFrequencyTableView().getItems().clear();
SubCategory subCategory = mSubCategoryComboBox.getValue();
mLoadingFrequencies = subCategory != null;
if(subCategory != null)
{
@@ -582,23 +453,14 @@ public class AgencyFrequencyEditor extends GridPane
}
Platform.runLater(() -> {
//Another subcategory was selected while loading - its frequencies are shown instead
if(getSubCategoryComboBox().getValue() != subCategory)
{
return;
}
mLoadingFrequencies = false;
getFrequencyTableView().getItems().addAll(frequencies);
setLoading(false);
selectFrequency();
});
}
catch(Throwable t)
{
mLog.error("Error retrieving frequencies for subcategory [" + subCategory.getName() + "]", t);
Platform.runLater(() -> {
mLoadingFrequencies = false;
setLoading(false);
new RadioReferenceUnavailableAlert(getSubCategoryComboBox()).showAndWait();
});

View File

@@ -26,17 +26,12 @@ import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.radioreference.RadioReferencePreference;
import io.github.dsheirer.rrapi.RadioReferenceException;
import io.github.dsheirer.rrapi.RadioReferenceService;
import io.github.dsheirer.rrapi.type.AgencyInfo;
import io.github.dsheirer.rrapi.type.Agency;
import io.github.dsheirer.rrapi.type.AuthorizationInformation;
import io.github.dsheirer.rrapi.type.Country;
import io.github.dsheirer.rrapi.type.CountryInfo;
import io.github.dsheirer.rrapi.type.County;
import io.github.dsheirer.rrapi.type.CountyInfo;
import io.github.dsheirer.rrapi.type.Site;
import io.github.dsheirer.rrapi.type.SystemInformation;
import io.github.dsheirer.service.radioreference.FrequencyCandidate;
import io.github.dsheirer.rrapi.type.State;
import io.github.dsheirer.rrapi.type.StateInfo;
import io.github.dsheirer.service.radioreference.RadioReference;
@@ -46,9 +41,7 @@ import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
@@ -69,9 +62,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
@@ -177,6 +168,8 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
{
getCountryComboBox().getItems().clear();
final int preferredCountryId = mUserPreferences.getRadioReferencePreference().getPreferredCountryId();
ThreadPool.CACHED.execute(() -> {
try
{
@@ -184,8 +177,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
Platform.runLater(() -> {
getCountryComboBox().getItems().addAll(countries);
//Read when the list arrives, so a view request made while loading is honored
int preferredCountryId = mUserPreferences.getRadioReferencePreference().getPreferredCountryId();
if(preferredCountryId >= 0)
{
@@ -208,342 +199,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
});
}
/**
* Where a view request's system or frequency is listed in the editor
* @param countryId of the country
* @param stateId of the state
* @param countyId of the county, or 0 for a state level listing
* @param level of the listing: COUNTY or STATE
* @param systemId of the trunked system, or null for an agency
* @param siteId of the site to select, or -1
* @param agencyId of the agency, or the negative county id for a county's own frequencies, or null for a system
* @param frequency to select in the agency, or null
*/
private record ViewTarget(int countryId, int stateId, int countyId, Level level, Integer systemId, int siteId,
Integer agencyId, AgencyFrequencyEditor.FrequencyTarget frequency)
{
}
/**
* Shows the request's trunked system site or conventional frequency: selects its country, state and county, the
* tab that lists it, and the system and site or the agency and frequency. Finds where it's listed in the
* background.
*/
public void view(ViewRadioReferenceRequest request)
{
ThreadPool.CACHED.execute(() -> {
try
{
ViewTarget target = resolve(request);
Platform.runLater(() -> {
if(target == null)
{
showViewError("Radio Reference doesn't list where this " +
(request.getSystemId() != null ? "system" : "frequency") + " is listed.");
}
else
{
navigate(target);
}
});
}
catch(RadioReferenceException rre)
{
mLog.error("Error finding radio reference listing to view - " + rre.getMessage());
Platform.runLater(() -> new RadioReferenceUnavailableAlert(getTabPane()).showAndWait());
}
});
}
/**
* Finds where the request's system or frequency is listed. Call from a background thread.
* @return target, or null when it can't be found
*/
private ViewTarget resolve(ViewRadioReferenceRequest request) throws RadioReferenceException
{
RadioReferenceService service = mRadioReference.getService();
if(request.getSystemId() != null)
{
int systemId = request.getSystemId();
int siteId = request.getSiteId() != null ? request.getSiteId() : -1;
//The site's county first, then the system's counties, then its states
Set<Integer> countyIds = new LinkedHashSet<>();
for(Site site: nonNull(service.getSites(systemId)))
{
if(site.getSiteId() == siteId && isCounty(site.getCountyId()))
{
countyIds.add(site.getCountyId());
}
}
SystemInformation systemInformation = service.getSystemInformation(systemId);
if(systemInformation != null)
{
for(County county: nonNull(systemInformation.getCounties()))
{
if(isCounty(county.getCountyId()))
{
countyIds.add(county.getCountyId());
}
}
}
//Limit the requests for systems that span many counties
int checked = 0;
for(Integer countyId: countyIds)
{
if(checked++ >= 10)
{
break;
}
CountyInfo countyInfo = service.getCountyInfo(countyId);
if(countyInfo != null && nonNull(countyInfo.getSystems()).stream()
.anyMatch(system -> system.getSystemId() == systemId))
{
return new ViewTarget(getCountryId(service, countyInfo.getStateId()), countyInfo.getStateId(),
countyId, Level.COUNTY, systemId, siteId, null, null);
}
}
if(systemInformation != null)
{
for(State state: nonNull(systemInformation.getStates()))
{
StateInfo stateInfo = service.getStateInfo(state.getStateId());
if(stateInfo != null && nonNull(stateInfo.getSystems()).stream()
.anyMatch(system -> system.getSystemId() == systemId))
{
return new ViewTarget(getCountryId(service, state.getStateId()), state.getStateId(), 0,
Level.STATE, systemId, siteId, null, null);
}
}
}
return null;
}
String key = request.getSourceKey();
AgencyFrequencyEditor.FrequencyTarget frequency = getFrequencyTarget(request.getCandidate());
if(key != null && key.startsWith("county:"))
{
int countyId = Integer.parseInt(key.substring("county:".length()));
CountyInfo countyInfo = service.getCountyInfo(countyId);
if(countyInfo != null)
{
return new ViewTarget(getCountryId(service, countyInfo.getStateId()), countyInfo.getStateId(),
countyId, Level.COUNTY, null, -1, -countyId, frequency);
}
}
else if(key != null && key.startsWith("agency:"))
{
int agencyId = Integer.parseInt(key.substring("agency:".length()));
AgencyInfo agencyInfo = service.getAgencyInfo(agencyId);
if(agencyInfo != null && isCounty(agencyInfo.getCountyId()))
{
CountyInfo countyInfo = service.getCountyInfo(agencyInfo.getCountyId());
if(countyInfo != null && nonNull(countyInfo.getAgencies()).stream()
.anyMatch(agency -> agency.getAgencyId() == agencyId))
{
return new ViewTarget(getCountryId(service, countyInfo.getStateId()), countyInfo.getStateId(),
countyInfo.getCountyId(), Level.COUNTY, null, -1, agencyId, frequency);
}
}
if(agencyInfo != null && agencyInfo.getStateId() > 0)
{
StateInfo stateInfo = service.getStateInfo(agencyInfo.getStateId());
if(stateInfo != null && nonNull(stateInfo.getAgencies()).stream()
.anyMatch(agency -> agency.getAgencyId() == agencyId))
{
return new ViewTarget(getCountryId(service, stateInfo.getStateId()), stateInfo.getStateId(), 0,
Level.STATE, null, -1, agencyId, frequency);
}
}
}
return null;
}
/**
* Frequency to select for the candidate: its source is the owner, category and subcategory
*/
private static AgencyFrequencyEditor.FrequencyTarget getFrequencyTarget(FrequencyCandidate candidate)
{
if(candidate == null)
{
return null;
}
String[] source = candidate.source() != null ? candidate.source().split(" › ") : new String[0];
String category = source.length >= 3 ? source[source.length - 2] : null;
String subCategory = source.length >= 3 ? source[source.length - 1] : null;
return new AgencyFrequencyEditor.FrequencyTarget(category, subCategory, candidate.frequencyHz(),
candidate.title(), candidate.alphaTag());
}
/**
* Country of the state: the preferred country when it has the state, or else the first country that has it
*/
private int getCountryId(RadioReferenceService service, int stateId) throws RadioReferenceException
{
int preferredCountryId = mUserPreferences.getRadioReferencePreference().getPreferredCountryId();
List<Integer> countryIds = new ArrayList<>();
if(preferredCountryId > 0)
{
countryIds.add(preferredCountryId);
}
for(Country country: nonNull(service.getCountries()))
{
if(country.getCountryId() != preferredCountryId)
{
countryIds.add(country.getCountryId());
}
}
for(Integer countryId: countryIds)
{
CountryInfo countryInfo = service.getCountryInfo(countryId);
if(countryInfo != null && nonNull(countryInfo.getStates()).stream()
.anyMatch(state -> state.getStateId() == stateId))
{
return countryId;
}
}
return preferredCountryId;
}
/**
* Indicates if the county id is a real county. Temporary sites in an unknown county have county id 99999.
*/
private static boolean isCounty(int countyId)
{
return countyId > 0 && countyId != 99999;
}
private static <T> List<T> nonNull(List<T> list)
{
return list != null ? list : List.of();
}
/**
* Selects the target's country, state and county, its tab, and its system or agency. Selecting a country, state
* or county loads the lists below it, which select the preferred ids set here, so only the first selection that
* changes is made here.
*/
private void navigate(ViewTarget target)
{
RadioReferencePreference preference = mUserPreferences.getRadioReferencePreference();
preference.setPreferredCountryId(target.countryId());
preference.setPreferredStateId(target.stateId());
if(target.countyId() > 0)
{
preference.setPreferredCountyId(target.countyId());
}
SystemEditor systemEditor = target.level() == Level.COUNTY ? getCountySystemEditor() : getStateSystemEditor();
AgencyEditor agencyEditor = target.level() == Level.COUNTY ? getCountyAgencyEditor() : getStateAgencyEditor();
if(target.systemId() != null)
{
systemEditor.prepareView(target.systemId(), target.siteId());
getTabPane().getSelectionModel().select(target.level() == Level.COUNTY ? getCountySystemTab() :
getStateSystemTab());
}
else
{
agencyEditor.prepareView(target.agencyId(), target.frequency());
getTabPane().getSelectionModel().select(target.level() == Level.COUNTY ? getCountyAgencyTab() :
getStateAgencyTab());
}
//Lists that are still loading select the preferred ids when they arrive
Country country = getCountryComboBox().getItems().stream()
.filter(item -> item.getCountryId() == target.countryId()).findFirst().orElse(null);
if(country == null)
{
return;
}
if(getCountryComboBox().getValue() != country)
{
getCountryComboBox().getSelectionModel().select(country);
return;
}
State state = getStateComboBox().getItems().stream()
.filter(item -> item.getStateId() == target.stateId()).findFirst().orElse(null);
if(state == null)
{
return;
}
if(getStateComboBox().getValue() != state)
{
getStateComboBox().getSelectionModel().select(state);
return;
}
if(target.level() == Level.COUNTY)
{
County county = getCountyComboBox().getItems().stream()
.filter(item -> item.getCountyId() == target.countyId()).findFirst().orElse(null);
if(county == null)
{
return;
}
if(getCountyComboBox().getValue() != county)
{
getCountyComboBox().getSelectionModel().select(county);
return;
}
}
boolean listed = target.systemId() != null ? systemEditor.view(target.systemId(), target.siteId()) :
agencyEditor.view(target.agencyId(), target.frequency());
if(!listed)
{
showViewError("The Radio Reference tab doesn't list this " + (target.systemId() != null ? "system" :
"agency") + ".");
}
}
private void showViewError(String message)
{
Alert alert = new Alert(Alert.AlertType.INFORMATION, message, ButtonType.OK);
alert.setTitle("Radio Reference");
alert.setHeaderText("Can't show the Radio Reference listing");
if(getScene() != null)
{
alert.initOwner(getScene().getWindow());
}
alert.show();
}
private TabPane getTabPane()
{
if(mTabPane == null)
@@ -941,6 +596,8 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
if(country != null)
{
int preferredStateId = mUserPreferences.getRadioReferencePreference().getPreferredStateId();
ThreadPool.CACHED.execute(() -> {
try
{
@@ -949,7 +606,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
Platform.runLater(() -> {
getNationalAgencyEditor().setAgencies(countryInfo.getAgencies());
getStateComboBox().getItems().addAll(countryInfo.getStates());
int preferredStateId = mUserPreferences.getRadioReferencePreference().getPreferredStateId();
for(State state: mStateComboBox.getItems())
{
@@ -996,6 +652,8 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
clearEditors(Level.STATE);
getCountyComboBox().getItems().clear();
int preferredCountyId = mUserPreferences.getRadioReferencePreference().getPreferredCountyId();
if(state != null)
{
ThreadPool.CACHED.execute(() -> {
@@ -1007,7 +665,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
getStateAgencyEditor().setAgencies(stateInfo.getAgencies());
getStateSystemEditor().setSystems(stateInfo.getSystems());
getCountyComboBox().getItems().addAll(stateInfo.getCounties());
int preferredCountyId = mUserPreferences.getRadioReferencePreference().getPreferredCountyId();
for(County county: mCountyComboBox.getItems())
{

View File

@@ -47,7 +47,7 @@ import org.slf4j.LoggerFactory;
/**
* Playlist actions for radio reference frequencies and trunked system sites: find the playlist channel that already
* decodes a frequency or site, enable or disable it, or add a channel and optionally start it. A frequency or site that already
* decodes a frequency or site, enable or disable it, or add a channel and start it. A frequency or site that already
* has a playlist channel with the same protocol isn't added again.
*
* The add, enable and disable actions run in the background and report errors to the caller's error handler, on the
@@ -452,17 +452,6 @@ public class RadioReferencePlaylistActions
* @param firstFrequency to start the new control channel on, e.g. the frequency the user picked, or null
*/
public void addSite(SiteRecord siteRecord, Long firstFrequency, Consumer<String> onError)
{
addSite(siteRecord, firstFrequency, true, onError);
}
/**
* Adds playlist channels for the trunked system site, like {@link #addSite(SiteRecord, Long, Consumer)}, and
* optionally starts them.
* @param firstFrequency to start the new control channel on, e.g. the frequency the user picked, or null
* @param start true to start the new channels, or the site's existing channels
*/
public void addSite(SiteRecord siteRecord, Long firstFrequency, boolean start, Consumer<String> onError)
{
ThreadPool.CACHED.execute(() -> {
SiteDetails details = getSiteDetails(siteRecord, onError);
@@ -486,22 +475,15 @@ public class RadioReferencePlaylistActions
return;
}
if(start)
{
enableAll(existing, onError);
}
//The channel model's list backs the playlist editor, so it's changed on the JavaFX thread
Platform.runLater(() -> {
for(Channel channel: channels)
{
mPlaylistManager.getChannelModel().addChannel(channel);
if(start)
{
enable(channel, onError);
}
}
});
return;
}
@@ -517,7 +499,7 @@ public class RadioReferencePlaylistActions
return;
}
add(channel, start, onError);
addAndStart(channel, onError);
});
}
@@ -525,16 +507,6 @@ public class RadioReferencePlaylistActions
* Adds a playlist channel for one repeater of a repeater site (LTR) and starts it, or starts its existing channel
*/
public void addRepeater(SiteRecord siteRecord, long frequency, Consumer<String> onError)
{
addRepeater(siteRecord, frequency, true, onError);
}
/**
* Adds a playlist channel for one repeater of a repeater site (LTR) unless the playlist has one, and optionally
* starts the channel
* @param start true to start the new or existing channel
*/
public void addRepeater(SiteRecord siteRecord, long frequency, boolean start, Consumer<String> onError)
{
ThreadPool.CACHED.execute(() -> {
SiteDetails details = getSiteDetails(siteRecord, onError);
@@ -554,7 +526,7 @@ public class RadioReferencePlaylistActions
return;
}
add(channels.get(0), start, onError);
addAndStart(channels.get(0), onError);
});
}
@@ -562,16 +534,6 @@ public class RadioReferencePlaylistActions
* Adds a playlist channel for the conventional frequency and starts it, or starts the existing channel
*/
public void addConventional(FrequencyCandidate candidate, Consumer<String> onError)
{
addConventional(candidate, true, onError);
}
/**
* Adds a playlist channel for the conventional frequency unless the playlist has one, and optionally starts the
* channel
* @param start true to start the new or existing channel
*/
public void addConventional(FrequencyCandidate candidate, boolean start, Consumer<String> onError)
{
ModeDecoderType mode = ModeDecoderType.fromName(candidate.mode());
String[] source = candidate.source() != null ? candidate.source().split(" › ") : new String[0];
@@ -588,36 +550,28 @@ public class RadioReferencePlaylistActions
return;
}
add(channel, start, onError);
addAndStart(channel, onError);
}
/**
* Adds the channel to the playlist and optionally starts it, unless the playlist already has a channel for its
* frequencies and protocol, which is started instead when starting
* Adds the channel to the playlist and starts it, unless the playlist already has a channel for its frequencies
* and protocol, which is started instead
*/
private void add(Channel channel, boolean start, Consumer<String> onError)
private void addAndStart(Channel channel, Consumer<String> onError)
{
Channel existing = findChannel(getFrequencies(channel.getSourceConfiguration()),
getProtocolFamily(channel.getDecodeConfiguration().getDecoderType()));
if(existing != null)
{
if(start)
{
enable(existing, onError);
}
return;
}
//The channel model's list backs the playlist editor, so it's changed on the JavaFX thread
Platform.runLater(() -> {
mPlaylistManager.getChannelModel().addChannel(channel);
if(start)
{
enable(channel, onError);
}
});
}

View File

@@ -19,7 +19,6 @@
package io.github.dsheirer.gui.playlist.radioreference;
import io.github.dsheirer.alias.AliasListConfiguration;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.eventbus.MyEventBus;
@@ -46,7 +45,6 @@ import io.github.dsheirer.rrapi.type.Site;
import io.github.dsheirer.rrapi.type.SiteFrequency;
import io.github.dsheirer.rrapi.type.System;
import io.github.dsheirer.rrapi.type.SystemInformation;
import io.github.dsheirer.service.radioreference.AliasListSynchronizer;
import io.github.dsheirer.source.config.SourceConfigTuner;
import io.github.dsheirer.source.config.SourceConfigTunerMultipleFrequency;
import java.text.DecimalFormat;
@@ -57,7 +55,6 @@ import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import javafx.animation.RotateTransition;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
@@ -78,7 +75,6 @@ import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
@@ -124,7 +120,6 @@ public class SiteEditor extends GridPane
private SystemInformation mCurrentSystemInformation;
private ComboBox mAliasListNameComboBox;
private Button mNewAliasListButton;
private Button mNewSystemAliasListButton;
private Label mP25ControlLabel;
private SegmentedButton mP25ControlSegmentedButton;
private ToggleButton mFdmaControlToggleButton;
@@ -227,12 +222,8 @@ public class SiteEditor extends GridPane
GridPane.setHgrow(getAliasListNameComboBox(), Priority.ALWAYS);
getChildren().add(getAliasListNameComboBox());
HBox aliasListButtonsBox = new HBox();
aliasListButtonsBox.setAlignment(Pos.CENTER_LEFT);
aliasListButtonsBox.setSpacing(10);
aliasListButtonsBox.getChildren().addAll(getNewAliasListButton(), getNewSystemAliasListButton());
GridPane.setConstraints(aliasListButtonsBox, 2, ++row);
getChildren().add(aliasListButtonsBox);
GridPane.setConstraints(getNewAliasListButton(), 2, ++row);
getChildren().add(getNewAliasListButton());
HBox createBox = new HBox();
createBox.setAlignment(Pos.CENTER_LEFT);
@@ -287,18 +278,6 @@ public class SiteEditor extends GridPane
getGoToChannelEditorCheckBox().setDisable(disable || !supported);
getAliasListNameComboBox().setDisable(disable || !supported);
getNewAliasListButton().setDisable(disable || !supported);
getNewSystemAliasListButton().setDisable(disable || !supported || system == null);
//Select an alias list that tracks this site's system, if there is one
if(system != null)
{
String trackingAliasList = mPlaylistManager.getAliasModel().getAliasListNameTracking(system.getSystemId());
if(trackingAliasList != null)
{
getAliasListNameComboBox().getSelectionModel().select(trackingAliasList);
}
}
getCreateChannelConfigurationButton().setVisible(false);
getGoToChannelEditorCheckBox().setVisible(false);
@@ -899,97 +878,6 @@ public class SiteEditor extends GridPane
return mNewAliasListButton;
}
/**
* Button to create an alias list that tracks the talkgroups of the current system on Radio Reference.
*/
private Button getNewSystemAliasListButton()
{
if(mNewSystemAliasListButton == null)
{
mNewSystemAliasListButton = new Button("New Alias List For System");
mNewSystemAliasListButton.setTooltip(new Tooltip("Create an alias list with the system's talkgroups " +
"that tracks the system on Radio Reference and automatically adds or updates talkgroup aliases"));
mNewSystemAliasListButton.setDisable(true);
mNewSystemAliasListButton.setOnAction(event -> createSystemAliasList());
}
return mNewSystemAliasListButton;
}
/**
* Prompts for a name and creates an alias list that tracks the current system, then imports the talkgroups.
*/
private void createSystemAliasList()
{
if(mCurrentSystem == null)
{
return;
}
String systemName = mCurrentSystem.getName() != null ? mCurrentSystem.getName().trim() : "";
if(systemName.length() > 25)
{
systemName = systemName.substring(0, 25).trim();
}
TextInputDialog dialog = new TextInputDialog(systemName);
dialog.setTitle("Create New Alias List For System");
dialog.setHeaderText("Create an alias list that tracks the talkgroups for " + mCurrentSystem.getName() +
".\nPlease enter an alias list name (max 25 chars).");
dialog.setContentText("Name:");
dialog.getEditor().setTextFormatter(new TextFormatter<String>(new MaxLengthUnaryOperator(25)));
dialog.initOwner(getNewSystemAliasListButton().getScene().getWindow());
Optional<String> result = dialog.showAndWait();
if(result.isEmpty() || result.get().trim().isEmpty())
{
return;
}
String name = result.get().trim();
AliasModel aliasModel = mPlaylistManager.getAliasModel();
if(name.equals(AliasModel.NO_ALIAS_LIST) || aliasModel.aliasListNames().contains(name))
{
Alert alert = new Alert(Alert.AlertType.ERROR, "An alias list named [" + name +
"] already exists. Please choose another name.", ButtonType.OK);
alert.setTitle("Create New Alias List For System");
alert.setHeaderText("Alias List Exists");
alert.initOwner(getNewSystemAliasListButton().getScene().getWindow());
alert.showAndWait();
return;
}
AliasListConfiguration configuration = aliasModel.getOrCreateAliasListConfiguration(name);
configuration.track(mCurrentSystem.getSystemId(), mCurrentSystem.getName());
configuration.setAutoUpdate(true);
getAliasListNameComboBox().getSelectionModel().select(name);
getNewSystemAliasListButton().setDisable(true);
mPlaylistManager.getAliasListSynchronizer().refresh(configuration)
.whenComplete((syncResult, throwable) -> Platform.runLater(() -> {
getNewSystemAliasListButton().setDisable(mCurrentSystem == null);
if(throwable != null)
{
Alert alert = new Alert(Alert.AlertType.ERROR, "Alias list [" + name + "] was created, but the " +
"talkgroups couldn't be imported from Radio Reference. Use Refresh Now in the Aliases tab " +
"to try again.\n\n" + AliasListSynchronizer.getMessage(throwable), ButtonType.OK);
alert.setTitle("Create New Alias List For System");
alert.setHeaderText("Talkgroup Import Failed");
if(getScene() != null)
{
alert.initOwner(getScene().getWindow());
}
alert.show();
}
}));
}
private Label getProtocolNotSupportedLabel()
{
if(mProtocolNotSupportedLabel == null)

View File

@@ -156,41 +156,6 @@ public class SystemEditor extends VBox
}
}
/**
* Prepares to show the system with the site selected when the systems are next set.
* @param systemId of the system
* @param siteId to select, or -1 for none
*/
public void prepareView(int systemId, int siteId)
{
mUserPreferences.getRadioReferencePreference().setPreferredSystemId(systemId, mLevel);
getTabPane().getSelectionModel().select(getSystemTab());
getSystemSiteSelectionEditor().viewSite(systemId, siteId);
}
/**
* Shows the system with the site selected
* @param systemId of the system
* @param siteId to select, or -1 for none
* @return false when the editor doesn't list the system
*/
public boolean view(int systemId, int siteId)
{
prepareView(systemId, siteId);
for(System system: getSystemComboBox().getItems())
{
if(system.getSystemId() == systemId)
{
//Selecting the shown system again doesn't reload it - the site is selected in the shown system
getSystemComboBox().getSelectionModel().select(system);
return true;
}
}
return getSystemComboBox().getItems().isEmpty();
}
private TabPane getTabPane()
{
if(mTabPane == null)

View File

@@ -58,8 +58,6 @@ public class SystemSiteSelectionEditor extends GridPane
private UserPreferences mUserPreferences;
private PlaylistManager mPlaylistManager;
private ProgressIndicator mProgressIndicator;
private int mPendingSystemId = -1;
private int mPendingSiteId = -1;
private Label mPlaceholderLabel;
private Label mProtocolLabel;
private Label mFlavorLabel;
@@ -134,46 +132,6 @@ public class SystemSiteSelectionEditor extends GridPane
Collections.sort(sites, Ordering.natural());
getSiteTableView().getItems().addAll(sites);
setLoading(false);
if(system != null && system.getSystemId() == mPendingSystemId)
{
selectSite(mPendingSiteId);
}
}
/**
* Selects the site once the system is shown, or now when it's already shown.
* @param systemId of the system
* @param siteId to select, or -1 for none
*/
public void viewSite(int systemId, int siteId)
{
if(mCurrentSystem != null && mCurrentSystem.getSystemId() == systemId &&
!getSiteTableView().getItems().isEmpty())
{
selectSite(siteId);
}
else
{
mPendingSystemId = systemId;
mPendingSiteId = siteId;
}
}
private void selectSite(int siteId)
{
mPendingSystemId = -1;
mPendingSiteId = -1;
for(EnrichedSite site: getSiteTableView().getItems())
{
if(site.getSite() != null && site.getSite().getSiteId() == siteId)
{
getSiteTableView().getSelectionModel().select(site);
getSiteTableView().scrollTo(site);
return;
}
}
}
public void clear()

View File

@@ -1,100 +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.playlist.radioreference;
import io.github.dsheirer.gui.playlist.PlaylistEditorRequest;
import io.github.dsheirer.service.radioreference.FrequencyCandidate;
/**
* Request to show a trunked system site, or a conventional frequency, in the playlist editor's Radio Reference tab
*/
public class ViewRadioReferenceRequest extends PlaylistEditorRequest
{
private final Integer mSystemId;
private final Integer mSiteId;
private final String mSourceKey;
private final FrequencyCandidate mCandidate;
private ViewRadioReferenceRequest(Integer systemId, Integer siteId, String sourceKey, FrequencyCandidate candidate)
{
mSystemId = systemId;
mSiteId = siteId;
mSourceKey = sourceKey;
mCandidate = candidate;
}
/**
* Request to show a trunked system with the site selected
* @param systemId radio reference system id
* @param siteId radio reference site id, or null to show the system only
*/
public static ViewRadioReferenceRequest site(int systemId, Integer siteId)
{
return new ViewRadioReferenceRequest(systemId, siteId, null, null);
}
/**
* Request to show a conventional frequency in the county or agency that lists it
* @param sourceKey of the county or agency that lists the frequency: county:123 or agency:789
* @param candidate frequency to select
*/
public static ViewRadioReferenceRequest frequency(String sourceKey, FrequencyCandidate candidate)
{
return new ViewRadioReferenceRequest(null, null, sourceKey, candidate);
}
/**
* Radio reference system id, or null for a conventional frequency
*/
public Integer getSystemId()
{
return mSystemId;
}
/**
* Radio reference site id, or null
*/
public Integer getSiteId()
{
return mSiteId;
}
/**
* Key of the county or agency that lists the conventional frequency, or null for a trunked system
*/
public String getSourceKey()
{
return mSourceKey;
}
/**
* Conventional frequency to select, or null for a trunked system
*/
public FrequencyCandidate getCandidate()
{
return mCandidate;
}
@Override
public TabName getTabName()
{
return TabName.RADIOREFERENCE;
}
}

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"));

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