Compare commits

...

14 Commits

Author SHA1 Message Date
denny
886ac2a070 #2688 NXDN Type-D audio fixes. New call audio or late call audio correctly handled. Call response (CALL_RESP) now parsed correctly per TS 1-E Figure 6.4-21 to handle multi-system formats. 2026-11-18 03:19:14 -05:00
Denny Sheirer
f47479b8d4 #2681 JavaFX Map Redesign
#2681 Map tab as a JavaFX component

Replaces the Swing JXMapViewer map with a pure JavaFX canvas tile map in gui/map:
OpenStreetMap tiles with a memory and disk cache, track, Radio Reference site and
user location layers, the site hover card and context menu, and the map controls.
Removes the bundled SwingX map viewer copy and moves GeoPosition to the map package.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-18 02:29:58 -05:00
Denny Sheirer
bc7dd201ab #2673 User preferences font scaling not working with display styling/theme updates (#2677)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-18 02:12:32 -05:00
Denny Sheirer
c46b80b06b Update README.md (#2686)
Adds badget for google groups
2026-11-17 06:51:15 -05:00
Denny Sheirer
7f1e7d9cd2 #2q683 Now playing channel adds new Alias List column (#2684)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 03:56:36 -05:00
Denny Sheirer
7a7364839b #2680 Alias List optionally auto-adds/upates radio ID to talker alias value. Enable the feature in the playlist editor in the channel config for protocols that produce talker alias (P25, NXDN, DMR). (#2682)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 03:52:59 -05:00
Denny Sheirer
2213544eec #2676 Alias List optionally tracks radio reference system with optional auto-update for talkgroup alias changes. (#2679)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 03:24:29 -05:00
Denny Sheirer
feeedb7c29 #2671 Spectral display right click on signal context menu radio reference options. Unifies the popout card to channels in order: 1) in playlist and enabled, in playlist, in radio reference, ordered by distance from the user's my location (#2675)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-17 02:25:50 -05:00
Denny Sheirer
6dd06288ac #2669 Adds System & Site columns to Now Playing, hidden by default (#2670)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:34:58 -05:00
Denny Sheirer
5fd469c402 #315 Adds Tuner column to Now Playing channels view (#2668)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:19:28 -05:00
Denny Sheirer
0bc5d6db64 #2620 Fix NPE in headless mode (#2667)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:04:33 -05:00
Denny Sheirer
80754558d6 #2662 Tuners monitor sample rate and log on excessive dropped samples. (#2663)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:02:11 -05:00
Denny Sheirer
2f9d52a56a #2665 Updates the README (#2666)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-16 03:01:40 -05:00
Denny Sheirer
5474a5a448 #2660 Now Playing Update With Talker Column & Column Management (#2661)
* #2660 Now Playing panel with events and messages are all recreated as JavaFX panels

* #2660 Talker alias cleanup across the decoders

* #2660 Talker alias cleanup across the decoders

---------

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 07:43:04 -05:00
200 changed files with 14818 additions and 14303 deletions

View File

@@ -1,7 +1,31 @@
![Gradle Build](https://github.com/dsheirer/sdrtrunk/actions/workflows/gradle.yml/badge.svg)
![Nightly Release](https://github.com/dsheirer/sdrtrunk/actions/workflows/nightly.yml/badge.svg)
[![Latest Release](https://img.shields.io/github/v/release/DSheirer/sdrtrunk?label=release)](https://github.com/DSheirer/sdrtrunk/releases/latest)
[![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)
# MacOS Tahoe 26.1 Users - Attention:
# sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
> ## 📖 [Read the sdrtrunk User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
> New to sdrtrunk? Start with the **[Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)** guide,
> then use the **[User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)** and
> **[How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)** to set up tuners, playlists, aliases and streaming.
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [How-To Guides](https://github.com/DSheirer/sdrtrunk/wiki/How-To-Guides)
* [FAQ](https://github.com/DSheirer/sdrtrunk/wiki/FAQ)
* [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![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.
```
@@ -19,18 +43,6 @@ Finally, create a symbolic link from the installed library to the place where us
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
# sdrtrunk
A cross-platform java application for decoding, monitoring, recording and streaming trunked mobile and related radio protocols using Software Defined Radios (SDR).
* [Help/Wiki Home Page](https://github.com/DSheirer/sdrtrunk/wiki)
* [Getting Started](https://github.com/DSheirer/sdrtrunk/wiki/Getting-Started)
* [User's Manual](https://github.com/DSheirer/sdrtrunk/wiki/User-Manual)
* [Download](https://github.com/DSheirer/sdrtrunk/releases)
* [Support](https://github.com/DSheirer/sdrtrunk/wiki/Support)
![sdrtrunk Application](https://github.com/DSheirer/sdrtrunk/wiki/images/sdrtrunk.png)
**Figure 1:** sdrtrunk Application Screenshot
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.

View File

@@ -0,0 +1,269 @@
/*
* *****************************************************************************
* 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,6 +46,8 @@ 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()
{
@@ -63,6 +65,99 @@ 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.
*/
@@ -79,6 +174,15 @@ 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());
}
}
}
/**
@@ -93,7 +197,22 @@ public class AliasModel
return;
}
mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName));
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);
}
}
}
/**
@@ -109,6 +228,7 @@ public class AliasModel
mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
mAliasListMap.remove(aliasListName);
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
}
/**
@@ -146,6 +266,7 @@ public class AliasModel
removeAlias(alias);
}
mAliasListConfigurations.clear();
mAliasListNames.clear();
}

View File

@@ -0,0 +1,455 @@
/*
* *****************************************************************************
* 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.
*
* 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)
{
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(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();
}
/**
* Number of identifiers (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming.
*/
private static int getIdentityCount(Alias alias)
{
int count = 0;
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isAudioIdentifier())
{
count++;
}
}
return count;
}
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

@@ -1,137 +0,0 @@
/*******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2017 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/
package io.github.dsheirer.channel.details;
import io.github.dsheirer.channel.state.DecoderState;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.sample.Listener;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChannelDetailPanel extends JPanel implements Listener<ProcessingChain>
{
private static final String EMPTY_DETAILS = "Please select a channel to view details";
private JLabel mSystemLabel;
private JLabel mSiteLabel;
private JLabel mNameLabel;
private JTextArea mDetailTextPane;
private ChannelProcessingManager mChannelProcessingManager;
private ProcessingChain mProcessingChain;
public ChannelDetailPanel(ChannelProcessingManager channelProcessingManager)
{
mChannelProcessingManager = channelProcessingManager;
init();
}
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[]0[grow,fill]"));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new MigLayout("insets 1 1 1 1", "[][grow,fill][][grow,fill][][grow,fill][]", ""));
buttonPanel.add(new JLabel("System:"));
mSystemLabel = new JLabel(" ");
buttonPanel.add(mSystemLabel);
buttonPanel.add(new JLabel("Site:"));
mSiteLabel = new JLabel(" ");
buttonPanel.add(mSiteLabel);
buttonPanel.add(new JLabel("Channel Name:"));
mNameLabel = new JLabel(" ");
buttonPanel.add(mNameLabel);
JButton refreshButton = new JButton("Refresh");
refreshButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
receive(mProcessingChain);
}
});
buttonPanel.add(refreshButton);
add(buttonPanel, "wrap");
mDetailTextPane = new JTextArea(EMPTY_DETAILS);
DefaultCaret caret = (DefaultCaret)mDetailTextPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
add(new JScrollPane(mDetailTextPane));
}
@Override
public void receive(ProcessingChain processingChain)
{
mProcessingChain = processingChain;
Channel channel = mChannelProcessingManager.getChannel(processingChain);
final String system = channel != null ? channel.getSystem() : null;
final String site = channel != null ? channel.getSite() : null;
final String name = channel != null ?
(channel.getChannelType() == Channel.ChannelType.TRAFFIC ? "Traffic Channel" : channel.getName()) : null;
final String details;
if(processingChain != null)
{
StringBuilder sb = new StringBuilder();
for(DecoderState decoderState : processingChain.getDecoderStates())
{
sb.append(decoderState.getActivitySummary());
}
details = sb.toString();
}
else
{
details = EMPTY_DETAILS;
}
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
mSystemLabel.setText(system);
mSiteLabel.setText(site);
mNameLabel.setText(name);
mDetailTextPane.setText(details);
}
});
}
}

View File

@@ -49,6 +49,7 @@ 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;
@@ -128,6 +129,19 @@ 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
*/
@@ -323,6 +337,15 @@ 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);
@@ -339,6 +362,7 @@ 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,6 +22,7 @@ package io.github.dsheirer.channel.metadata;
public enum ChannelMetadataField
{
CONFIGURATION_ALIAS_LIST,
CONFIGURATION_CHANNEL,
CONFIGURATION_FREQUENCY,
CONFIGURATION_SITE,

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -18,67 +18,73 @@
*/
package io.github.dsheirer.channel.metadata;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.decoder.DecoderLogicalChannelNameIdentifier;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.sample.Listener;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.table.AbstractTableModel;
public class ChannelMetadataModel extends AbstractTableModel implements IChannelMetadataUpdateListener
/**
* Model of the channel metadata for the currently processing channels, with a map from each channel metadata to the
* channel that it belongs to. The model is thread-safe and isn't tied to a user interface toolkit: listeners are
* notified on the thread that changes the model and pass the changes to their user interface thread.
*/
public class ChannelMetadataModel implements IChannelMetadataUpdateListener
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadataModel.class);
private final List<ChannelMetadata> mChannelMetadata = new ArrayList<>();
private final Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap<>();
private final List<Listener> mListeners = new CopyOnWriteArrayList<>();
public static final int COLUMN_DECODER_STATE = 0;
public static final int COLUMN_DECODER_TYPE = 1;
public static final int COLUMN_USER_FROM = 2;
public static final int COLUMN_USER_FROM_ALIAS = 3;
public static final int COLUMN_USER_TO = 4;
public static final int COLUMN_USER_TO_ALIAS = 5;
public static final int COLUMN_DECODER_LOGICAL_CHANNEL_NAME = 6;
public static final int COLUMN_CONFIGURATION_FREQUENCY = 7;
public static final int COLUMN_CONFIGURATION_CHANNEL = 8;
private static final String[] COLUMNS = {"Status", "Decoder", "From", "Alias", "To", "Alias", "Channel", "Frequency", "Channel Name"};
private List<ChannelMetadata> mChannelMetadata = new ArrayList();
private Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap();
private Listener<ChannelAndMetadata> mChannelAddListener;
public ChannelMetadataModel()
/**
* Listener for changes to the channel metadata model. Notifications arrive on the thread that changed the
* model, sometimes while the model is locked, so implementations must not block and must not call back into
* the model from the notification thread.
*/
public interface Listener
{
MyEventBus.getGlobalEventBus().register(this);
/**
* Channel metadata(s) for a channel were added to the model.
*/
void added(ChannelAndMetadata channelAndMetadata);
/**
* Channel metadata was removed from the model.
*/
void removed(ChannelMetadata channelMetadata);
/**
* A field of a channel metadata in the model was updated.
*/
void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField);
}
/**
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
* Constructs an instance
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
public ChannelMetadataModel()
{
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
EventQueue.invokeLater(() -> {
for(int row = 0; row < mChannelMetadata.size(); row++)
{
fireTableCellUpdated(row, COLUMN_USER_FROM);
fireTableCellUpdated(row, COLUMN_USER_TO);
}
});
}
}
/**
* Registers the listener to receive model change notifications.
* @param listener to register
* @return the channel metadata in the model when the listener is registered, so that the listener starts from
* the current state and receives the changes that follow.
*/
public synchronized List<ChannelMetadata> addListener(Listener listener)
{
mListeners.add(listener);
return new ArrayList<>(mChannelMetadata);
}
/**
* Removes the listener from receiving model change notifications.
*/
public void removeListener(Listener listener)
{
mListeners.remove(listener);
}
/**
@@ -87,10 +93,16 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
*/
public String getDiagnosticInformation()
{
StringBuilder sb = new StringBuilder();
Map<ChannelMetadata,Channel> mapCopy = new HashMap<>(mMetadataChannelMap);
List<ChannelMetadata> metadataCopy = new ArrayList<>(mChannelMetadata);
Map<ChannelMetadata,Channel> mapCopy;
List<ChannelMetadata> metadataCopy;
synchronized(this)
{
mapCopy = new HashMap<>(mMetadataChannelMap);
metadataCopy = new ArrayList<>(mChannelMetadata);
}
StringBuilder sb = new StringBuilder();
sb.append("Channel Metadata Model Diagnostics\n");
for(ChannelMetadata channelMetadata: metadataCopy)
@@ -122,51 +134,34 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
return sb.toString();
}
/**
* Prepares the model for disposal.
*/
public void dispose()
{
MyEventBus.getGlobalEventBus().unregister(this);
mListeners.clear();
}
/**
* Lookup model row for the specified channel metadata
* Adds the channel metadata(s) for a channel to the model.
*/
public int getRow(ChannelMetadata channelMetadata)
public synchronized void add(ChannelAndMetadata channelAndMetadata)
{
if(mChannelMetadata.contains(channelMetadata))
for(ChannelMetadata channelMetadata: channelAndMetadata.getChannelMetadata())
{
return mChannelMetadata.indexOf(channelMetadata);
}
return -1;
}
/**
* Registers the listener to be notified when channel metadata(s) are added to the model.
* @param listener to receive channel associated with the channel metadata(s) that were added
*/
public void setChannelAddListener(Listener<ChannelAndMetadata> listener)
{
mChannelAddListener = listener;
}
public void add(ChannelAndMetadata channelAndMetadata)
{
//Execute on the swing thread to avoid threading issues
EventQueue.invokeLater(() -> {
for(ChannelMetadata channelMetadata: channelAndMetadata.getChannelMetadata())
if(!mChannelMetadata.contains(channelMetadata))
{
mChannelMetadata.add(channelMetadata);
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
int index = mChannelMetadata.indexOf(channelMetadata);
fireTableRowsInserted(index, index);
channelMetadata.setUpdateEventListener(ChannelMetadataModel.this);
}
if(mChannelAddListener != null)
{
mChannelAddListener.receive(channelAndMetadata);
}
});
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
channelMetadata.setUpdateEventListener(this);
}
for(Listener listener: mListeners)
{
listener.added(channelAndMetadata);
}
}
/**
@@ -174,7 +169,7 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
* @param channelMetadatas
* @param channel
*/
public void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
public synchronized void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
{
for(ChannelMetadata channelMetadata: channelMetadatas)
{
@@ -182,178 +177,46 @@ public class ChannelMetadataModel extends AbstractTableModel implements IChannel
}
}
public void remove(ChannelMetadata channelMetadata)
/**
* Removes the channel metadata from the model.
*/
public synchronized void remove(ChannelMetadata channelMetadata)
{
//Execute on the swing thread to avoid threading issues
EventQueue.invokeLater(() -> {
channelMetadata.removeUpdateEventListener();
int index = mChannelMetadata.indexOf(channelMetadata);
mChannelMetadata.remove(channelMetadata);
mMetadataChannelMap.remove(channelMetadata);
channelMetadata.removeUpdateEventListener();
mMetadataChannelMap.remove(channelMetadata);
if(index >= 0)
if(mChannelMetadata.remove(channelMetadata))
{
for(Listener listener: mListeners)
{
fireTableRowsDeleted(index, index);
listener.removed(channelMetadata);
}
});
}
}
/**
* Get the channel metadata at the specified model row index
* Current channel metadata in the model.
* @return copy of the channel metadata list.
*/
public ChannelMetadata getChannelMetadata(int row)
public synchronized List<ChannelMetadata> getChannelMetadata()
{
if(row < mChannelMetadata.size())
{
return mChannelMetadata.get(row);
}
return null;
return new ArrayList<>(mChannelMetadata);
}
/**
* Returns the channel that matches the metadata or null
*/
public Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
public synchronized Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
{
return mMetadataChannelMap.get(channelMetadata);
}
@Override
public int getRowCount()
{
return mChannelMetadata.size();
}
@Override
public int getColumnCount()
{
return COLUMNS.length;
}
@Override
public String getColumnName(int column)
{
return COLUMNS[column];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch(columnIndex)
{
case COLUMN_USER_FROM:
case COLUMN_USER_TO:
return ChannelMetadata.class;
case COLUMN_USER_FROM_ALIAS:
case COLUMN_USER_TO_ALIAS:
return Alias.class;
case COLUMN_DECODER_LOGICAL_CHANNEL_NAME:
return String.class;
default:
return Identifier.class;
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if(rowIndex <= mChannelMetadata.size())
{
ChannelMetadata channelMetadata = mChannelMetadata.get(rowIndex);
switch(columnIndex)
{
case COLUMN_DECODER_STATE:
return channelMetadata.getChannelStateIdentifier();
case COLUMN_DECODER_TYPE:
return channelMetadata.getDecoderTypeConfigurationIdentifier();
case COLUMN_DECODER_LOGICAL_CHANNEL_NAME:
DecoderLogicalChannelNameIdentifier id = channelMetadata.getDecoderLogicalChannelNameIdentifier();
if(channelMetadata.hasTimeslot())
{
if(id == null)
{
return "TS:" + channelMetadata.getTimeslot();
}
else
{
String value = id.getValue().replace(" TS1", "")
.replace(" TS2", "");
return value + " TS:" + channelMetadata.getTimeslot();
}
}
else
{
if(id == null)
{
return null;
}
else
{
return id.getValue();
}
}
case COLUMN_CONFIGURATION_FREQUENCY:
return channelMetadata.getFrequencyConfigurationIdentifier();
case COLUMN_CONFIGURATION_CHANNEL:
return channelMetadata.getChannelNameConfigurationIdentifier();
case COLUMN_USER_TO:
return channelMetadata;
case COLUMN_USER_FROM:
return channelMetadata;
case COLUMN_USER_FROM_ALIAS:
return channelMetadata.getFromIdentifierAliases();
case COLUMN_USER_TO_ALIAS:
return channelMetadata.getToIdentifierAliases();
}
}
return null;
}
@Override
public void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField)
{
final int rowIndex = mChannelMetadata.indexOf(channelMetadata);
if(rowIndex >= 0)
for(Listener listener: mListeners)
{
//Execute on the swing thread to avoid threading issues
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
switch(channelMetadataField)
{
case CONFIGURATION_CHANNEL:
fireTableCellUpdated(rowIndex, COLUMN_CONFIGURATION_CHANNEL);
break;
case CONFIGURATION_FREQUENCY:
fireTableCellUpdated(rowIndex, COLUMN_CONFIGURATION_FREQUENCY);
break;
case DECODER_CHANNEL_NAME:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_LOGICAL_CHANNEL_NAME);
break;
case DECODER_TYPE:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_TYPE);
break;
case DECODER_STATE:
fireTableCellUpdated(rowIndex, COLUMN_DECODER_STATE);
break;
case USER_FROM:
fireTableCellUpdated(rowIndex, COLUMN_USER_FROM);
fireTableCellUpdated(rowIndex, COLUMN_USER_FROM_ALIAS);
break;
case USER_TO:
fireTableCellUpdated(rowIndex, COLUMN_USER_TO);
fireTableCellUpdated(rowIndex, COLUMN_USER_TO_ALIAS);
break;
}
}
});
listener.updated(channelMetadata, channelMetadataField);
}
}
}

View File

@@ -1,494 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.channel.metadata;
import com.google.common.base.Joiner;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.channel.state.State;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelModel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.channel.ViewChannelRequest;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.configuration.FrequencyConfigurationIdentifier;
import io.github.dsheirer.identifier.decoder.ChannelStateIdentifier;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
public class ChannelMetadataPanel extends JPanel implements ListSelectionListener
{
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadataPanel.class);
private static final String TABLE_PREFERENCE_KEY = "channel.metadata.panel";
private ChannelModel mChannelModel;
private ChannelProcessingManager mChannelProcessingManager;
private IconModel mIconModel;
private UserPreferences mUserPreferences;
private JTable mTable;
private Broadcaster<ProcessingChain> mSelectedProcessingChainBroadcaster = new Broadcaster<>();
private Map<State,Color> mBackgroundColors = new EnumMap<>(State.class);
private Map<State,Color> mForegroundColors = new EnumMap<>(State.class);
private JTableColumnWidthMonitor mTableColumnMonitor;
private Channel mUserSelectedChannel;
/**
* Table view for currently decoding channel metadata
*/
public ChannelMetadataPanel(PlaylistManager playlistManager, IconModel iconModel, UserPreferences userPreferences)
{
mChannelModel = playlistManager.getChannelModel();
mChannelProcessingManager = playlistManager.getChannelProcessingManager();
mIconModel = iconModel;
mUserPreferences = userPreferences;
init();
}
/**
* Initializes the panel
*/
private void init()
{
setLayout( new MigLayout( "insets 0 0 0 0", "[grow,fill]", "[grow,fill]") );
mTable = new JTable(mChannelProcessingManager.getChannelMetadataModel());
mChannelProcessingManager.getChannelMetadataModel().setChannelAddListener(new ChannelAddListener());
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)mTable.getDefaultRenderer(String.class);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
mTable.getSelectionModel().addListSelectionListener(this);
mTable.addMouseListener(new MouseSupport());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_DECODER_STATE)
.setCellRenderer(new ColoredStateCellRenderer());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_FROM)
.setCellRenderer(new FromCellRenderer(mUserPreferences.getTalkgroupFormatPreference()));
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_TO)
.setCellRenderer(new ToCellRenderer(mUserPreferences.getTalkgroupFormatPreference()));
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_FROM_ALIAS)
.setCellRenderer(new AliasCellRenderer());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_USER_TO_ALIAS)
.setCellRenderer(new AliasCellRenderer());
mTable.getColumnModel().getColumn(ChannelMetadataModel.COLUMN_CONFIGURATION_FREQUENCY)
.setCellRenderer(new FrequencyCellRenderer());
//Add a table column width monitor to store/restore column widths
mTableColumnMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTable, TABLE_PREFERENCE_KEY);
JScrollPane scrollPane = new JScrollPane(mTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrollPane);
setColors();
}
/**
* Setup the background and foreground color palette for the various channel states.
*/
private void setColors()
{
mBackgroundColors.put(State.ACTIVE, Color.CYAN);
mForegroundColors.put(State.ACTIVE, Color.BLUE);
mBackgroundColors.put(State.CALL, Color.BLUE);
mForegroundColors.put(State.CALL, Color.YELLOW);
mBackgroundColors.put(State.CONTROL, Color.ORANGE);
mForegroundColors.put(State.CONTROL, Color.BLUE);
mBackgroundColors.put(State.DATA, Color.GREEN);
mForegroundColors.put(State.DATA, Color.BLUE);
mBackgroundColors.put(State.ENCRYPTED, Color.MAGENTA);
mForegroundColors.put(State.ENCRYPTED, Color.WHITE);
mBackgroundColors.put(State.FADE, Color.LIGHT_GRAY);
mForegroundColors.put(State.FADE, Color.DARK_GRAY);
mBackgroundColors.put(State.IDLE, Color.WHITE);
mForegroundColors.put(State.IDLE, Color.DARK_GRAY);
mBackgroundColors.put(State.RESET, Color.PINK);
mForegroundColors.put(State.RESET, Color.YELLOW);
mBackgroundColors.put(State.TEARDOWN, Color.DARK_GRAY);
mForegroundColors.put(State.TEARDOWN, Color.WHITE);
}
@Override
public void valueChanged(ListSelectionEvent e)
{
if(!mTable.getSelectionModel().getValueIsAdjusting())
{
ProcessingChain processingChain = null;
int selectedViewRow = mTable.getSelectedRow();
if(selectedViewRow >= 0)
{
int selectedModelRow = mTable.convertRowIndexToModel(selectedViewRow);
ChannelMetadata selectedMetadata = mChannelProcessingManager.getChannelMetadataModel()
.getChannelMetadata(selectedModelRow);
if(selectedMetadata != null)
{
mUserSelectedChannel = mChannelProcessingManager.getChannelMetadataModel()
.getChannelFromMetadata(selectedMetadata);
processingChain = mChannelProcessingManager.getProcessingChain(mUserSelectedChannel);
}
}
mSelectedProcessingChainBroadcaster.broadcast(processingChain);
}
}
/**
* Adds the listener to receive the processing chain associated with the metadata selected in the
* metadata table.
*/
public void addProcessingChainSelectionListener(Listener<ProcessingChain> listener)
{
mSelectedProcessingChainBroadcaster.addListener(listener);
}
/**
* Cell renderer for frequency values
*/
public class FrequencyCellRenderer extends DefaultTableCellRenderer
{
private final DecimalFormat FREQUENCY_FORMATTER = new DecimalFormat( "#.00000" );
public FrequencyCellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof FrequencyConfigurationIdentifier)
{
long frequency = ((FrequencyConfigurationIdentifier)value).getValue();
label.setText(FREQUENCY_FORMATTER.format(frequency / 1e6d));
}
else
{
label.setText(null);
}
return label;
}
}
/**
* Alias cell renderer
*/
public class AliasCellRenderer extends DefaultTableCellRenderer
{
public AliasCellRenderer()
{
setHorizontalAlignment(JLabel.LEFT);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof List<?>)
{
List<Alias> aliases = (List<Alias>)value;
if(!aliases.isEmpty())
{
label.setText(Joiner.on(", ").skipNulls().join(aliases));
label.setIcon(mIconModel.getIcon(aliases.get(0).getIconName(), IconModel.DEFAULT_ICON_SIZE));
label.setForeground(ThemeManager.getInstance().getReadableColor(aliases.get(0).getDisplayColor(),
label.getBackground()));
}
else
{
label.setText(null);
label.setIcon(null);
label.setForeground(table.getForeground());
}
}
else
{
label.setText(null);
label.setIcon(null);
label.setForeground(table.getForeground());
}
return label;
}
}
/**
* Abstract cell renderer for identifiers
*/
public abstract class IdentifierCellRenderer extends DefaultTableCellRenderer
{
private final static String EMPTY_VALUE = "-----";
private TalkgroupFormatPreference mTalkgroupFormatPreference;
public IdentifierCellRenderer(TalkgroupFormatPreference talkgroupFormatPreference)
{
mTalkgroupFormatPreference = talkgroupFormatPreference;
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof ChannelMetadata)
{
ChannelMetadata channelMetadata = (ChannelMetadata)value;
Identifier identifier = getIdentifier(channelMetadata);
String text = mTalkgroupFormatPreference.format(identifier);
if(text == null || text.isEmpty())
{
text = EMPTY_VALUE;
}
else if(hasAdditionalIdentifier(channelMetadata))
{
text = text + " " + getAdditionalIdentifier(channelMetadata);
}
label.setText(text);
}
else
{
label.setText(EMPTY_VALUE);
}
return label;
}
public abstract Identifier getIdentifier(ChannelMetadata channelMetadata);
public abstract boolean hasAdditionalIdentifier(ChannelMetadata channelMetadata);
public abstract Identifier getAdditionalIdentifier(ChannelMetadata channelMetadata);
}
/**
* Cell renderer for the FROM identifier
*/
public class FromCellRenderer extends IdentifierCellRenderer
{
public FromCellRenderer(TalkgroupFormatPreference talkgroupFormatPreference)
{
super(talkgroupFormatPreference);
}
@Override
public Identifier getIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.getFromIdentifier();
}
@Override
public Identifier getAdditionalIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.getTalkerAliasIdentifier();
}
@Override
public boolean hasAdditionalIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.hasTalkerAliasIdentifier();
}
}
/**
* Cell renderer for the TO identifier
*/
public class ToCellRenderer extends IdentifierCellRenderer
{
public ToCellRenderer(TalkgroupFormatPreference talkgroupFormatPreference)
{
super(talkgroupFormatPreference);
}
@Override
public Identifier getIdentifier(ChannelMetadata channelMetadata)
{
return channelMetadata.getToIdentifier();
}
@Override
public Identifier getAdditionalIdentifier(ChannelMetadata channelMetadata) {return null;}
@Override
public boolean hasAdditionalIdentifier(ChannelMetadata channelMetadata) {return false;}
}
public class ColoredStateCellRenderer extends DefaultTableCellRenderer
{
public ColoredStateCellRenderer()
{
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Color background = table.getBackground();
Color foreground = table.getForeground();
if(value instanceof ChannelStateIdentifier)
{
State state = ((ChannelStateIdentifier)value).getValue();
label.setText(state.getDisplayValue());
if(mBackgroundColors.containsKey(state))
{
background = mBackgroundColors.get(state);
}
if(mForegroundColors.containsKey(state))
{
foreground = mForegroundColors.get(state);
}
}
else
{
setText("----");
}
setBackground(background);
setForeground(foreground);
return label;
}
}
public class MouseSupport extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent e)
{
if(e.getButton() == MouseEvent.BUTTON3) //Right click for context
{
JPopupMenu popupMenu = new JPopupMenu();
boolean populated = false;
int viewRowIndex = mTable.rowAtPoint(e.getPoint());
if(viewRowIndex >= 0)
{
int modelRowIndex = mTable.convertRowIndexToModel(viewRowIndex);
if(modelRowIndex >= 0)
{
ChannelMetadata metadata = mChannelProcessingManager.getChannelMetadataModel().getChannelMetadata(modelRowIndex);
if(metadata != null)
{
Channel channel = mChannelProcessingManager.getChannelMetadataModel()
.getChannelFromMetadata(metadata);
if(channel != null)
{
JMenuItem viewChannel = new JMenuItem("View/Edit: " + channel.getShortTitle());
viewChannel.addActionListener(e2 -> MyEventBus.getGlobalEventBus().post(new ViewChannelRequest(channel)));
popupMenu.add(viewChannel);
populated = true;
}
}
}
}
if(!populated)
{
popupMenu.add(new JMenuItem("No Actions Available"));
}
popupMenu.show(mTable, e.getX(), e.getY());
}
}
}
/**
* Listener to be notified when a channel and associated channel metadata(s) are added to the underlying
* channel metadata model.
*
* When a channel is added, it is compared the the last user selected channel and if they are the same, it
* invokes a selection event on the channel metadata row so that the channel metadata is re-selected. This is
* primarily a hack to counter-act the DMR Capacity+ REST channel rotation where a channel is converted to a
* traffic channel and the previous channel is restarted. The UI effect is that the user selected channel row
* in the Now Playing window continually loses selection over the channel and causes the user to perpetually
* chase the channel row.
*/
public class ChannelAddListener implements Listener<ChannelAndMetadata>
{
@Override
public void receive(ChannelAndMetadata channelAndMetadata)
{
if(mUserSelectedChannel != null &&
mUserSelectedChannel.getChannelID() == channelAndMetadata.getChannel().getChannelID())
{
List<ChannelMetadata> metadata = channelAndMetadata.getChannelMetadata();
if(metadata.size() > 0)
{
int modelRow = mChannelProcessingManager.getChannelMetadataModel().getRow(metadata.get(0));
if(modelRow >= 0)
{
int tableRow = mTable.convertRowIndexToView(modelRow);
mTable.getSelectionModel().setSelectionInterval(tableRow, tableRow);
}
}
}
}
}
}

View File

@@ -1,138 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 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.channel.metadata;
import com.jidesoft.swing.JideSplitPane;
import com.jidesoft.swing.JideTabbedPane;
import io.github.dsheirer.channel.details.ChannelDetailPanel;
import io.github.dsheirer.gui.channel.ChannelSpectrumPanel;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.module.decode.event.DecodeEventPanel;
import io.github.dsheirer.module.decode.event.MessageActivityPanel;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.settings.SettingsManager;
import net.miginfocom.swing.MigLayout;
import javax.swing.JPanel;
/**
* Swing panel for Now Playing channels table and channel details tab set.
*/
public class NowPlayingPanel extends JPanel
{
private final ChannelMetadataPanel mChannelMetadataPanel;
private final ChannelDetailPanel mChannelDetailPanel;
private final DecodeEventPanel mDecodeEventPanel;
private final MessageActivityPanel mMessageActivityPanel;
private final ChannelSpectrumPanel mChannelSpectrumSquelchPanel;
private JideTabbedPane mTabbedPane;
private JideSplitPane mSplitPane;
private boolean mDetailTabsVisible;
/**
* GUI panel that combines the currently decoding channels metadata table and viewers for channel details,
* messages, events, and spectral view.
*/
public NowPlayingPanel(PlaylistManager playlistManager, IconModel iconModel, UserPreferences userPreferences,
SettingsManager settingsManager, boolean detailTabsVisible)
{
mChannelDetailPanel = new ChannelDetailPanel(playlistManager.getChannelProcessingManager());
mDecodeEventPanel = new DecodeEventPanel(iconModel, userPreferences, playlistManager.getAliasModel());
mMessageActivityPanel = new MessageActivityPanel(userPreferences);
mChannelMetadataPanel = new ChannelMetadataPanel(playlistManager, iconModel, userPreferences);
mChannelSpectrumSquelchPanel = new ChannelSpectrumPanel(playlistManager);
mDetailTabsVisible = detailTabsVisible;
init();
}
/**
* Change the visibility of the channel details tabs panel.
* @param visible true to show or false to hide.
*/
public void setDetailTabsVisible(boolean visible)
{
//Only adjust if there is a change in state
if(visible ^ mDetailTabsVisible)
{
mDetailTabsVisible = visible;
if(mDetailTabsVisible)
{
getSplitPane().add(getTabbedPane());
}
else
{
getSplitPane().remove(getTabbedPane());
}
revalidate();
}
}
private JideTabbedPane getTabbedPane()
{
if(mTabbedPane == null)
{
mTabbedPane = new JideTabbedPane();
mTabbedPane.addTab("Details", mChannelDetailPanel);
mTabbedPane.addTab("Events", mDecodeEventPanel);
mTabbedPane.addTab("Messages", mMessageActivityPanel);
mTabbedPane.addTab("Channel", mChannelSpectrumSquelchPanel);
mTabbedPane.setFont(this.getFont());
//Register state change listener to toggle visibility state for channel tab to turn-on/off FFT processing
mTabbedPane.addChangeListener(e -> mChannelSpectrumSquelchPanel.setPanelVisible(getTabbedPane().getSelectedIndex() == getTabbedPane()
.indexOfComponent(mChannelSpectrumSquelchPanel)));
}
return mTabbedPane;
}
/**
* Split pane for channels table and channel details tabs.
*/
private JideSplitPane getSplitPane()
{
if(mSplitPane == null)
{
mSplitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT);
mSplitPane.setShowGripper(true);
}
return mSplitPane;
}
private void init()
{
setLayout( new MigLayout( "insets 0 0 0 0", "[grow,fill]", "[grow,fill]") );
getSplitPane().add(mChannelMetadataPanel);
if(mDetailTabsVisible)
{
getSplitPane().add(getTabbedPane());
}
add(getSplitPane());
mChannelMetadataPanel.addProcessingChainSelectionListener(mChannelDetailPanel);
mChannelMetadataPanel.addProcessingChainSelectionListener(mDecodeEventPanel);
mChannelMetadataPanel.addProcessingChainSelectionListener(mMessageActivityPanel);
mChannelMetadataPanel.addProcessingChainSelectionListener(mChannelSpectrumSquelchPanel);
}
}

View File

@@ -21,12 +21,12 @@ 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.channel.metadata.NowPlayingPanel;
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.gui.map.MapPanel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
@@ -63,8 +63,8 @@ public class ControllerPanel extends JPanel
{
mAudioPanel = new AudioPanel(iconModel, userPreferences, settingsManager, audioPlaybackManager,
playlistManager.getAliasModel());
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, settingsManager, detailTabsVisible);
mMapPanel = new MapPanel(mapService, playlistManager.getAliasModel(), iconModel, userPreferences,
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, detailTabsVisible);
mMapPanel = new MapPanel(mapService, iconModel, userPreferences,
playlistManager.getRadioReference() != null ? playlistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(playlistManager));
mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences);

View File

@@ -18,6 +18,7 @@
*/
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;
@@ -83,6 +84,8 @@ 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;
@@ -123,6 +126,19 @@ 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
*/
@@ -134,6 +150,7 @@ 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();
@@ -509,6 +526,36 @@ 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

@@ -840,11 +840,16 @@ public class SDRTrunk implements Listener<TunerEvent>
}
/**
* Updates the title bar with the tuner name
* Updates the title bar with the tuner name. No-op when running headless (no main window).
* @param tunerName optional
*/
private void updateTitle(String tunerName)
{
if(mMainGui == null)
{
return;
}
if(tunerName != null)
{
mMainGui.setTitle(mTitle + " - " + tunerName);

View File

@@ -1,483 +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.channel;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.dsp.filter.channelizer.PolyphaseChannelSource;
import io.github.dsheirer.gui.power.SignalPowerView;
import io.github.dsheirer.gui.spectrum.ChannelSpectralDisplay;
import io.github.dsheirer.gui.spectrum.DftSpectralDisplay;
import io.github.dsheirer.gui.squelch.NoiseSquelchView;
import io.github.dsheirer.gui.symbol.SymbolView;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.module.decode.FeedbackDecoder;
import io.github.dsheirer.module.decode.PrimaryDecoder;
import io.github.dsheirer.module.decode.am.AMDecoder;
import io.github.dsheirer.module.decode.nbfm.NBFMDecoder;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamplesToNativeBufferModule;
import io.github.dsheirer.source.ChannelFrequencyCorrectionStatusNotification;
import io.github.dsheirer.source.Source;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.tuner.channel.HalfBandTunerChannelSource;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import java.awt.Component;
import java.awt.EventQueue;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
/**
* Display for channel FFT and squelch details
*/
public class ChannelSpectrumPanel extends JPanel implements Listener<ProcessingChain>
{
private static final Logger LOGGER = LoggerFactory.getLogger(ChannelSpectrumPanel.class);
private static final DecimalFormat FREQUENCY_FORMAT = new DecimalFormat("0.00000");
private static final DecimalFormat PPM_FORMAT = new DecimalFormat("0.00000");
private static final String LABEL_PREFIX_PPM = "Tuner PPM: ";
private static final String LABEL_PREFIX_TUNER = "Tuner:";
private static final String LABEL_PREFIX_CHANNEL = "Channel:";
private static final String LABEL_PREFIX_DECODER = "Decoder:";
private final PlaylistManager mPlaylistManager;
private ProcessingChain mProcessingChain;
private final ComplexSamplesToNativeBufferModule mSampleStreamTapModule = new ComplexSamplesToNativeBufferModule();
private final JFXPanel mSpectralPanel = new JFXPanel();
//Created on the JavaFX thread - guarded by this. Channel state is kept here until the display exists.
private ChannelSpectralDisplay mChannelSpectralDisplay;
private long mChannelFrequency;
private int mChannelSampleRate;
private int mChannelBandwidth;
private Long mCarrierOffset;
private final SourceEventProcessor mSourceEventProcessor = new SourceEventProcessor();
private final JLabel mTunerPPMLabel;
private final JLabel mTunerCorrectionLabel;
private final JLabel mChannelCorrectionLabel;
private final JLabel mDecoderCorrectionLabel;
private final JLabel mDummyLabel = new JLabel(" ");
private boolean mPanelVisible = false;
private final NoiseSquelchView mNoiseSquelchView;
private final SignalPowerView mSignalPowerView;
private final SymbolView mSymbolView = new SymbolView();
private final JFXPanel mNoiseSquelchPanel;
private final JFXPanel mSymbolPanel;
private JSplitPane mSplitPane;
private FeedbackDecoder mFeedbackDecoder;
/**
* Constructs an instance.
*/
public ChannelSpectrumPanel(PlaylistManager playlistManager)
{
mPlaylistManager = playlistManager;
mNoiseSquelchView = new NoiseSquelchView(mPlaylistManager);
mSignalPowerView = new SignalPowerView(mPlaylistManager);
//Register the three swappable right-pane components with the theme manager. Only one is
//attached to the split pane at a time, so the LAF-toggle walk of Window.getWindows() can
//miss the detached ones - they get refreshed explicitly via registerSwing.
ThemeManager.getInstance().registerSwing(mSignalPowerView);
setLayout(new MigLayout("insets 0", "[grow,fill]", "[grow,fill]"));
JPanel fftPanel = new JPanel();
fftPanel.setLayout(new MigLayout("insets 0", "[grow,fill]", "[][grow,fill]"));
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new MigLayout("insets 2", "[grow,fill][][][][][grow,fill]", ""));
mTunerPPMLabel = new JLabel(LABEL_PREFIX_PPM);
mTunerPPMLabel.setEnabled(false);
labelPanel.add(mTunerPPMLabel);
labelPanel.add(new JLabel("Corrections (Hz) "));
mTunerCorrectionLabel = new JLabel(LABEL_PREFIX_TUNER);
mTunerCorrectionLabel.setEnabled(false);
labelPanel.add(mTunerCorrectionLabel);
mChannelCorrectionLabel = new JLabel(LABEL_PREFIX_CHANNEL);
mChannelCorrectionLabel.setEnabled(false);
labelPanel.add(mChannelCorrectionLabel);
mDecoderCorrectionLabel = new JLabel(LABEL_PREFIX_DECODER);
mDecoderCorrectionLabel.setEnabled(false);
labelPanel.add(mDecoderCorrectionLabel);
labelPanel.add(mDummyLabel);
JButton logIndexesButton = new JButton("Log Settings");
logIndexesButton.addActionListener(e -> {
if(mProcessingChain != null)
{
Source source = mProcessingChain.getSource();
if(source instanceof PolyphaseChannelSource pcs)
{
List<Integer> indexes = pcs.getOutputProcessorIndexes();
double sampleRate = pcs.getSampleRate();
long indexCenterFrequency = pcs.getIndexCenterFrequency();
long appliedFrequencyOffset = pcs.getFrequencyOffset();
long requestedCenterFrequency = pcs.getFrequency();
StringBuilder sb = new StringBuilder();
sb.append("Polyphase Channel - BW: ").append(FREQUENCY_FORMAT.format(sampleRate / 1E6d));
sb.append(" Center/Requested/Mixer: ").append(FREQUENCY_FORMAT.format(indexCenterFrequency / 1E6d));
sb.append("/").append(FREQUENCY_FORMAT.format(requestedCenterFrequency / 1E6d));
sb.append("/").append(FREQUENCY_FORMAT.format(appliedFrequencyOffset / 1E6d));
sb.append(" Polyphase Indexes: ").append(indexes);
sb.append(" Tuner SR:").append(FREQUENCY_FORMAT.format(pcs.getTunerSampleRate() / 1E6d));
sb.append(" CF:").append(FREQUENCY_FORMAT.format(pcs.getTunerCenterFrequency() / 1E6d));
LOGGER.info(sb.toString());
LOGGER.info("Output Processor: " + pcs.getStateDescription());
}
else if(source instanceof HalfBandTunerChannelSource<?> hbtcs)
{
StringBuilder sb = new StringBuilder();
sb.append("Heterodyne Channel - CF:").append(FREQUENCY_FORMAT.format(hbtcs.getFrequency() / 1E6d));
sb.append(" SR:").append(FREQUENCY_FORMAT.format(hbtcs.getSampleRate() / 1E6d));
sb.append(" Mixer:").append(FREQUENCY_FORMAT.format(hbtcs.getMixerFrequency() / 1E6d));
LOGGER.info(sb.toString());
}
else
{
LOGGER.info("Unsupported channel type: " + (source != null ? source.getClass() : " null"));
}
}
});
//This is a debug button to log the current settings to the app log.
// labelPanel.add(mLogIndexesButton);
fftPanel.add(labelPanel, "wrap");
fftPanel.add(mSpectralPanel);
ThemeManager.getInstance().registerSwing(mSpectralPanel);
Platform.runLater(() -> {
ChannelSpectralDisplay display = new ChannelSpectralDisplay();
Scene scene = new Scene(display);
ThemeManager.getInstance().register(scene);
mSpectralPanel.setScene(scene);
displayCreated(display);
});
mNoiseSquelchPanel = new JFXPanel();
mSymbolPanel = new JFXPanel();
ThemeManager.getInstance().registerSwing(mNoiseSquelchPanel);
ThemeManager.getInstance().registerSwing(mSymbolPanel);
//Spin noise squelch panel construction off onto the JavafX UI thread.
Platform.runLater(() -> {
Scene scene = new Scene(mNoiseSquelchView);
ThemeManager.getInstance().register(scene);
mNoiseSquelchPanel.setScene(scene);
Scene scene2 = new Scene(mSymbolView);
URL resource = getClass().getResource("/sdrtrunk_style.css");
if(resource != null)
{
scene2.getStylesheets().add(resource.toExternalForm());
}
else
{
LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
}
ThemeManager.getInstance().register(scene2);
//Use the same color theme as the channel spectral display
mSymbolView.followTheme(DftSpectralDisplay.getSharedTheme());
mSymbolPanel.setScene(scene2);
});
mSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
mSplitPane.add(fftPanel, JSplitPane.LEFT);
mSplitPane.add(mNoiseSquelchPanel, JSplitPane.RIGHT);
add(mSplitPane);
// mSplitPane.setDividerLocation(0.5);
}
/**
* Stores the spectral display once it's created on the JavaFX thread and applies the current channel state.
*/
private synchronized void displayCreated(ChannelSpectralDisplay display)
{
mChannelSpectralDisplay = display;
if(mChannelSampleRate > 0)
{
display.setChannel(mChannelFrequency, mChannelSampleRate, mChannelBandwidth);
}
if(mCarrierOffset != null)
{
display.setCarrierOffset(mCarrierOffset);
}
updateFFTProcessing();
}
private synchronized void setChannel(long frequency, int sampleRate, int bandwidth)
{
mChannelFrequency = frequency;
mChannelSampleRate = sampleRate;
mChannelBandwidth = bandwidth;
mCarrierOffset = null;
if(mChannelSpectralDisplay != null)
{
mChannelSpectralDisplay.setChannel(frequency, sampleRate, bandwidth);
}
}
private synchronized void setCarrierOffset(long offset)
{
mCarrierOffset = offset;
if(mChannelSpectralDisplay != null)
{
mChannelSpectralDisplay.setCarrierOffset(offset);
}
}
/**
* Pads the value to a fixed width and returns the previx and padded value.
* @param prefix of the label
* @param value to pad with spaces
* @return padded, prefixed label
*/
private String getPaddedLabel(String prefix, Number value)
{
return prefix + StringUtils.leftPad(String.valueOf(value), 7);
}
/**
* Signals this panel to indicate if this panel is visible to turn on the FFT processor when the panel is visible
* and turn off the FFT processor when it's not.
*
* Note: this method is intended to be called by the Swing event thread to ensure that only a single thread is
* invoking either this method, or the receive() method, since there is no thread synchronization between these
* two methods and they each depend on stable access to the mPanelVisible variable.
*
* @param visible true to indicate that this panel is showing/visible.
*/
public void setPanelVisible(boolean visible)
{
mPanelVisible = visible;
updateFFTProcessing();
mNoiseSquelchView.setShowing(visible);
mSymbolView.setShowing(visible);
}
/**
* Updates processing state for the spectral display. Turns on DFT processing when we have a processing chain and
* when the user has this tab selected and visible. Otherwise, turns off DFT processing.
*/
private synchronized void updateFFTProcessing()
{
if(mChannelSpectralDisplay == null)
{
return;
}
boolean active = mPanelVisible && mProcessingChain != null;
if(active)
{
mSampleStreamTapModule.setListener(mChannelSpectralDisplay.getSampleListener());
}
else
{
mSampleStreamTapModule.removeListener();
}
mChannelSpectralDisplay.setActive(active);
}
private void broadcast(SourceEvent sourceEvent)
{
if(mProcessingChain != null)
{
mProcessingChain.broadcast(sourceEvent);
}
}
/**
* Resets controls when changing processing chain source. Note: this must be called on the Swing
* dispatch thread because it directly invokes swing components.
*/
private void reset()
{
mTunerPPMLabel.setText(LABEL_PREFIX_PPM);
mTunerPPMLabel.setEnabled(false);
mTunerCorrectionLabel.setText(LABEL_PREFIX_TUNER);
mTunerCorrectionLabel.setEnabled(false);
mChannelCorrectionLabel.setText(LABEL_PREFIX_CHANNEL);
mChannelCorrectionLabel.setEnabled(false);
mDecoderCorrectionLabel.setText(LABEL_PREFIX_DECODER);
mDecoderCorrectionLabel.setEnabled(false);
setChannel(0, 0, 0);
}
/**
* Receive notifications of request to provide display of processing chain details.
*/
@Override
public void receive(ProcessingChain processingChain)
{
//Disconnect the previous processing chain.
if(mProcessingChain != null)
{
mNoiseSquelchView.setController(null);
mSignalPowerView.setProcessingChain(null);
mSymbolView.removeSymbolProvider();
mSymbolView.setProtocol("");
mProcessingChain.removeSourceEventListener(mSourceEventProcessor);
mProcessingChain.removeModule(mSampleStreamTapModule);
mFeedbackDecoder = null;
}
//Invoking reset - we're on the Swing dispatch thread here
reset();
mProcessingChain = processingChain;
if(mProcessingChain != null)
{
mProcessingChain.addSourceEventListener(mSourceEventProcessor);
PrimaryDecoder primaryDecoder = mProcessingChain.getPrimaryDecoder();
if(primaryDecoder instanceof NBFMDecoder nbfmDecoder)
{
setRightComponent(mNoiseSquelchPanel);
mNoiseSquelchView.setController(nbfmDecoder);
}
else if(primaryDecoder instanceof AMDecoder)
{
setRightComponent(mSignalPowerView);
mSignalPowerView.setProcessingChain(mProcessingChain);
}
else if(primaryDecoder instanceof FeedbackDecoder feedbackDecoder)
{
setRightComponent(mSymbolPanel);
mSymbolView.setSymbolProvider(feedbackDecoder);
mSymbolView.setProtocol(feedbackDecoder.getProtocolDescription());
mFeedbackDecoder = feedbackDecoder;
}
mProcessingChain.addModule(mSampleStreamTapModule);
Source source = mProcessingChain.getSource();
int bandwidth = 0;
Channel channel = mPlaylistManager.getChannelProcessingManager().getChannel(mProcessingChain);
if(channel != null)
{
List<TunerChannel> tunerChannels = channel.getTunerChannels();
if(!tunerChannels.isEmpty())
{
bandwidth = tunerChannels.getFirst().getBandwidth();
}
}
if(source instanceof TunerChannelSource tcs)
{
setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth);
}
}
updateFFTProcessing();
}
/**
* Shows the component on the right side of the split pane.
* @param component to show.
*/
private void setRightComponent(Component component)
{
Component rightComponent = mSplitPane.getRightComponent();
if(rightComponent != component)
{
mSplitPane.remove(rightComponent);
mSplitPane.setRightComponent(component);
mSplitPane.setDividerLocation(0.4);
}
}
/**
* Processor for source event stream to capture power level and squelch related source events.
*/
private class SourceEventProcessor implements Listener<SourceEvent>
{
@Override
public void receive(SourceEvent sourceEvent)
{
if(sourceEvent.getEvent() == SourceEvent.Event.NOTIFICATION_CHANNEL_FREQUENCY_CORRECTION_STATUS)
{
if(sourceEvent instanceof ChannelFrequencyCorrectionStatusNotification status)
{
//Note: we flip the sign on the error measurement because the value represents the amount of offset the PLL
//has to apply to move the signal to center/baseband
EventQueue.invokeLater(() -> {
mTunerPPMLabel.setText(LABEL_PREFIX_PPM + PPM_FORMAT.format(status.getTunerPPM()));
mTunerPPMLabel.setEnabled(true);
if(status.isAutoPPM())
{
mTunerCorrectionLabel.setText(getPaddedLabel(LABEL_PREFIX_TUNER, status.getTunerCorrection()));
}
else
{
mTunerCorrectionLabel.setText(LABEL_PREFIX_TUNER + " disabled");
}
mTunerCorrectionLabel.setEnabled(true);
mChannelCorrectionLabel.setText(getPaddedLabel(LABEL_PREFIX_CHANNEL, status.getChannelCorrection()));
mChannelCorrectionLabel.setEnabled(true);
mDecoderCorrectionLabel.setText(getPaddedLabel(LABEL_PREFIX_DECODER, status.getDecoderCorrection()));
mDecoderCorrectionLabel.setEnabled(true);
//We se the offset cursor line to negative so that it aligns with where the signal is located
//instead of the correction that's needed to bring the signal to zero.
setCarrierOffset(-status.getDecoderCorrection());
});
}
}
//TODO: is this still needed?
mSignalPowerView.receive(sourceEvent);
}
}
}

View File

@@ -0,0 +1,309 @@
/*
* *****************************************************************************
* 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.channel;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.gui.power.SignalPowerView;
import io.github.dsheirer.gui.spectrum.ChannelSpectralDisplay;
import io.github.dsheirer.gui.spectrum.DftSpectralDisplay;
import io.github.dsheirer.gui.squelch.NoiseSquelchView;
import io.github.dsheirer.gui.symbol.SymbolView;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.module.decode.FeedbackDecoder;
import io.github.dsheirer.module.decode.PrimaryDecoder;
import io.github.dsheirer.module.decode.am.AMDecoder;
import io.github.dsheirer.module.decode.nbfm.NBFMDecoder;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamplesToNativeBufferModule;
import io.github.dsheirer.source.ChannelFrequencyCorrectionStatusNotification;
import io.github.dsheirer.source.Source;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Display for channel spectrum, frequency corrections and the decoder squelch, power or symbol view.
*
* Use this class on the JavaFX application thread.
*/
public class ChannelSpectrumView extends SplitPane implements Listener<ProcessingChain>
{
private static final Logger LOGGER = LoggerFactory.getLogger(ChannelSpectrumView.class);
private static final DecimalFormat PPM_FORMAT = new DecimalFormat("0.00000");
private static final String LABEL_PREFIX_PPM = "Tuner PPM: ";
private static final String LABEL_PREFIX_TUNER = "Tuner:";
private static final String LABEL_PREFIX_CHANNEL = "Channel:";
private static final String LABEL_PREFIX_DECODER = "Decoder:";
private static final double DIVIDER_POSITION = 0.4;
private final PlaylistManager mPlaylistManager;
private final ComplexSamplesToNativeBufferModule mSampleStreamTapModule = new ComplexSamplesToNativeBufferModule();
private final ChannelSpectralDisplay mChannelSpectralDisplay = new ChannelSpectralDisplay();
private final SourceEventProcessor mSourceEventProcessor = new SourceEventProcessor();
private final Label mTunerPPMLabel = new Label(LABEL_PREFIX_PPM);
private final Label mTunerCorrectionLabel = new Label(LABEL_PREFIX_TUNER);
private final Label mChannelCorrectionLabel = new Label(LABEL_PREFIX_CHANNEL);
private final Label mDecoderCorrectionLabel = new Label(LABEL_PREFIX_DECODER);
private final NoiseSquelchView mNoiseSquelchView;
private final SignalPowerView mSignalPowerView;
private final SymbolView mSymbolView = new SymbolView();
private ProcessingChain mProcessingChain;
private boolean mPanelVisible = false;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param playlistManager for the channel configurations
*/
public ChannelSpectrumView(PlaylistManager playlistManager)
{
mPlaylistManager = playlistManager;
mNoiseSquelchView = new NoiseSquelchView(mPlaylistManager);
mSignalPowerView = new SignalPowerView(mPlaylistManager);
URL resource = getClass().getResource("/sdrtrunk_style.css");
if(resource != null)
{
mSymbolView.getStylesheets().add(resource.toExternalForm());
}
else
{
LOGGER.warn("Can't find stylesheet resource for sdrtrunk");
}
//Use the same color theme as the channel spectral display
mSymbolView.followTheme(DftSpectralDisplay.getSharedTheme());
Region leftSpacer = new Region();
Region rightSpacer = new Region();
HBox.setHgrow(leftSpacer, Priority.ALWAYS);
HBox.setHgrow(rightSpacer, Priority.ALWAYS);
HBox labels = new HBox(10, leftSpacer, mTunerPPMLabel, new Label("Corrections (Hz) "), mTunerCorrectionLabel,
mChannelCorrectionLabel, mDecoderCorrectionLabel, rightSpacer);
labels.setAlignment(Pos.CENTER);
labels.setPadding(new Insets(2));
VBox.setVgrow(mChannelSpectralDisplay, Priority.ALWAYS);
VBox spectrumBox = new VBox(labels, mChannelSpectralDisplay);
spectrumBox.setMinWidth(0);
getItems().addAll(spectrumBox, mNoiseSquelchView);
reset();
}
/**
* Pads the value to a fixed width and returns the prefix and padded value.
*/
private static String getPaddedLabel(String prefix, Number value)
{
return prefix + StringUtils.leftPad(String.valueOf(value), 7);
}
/**
* Signals this view to indicate if it is visible, to turn on the DFT processor when the view is visible and turn
* it off when it's not.
* @param visible true to indicate that this view is showing/visible.
*/
public void setPanelVisible(boolean visible)
{
mPanelVisible = visible;
updateFFTProcessing();
mNoiseSquelchView.setShowing(visible);
mSymbolView.setShowing(visible);
}
/**
* Turns on DFT processing when there is a processing chain and the user has this view selected and visible.
* Otherwise, turns off DFT processing.
*/
private void updateFFTProcessing()
{
boolean active = mPanelVisible && mProcessingChain != null;
if(active)
{
mSampleStreamTapModule.setListener(mChannelSpectralDisplay.getSampleListener());
}
else
{
mSampleStreamTapModule.removeListener();
}
mChannelSpectralDisplay.setActive(active);
}
/**
* Resets controls when changing processing chain source.
*/
private void reset()
{
mTunerPPMLabel.setText(LABEL_PREFIX_PPM);
mTunerPPMLabel.setDisable(true);
mTunerCorrectionLabel.setText(LABEL_PREFIX_TUNER);
mTunerCorrectionLabel.setDisable(true);
mChannelCorrectionLabel.setText(LABEL_PREFIX_CHANNEL);
mChannelCorrectionLabel.setDisable(true);
mDecoderCorrectionLabel.setText(LABEL_PREFIX_DECODER);
mDecoderCorrectionLabel.setDisable(true);
mChannelSpectralDisplay.setChannel(0, 0, 0);
}
/**
* Shows the processing chain details. Call on the JavaFX application thread.
* @param processingChain to show, or null to clear the view
*/
@Override
public void receive(ProcessingChain processingChain)
{
//Disconnect the previous processing chain.
if(mProcessingChain != null)
{
mNoiseSquelchView.setController(null);
mSignalPowerView.setProcessingChain(null);
mSymbolView.removeSymbolProvider();
mSymbolView.setProtocol("");
mProcessingChain.removeSourceEventListener(mSourceEventProcessor);
mProcessingChain.removeModule(mSampleStreamTapModule);
}
reset();
mProcessingChain = processingChain;
if(mProcessingChain != null)
{
mProcessingChain.addSourceEventListener(mSourceEventProcessor);
PrimaryDecoder primaryDecoder = mProcessingChain.getPrimaryDecoder();
if(primaryDecoder instanceof NBFMDecoder nbfmDecoder)
{
setRightComponent(mNoiseSquelchView);
mNoiseSquelchView.setController(nbfmDecoder);
}
else if(primaryDecoder instanceof AMDecoder)
{
setRightComponent(mSignalPowerView);
mSignalPowerView.setProcessingChain(mProcessingChain);
}
else if(primaryDecoder instanceof FeedbackDecoder feedbackDecoder)
{
setRightComponent(mSymbolView);
mSymbolView.setSymbolProvider(feedbackDecoder);
mSymbolView.setProtocol(feedbackDecoder.getProtocolDescription());
}
mProcessingChain.addModule(mSampleStreamTapModule);
Source source = mProcessingChain.getSource();
int bandwidth = 0;
Channel channel = mPlaylistManager.getChannelProcessingManager().getChannel(mProcessingChain);
if(channel != null)
{
List<TunerChannel> tunerChannels = channel.getTunerChannels();
if(!tunerChannels.isEmpty())
{
bandwidth = tunerChannels.getFirst().getBandwidth();
}
}
if(source instanceof TunerChannelSource tcs)
{
mChannelSpectralDisplay.setChannel(tcs.getFrequency(), (int)tcs.getSampleRate(), bandwidth);
}
}
updateFFTProcessing();
}
/**
* Shows the node on the right side of the split pane.
*/
private void setRightComponent(Node node)
{
if(getItems().size() < 2 || getItems().get(1) != node)
{
if(getItems().size() > 1)
{
getItems().remove(1);
}
getItems().add(node);
setDividerPositions(DIVIDER_POSITION);
}
}
/**
* Processor for source event stream to capture power level and squelch related source events.
*/
private class SourceEventProcessor implements Listener<SourceEvent>
{
@Override
public void receive(SourceEvent sourceEvent)
{
if(sourceEvent.getEvent() == SourceEvent.Event.NOTIFICATION_CHANNEL_FREQUENCY_CORRECTION_STATUS &&
sourceEvent instanceof ChannelFrequencyCorrectionStatusNotification status)
{
Platform.runLater(() -> {
mTunerPPMLabel.setText(LABEL_PREFIX_PPM + PPM_FORMAT.format(status.getTunerPPM()));
mTunerPPMLabel.setDisable(false);
if(status.isAutoPPM())
{
mTunerCorrectionLabel.setText(getPaddedLabel(LABEL_PREFIX_TUNER, status.getTunerCorrection()));
}
else
{
mTunerCorrectionLabel.setText(LABEL_PREFIX_TUNER + " disabled");
}
mTunerCorrectionLabel.setDisable(false);
mChannelCorrectionLabel.setText(getPaddedLabel(LABEL_PREFIX_CHANNEL, status.getChannelCorrection()));
mChannelCorrectionLabel.setDisable(false);
mDecoderCorrectionLabel.setText(getPaddedLabel(LABEL_PREFIX_DECODER, status.getDecoderCorrection()));
mDecoderCorrectionLabel.setDisable(false);
});
//The offset cursor line is negative so that it aligns with where the signal is located instead of the
//correction that's needed to bring the signal to zero.
mChannelSpectralDisplay.setCarrierOffset(-status.getDecoderCorrection());
}
mSignalPowerView.receive(sourceEvent);
}
}
}

View File

@@ -1,349 +0,0 @@
package io.github.dsheirer.gui.control;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Power meter for displaying signal power levels in dB scale with optional peak value and squelch threshold lines.
*/
public class DbPowerMeter extends JComponent
{
public static final double DEFAULT_MINIMUM_POWER = -110.0d;
public static final double DEFAULT_MAXIMUM_POWER = 0.0d;
private static final int BAR_WIDTH = 30;
private static final int PADDING = 3;
private static final int DOUBLE_PADDING = PADDING * 2;
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0");
private static final Color COLOR_BAR = Color.LIGHT_GRAY;
private static final Color COLOR_THRESHOLD = Color.BLUE;
private static final Color COLOR_PEAK = Color.PINK;
private double mMinimumValue = DEFAULT_MINIMUM_POWER;
private double mMaximumValue = DEFAULT_MAXIMUM_POWER;
private double mExtent = mMaximumValue - mMinimumValue;
private double mPeak = mMinimumValue;
private double mPower = mMinimumValue;
private double mSquelchThreshold = mMinimumValue;
private boolean mPeakVisible = false;
private boolean mSquelchThresholdVisible = false;
/**
* Constructs an instance.
*/
public DbPowerMeter()
{
setPreferredSize(new Dimension(90, 100));
setBorder(BorderFactory.createTitledBorder("Power (dB)"));
}
/**
* Resets peak, power and squelch to minimums
*/
public void reset()
{
mPeak = mMinimumValue;
mPower = mMinimumValue;
mSquelchThreshold = mMinimumValue;
repaint();
}
/**
* Primary method for rendering the control
*/
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
//Draw meter border
g.setColor(getForeground());
g.drawRect(getInsets().left, getInsets().top, BAR_WIDTH, getHeight() - getInsets().top - getInsets().bottom);
//Draw filled bar
g.setColor(COLOR_BAR);
int fillHeight = getHeight() - getInsets().top - getInsets().bottom - DOUBLE_PADDING;
int height = (int) (fillHeight * getPowerPercent() - PADDING);
int top = (fillHeight - height) + getInsets().top + PADDING;
g.fillRect(getInsets().left + PADDING, top, BAR_WIDTH - DOUBLE_PADDING, height);
//Draw threshold
if(isSquelchThresholdVisible())
{
g.setColor(COLOR_THRESHOLD);
drawPercentLine(g, getSquelchThresholdPercent());
}
//Draw peak line
if(isPeakVisible())
{
g.setColor(COLOR_PEAK);
drawPercentLine(g, getPeakPercent());
}
//Draw legend/scale
g.setColor(getForeground());
for(double legendValue: getScaleValues())
{
drawScaleText(g, legendValue);
}
}
/**
* Draws a line as a percentage of the value range (extent) using the current graphics color.
*/
private void drawPercentLine(Graphics g, double percentValue)
{
int totalHeight = getHeight() - getInsets().top - getInsets().bottom - DOUBLE_PADDING;
int height = (int) (totalHeight * percentValue - PADDING);
int top = (totalHeight - height) + getInsets().top + PADDING;
int left = getInsets().left;
g.drawLine(left, top, left + BAR_WIDTH, top);
}
/**
* Draws a tick and text for the value
* @param g graphics object
* @param value to draw
*/
private void drawScaleText(Graphics g, double value)
{
double percent = getPercent(value);
int totalHeight = getHeight() - getInsets().top - getInsets().bottom - DOUBLE_PADDING;
int height = (int) (totalHeight * percent - PADDING);
int top = (totalHeight - height) + getInsets().top + PADDING;
int left = getInsets().left + BAR_WIDTH - PADDING;
int textOffset = getFontMetrics(getFont()).getMaxAscent() / 2 - 2;
String label = DECIMAL_FORMAT.format(value);
g.drawString(label, left + DOUBLE_PADDING, top + textOffset);
}
/**
* Scale values to display, dynamically adapted to the height of the control
*/
private List<Double> getScaleValues()
{
double ascent = getFontMetrics(getFont()).getMaxAscent() * 2;
double labelCount = getHeight() / ascent;
double interval = getExtent() / labelCount;
List<Double> values = new ArrayList<>();
for(double x = 0; x > getMinimumValue(); x -= interval)
{
values.add(x);
}
return values;
}
/**
* Current power level
* @return power level (dB)
*/
public double getPower()
{
return mPower;
}
/**
* Sets the current power level constrained to the minimum and maximum values for this control.
* @param power (dB)
*/
public void setPower(double power)
{
if(power > getMaximumValue())
{
mPower = getMaximumValue();
}
else if(power < getMinimumValue())
{
mPower = getMinimumValue();
}
else
{
mPower = power;
}
repaint();
}
/**
* Squelch threshold value.
* @return threshold (dB)
*/
public double getSquelchThreshold()
{
return mSquelchThreshold;
}
/**
* Sets the squelch thresold value
* @param squelchThreshold (dB)
*/
public void setSquelchThreshold(double squelchThreshold)
{
mSquelchThreshold = squelchThreshold;
repaint();
}
/**
* Minimum displayable power level
* @return minimum (dB) - defaults to -110 dB
*/
public double getMinimumValue()
{
return mMinimumValue;
}
/**
* Sets the minimum displayable power level
* @param minimumValue (dB)
*/
public void setMinimumValue(double minimumValue)
{
mMinimumValue = minimumValue;
updateExtent();
repaint();
}
/**
* Maximum displayable power level
* @return maximum (dB) - defaults to 0 dB
*/
public double getMaximumValue()
{
return mMaximumValue;
}
/**
* Sets the maximum displayable power level
* @param maximumValue (dB)
*/
public void setMaximumValue(double maximumValue)
{
mMaximumValue = maximumValue;
updateExtent();
repaint();
}
/**
* Updates the min/max extent
*/
private void updateExtent()
{
mExtent = getMaximumValue() - getMinimumValue();
}
/**
* Extent or range of displayable values.
* @return extent (dB)
*/
private double getExtent()
{
return mExtent;
}
/**
* Peak value line
* @return peak (dB)
*/
public double getPeak()
{
return mPeak;
}
/**
* Sets the peak value line
* @param peak (db)
*/
public void setPeak(double peak)
{
mPeak = peak;
repaint();
}
/**
* Indicates if the peak line is set to visible and the current peak value is within the min/max range.
*/
public boolean isPeakVisible()
{
return mPeakVisible & isValidValue(getPeak());
}
/**
* Sets the peak line visibility
* @param peakVisible value
*/
public void setPeakVisible(boolean peakVisible)
{
mPeakVisible = peakVisible;
repaint();
}
/**
* Indicates if the squelch threshold line is set to visible and the current squelch threshold value is
* within the min/max displayable value range.
* @return true if visible.
*/
public boolean isSquelchThresholdVisible()
{
return mSquelchThresholdVisible & isValidValue(getSquelchThreshold());
}
/**
* Sets the visibility of the squelch threshold line
* @param squelchThresholdVisible visibility
*/
public void setSquelchThresholdVisible(boolean squelchThresholdVisible)
{
mSquelchThresholdVisible = squelchThresholdVisible;
repaint();
}
/**
* Calculates the percentage of the min/max extent for the value
* @param value to calculate
* @return percentage of displayable value range
*/
private double getPercent(double value)
{
return (value - getMinimumValue()) / getExtent();
}
/**
* Power as percentage of displayable range
*/
private double getPowerPercent()
{
return getPercent(mPower);
}
/**
* Squelch threshold as percentage of displayable range
*/
private double getSquelchThresholdPercent()
{
return getPercent(mSquelchThreshold);
}
/**
* Peak as percentage of displayable range
*/
private double getPeakPercent()
{
return getPercent(mPeak);
}
/**
* Indicates if the value is valid, meaning it falls within the min/max range of displayable values.
*/
private boolean isValidValue(double value)
{
return getMinimumValue() <= value && value <= getMaximumValue();
}
}

View File

@@ -0,0 +1,35 @@
/*
* *****************************************************************************
* 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);
}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

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

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

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

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

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

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

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

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

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

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

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

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

@@ -0,0 +1,64 @@
/*
* *****************************************************************************
* 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 com.google.common.base.Joiner;
import io.github.dsheirer.alias.Alias;
import java.util.List;
/**
* Alias table cell value: the alias names to show, with the color and icon of the alias that styles the cell.
* @param text of the alias names
* @param color of the styling alias as a 32-bit RGB integer
* @param iconName of the styling alias, or null
*/
public record AliasDisplay(String text, int color, String iconName) implements Comparable<AliasDisplay>
{
/**
* Creates the display for the aliases, styled by the first alias.
* @param aliases to display
* @return display or null when there are no aliases.
*/
public static AliasDisplay of(List<Alias> aliases)
{
if(aliases == null || aliases.isEmpty())
{
return null;
}
return of(Joiner.on(", ").skipNulls().join(aliases), aliases.getFirst());
}
/**
* Creates the display for the text, styled by the alias
* @param text to display
* @param alias to style the display
* @return display
*/
public static AliasDisplay of(String text, Alias alias)
{
return new AliasDisplay(text, alias.getColor(), alias.getIconName());
}
@Override
public int compareTo(AliasDisplay other)
{
return String.CASE_INSENSITIVE_ORDER.compare(text, other.text);
}
}

View File

@@ -0,0 +1,120 @@
/*
* *****************************************************************************
* 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.channel.state.DecoderState;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.sample.Listener;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Activity summary details for the selected channel.
*/
public class ChannelDetailView extends VBox implements Listener<ProcessingChain>
{
private static final String EMPTY_DETAILS = "Please select a channel to view details";
private final ChannelProcessingManager mChannelProcessingManager;
private final Label mSystemLabel = new Label();
private final Label mSiteLabel = new Label();
private final Label mNameLabel = new Label();
private final TextArea mDetailTextArea = new TextArea(EMPTY_DETAILS);
private ProcessingChain mProcessingChain;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param channelProcessingManager for the channel of the processing chain
*/
public ChannelDetailView(ChannelProcessingManager channelProcessingManager)
{
mChannelProcessingManager = channelProcessingManager;
Button refreshButton = new Button("Refresh");
refreshButton.setTooltip(new Tooltip("Update the channel details"));
refreshButton.setOnAction(event -> refresh());
HBox labels = new HBox(5, new Label("System:"), grow(mSystemLabel), new Label("Site:"), grow(mSiteLabel),
new Label("Channel Name:"), grow(mNameLabel), refreshButton);
labels.setAlignment(Pos.CENTER_LEFT);
labels.setPadding(new Insets(3, 2, 3, 2));
mDetailTextArea.setEditable(false);
VBox.setVgrow(mDetailTextArea, Priority.ALWAYS);
getChildren().addAll(labels, mDetailTextArea);
}
/**
* Updates the details for the currently selected channel. Call on the JavaFX application thread.
*/
public void refresh()
{
receive(mProcessingChain);
}
private static Label grow(Label label)
{
label.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(label, Priority.ALWAYS);
return label;
}
/**
* Shows the details for the processing chain. Call on the JavaFX application thread.
* @param processingChain to show, or null to clear the view
*/
@Override
public void receive(ProcessingChain processingChain)
{
mProcessingChain = processingChain;
Channel channel = mChannelProcessingManager.getChannel(processingChain);
mSystemLabel.setText(channel != null ? channel.getSystem() : null);
mSiteLabel.setText(channel != null ? channel.getSite() : null);
mNameLabel.setText(channel != null ?
(channel.getChannelType() == Channel.ChannelType.TRAFFIC ? "Traffic Channel" : channel.getName()) : null);
if(processingChain != null)
{
StringBuilder sb = new StringBuilder();
for(DecoderState decoderState: processingChain.getDecoderStates())
{
sb.append(decoderState.getActivitySummary());
}
//Keep the scroll position, so that a refresh doesn't move the user back to the top
double scrollTop = mDetailTextArea.getScrollTop();
mDetailTextArea.setText(sb.toString());
mDetailTextArea.setScrollTop(scrollTop);
}
else
{
mDetailTextArea.setText(EMPTY_DETAILS);
}
}
}

View File

@@ -0,0 +1,500 @@
/*
* *****************************************************************************
* 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 com.google.common.eventbus.Subscribe;
import io.github.dsheirer.channel.metadata.ChannelAndMetadata;
import io.github.dsheirer.channel.metadata.ChannelMetadata;
import io.github.dsheirer.channel.metadata.ChannelMetadataField;
import io.github.dsheirer.channel.metadata.ChannelMetadataModel;
import io.github.dsheirer.channel.state.State;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.channel.ViewChannelRequest;
import io.github.dsheirer.gui.table.ColumnConfigurationButton;
import io.github.dsheirer.gui.table.TableColumnMonitor;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.decoder.ChannelStateIdentifier;
import io.github.dsheirer.identifier.decoder.DecoderLogicalChannelNameIdentifier;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
import io.github.dsheirer.sample.Broadcaster;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.source.tuner.channel.TunerChannelSource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
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;
/**
* Table of the channel metadata for the currently processing channels. Selecting a row broadcasts the processing
* chain for the channel to the registered listeners.
*/
public class ChannelMetadataView extends VBox implements ChannelMetadataModel.Listener
{
private static final String TABLE_KEY = "now.playing.channels";
private static final String SWING_TABLE_KEY = "channel.metadata.panel";
private static final String EMPTY_IDENTIFIER = "-----";
private static final String EMPTY_STATE = "----";
private static final Map<State,String> STATE_STYLES = new EnumMap<>(State.class);
static
{
//Colors match the Swing version of the table (java.awt.Color constants)
STATE_STYLES.put(State.ACTIVE, style("#00FFFF", "#0000FF"));
STATE_STYLES.put(State.CALL, style("#0000FF", "#FFFF00"));
STATE_STYLES.put(State.CONTROL, style("#FFC800", "#0000FF"));
STATE_STYLES.put(State.DATA, style("#00FF00", "#0000FF"));
STATE_STYLES.put(State.ENCRYPTED, style("#FF00FF", "#FFFFFF"));
STATE_STYLES.put(State.FADE, style("#C0C0C0", "#404040"));
STATE_STYLES.put(State.IDLE, style("#FFFFFF", "#404040"));
STATE_STYLES.put(State.RESET, style("#FFAFAF", "#FFFF00"));
STATE_STYLES.put(State.TEARDOWN, style("#404040", "#FFFFFF"));
}
private final ChannelProcessingManager mChannelProcessingManager;
private final ChannelMetadataModel mChannelMetadataModel;
private final IconModel mIconModel;
private final TalkgroupFormatPreference mTalkgroupFormatPreference;
private final TableView<Row> mTableView = new TableView<>();
private final ObservableList<Row> mRows = FXCollections.observableArrayList();
//Changed on the JavaFX thread and read on the decoder threads that send channel metadata updates
private final Map<ChannelMetadata,Row> mRowMap = new ConcurrentHashMap<>();
private final Broadcaster<ProcessingChain> mSelectedProcessingChainBroadcaster = new Broadcaster<>();
private final TableColumnMonitor<Row> mTableColumnMonitor;
private Channel mUserSelectedChannel;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param channelProcessingManager for the channel metadata and processing chains
* @param iconModel for alias icons
* @param userPreferences for talkgroup formatting and column settings
*/
public ChannelMetadataView(ChannelProcessingManager channelProcessingManager, IconModel iconModel,
UserPreferences userPreferences)
{
mChannelProcessingManager = channelProcessingManager;
mChannelMetadataModel = mChannelProcessingManager.getChannelMetadataModel();
mIconModel = iconModel;
mTalkgroupFormatPreference = userPreferences.getTalkgroupFormatPreference();
mTableView.getColumns().addAll(createColumns());
mTableView.setItems(mRows);
mTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_SUBSEQUENT_COLUMNS);
mTableView.setPlaceholder(new javafx.scene.control.Label("No channels are processing"));
mTableView.setRowFactory(tableView -> createRow());
mTableView.getSelectionModel().selectedItemProperty().addListener((observable, oldRow, newRow) -> selected(newRow));
mTableColumnMonitor = new TableColumnMonitor<>(mTableView, TABLE_KEY, userPreferences.getSwingPreference(),
SWING_TABLE_KEY);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox toolbar = new HBox(5, spacer, new ColumnConfigurationButton(mTableColumnMonitor, "Now Playing Columns"));
toolbar.setAlignment(Pos.CENTER_RIGHT);
toolbar.setPadding(new Insets(2, 2, 2, 2));
VBox.setVgrow(mTableView, Priority.ALWAYS);
getChildren().addAll(toolbar, mTableView);
for(ChannelMetadata channelMetadata: mChannelMetadataModel.addListener(this))
{
addRow(channelMetadata);
}
MyEventBus.getGlobalEventBus().register(this);
}
/**
* Adds the listener to receive the processing chain for the channel that the user selects in the table, or null
* when the selection is cleared. Notifications arrive on the JavaFX application thread.
*/
public void addProcessingChainSelectionListener(Listener<ProcessingChain> listener)
{
mSelectedProcessingChainBroadcaster.addListener(listener);
}
/**
* Prepares this view for disposal.
*/
public void dispose()
{
mChannelMetadataModel.removeListener(this);
MyEventBus.getGlobalEventBus().unregister(this);
}
/**
* Receives preference update notifications via the event bus
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
//Talkgroup format changes the identifiers and the application preference can change the alias colors
if(preferenceType == PreferenceType.TALKGROUP_FORMAT || preferenceType == PreferenceType.APPLICATION)
{
Platform.runLater(() -> mRows.forEach(Row::refresh));
}
}
@Override
public void added(ChannelAndMetadata channelAndMetadata)
{
List<ChannelMetadata> channelMetadata = new ArrayList<>(channelAndMetadata.getChannelMetadata());
Platform.runLater(() -> {
for(ChannelMetadata metadata: channelMetadata)
{
addRow(metadata);
}
//The DMR Capacity+ rest channel rotation converts the selected channel to a traffic channel and restarts
//the previous channel. Re-select the row of the restarted channel so that the user isn't chasing it.
if(mUserSelectedChannel != null && !channelMetadata.isEmpty() &&
mUserSelectedChannel.getChannelID() == channelAndMetadata.getChannel().getChannelID())
{
Row row = mRowMap.get(channelMetadata.getFirst());
if(row != null)
{
mTableView.getSelectionModel().select(row);
}
}
});
}
@Override
public void removed(ChannelMetadata channelMetadata)
{
Platform.runLater(() -> {
Row row = mRowMap.remove(channelMetadata);
if(row != null)
{
mRows.remove(row);
}
});
}
@Override
public void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField)
{
Row row = mRowMap.get(channelMetadata);
if(row != null)
{
row.scheduleRefresh();
}
}
/**
* Adds a row for the channel metadata. Call on the JavaFX application thread.
*/
private void addRow(ChannelMetadata channelMetadata)
{
if(!mRowMap.containsKey(channelMetadata))
{
Row row = new Row(channelMetadata);
mRowMap.put(channelMetadata, row);
mRows.add(row);
}
}
private void selected(Row row)
{
ProcessingChain processingChain = null;
if(row != null)
{
mUserSelectedChannel = mChannelMetadataModel.getChannelFromMetadata(row.getChannelMetadata());
processingChain = mChannelProcessingManager.getProcessingChain(mUserSelectedChannel);
}
mSelectedProcessingChainBroadcaster.broadcast(processingChain);
}
private TableRow<Row> createRow()
{
TableRow<Row> tableRow = new TableRow<>();
ContextMenu contextMenu = new ContextMenu();
contextMenu.setOnShowing(event -> {
contextMenu.getItems().clear();
Row row = tableRow.getItem();
Channel channel = row != null ? mChannelMetadataModel.getChannelFromMetadata(row.getChannelMetadata()) : null;
if(channel != null)
{
MenuItem viewChannel = new MenuItem("View/Edit: " + channel.getShortTitle());
viewChannel.setOnAction(e -> MyEventBus.getGlobalEventBus().post(new ViewChannelRequest(channel)));
contextMenu.getItems().add(viewChannel);
}
else
{
MenuItem none = new MenuItem("No Actions Available");
none.setDisable(true);
contextMenu.getItems().add(none);
}
});
tableRow.setContextMenu(contextMenu);
return tableRow;
}
private List<TableColumn<Row,?>> createColumns()
{
List<TableColumn<Row,?>> columns = new ArrayList<>();
TableColumn<Row,State> status = NowPlayingCells.column("status", "Status", null, Pos.CENTER,
row -> {
ChannelStateIdentifier identifier = row.getChannelMetadata().getChannelStateIdentifier();
return identifier != null ? identifier.getValue() : null;
}, Row::revisionProperty);
status.setCellFactory(column -> new NowPlayingCells.AlignedCell<>(column)
{
@Override
protected void updateItem(State state, boolean empty)
{
super.updateItem(state, empty);
if(empty)
{
setText(null);
setStyle(null);
}
else if(state == null)
{
setText(EMPTY_STATE);
setStyle(null);
}
else
{
setText(state.getDisplayValue());
setStyle(STATE_STYLES.get(state));
}
}
});
columns.add(status);
columns.add(NowPlayingCells.column("decoder", "Decoder", null, Pos.CENTER,
row -> toText(row.getChannelMetadata().getDecoderTypeConfigurationIdentifier()), Row::revisionProperty));
columns.add(NowPlayingCells.column("from", "From", null, Pos.CENTER,
row -> {
String text = mTalkgroupFormatPreference.format(row.getChannelMetadata().getFromIdentifier());
return text == null || text.isEmpty() ? EMPTY_IDENTIFIER : text;
}, Row::revisionProperty));
//Talker alias sent over the air by the radio (e.g. DMR or P25)
columns.add(NowPlayingCells.column("talker", "Talker", null, Pos.CENTER,
row -> {
Identifier talkerAlias = row.getChannelMetadata().getTalkerAliasIdentifier();
return talkerAlias != null && talkerAlias.getValue() != null ? talkerAlias.getValue().toString() : null;
}, Row::revisionProperty));
TableColumn<Row,AliasDisplay> fromAlias = NowPlayingCells.column("from.alias", "Alias", "From Alias",
Pos.CENTER_LEFT, row -> AliasDisplay.of(row.getChannelMetadata().getFromIdentifierAliases()),
Row::revisionProperty);
fromAlias.setCellFactory(NowPlayingCells.alias(mIconModel));
columns.add(fromAlias);
columns.add(NowPlayingCells.column("to", "To", null, Pos.CENTER,
row -> {
String text = mTalkgroupFormatPreference.format(row.getChannelMetadata().getToIdentifier());
return text == null || text.isEmpty() ? EMPTY_IDENTIFIER : text;
}, Row::revisionProperty));
TableColumn<Row,AliasDisplay> toAlias = NowPlayingCells.column("to.alias", "Alias", "To Alias",
Pos.CENTER_LEFT, row -> AliasDisplay.of(row.getChannelMetadata().getToIdentifierAliases()),
Row::revisionProperty);
toAlias.setCellFactory(NowPlayingCells.alias(mIconModel));
columns.add(toAlias);
columns.add(NowPlayingCells.column("channel", "Channel", null, Pos.CENTER,
row -> getLogicalChannelName(row.getChannelMetadata()), Row::revisionProperty));
TableColumn<Row,Long> frequency = NowPlayingCells.column("frequency", "Frequency", null, Pos.CENTER,
row -> row.getChannelMetadata().getFrequencyConfigurationIdentifier() != null ?
row.getChannelMetadata().getFrequencyConfigurationIdentifier().getValue() : null,
Row::revisionProperty);
DecimalFormat frequencyFormat = new DecimalFormat("#.00000");
frequency.setCellFactory(NowPlayingCells.formatted(value -> frequencyFormat.format(value / 1e6d)));
columns.add(frequency);
//Tuner that sources the channel
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.
String[] swingColumns = {"status", "decoder", "from", "from.alias", "to", "to.alias", "channel", "frequency",
"channel.name"};
for(TableColumn<Row,?> column: columns)
{
int swingColumn = Arrays.asList(swingColumns).indexOf(column.getId());
if(swingColumn >= 0)
{
TableColumnMonitor.setLegacyIndex(column, swingColumn);
}
}
return columns;
}
/**
* Name of the tuner that sources the channel, or null if the channel isn't sourced by a tuner.
*/
private String getTunerName(ChannelMetadata channelMetadata)
{
Channel channel = mChannelMetadataModel.getChannelFromMetadata(channelMetadata);
ProcessingChain processingChain = channel != null ? mChannelProcessingManager.getProcessingChain(channel) : null;
if(processingChain != null && processingChain.getSource() instanceof TunerChannelSource tunerChannelSource)
{
return tunerChannelSource.getTunerName();
}
return null;
}
/**
* Decoder logical channel name with the timeslot, if any
*/
private static String getLogicalChannelName(ChannelMetadata channelMetadata)
{
DecoderLogicalChannelNameIdentifier id = channelMetadata.getDecoderLogicalChannelNameIdentifier();
if(channelMetadata.hasTimeslot())
{
if(id == null)
{
return "TS:" + channelMetadata.getTimeslot();
}
return id.getValue().replace(" TS1", "").replace(" TS2", "") + " TS:" + channelMetadata.getTimeslot();
}
return id != null ? id.getValue() : null;
}
private static String toText(Identifier identifier)
{
return identifier != null ? identifier.toString() : null;
}
private static String style(String background, String foreground)
{
return "-fx-background-color: " + background + "; -fx-text-fill: " + foreground + ";";
}
/**
* Table row item for a channel metadata. The revision increments each time the channel metadata changes so that
* the row cells update.
*/
public static class Row
{
private final ChannelMetadata mChannelMetadata;
private final IntegerProperty mRevision = new SimpleIntegerProperty();
private final AtomicBoolean mRefreshPending = new AtomicBoolean();
Row(ChannelMetadata channelMetadata)
{
mChannelMetadata = channelMetadata;
}
public ChannelMetadata getChannelMetadata()
{
return mChannelMetadata;
}
public IntegerProperty revisionProperty()
{
return mRevision;
}
/**
* Updates the row cells. Call on the JavaFX application thread.
*/
void refresh()
{
mRevision.set(mRevision.get() + 1);
}
/**
* Schedules a row cell update on the JavaFX application thread. Can be called from any thread. Updates
* that arrive while one is pending are combined.
*/
void scheduleRefresh()
{
if(mRefreshPending.compareAndSet(false, true))
{
Platform.runLater(() -> {
mRefreshPending.set(false);
refresh();
});
}
}
}
}

View File

@@ -0,0 +1,407 @@
/*
* *****************************************************************************
* 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 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.channel.IChannelDescriptor;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.filter.FilterSet;
import io.github.dsheirer.gui.table.TableColumnMonitor;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.module.decode.event.DecodeEventHistory;
import io.github.dsheirer.module.decode.event.IDecodeEvent;
import io.github.dsheirer.module.decode.event.filter.DecodeEventFilterSet;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.TableColumn;
/**
* Table of the decode events for the selected channel.
*/
public class DecodeEventView extends HistoryTableView<IDecodeEvent,IDecodeEvent> implements Listener<ProcessingChain>
{
private static final String TABLE_KEY = "now.playing.events";
private static final String SWING_TABLE_KEY = "decode.event.panel";
private final TimestampFormatter mTimestampFormatter;
private final FilterSet<IDecodeEvent> mFilterSet = new DecodeEventFilterSet();
private DecodeEventHistory mCurrentEventHistory;
private Listener<IDecodeEvent> mCurrentEventListener;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param iconModel for alias icons
* @param userPreferences for display formats and column settings
* @param aliasModel for aliasing identifiers
*/
public DecodeEventView(IconModel iconModel, UserPreferences userPreferences, AliasModel aliasModel)
{
this(iconModel, userPreferences, aliasModel, new TimestampFormatter(userPreferences));
}
private DecodeEventView(IconModel iconModel, UserPreferences userPreferences, AliasModel aliasModel,
TimestampFormatter timestampFormatter)
{
super(createColumns(iconModel, userPreferences, aliasModel, timestampFormatter), TABLE_KEY,
userPreferences.getSwingPreference(), SWING_TABLE_KEY, "Event Filter Editor", "Event Columns");
mTimestampFormatter = timestampFormatter;
getHistoryControls().setFilterSet(mFilterSet);
//Filter changes come from the Swing filter editor
mFilterSet.register(() -> Platform.runLater(this::refilter));
MyEventBus.getGlobalEventBus().register(this);
}
/**
* Prepares this view for disposal
*/
public void dispose()
{
MyEventBus.getGlobalEventBus().unregister(this);
receive(null);
}
/**
* Receives preference update notifications via the event bus
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.DECODE_EVENT || preferenceType == PreferenceType.TALKGROUP_FORMAT ||
preferenceType == PreferenceType.APPLICATION)
{
Platform.runLater(this::refreshAll);
}
}
@Override
protected boolean include(IDecodeEvent event)
{
return mFilterSet.canProcess(event) && mFilterSet.passes(event);
}
/**
* Shows the decode events for the processing chain. Call on the JavaFX application thread.
* @param processingChain to show, or null to clear the view
*/
@Override
public void receive(ProcessingChain processingChain)
{
if(mCurrentEventHistory != null)
{
mCurrentEventHistory.removeListener(mCurrentEventListener);
}
mCurrentEventHistory = null;
mCurrentEventListener = null;
if(processingChain != null)
{
DecodeEventHistory history = processingChain.getDecodeEventHistory();
//A listener for each history so that events from the previous channel are ignored after a change
Listener<IDecodeEvent> listener = new Listener<>()
{
@Override
public void receive(IDecodeEvent event)
{
Platform.runLater(() -> {
if(mCurrentEventListener == this)
{
add(event);
}
});
}
};
mCurrentEventHistory = history;
mCurrentEventListener = listener;
setItems(history.getItems());
history.addListener(listener);
getHistoryControls().setControlsEnabled(true);
}
else
{
clear();
getHistoryControls().setControlsEnabled(false);
}
}
@Override
protected void refreshAll()
{
mTimestampFormatter.update();
super.refreshAll();
}
private static List<TableColumn<Row<IDecodeEvent>,?>> createColumns(IconModel iconModel,
UserPreferences userPreferences,
AliasModel aliasModel,
TimestampFormatter timestampFormatter)
{
List<TableColumn<Row<IDecodeEvent>,?>> columns = new ArrayList<>();
TableColumn<Row<IDecodeEvent>,Long> time = NowPlayingCells.column("time", "Time", null, Pos.CENTER,
row -> row.getItem().getTimeStart(), Row::revisionProperty);
time.setCellFactory(NowPlayingCells.formatted(timestampFormatter::format));
columns.add(time);
TableColumn<Row<IDecodeEvent>,Long> duration = NowPlayingCells.column("duration", "Duration", null,
Pos.CENTER, row -> row.getItem().getDuration(), Row::revisionProperty);
DecimalFormat durationFormat = new DecimalFormat("0.0");
duration.setCellFactory(NowPlayingCells.formatted(value -> value > 0 ? durationFormat.format(value / 1e3d) : null));
columns.add(duration);
columns.add(NowPlayingCells.column("event", "Event", null, Pos.CENTER_LEFT,
row -> row.getItem().getEventType() != null ? row.getItem().getEventType().getLabel() : null,
Row::revisionProperty));
columns.add(NowPlayingCells.column("from", "From", null, Pos.CENTER,
row -> formatIdentifiers(row.getItem().getIdentifierCollection(), Role.FROM, userPreferences),
Row::revisionProperty));
//Talker alias sent over the air by the radio (e.g. DMR, P25 or NXDN)
columns.add(NowPlayingCells.column("talker", "Talker", null, Pos.CENTER,
row -> getTalkerAlias(row.getItem().getIdentifierCollection()), Row::revisionProperty));
TableColumn<Row<IDecodeEvent>,AliasDisplay> fromAlias = NowPlayingCells.column("from.alias", "Alias",
"From Alias", Pos.CENTER, row -> getAliases(row.getItem().getIdentifierCollection(), Role.FROM, aliasModel),
Row::revisionProperty);
fromAlias.setCellFactory(NowPlayingCells.alias(iconModel));
columns.add(fromAlias);
columns.add(NowPlayingCells.column("to", "To", null, Pos.CENTER,
row -> formatIdentifiers(row.getItem().getIdentifierCollection(), Role.TO, userPreferences),
Row::revisionProperty));
TableColumn<Row<IDecodeEvent>,AliasDisplay> toAlias = NowPlayingCells.column("to.alias", "Alias",
"To Alias", Pos.CENTER, row -> getAliases(row.getItem().getIdentifierCollection(), Role.TO, aliasModel),
Row::revisionProperty);
toAlias.setCellFactory(NowPlayingCells.alias(iconModel));
columns.add(toAlias);
columns.add(NowPlayingCells.column("channel", "Channel", null, Pos.CENTER,
row -> getChannel(row.getItem()), Row::revisionProperty));
TableColumn<Row<IDecodeEvent>,Long> frequency = NowPlayingCells.column("frequency", "Frequency", null,
Pos.CENTER, row -> {
IChannelDescriptor descriptor = row.getItem().getChannelDescriptor();
return descriptor != null && descriptor.getDownlinkFrequency() > 0 ?
descriptor.getDownlinkFrequency() : null;
}, Row::revisionProperty);
DecimalFormat frequencyFormat = new DecimalFormat("0.00000");
frequency.setCellFactory(NowPlayingCells.formatted(value -> frequencyFormat.format(value / 1e6d)));
columns.add(frequency);
columns.add(NowPlayingCells.column("details", "Details", null, Pos.CENTER_LEFT,
row -> row.getItem().getDetails(), Row::revisionProperty));
//Column numbers in the Swing version of the table, for its stored column widths. Talker is a new column.
List<String> swingColumns = List.of("time", "duration", "event", "from", "from.alias", "to", "to.alias",
"channel", "frequency", "details");
for(TableColumn<Row<IDecodeEvent>,?> column: columns)
{
if(swingColumns.contains(column.getId()))
{
TableColumnMonitor.setLegacyIndex(column, swingColumns.indexOf(column.getId()));
}
}
return columns;
}
/**
* Talker alias(es) in the identifier collection
*/
private static String getTalkerAlias(IdentifierCollection identifierCollection)
{
if(identifierCollection == null)
{
return null;
}
List<String> aliases = new ArrayList<>();
for(Identifier identifier: identifierCollection.getIdentifiers(Form.TALKER_ALIAS))
{
if(identifier.getValue() != null)
{
aliases.add(identifier.getValue().toString());
}
}
return aliases.isEmpty() ? null : String.join(",", aliases);
}
/**
* Identifiers with the role, without talker aliases, which have their own column
*/
private static List<Identifier> getIdentifiers(IdentifierCollection identifierCollection, Role role)
{
List<Identifier> identifiers = new ArrayList<>(identifierCollection.getIdentifiers(role));
identifiers.removeIf(identifier -> identifier.getForm() == Form.TALKER_ALIAS);
return identifiers;
}
/**
* Event timestamp formatter that uses the timestamp format preference.
*/
private static class TimestampFormatter
{
private final UserPreferences mUserPreferences;
private SimpleDateFormat mFormat;
TimestampFormatter(UserPreferences userPreferences)
{
mUserPreferences = userPreferences;
update();
}
/**
* Updates the format from the preference
*/
void update()
{
mFormat = mUserPreferences.getDecodeEventPreference().getTimestampFormat().getFormatter();
}
String format(long timestamp)
{
return mFormat.format(new Date(timestamp));
}
}
/**
* Channel descriptor and timeslot for the event
*/
private static String getChannel(IDecodeEvent event)
{
IChannelDescriptor channelDescriptor = event.getChannelDescriptor();
boolean timeslot = event.hasTimeslot() && !event.toString().contains("TS");
if(channelDescriptor != null)
{
return timeslot ? channelDescriptor + " TS" + event.getTimeslot() : channelDescriptor.toString();
}
return timeslot ? "TS" + event.getTimeslot() : null;
}
/**
* Formats the identifiers for the role as a comma separated list
*/
private static String formatIdentifiers(IdentifierCollection identifierCollection, Role role,
UserPreferences userPreferences)
{
if(identifierCollection == null)
{
return null;
}
List<Identifier> identifiers = getIdentifiers(identifierCollection, role);
if(identifiers == null || identifiers.isEmpty())
{
return null;
}
StringBuilder sb = new StringBuilder();
for(Identifier identifier: identifiers)
{
if(!sb.isEmpty())
{
sb.append(",");
}
if(identifier.getForm() == Form.TALKGROUP || identifier.getForm() == Form.RADIO ||
identifier.getForm() == Form.PATCH_GROUP)
{
sb.append(userPreferences.getTalkgroupFormatPreference().format(identifier));
}
else
{
sb.append(identifier);
}
}
return sb.toString();
}
/**
* Aliases for the identifiers with the role. The display is styled by the first alias of the last aliased
* identifier, the same as the Swing version of the table.
*/
private static AliasDisplay getAliases(IdentifierCollection identifierCollection, Role role, AliasModel aliasModel)
{
if(identifierCollection == null)
{
return null;
}
List<Identifier> identifiers = getIdentifiers(identifierCollection, role);
if(identifiers == null || identifiers.isEmpty())
{
return null;
}
AliasList aliasList = aliasModel.getAliasList(identifierCollection);
if(aliasList == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
Alias styleAlias = null;
for(Identifier identifier: identifiers)
{
List<Alias> aliases = aliasList.getAliases(identifier);
if(!aliases.isEmpty())
{
if(!sb.isEmpty())
{
sb.append(",");
}
sb.append(Joiner.on(", ").skipNulls().join(aliases));
styleAlias = aliases.getFirst();
}
}
return styleAlias != null ? AliasDisplay.of(sb.toString(), styleAlias) : null;
}
}

View File

@@ -0,0 +1,153 @@
/*
* *****************************************************************************
* 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.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;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
/**
* Toolbar for a history table: filter editor, clear, history size and column configuration controls.
*/
public class HistoryControls<T> extends HBox
{
/**
* Default number of items in the history
*/
public static final int DEFAULT_HISTORY_SIZE = 200;
private static final int MAXIMUM_HISTORY_SIZE = 2000;
private final String mFilterEditorTitle;
private final Button mFilterButton = new Button("Filters");
private final Button mClearButton = new Button("Clear");
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;
/**
* Constructs an instance
* @param filterEditorTitle for the filter editor window
* @param clear action for the clear button
* @param historySizeListener to receive history size changes
* @param tableColumnMonitor for the column configuration button
* @param columnsTitle for the column configuration editor
*/
public HistoryControls(String filterEditorTitle, Runnable clear, IntConsumer historySizeListener,
TableColumnMonitor<?> tableColumnMonitor, String columnsTitle)
{
super(5);
mFilterEditorTitle = filterEditorTitle;
setAlignment(Pos.CENTER_LEFT);
setPadding(new Insets(3, 2, 3, 2));
mFilterButton.setTooltip(new Tooltip("Edit filters"));
mFilterButton.setOnAction(event -> showFilterEditor());
mClearButton.setTooltip(new Tooltip("Clears the history"));
mClearButton.setOnAction(event -> clear.run());
mHistorySlider.setTooltip(new Tooltip("Adjust history size. Double-click to reset to default " +
DEFAULT_HISTORY_SIZE));
mHistorySlider.setBlockIncrement(25);
mHistorySlider.setPrefWidth(200);
mHistorySlider.valueProperty().addListener((observable, oldValue, newValue) -> {
int size = newValue.intValue();
mHistoryValueLabel.setText(String.valueOf(size));
historySizeListener.accept(size);
});
mHistorySlider.setOnMouseClicked(event -> {
if(event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2)
{
mHistorySlider.setValue(DEFAULT_HISTORY_SIZE);
}
});
mHistoryValueLabel.setMinWidth(40);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
getChildren().addAll(mFilterButton, mClearButton, mHistoryLabel, mHistorySlider, mHistoryValueLabel, spacer,
new ColumnConfigurationButton(tableColumnMonitor, columnsTitle));
setControlsEnabled(false);
}
/**
* Sets the enabled state of the history controls. The column configuration button is always enabled.
*/
public void setControlsEnabled(boolean enabled)
{
mFilterButton.setDisable(!enabled);
mClearButton.setDisable(!enabled);
mHistoryLabel.setDisable(!enabled);
mHistorySlider.setDisable(!enabled);
mHistoryValueLabel.setDisable(!enabled);
}
/**
* Updates the filter set for the filter editor.
* @param filterSet to edit, or null
*/
public void setFilterSet(FilterSet<T> filterSet)
{
mFilterSet = filterSet;
EventQueue.invokeLater(() -> {
if(mFilterEditor != null && filterSet != null)
{
mFilterEditor.updateFilterSet(filterSet);
}
});
}
/**
* Shows the filter editor. The filter editor is a Swing window.
*/
private void showFilterEditor()
{
FilterSet<T> filterSet = mFilterSet;
if(filterSet != null)
{
EventQueue.invokeLater(() -> {
if(mFilterEditor == null)
{
mFilterEditor = new FilterEditor<>(mFilterEditorTitle, null, filterSet);
}
mFilterEditor.setVisible(true);
mFilterEditor.toFront();
});
}
}
}

View File

@@ -0,0 +1,206 @@
/*
* *****************************************************************************
* 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.table.TableColumnMonitor;
import io.github.dsheirer.preference.swing.SwingPreference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Table of a history of items, newest first, with filter, clear, history size and column configuration controls.
*
* Use this class on the JavaFX application thread.
*
* @param <T> type of the history items
* @param <F> type of the filtered objects
*/
public abstract class HistoryTableView<T,F> extends VBox
{
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<>();
private final TableView<Row<T>> mTableView = new TableView<>();
private final TableColumnMonitor<Row<T>> mTableColumnMonitor;
private final HistoryControls<F> mHistoryControls;
private int mHistorySize = HistoryControls.DEFAULT_HISTORY_SIZE;
/**
* Constructs an instance
* @param columns for the table
* @param tableKey for the stored column settings
* @param swingPreference with the legacy Swing column widths
* @param swingTableKey of the legacy Swing table
* @param filterEditorTitle for the filter editor window
* @param columnsTitle for the column configuration editor window
*/
protected HistoryTableView(List<TableColumn<Row<T>,?>> columns, String tableKey, SwingPreference swingPreference,
String swingTableKey, String filterEditorTitle, String columnsTitle)
{
mTableView.getColumns().addAll(columns);
SortedList<Row<T>> sortedRows = new SortedList<>(mFilteredRows);
sortedRows.comparatorProperty().bind(mTableView.comparatorProperty());
mTableView.setItems(sortedRows);
mTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_SUBSEQUENT_COLUMNS);
mTableView.setPlaceholder(new Label(""));
mTableColumnMonitor = new TableColumnMonitor<>(mTableView, tableKey, swingPreference, swingTableKey);
mHistoryControls = new HistoryControls<>(filterEditorTitle, this::clear, this::setHistorySize,
mTableColumnMonitor, columnsTitle);
VBox.setVgrow(mTableView, Priority.ALWAYS);
getChildren().addAll(mHistoryControls, mTableView);
refilter();
}
/**
* Indicates if the item passes the current filters
*/
protected abstract boolean include(T item);
/**
* History controls toolbar
*/
protected HistoryControls<F> getHistoryControls()
{
return mHistoryControls;
}
/**
* Re-applies the filters to the items, after a filter change.
*/
protected void refilter()
{
mFilteredRows.setPredicate(row -> include(row.getItem()));
}
/**
* Adds the item to the top of the history, or updates the row of the item when it is already in the history.
* Removes the oldest items when the history is larger than the history size.
*/
protected void add(T item)
{
Row<T> row = mRowMap.get(item);
if(row != null)
{
//Replace the row with itself so that the filter re-checks the updated item
int index = mRows.indexOf(row);
if(index >= 0)
{
mRows.set(index, row);
}
row.refresh();
}
else
{
row = new Row<>(item);
mRowMap.put(item, row);
mRows.addFirst(row);
trim();
}
}
/**
* Replaces the history with the items, oldest first.
*/
protected void setItems(List<T> items)
{
clear();
for(T item: items)
{
add(item);
}
}
/**
* Removes all items from the history
*/
protected void clear()
{
mRows.clear();
mRowMap.clear();
}
/**
* Updates the cells of all rows, after a change to the display formats.
*/
protected void refreshAll()
{
mRows.forEach(Row::refresh);
}
private void setHistorySize(int historySize)
{
mHistorySize = historySize;
trim();
}
private void trim()
{
while(mRows.size() > mHistorySize)
{
mRowMap.remove(mRows.removeLast().getItem());
}
}
/**
* Table row item for a history item. The revision increments each time the item changes so that the row cells
* update.
*/
public static class Row<T>
{
private final T mItem;
private final IntegerProperty mRevision = new SimpleIntegerProperty();
Row(T item)
{
mItem = item;
}
public T getItem()
{
return mItem;
}
public IntegerProperty revisionProperty()
{
return mRevision;
}
void refresh()
{
mRevision.set(mRevision.get() + 1);
}
}
}

View File

@@ -0,0 +1,164 @@
/*
* *****************************************************************************
* 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.filter.FilterSet;
import io.github.dsheirer.message.IMessage;
import io.github.dsheirer.message.MessageHistory;
import io.github.dsheirer.message.StuffBitsMessage;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.module.decode.DecoderFactory;
import io.github.dsheirer.module.decode.event.MessageItem;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.TableColumn;
/**
* Table of the decoded messages for the selected channel.
*/
public class MessageActivityView extends HistoryTableView<MessageItem,IMessage> implements Listener<ProcessingChain>
{
private static final String TABLE_KEY = "now.playing.messages";
private static final String SWING_TABLE_KEY = "message.activity.panel";
private MessageHistory mCurrentMessageHistory;
private Listener<IMessage> mCurrentMessageListener;
private FilterSet<IMessage> mMessageFilterSet;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param userPreferences for the column settings
*/
public MessageActivityView(UserPreferences userPreferences)
{
super(createColumns(), TABLE_KEY, userPreferences.getSwingPreference(), SWING_TABLE_KEY,
"Message Filter Editor", "Message Columns");
}
@Override
protected boolean include(MessageItem item)
{
FilterSet<IMessage> filterSet = mMessageFilterSet;
if(filterSet != null && item.getMessage() != null)
{
return filterSet.canProcess(item.getMessage()) && filterSet.passes(item.getMessage());
}
return false;
}
/**
* Shows the messages for the processing chain. Call on the JavaFX application thread.
* @param processingChain to show, or null to clear the view
*/
@Override
public void receive(ProcessingChain processingChain)
{
if(mCurrentMessageHistory != null)
{
mCurrentMessageHistory.removeListener(mCurrentMessageListener);
}
//Unregister from changes made to the filter set
if(mMessageFilterSet != null)
{
mMessageFilterSet.register(null);
}
mCurrentMessageHistory = null;
mCurrentMessageListener = null;
if(processingChain != null)
{
MessageHistory history = processingChain.getMessageHistory();
FilterSet<IMessage> filterSet = DecoderFactory.getMessageFilters(processingChain.getModules());
mMessageFilterSet = filterSet;
//Filter changes come from the Swing filter editor
filterSet.register(() -> Platform.runLater(() -> {
if(mMessageFilterSet == filterSet)
{
refilter();
}
}));
getHistoryControls().setFilterSet(filterSet);
//A listener for each history so that messages from the previous channel are ignored after a change
Listener<IMessage> listener = new Listener<>()
{
@Override
public void receive(IMessage message)
{
//Don't process tail bits or stuff bits message fragments
if(!(message instanceof StuffBitsMessage))
{
MessageItem item = new MessageItem(message);
Platform.runLater(() -> {
if(mCurrentMessageListener == this)
{
add(item);
}
});
}
}
};
mCurrentMessageHistory = history;
mCurrentMessageListener = listener;
List<MessageItem> items = new ArrayList<>();
for(IMessage message: history.getItems())
{
items.add(new MessageItem(message));
}
setItems(items);
refilter();
history.addListener(listener);
getHistoryControls().setControlsEnabled(true);
}
else
{
mMessageFilterSet = null;
clear();
getHistoryControls().setControlsEnabled(false);
}
}
private static List<TableColumn<Row<MessageItem>,?>> createColumns()
{
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
List<TableColumn<Row<MessageItem>,?>> columns = new ArrayList<>();
columns.add(NowPlayingCells.column("time", "Time", null, Pos.CENTER_LEFT,
row -> row.getItem().getTimestamp(timeFormat), null));
columns.add(NowPlayingCells.column("protocol", "Protocol", null, Pos.CENTER_LEFT,
row -> row.getItem().getProtocol(), null));
columns.add(NowPlayingCells.column("timeslot", "Timeslot", null, Pos.CENTER_LEFT,
row -> row.getItem().getTimeslot(), null));
columns.add(NowPlayingCells.column("message", "Message", null, Pos.CENTER_LEFT,
row -> row.getItem().getText(), null));
return columns;
}
}

View File

@@ -0,0 +1,166 @@
/*
* *****************************************************************************
* 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.table.TableColumnMonitor;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import java.util.function.Function;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.control.TableCell;
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.
*/
public final class NowPlayingCells
{
private static final String ALIGNMENT = "now.playing.cell.alignment";
private NowPlayingCells()
{
}
/**
* Creates a table column.
* @param id that identifies the column for storing the column settings. Don't change it, or users lose the
* stored order, visibility and width of the column.
* @param text for the column header
* @param configurationName for the column in the column configuration editor, or null to use the header text
* @param alignment of the cell contents
* @param value of the column for the row item. The value is recalculated each time the row revision changes.
* @param revision of the row item, or null when the row value doesn't change
*/
public static <S,T> TableColumn<S,T> column(String id, String text, String configurationName, Pos alignment,
Function<S,T> value, Function<S,ObservableValue<?>> revision)
{
TableColumn<S,T> column = new TableColumn<>(text);
column.setId(id);
if(configurationName != null)
{
TableColumnMonitor.setName(column, configurationName);
}
column.getProperties().put(ALIGNMENT, alignment);
column.setCellFactory(formatted(Object::toString));
if(revision == null)
{
column.setCellValueFactory(param -> Bindings.createObjectBinding(() -> value.apply(param.getValue())));
}
else
{
column.setCellValueFactory(param -> Bindings.createObjectBinding(() -> value.apply(param.getValue()),
revision.apply(param.getValue())));
}
return column;
}
/**
* Cell factory that shows the cell value formatted as text.
* @param formatter for non-null values. Can return null for an empty cell.
*/
public static <S,T> Callback<TableColumn<S,T>,TableCell<S,T>> formatted(Function<T,String> formatter)
{
return column -> new AlignedCell<>(column)
{
@Override
protected void updateItem(T item, boolean empty)
{
super.updateItem(item, empty);
setText(empty || item == null ? null : formatter.apply(item));
}
};
}
/**
* Cell factory for alias values that shows the alias names in the alias color with the alias icon.
* @param iconModel for the alias icons
*/
public static <S> Callback<TableColumn<S,AliasDisplay>,TableCell<S,AliasDisplay>> alias(IconModel iconModel)
{
return column -> new AlignedCell<>(column)
{
@Override
protected void updateItem(AliasDisplay item, boolean empty)
{
super.updateItem(item, empty);
if(empty || item == null)
{
setText(null);
setGraphic(null);
setStyle(null);
}
else
{
setText(item.text());
Icon icon = iconModel.getIcon(item.iconName());
setGraphic(icon != null && icon.getFxImage() != null ? new ImageView(icon.getFxImage()) : null);
java.awt.Color color = new java.awt.Color(item.color());
java.awt.Color background = UIManager.getColor("Table.background");
java.awt.Color readable = background != null ?
ThemeManager.getInstance().getReadableColor(color, background) : color;
String fill = toWebColor(readable.getRGB());
//An inline style, since the themed table row style otherwise replaces the text fill
setStyle("-fx-text-fill: " + fill + ";");
}
}
};
}
/**
* Formats the RGB value as a web color.
* @param rgb color value
* @return web color, e.g. #FF0000
*/
public static String toWebColor(int rgb)
{
return String.format("#%06X", rgb & 0xFFFFFF);
}
/**
* Table cell that aligns its contents with the alignment of its column.
*/
public static class AlignedCell<S,T> extends TableCell<S,T>
{
/**
* Constructs an instance
* @param column of the cell
*/
public AlignedCell(TableColumn<S,T> column)
{
if(column.getProperties().get(ALIGNMENT) instanceof Pos alignment)
{
setAlignment(alignment);
}
}
}
}

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

@@ -0,0 +1,121 @@
/*
* *****************************************************************************
* 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.channel.ChannelSpectrumView;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import javafx.geometry.Orientation;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
/**
* Now Playing view: the table of currently processing channels above the details, events, messages and channel tabs
* for the selected channel.
*
* Use this class on the JavaFX application thread.
*/
public class NowPlayingView extends SplitPane
{
private static final double DIVIDER_POSITION = 0.5;
private final ChannelMetadataView mChannelMetadataView;
private final ChannelDetailView mChannelDetailView;
private final DecodeEventView mDecodeEventView;
private final MessageActivityView mMessageActivityView;
private final ChannelSpectrumView mChannelSpectrumView;
private final TabPane mTabPane = new TabPane();
private boolean mDetailTabsVisible;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param playlistManager for the channels
* @param iconModel for alias icons
* @param userPreferences for display formats and column settings
* @param detailTabsVisible to show the detail tabs
*/
public NowPlayingView(PlaylistManager playlistManager, IconModel iconModel, UserPreferences userPreferences,
boolean detailTabsVisible)
{
setOrientation(Orientation.VERTICAL);
mChannelMetadataView = new ChannelMetadataView(playlistManager.getChannelProcessingManager(), iconModel, userPreferences);
mChannelDetailView = new ChannelDetailView(playlistManager.getChannelProcessingManager());
mDecodeEventView = new DecodeEventView(iconModel, userPreferences, playlistManager.getAliasModel());
mMessageActivityView = new MessageActivityView(userPreferences);
mChannelSpectrumView = new ChannelSpectrumView(playlistManager);
Tab detailsTab = new Tab("Details", mChannelDetailView);
Tab channelTab = new Tab("Channel", mChannelSpectrumView);
mTabPane.getTabs().addAll(detailsTab, new Tab("Events", mDecodeEventView),
new Tab("Messages", mMessageActivityView), channelTab);
mTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
//Turn the channel spectrum processing on only while the channel tab is selected
mTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
mChannelSpectrumView.setPanelVisible(newTab == channelTab);
//Show current details each time the user opens the details tab
if(newTab == detailsTab)
{
mChannelDetailView.refresh();
}
});
mChannelMetadataView.addProcessingChainSelectionListener(mChannelDetailView);
mChannelMetadataView.addProcessingChainSelectionListener(mDecodeEventView);
mChannelMetadataView.addProcessingChainSelectionListener(mMessageActivityView);
mChannelMetadataView.addProcessingChainSelectionListener(mChannelSpectrumView);
getItems().add(mChannelMetadataView);
setDetailTabsVisible(detailTabsVisible);
}
/**
* Changes the visibility of the channel details tabs.
* @param visible true to show or false to hide.
*/
public void setDetailTabsVisible(boolean visible)
{
if(visible && !getItems().contains(mTabPane))
{
getItems().add(mTabPane);
setDividerPositions(DIVIDER_POSITION);
}
else if(!visible)
{
getItems().remove(mTabPane);
}
mDetailTabsVisible = visible;
//The channel tab is hidden with the detail tabs, so stop its spectrum processing
mChannelSpectrumView.setPanelVisible(mDetailTabsVisible &&
mTabPane.getSelectionModel().getSelectedIndex() == mTabPane.getTabs().size() - 1);
}
/**
* Prepares this view for disposal.
*/
public void dispose()
{
mChannelMetadataView.dispose();
mDecodeEventView.dispose();
}
}

View File

@@ -27,6 +27,7 @@ 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;
@@ -77,6 +78,7 @@ public class PlaylistEditor extends BorderPane
private Tab mStreamingTab;
private AliasEditor mAliasEditor;
private ChannelEditor mChannelEditor;
private RadioReferenceEditor mRadioReferenceEditor;
/**
* Constructs an instance
@@ -122,6 +124,13 @@ 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 PLAYLIST:
//Ignore - this is a request to simply show te playlist editor
break;
@@ -266,12 +275,22 @@ public class PlaylistEditor extends BorderPane
if(mRadioReferenceTab == null)
{
mRadioReferenceTab = new Tab("Radio Reference");
mRadioReferenceTab.setContent(new RadioReferenceEditor(mUserPreferences, mPlaylistManager));
mRadioReferenceTab.setContent(getRadioReferenceEditor());
}
return mRadioReferenceTab;
}
private RadioReferenceEditor getRadioReferenceEditor()
{
if(mRadioReferenceEditor == null)
{
mRadioReferenceEditor = new RadioReferenceEditor(mUserPreferences, mPlaylistManager);
}
return mRadioReferenceEditor;
}
private Tab getStreamingTab()
{
if(mStreamingTab == null)

View File

@@ -23,6 +23,7 @@ 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;
@@ -33,6 +34,11 @@ 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;
@@ -49,6 +55,7 @@ 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;
@@ -62,10 +69,12 @@ 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;
@@ -106,6 +115,13 @@ 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
@@ -120,7 +136,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
VBox leftBox = new VBox();
VBox.setVgrow(getAliasTableView(), Priority.ALWAYS);
leftBox.getChildren().addAll(getSearchAndListSelectionBox(), getAliasTableView());
leftBox.getChildren().addAll(getSearchAndListSelectionBox(), getRadioReferenceBox(), getAliasTableView());
HBox topBox = new HBox();
HBox.setHgrow(leftBox, Priority.ALWAYS);
@@ -130,9 +146,191 @@ 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.
*/
@@ -331,6 +529,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
{
getNewAliasButton().setDisable(newValue == null || newValue.contentEquals(AliasModel.NO_ALIAS_LIST));
update();
updateRadioReferenceControls();
});
if(mAliasListNameComboBox.getItems().size() > 1)

View File

@@ -21,7 +21,7 @@ package io.github.dsheirer.gui.playlist.channel;
import io.github.dsheirer.gui.control.AccessibilityUtil;
import io.github.dsheirer.gui.control.AccessibleToggleSwitch;
import io.github.dsheirer.gui.control.DbPowerMeter;
import io.github.dsheirer.gui.power.PowerMeter;
import io.github.dsheirer.gui.control.HexFormatter;
import io.github.dsheirer.gui.control.IntegerFormatter;
import io.github.dsheirer.gui.playlist.eventlog.EventLogConfigurationEditor;
@@ -80,8 +80,8 @@ public class AMConfigurationEditor extends ChannelConfigurationEditor
private TextField mSquelchThresholdField;
private ToggleSwitch mSquelchAutoTrackSwitch;
private TextFormatter<Integer> mTalkgroupTextFormatter;
private IntegerFormatter mSquelchTextFormatter = new IntegerFormatter((int)DbPowerMeter.DEFAULT_MINIMUM_POWER,
(int)DbPowerMeter.DEFAULT_MAXIMUM_POWER);
private IntegerFormatter mSquelchTextFormatter = new IntegerFormatter((int)PowerMeter.DEFAULT_MINIMUM_POWER,
(int)PowerMeter.DEFAULT_MAXIMUM_POWER);
private EventLogConfigurationEditor mEventLogConfigurationEditor;
private TalkgroupValueChangeListener mTalkgroupValueChangeListener = new TalkgroupValueChangeListener();
private IntegerFormatter mDecimalFormatter = new IntegerFormatter(1, 65535);

View File

@@ -96,6 +96,7 @@ 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;
@@ -187,6 +188,7 @@ 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)
@@ -210,6 +212,7 @@ 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();
@@ -251,6 +254,7 @@ 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);
@@ -277,6 +281,12 @@ 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();
@@ -598,6 +608,12 @@ 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;
@@ -660,6 +676,32 @@ 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 a radio alias for each talker alias decoded " +
"on this system, named with the talker alias, and renames the radio alias when its talker alias " +
"changes. Applies when the channel is (re)started."));
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
}
return mAutoAddTalkerAliasesCheckBox;
}
private Button getNewAliasListButton()
{
if(mNewAliasListButton == null)

View File

@@ -55,6 +55,8 @@ 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
@@ -109,6 +111,56 @@ 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();
@@ -155,6 +207,17 @@ 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,6 +68,21 @@ 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;
@@ -165,7 +180,11 @@ public class AgencyFrequencyEditor extends GridPane
sorted.add(0, ALL_CATEGORIES);
}
getCategoryComboBox().getItems().addAll(sorted);
getCategoryComboBox().getSelectionModel().select(sorted.get(0));
if(mPendingFrequency == null || !selectPendingFrequency())
{
getCategoryComboBox().getSelectionModel().select(sorted.get(0));
}
}
else
{
@@ -173,6 +192,115 @@ public class AgencyFrequencyEditor extends GridPane
}
}
/**
* 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)
@@ -400,6 +528,7 @@ public class AgencyFrequencyEditor extends GridPane
getFrequencyTableView().getItems().clear();
SubCategory subCategory = mSubCategoryComboBox.getValue();
mLoadingFrequencies = subCategory != null;
if(subCategory != null)
{
@@ -453,14 +582,23 @@ 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,12 +26,17 @@ 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;
@@ -41,7 +46,9 @@ 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;
@@ -62,7 +69,9 @@ 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;
@@ -168,8 +177,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
{
getCountryComboBox().getItems().clear();
final int preferredCountryId = mUserPreferences.getRadioReferencePreference().getPreferredCountryId();
ThreadPool.CACHED.execute(() -> {
try
{
@@ -177,6 +184,8 @@ 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)
{
@@ -199,6 +208,342 @@ 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)
@@ -596,8 +941,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
if(country != null)
{
int preferredStateId = mUserPreferences.getRadioReferencePreference().getPreferredStateId();
ThreadPool.CACHED.execute(() -> {
try
{
@@ -606,6 +949,7 @@ 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())
{
@@ -652,8 +996,6 @@ 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(() -> {
@@ -665,6 +1007,7 @@ 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 start it. A frequency or site 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
* 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,6 +452,17 @@ 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);
@@ -475,14 +486,21 @@ public class RadioReferencePlaylistActions
return;
}
enableAll(existing, onError);
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);
enable(channel, onError);
if(start)
{
enable(channel, onError);
}
}
});
return;
@@ -499,7 +517,7 @@ public class RadioReferencePlaylistActions
return;
}
addAndStart(channel, onError);
add(channel, start, onError);
});
}
@@ -507,6 +525,16 @@ 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);
@@ -526,7 +554,7 @@ public class RadioReferencePlaylistActions
return;
}
addAndStart(channels.get(0), onError);
add(channels.get(0), start, onError);
});
}
@@ -534,6 +562,16 @@ 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];
@@ -550,28 +588,36 @@ public class RadioReferencePlaylistActions
return;
}
addAndStart(channel, onError);
add(channel, start, onError);
}
/**
* 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
* 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
*/
private void addAndStart(Channel channel, Consumer<String> onError)
private void add(Channel channel, boolean start, Consumer<String> onError)
{
Channel existing = findChannel(getFrequencies(channel.getSourceConfiguration()),
getProtocolFamily(channel.getDecodeConfiguration().getDecoderType()));
if(existing != null)
{
enable(existing, onError);
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);
enable(channel, onError);
if(start)
{
enable(channel, onError);
}
});
}

View File

@@ -19,6 +19,7 @@
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;
@@ -45,6 +46,7 @@ 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;
@@ -55,6 +57,7 @@ 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;
@@ -75,6 +78,7 @@ 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;
@@ -120,6 +124,7 @@ 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;
@@ -222,8 +227,12 @@ public class SiteEditor extends GridPane
GridPane.setHgrow(getAliasListNameComboBox(), Priority.ALWAYS);
getChildren().add(getAliasListNameComboBox());
GridPane.setConstraints(getNewAliasListButton(), 2, ++row);
getChildren().add(getNewAliasListButton());
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);
HBox createBox = new HBox();
createBox.setAlignment(Pos.CENTER_LEFT);
@@ -278,6 +287,18 @@ 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);
@@ -878,6 +899,97 @@ 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,6 +156,41 @@ 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,6 +58,8 @@ 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;
@@ -132,6 +134,46 @@ 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

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

@@ -0,0 +1,235 @@
/*
* *****************************************************************************
* 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.power;
import java.text.DecimalFormat;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.VPos;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
/**
* Vertical bar meter for a decibel power level, with optional peak and squelch threshold lines and a value scale.
*
* Use this class on the JavaFX application thread.
*/
public class PowerMeter extends Region
{
public static final double DEFAULT_MINIMUM_POWER = -110.0d;
public static final double DEFAULT_MAXIMUM_POWER = 0.0d;
private static final double BAR_WIDTH = 30;
private static final double PADDING = 3;
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0");
private static final Color COLOR_BAR = Color.LIGHTGRAY;
private static final Color COLOR_THRESHOLD = Color.BLUE;
private static final Color COLOR_PEAK = Color.PINK;
private final Canvas mCanvas = new Canvas();
private final ObjectProperty<Paint> mForeground = new SimpleObjectProperty<>(Color.BLACK);
private final ObjectProperty<Font> mFont = new SimpleObjectProperty<>(Font.getDefault());
private final double mMinimumValue = DEFAULT_MINIMUM_POWER;
private final double mMaximumValue = DEFAULT_MAXIMUM_POWER;
private double mPeak = mMinimumValue;
private double mPower = mMinimumValue;
private double mSquelchThreshold = mMinimumValue;
private boolean mPeakVisible = false;
private boolean mSquelchThresholdVisible = false;
/**
* Constructs an instance.
*/
public PowerMeter()
{
getChildren().add(mCanvas);
setPrefSize(90, 100);
setMinSize(70, 60);
mForeground.addListener((observable, oldValue, newValue) -> draw());
mFont.addListener((observable, oldValue, newValue) -> draw());
}
/**
* Color for the meter outline and scale text. Bind it to a themed control's text color.
*/
public ObjectProperty<Paint> foregroundProperty()
{
return mForeground;
}
/**
* Font for the scale text.
*/
public ObjectProperty<Font> fontProperty()
{
return mFont;
}
@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();
}
}
/**
* Resets peak, power and squelch to minimums
*/
public void reset()
{
mPeak = mMinimumValue;
mPower = mMinimumValue;
mSquelchThreshold = mMinimumValue;
draw();
}
/**
* Sets the current power level constrained to the minimum and maximum values for this control.
* @param power (dB)
*/
public void setPower(double power)
{
mPower = Math.clamp(power, mMinimumValue, mMaximumValue);
draw();
}
/**
* Sets the peak value line
* @param peak (db)
*/
public void setPeak(double peak)
{
mPeak = peak;
draw();
}
/**
* Sets the squelch threshold value
* @param squelchThreshold (dB)
*/
public void setSquelchThreshold(double squelchThreshold)
{
mSquelchThreshold = squelchThreshold;
draw();
}
/**
* Sets the peak line visibility
*/
public void setPeakVisible(boolean peakVisible)
{
mPeakVisible = peakVisible;
draw();
}
/**
* Sets the visibility of the squelch threshold line
*/
public void setSquelchThresholdVisible(boolean squelchThresholdVisible)
{
mSquelchThresholdVisible = squelchThresholdVisible;
draw();
}
private void draw()
{
double width = mCanvas.getWidth();
double height = mCanvas.getHeight();
GraphicsContext gc = mCanvas.getGraphicsContext2D();
gc.clearRect(0, 0, width, height);
if(width <= 0 || height <= 0)
{
return;
}
double meterHeight = height - 1;
//Meter outline
gc.setStroke(mForeground.get());
gc.setLineWidth(1);
gc.strokeRect(0.5, 0.5, BAR_WIDTH, meterHeight - 0.5);
//Filled bar
gc.setFill(COLOR_BAR);
double top = getY(getPercent(mPower), meterHeight);
gc.fillRect(PADDING, top, BAR_WIDTH - 2 * PADDING + 1, meterHeight - PADDING - top);
if(mSquelchThresholdVisible && isValidValue(mSquelchThreshold))
{
gc.setStroke(COLOR_THRESHOLD);
drawLine(gc, getY(getPercent(mSquelchThreshold), meterHeight));
}
if(mPeakVisible && isValidValue(mPeak))
{
gc.setStroke(COLOR_PEAK);
drawLine(gc, getY(getPercent(mPeak), meterHeight));
}
//Scale, with the number of labels adapted to the height of the control
Font font = mFont.get() != null ? mFont.get() : Font.getDefault();
gc.setFont(font);
gc.setFill(mForeground.get());
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.CENTER);
double extent = mMaximumValue - mMinimumValue;
double labelCount = Math.max(1, height / (font.getSize() * 2.5));
double interval = extent / labelCount;
for(double value = mMaximumValue; value > mMinimumValue; value -= interval)
{
double y = Math.clamp(getY(getPercent(value), meterHeight), font.getSize() / 2, height - font.getSize() / 2);
gc.fillText(DECIMAL_FORMAT.format(value), BAR_WIDTH + PADDING * 2, y);
}
}
private void drawLine(GraphicsContext gc, double y)
{
double snapped = Math.floor(y) + 0.5;
gc.strokeLine(0.5, snapped, BAR_WIDTH + 0.5, snapped);
}
private double getY(double percent, double meterHeight)
{
double fillHeight = meterHeight - 2 * PADDING;
return PADDING + fillHeight * (1.0 - percent);
}
private double getPercent(double value)
{
return (value - mMinimumValue) / (mMaximumValue - mMinimumValue);
}
private boolean isValidValue(double value)
{
return mMinimumValue <= value && value <= mMaximumValue;
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,99 +21,109 @@ package io.github.dsheirer.gui.power;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.dsp.squelch.ISquelchConfiguration;
import io.github.dsheirer.gui.control.DbPowerMeter;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.source.SourceEvent;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.swing.IconFontSwing;
import net.miginfocom.swing.MigLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import jiconfont.javafx.IconNode;
/**
* Swing view for displaying signal power measurements with integrated squelch control.
* Signal power meter with squelch threshold controls for the AM decoder.
*/
public class SignalPowerView extends JPanel
public class SignalPowerView extends HBox
{
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0");
private static final String NOT_AVAILABLE = "Not Available";
private final DbPowerMeter mPowerMeter = new DbPowerMeter();
private final PeakMonitor mPeakMonitor = new PeakMonitor(DbPowerMeter.DEFAULT_MINIMUM_POWER);
private final JLabel mPowerLabel;
private final JLabel mPeakLabel;
private final JLabel mSquelchLabel;
private final JLabel mSquelchValueLabel;
private final JButton mSquelchUpButton;
private final JButton mSquelchDownButton;
private final JCheckBox mSquelchAutoTrackCheckBox;
private double mSquelchThreshold;
private final PowerMeter mPowerMeter = new PowerMeter();
private final PeakMonitor mPeakMonitor = new PeakMonitor(PowerMeter.DEFAULT_MINIMUM_POWER);
private final Label mPowerLabel = new Label("0");
private final Label mPeakLabel = new Label("0");
private final Label mSquelchLabel = new Label("Squelch:");
private final Label mSquelchValueLabel = new Label(NOT_AVAILABLE);
private final Button mSquelchUpButton = new Button();
private final Button mSquelchDownButton = new Button();
private final CheckBox mSquelchAutoTrackCheckBox = new CheckBox("Auto Track");
private final AtomicBoolean mPowerUpdatePending = new AtomicBoolean();
private volatile double mPower;
private volatile double mPeak;
private volatile double mSquelchThreshold;
private final PlaylistManager mPlaylistManager;
private ProcessingChain mProcessingChain;
private volatile ProcessingChain mProcessingChain;
/**
* Constructs an instance. Construct on the JavaFX application thread.
* @param playlistManager for saving squelch changes to the channel configuration
*/
public SignalPowerView(PlaylistManager playlistManager)
{
super(10);
mPlaylistManager = playlistManager;
setPadding(new Insets(5));
setLayout(new MigLayout("", "[][][][grow,fill]", "[grow,fill]"));
Label meterTitle = new Label("Power (dB)");
mPowerMeter.setPeakVisible(true);
mPowerMeter.setSquelchThresholdVisible(true);
add(mPowerMeter);
//Follow the themed label text color and font so that the meter is readable in light and dark themes
mPowerMeter.foregroundProperty().bind(meterTitle.textFillProperty());
mPowerMeter.fontProperty().bind(meterTitle.fontProperty());
VBox.setVgrow(mPowerMeter, Priority.ALWAYS);
VBox meterBox = new VBox(3, meterTitle, mPowerMeter);
meterBox.setMinWidth(90);
JPanel valuePanel = new JPanel();
valuePanel.setLayout(new MigLayout("", "[right][left][][]", ""));
mPeakLabel.setTooltip(new Tooltip("Current peak power level in decibels."));
mPowerLabel.setTooltip(new Tooltip("Current Power level in decibels"));
mSquelchValueLabel.setTooltip(new Tooltip("Squelch threshold value in decibels"));
mPeakLabel = new JLabel("0");
mPeakLabel.setToolTipText("Current peak power level in decibels.");
valuePanel.add(new JLabel("Peak:"));
valuePanel.add(mPeakLabel, "wrap");
mSquelchUpButton.setGraphic(icon(FontAwesome.ANGLE_UP));
mSquelchUpButton.setTooltip(new Tooltip("Increases the squelch threshold value"));
mSquelchUpButton.setOnAction(e -> broadcast(SourceEvent.requestSquelchThreshold(null, mSquelchThreshold + 1)));
mPowerLabel = new JLabel("0");
mPowerLabel.setToolTipText("Current Power level in decibels");
valuePanel.add(new JLabel("Power:"));
valuePanel.add(mPowerLabel, "wrap");
mSquelchDownButton.setGraphic(icon(FontAwesome.ANGLE_DOWN));
mSquelchDownButton.setTooltip(new Tooltip("Decreases the squelch threshold value."));
mSquelchDownButton.setOnAction(e -> broadcast(SourceEvent.requestSquelchThreshold(null, mSquelchThreshold - 1)));
mSquelchLabel = new JLabel("Squelch:");
mSquelchLabel.setEnabled(false);
valuePanel.add(mSquelchLabel);
mSquelchValueLabel = new JLabel(NOT_AVAILABLE);
mSquelchValueLabel.setToolTipText("Squelch threshold value in decibels");
mSquelchValueLabel.setEnabled(false);
valuePanel.add(mSquelchValueLabel, "wrap");
IconFontSwing.register(FontAwesome.getIconFont());
Icon iconUp = IconFontSwing.buildIcon(FontAwesome.ANGLE_UP, 12);
mSquelchUpButton = new JButton(iconUp);
mSquelchUpButton.setToolTipText("Increases the squelch threshold value");
mSquelchUpButton.setEnabled(false);
mSquelchUpButton.addActionListener(e -> broadcast(SourceEvent.requestSquelchThreshold(null, mSquelchThreshold + 1)));
valuePanel.add(mSquelchUpButton);
Icon iconDown = IconFontSwing.buildIcon(FontAwesome.ANGLE_DOWN, 12);
mSquelchDownButton = new JButton(iconDown);
mSquelchDownButton.setToolTipText("Decreases the squelch threshold value.");
mSquelchDownButton.setEnabled(false);
mSquelchDownButton.addActionListener(e -> broadcast(SourceEvent.requestSquelchThreshold(null, mSquelchThreshold - 1)));
valuePanel.add(mSquelchDownButton, "wrap");
mSquelchAutoTrackCheckBox = new JCheckBox("Auto Track");
mSquelchAutoTrackCheckBox.setToolTipText("Enable or disable monitoring of the noise floor to auto-adjust the " +
"squelch threshold value maintaining a consistent level/buffer above the noise floor");
mSquelchAutoTrackCheckBox.setEnabled(false);
mSquelchAutoTrackCheckBox.addActionListener(e ->
{
mSquelchAutoTrackCheckBox.setTooltip(new Tooltip("Enable or disable monitoring of the noise floor to " +
"auto-adjust the squelch threshold value maintaining a consistent level/buffer above the noise floor"));
mSquelchAutoTrackCheckBox.setOnAction(e -> {
broadcast(SourceEvent.requestSquelchAutoTrack(mSquelchAutoTrackCheckBox.isSelected()));
setConfigSquelchAutoTrack(mSquelchAutoTrackCheckBox.isSelected());
});
valuePanel.add(mSquelchAutoTrackCheckBox, "span,left");
add(valuePanel);
GridPane values = new GridPane();
values.setHgap(5);
values.setVgap(5);
values.add(new Label("Peak:"), 0, 0);
values.add(mPeakLabel, 1, 0);
values.add(new Label("Power:"), 0, 1);
values.add(mPowerLabel, 1, 1);
values.add(mSquelchLabel, 0, 2);
values.add(mSquelchValueLabel, 1, 2);
values.add(new HBox(3, mSquelchUpButton, mSquelchDownButton), 0, 3, 2, 1);
values.add(mSquelchAutoTrackCheckBox, 0, 4, 2, 1);
values.setAlignment(Pos.TOP_LEFT);
getChildren().addAll(meterBox, values);
reset();
}
private IconNode icon(FontAwesome fontAwesome)
{
IconNode iconNode = new IconNode(fontAwesome);
iconNode.fillProperty().bind(mSquelchLabel.textFillProperty());
return iconNode;
}
/**
@@ -125,9 +135,11 @@ public class SignalPowerView extends JPanel
*/
private void setConfigSquelchThreshold(int threshold)
{
if(mProcessingChain != null)
ProcessingChain processingChain = mProcessingChain;
if(processingChain != null)
{
Channel channel = mPlaylistManager.getChannelProcessingManager().getChannel(mProcessingChain);
Channel channel = mPlaylistManager.getChannelProcessingManager().getChannel(processingChain);
if(channel != null && channel.getDecodeConfiguration() instanceof ISquelchConfiguration configuration)
{
@@ -154,15 +166,16 @@ public class SignalPowerView extends JPanel
private void broadcast(SourceEvent sourceEvent)
{
if(mProcessingChain != null)
ProcessingChain processingChain = mProcessingChain;
if(processingChain != null)
{
mProcessingChain.broadcast(sourceEvent);
processingChain.broadcast(sourceEvent);
}
}
/**
* Resets controls when changing processing chain source. Note: this must be called on the Swing
* dispatch thread because it directly invokes swing components.
* Resets controls when changing processing chain source. Call on the JavaFX application thread.
*/
private void reset()
{
@@ -170,44 +183,53 @@ public class SignalPowerView extends JPanel
mPowerMeter.reset();
mPeakLabel.setText("0");
mPowerLabel.setText("0");
mSquelchLabel.setEnabled(false);
mSquelchValueLabel.setText("Not Available");
mSquelchValueLabel.setEnabled(false);
mSquelchUpButton.setEnabled(false);
mSquelchDownButton.setEnabled(false);
mSquelchAutoTrackCheckBox.setEnabled(false);
mSquelchLabel.setDisable(true);
mSquelchValueLabel.setText(NOT_AVAILABLE);
mSquelchValueLabel.setDisable(true);
mSquelchUpButton.setDisable(true);
mSquelchDownButton.setDisable(true);
mSquelchAutoTrackCheckBox.setDisable(true);
mSquelchAutoTrackCheckBox.setSelected(false);
}
/**
* Processes power and squelch source events from the processing chain. Can be called from any thread.
*/
public void receive(SourceEvent sourceEvent)
{
switch(sourceEvent.getEvent())
{
case NOTIFICATION_CHANNEL_POWER ->
{
final double power = sourceEvent.getValue().doubleValue();
final double peak = mPeakMonitor.process(power);
mPower = sourceEvent.getValue().doubleValue();
mPeak = mPeakMonitor.process(mPower);
EventQueue.invokeLater(() -> {
mPowerMeter.setPower(power);
mPowerLabel.setText(DECIMAL_FORMAT.format(power));
mPowerMeter.setPeak(peak);
mPeakLabel.setText(DECIMAL_FORMAT.format(peak));
});
//Power notifications are frequent, so combine the updates that arrive while one is pending
if(mPowerUpdatePending.compareAndSet(false, true))
{
Platform.runLater(() -> {
mPowerUpdatePending.set(false);
double power = mPower;
double peak = mPeak;
mPowerMeter.setPower(power);
mPowerLabel.setText(DECIMAL_FORMAT.format(power));
mPowerMeter.setPeak(peak);
mPeakLabel.setText(DECIMAL_FORMAT.format(peak));
});
}
}
case NOTIFICATION_SQUELCH_THRESHOLD ->
{
final double threshold = sourceEvent.getValue().doubleValue();
mSquelchThreshold = threshold;
EventQueue.invokeLater(() -> {
Platform.runLater(() -> {
mPowerMeter.setSquelchThreshold(threshold);
mSquelchLabel.setEnabled(true);
mSquelchValueLabel.setEnabled(true);
mSquelchLabel.setDisable(false);
mSquelchValueLabel.setDisable(false);
mSquelchValueLabel.setText(DECIMAL_FORMAT.format(threshold));
mSquelchDownButton.setEnabled(true);
mSquelchUpButton.setEnabled(true);
mSquelchDownButton.setDisable(false);
mSquelchUpButton.setDisable(false);
});
}
case NOTIFICATION_SQUELCH_USER_THRESHOLD ->
@@ -215,16 +237,16 @@ public class SignalPowerView extends JPanel
case NOTIFICATION_SQUELCH_AUTO_TRACK ->
{
boolean autoTrack = sourceEvent.getValue().intValue() == 1;
EventQueue.invokeLater(() -> {
Platform.runLater(() -> {
mSquelchAutoTrackCheckBox.setSelected(autoTrack);
mSquelchAutoTrackCheckBox.setEnabled(true);
mSquelchAutoTrackCheckBox.setDisable(false);
});
}
}
}
/**
* Sets the processing chain for this view
* Sets the processing chain for this view. Call on the JavaFX application thread.
*/
public void setProcessingChain(ProcessingChain processingChain)
{

View File

@@ -27,6 +27,7 @@ import io.github.dsheirer.gui.preference.decoder.JmbeLibraryPreferenceEditor;
import io.github.dsheirer.gui.preference.directory.DirectoryPreferenceEditor;
import io.github.dsheirer.gui.preference.mp3.MP3PreferenceEditor;
import io.github.dsheirer.gui.preference.playback.PlaybackPreferenceEditor;
import io.github.dsheirer.gui.preference.radioreference.RadioReferencePreferenceEditor;
import io.github.dsheirer.gui.preference.record.RecordPreferenceEditor;
import io.github.dsheirer.gui.preference.tuner.TunerPreferenceEditor;
import io.github.dsheirer.preference.UserPreferences;
@@ -59,6 +60,8 @@ public class PreferenceEditorFactory
return new DirectoryPreferenceEditor(userPreferences);
case JMBE_LIBRARY:
return new JmbeLibraryPreferenceEditor(userPreferences);
case RADIO_REFERENCE_ALIAS_LISTS:
return new RadioReferencePreferenceEditor(userPreferences);
case SOURCE_TUNERS:
return new TunerPreferenceEditor(userPreferences);
case TALKGROUP_FORMAT:

View File

@@ -29,6 +29,7 @@ public enum PreferenceEditorType
CHANNEL_EVENT("Channel Events"),
DIRECTORY("Directories"),
JMBE_LIBRARY("JMBE Audio Library"),
RADIO_REFERENCE_ALIAS_LISTS("Alias Lists"),
AUDIO_MP3("MP3"),
AUDIO_RECORD("Record"),
AUDIO_OUTPUT("Playback/Tones"),

View File

@@ -200,6 +200,11 @@ public class UserPreferencesEditor extends BorderPane
treeRoot.getChildren().add(storageItem);
storageItem.setExpanded(true);
TreeItem<String> radioReferenceItem = new TreeItem<>("Radio Reference");
radioReferenceItem.getChildren().add(new TreeItem(PreferenceEditorType.RADIO_REFERENCE_ALIAS_LISTS));
treeRoot.getChildren().add(radioReferenceItem);
radioReferenceItem.setExpanded(true);
TreeItem<String> sourceItem = new TreeItem<>("Source");
sourceItem.getChildren().add(new TreeItem(PreferenceEditorType.SOURCE_TUNERS));
treeRoot.getChildren().add(sourceItem);

View File

@@ -0,0 +1,80 @@
/*
* *****************************************************************************
* 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.preference.radioreference;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.radioreference.AliasListUpdateInterval;
import io.github.dsheirer.preference.radioreference.RadioReferencePreference;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
/**
* Preference settings for alias lists that track a Radio Reference system.
*/
public class RadioReferencePreferenceEditor extends VBox
{
private RadioReferencePreference mRadioReferencePreference;
private ComboBox<AliasListUpdateInterval> mUpdateIntervalComboBox;
public RadioReferencePreferenceEditor(UserPreferences userPreferences)
{
mRadioReferencePreference = userPreferences.getRadioReferencePreference();
setPadding(new Insets(10, 10, 10, 10));
setSpacing(10);
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
Label intervalLabel = new Label("Check Tracked Systems For Talkgroup Changes:");
intervalLabel.setLabelFor(getUpdateIntervalComboBox());
GridPane.setHalignment(intervalLabel, HPos.RIGHT);
gridPane.add(intervalLabel, 0, 0);
gridPane.add(getUpdateIntervalComboBox(), 1, 0);
Label help = new Label("Alias lists that track a Radio Reference system check the system on this schedule " +
"while sdrtrunk is running and a Radio Reference login is stored. Alias lists with Auto-Update enabled " +
"add or update talkgroup aliases when the system changed. Use Refresh Now in the playlist editor's " +
"Aliases tab to update an alias list immediately.");
help.setWrapText(true);
help.setMaxWidth(500);
getChildren().addAll(gridPane, help);
}
private ComboBox<AliasListUpdateInterval> getUpdateIntervalComboBox()
{
if(mUpdateIntervalComboBox == null)
{
mUpdateIntervalComboBox = new ComboBox<>();
mUpdateIntervalComboBox.getItems().addAll(AliasListUpdateInterval.values());
mUpdateIntervalComboBox.getSelectionModel().select(mRadioReferencePreference.getAliasListUpdateInterval());
mUpdateIntervalComboBox.setOnAction(event -> mRadioReferencePreference
.setAliasListUpdateInterval(mUpdateIntervalComboBox.getSelectionModel().getSelectedItem()));
}
return mUpdateIntervalComboBox;
}
}

View File

@@ -0,0 +1,36 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import java.util.List;
/**
* Channel shown in the display's Channels hover card
* @param title of the channel, drawn in the color of its state
* @param details lines
* @param state of the channel: an enabled or disabled playlist channel, or a radio reference candidate
* @param key identifying the channel, e.g. the playlist channel, so the card lists it once, or null
* @param prompts true when the entry is reason to show the card, e.g. the channel's labels don't fit in its box, or
* false when it's only listed while the card is shown for other entries
*/
public record ChannelCardEntry(String title, List<String> details, ChannelMenus.State state, Object key,
boolean prompts)
{
}

View File

@@ -0,0 +1,399 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.channel.ViewChannelRequest;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.WindowEvent;
/**
* Context menu entries of the Channels section, shared by the playlist channel and radio reference layers. Each
* channel is a submenu showing its title and details, like the display's hover cards, with the actions for its state.
* The entries have the display theme's colors: the card background, with the title colored by state - the theme's
* active color (a green) for an enabled playlist channel, its inactive color (a blue) for a disabled one, and its
* plain text color for a radio reference candidate that isn't in the playlist.
*/
public final class ChannelMenus
{
/**
* Context menu section of the channel entries
*/
public static final String SECTION = "Channels";
private static final DecimalFormat FREQUENCY_FORMAT = new DecimalFormat("0.00000");
private static final String STYLE_ITEM = "channel-menu-item";
private static final String STYLE_TITLE = "channel-menu-title";
private static final String STYLE_DETAIL = "channel-menu-detail";
private static final String STYLE_NOTE = "channel-menu-note";
//Minimum contrast ratio of the colored text against the menu background
private static final double MIN_CONTRAST = 3.0;
/**
* State of a channel entry, which sets its color
*/
public enum State
{
ENABLED("channel-menu-enabled"),
DISABLED("channel-menu-disabled"),
CANDIDATE("channel-menu-candidate");
private final String mStyleClass;
State(String styleClass)
{
mStyleClass = styleClass;
}
public String getStyleClass()
{
return mStyleClass;
}
}
private ChannelMenus()
{
}
/**
* Channel entry submenu showing the title and details
* @param title of the channel
* @param details line, or null
* @param state of the channel
* @param key identifying the channel, e.g. the playlist channel, so the display lists it once, or null
*/
public static Menu createEntry(String title, String details, State state, Object key)
{
Label titleLabel = new Label(title);
titleLabel.getStyleClass().add(STYLE_TITLE);
VBox box = new VBox(titleLabel);
if(details != null)
{
Label detailLabel = new Label(details);
detailLabel.getStyleClass().add(STYLE_DETAIL);
box.getChildren().add(detailLabel);
}
Menu menu = new Menu(null, box);
menu.getStyleClass().addAll(STYLE_ITEM, state.getStyleClass());
menu.setUserData(key);
return menu;
}
/**
* Entry for a playlist channel: enable or disable it, and view or edit it in the playlist editor
* @param channel in the playlist
* @param tunerChannel of the channel to describe, or null for the channel's first
* @param toggle that enables the channel when it's disabled or disables it when it's enabled, or null when the
* channel can't be started or stopped from the menu, e.g. a traffic channel
*/
public static Menu createChannelEntry(Channel channel, TunerChannel tunerChannel, Runnable toggle)
{
boolean processing = channel.isProcessing();
State state = getState(channel);
Menu menu = createEntry(getTitle(channel), String.join(" \u00B7 ", getDetails(channel, tunerChannel)), state,
channel);
if(toggle != null)
{
menu.getItems().add(createItem(processing ? "Disable" : "Enable", state, toggle));
}
menu.getItems().add(createItem("View/Edit in Playlist", state,
() -> MyEventBus.getGlobalEventBus().post(new ViewChannelRequest(channel))));
return menu;
}
/**
* Hover card entry for a playlist channel
* @param channel in the playlist
* @param tunerChannel of the channel to describe, or null for the channel's first
* @param prompts true when the entry is reason to show the card
*/
public static ChannelCardEntry createCardEntry(Channel channel, TunerChannel tunerChannel, boolean prompts)
{
//One details line, as in the menu entry, so the card has room for more channels
return new ChannelCardEntry(getTitle(channel), List.of(String.join(" \u00B7 ", getDetails(channel,
tunerChannel))), getState(channel), channel, prompts);
}
/**
* State of a playlist channel
*/
public static State getState(Channel channel)
{
return channel.isProcessing() ? State.ENABLED : State.DISABLED;
}
private static String getTitle(Channel channel)
{
return channel.getName() != null && !channel.getName().isEmpty() ? channel.getName() : "(unnamed)";
}
/**
* Detail lines of a playlist channel: the system and site, then the decoder, frequency and state
* @param tunerChannel of the channel to describe, or null for the channel's first
*/
public static List<String> getDetails(Channel channel, TunerChannel tunerChannel)
{
if(tunerChannel == null)
{
List<TunerChannel> tunerChannels = channel.getTunerChannels();
tunerChannel = tunerChannels.isEmpty() ? null : tunerChannels.get(0);
}
List<String> details = new ArrayList<>();
String systemSite = join(channel.hasSystem() ? channel.getSystem() : null,
channel.hasSite() ? channel.getSite() : null);
if(systemSite != null)
{
details.add(systemSite);
}
details.add(join(channel.getDecodeConfiguration().getDecoderType().getShortDisplayString(),
tunerChannel != null ? FREQUENCY_FORMAT.format(tunerChannel.getFrequency() / 1E6) + " MHz" : null,
channel.isProcessing() ? "Enabled" : "Disabled"));
return details;
}
/**
* Action item of an entry's submenu
*/
public static MenuItem createItem(String text, State state, Runnable action)
{
MenuItem item = new MenuItem(text);
item.getStyleClass().addAll(STYLE_ITEM, state.getStyleClass());
item.setOnAction(event -> action.run());
return item;
}
/**
* Inactive item of an entry's submenu that explains something, e.g. why a candidate can't be added
*/
public static MenuItem createNote(String text)
{
MenuItem item = new MenuItem(text);
item.getStyleClass().addAll(STYLE_ITEM, STYLE_NOTE);
item.setDisable(true);
return item;
}
/**
* Separator of an entry's submenu
*/
public static SeparatorMenuItem createSeparator()
{
SeparatorMenuItem separator = new SeparatorMenuItem();
separator.getStyleClass().add(STYLE_ITEM);
return separator;
}
/**
* Gives the context menu's channel entries the theme's colors. The stylesheet goes into the scenes of the menu
* and the entry submenus, since a popup takes its owner's stylesheets when it's shown and the application theme's
* stylesheets are added to each popup's scene: the more specific rules win in the same scene.
*/
public static void style(ContextMenu menu, SpectralDisplayTheme theme)
{
String stylesheet = createStylesheet(theme);
menu.addEventHandler(WindowEvent.WINDOW_SHOWN, event -> addStylesheet(menu.getScene(), stylesheet));
for(MenuItem item: menu.getItems())
{
if(item instanceof Menu entry && entry.getStyleClass().contains(STYLE_ITEM))
{
//The submenu's popup isn't exposed, but its items' nodes are in its scene once it's showing
EventHandler<Event> handler = event -> {
for(MenuItem child: entry.getItems())
{
Node node = child.getStyleableNode();
if(node != null && node.getScene() != null)
{
addStylesheet(node.getScene(), stylesheet);
return;
}
}
};
entry.setOnShowing(handler);
entry.setOnShown(handler);
}
}
}
private static void addStylesheet(Scene scene, String stylesheet)
{
if(scene != null && !scene.getStylesheets().contains(stylesheet))
{
scene.getStylesheets().add(stylesheet);
}
}
/**
* Stylesheet with the theme's colors
* @return data URL of the stylesheet
*/
static String createStylesheet(SpectralDisplayTheme theme)
{
Color background = opaque(theme.getBackground());
String detail = css(readable(opaque(theme.getLine()), background));
String item = ".menu-item." + STYLE_ITEM;
StringBuilder sb = new StringBuilder();
sb.append(item).append(" { -fx-background-color: ").append(css(background)).append("; }\n");
sb.append(item).append(":focused, ").append(item).append(":hover { -fx-background-color: ")
.append(css(background)).append(", ").append(css(theme.getLine(0.35))).append("; }\n");
sb.append(item).append(":disabled, ").append(item).append(":disabled .label { -fx-opacity: 1; }\n");
for(State state: State.values())
{
String color = css(readable(getColor(theme, state), background));
String stateItem = item + "." + state.getStyleClass();
//The item labels, and the title of an entry
sb.append(textRules(color, stateItem + " .label", stateItem + ":focused .label",
stateItem + ":hover .label"));
}
//More specific than the state rules, so the details keep their color on hover
sb.append(textRules(detail, item + " .label." + STYLE_DETAIL, item + ":focused .label." + STYLE_DETAIL,
item + ":hover .label." + STYLE_DETAIL, item + "." + STYLE_NOTE + " .label"));
sb.append(item).append(" .label.").append(STYLE_TITLE).append(" { -fx-font-weight: bold; }\n");
sb.append(".menu.").append(STYLE_ITEM).append(" > .right-container > .arrow { -fx-background-color: ")
.append(detail).append("; }\n");
sb.append(".separator-menu-item.").append(STYLE_ITEM).append(" { -fx-padding: 0.25em 0; }\n");
sb.append(".separator-menu-item.").append(STYLE_ITEM).append(" > .line { -fx-border-color: ")
.append(css(theme.getLine(0.5)))
.append(" transparent transparent transparent; -fx-border-insets: 0; -fx-padding: 0; }\n");
return "data:text/css;base64," +
Base64.getEncoder().encodeToString(sb.toString().getBytes(StandardCharsets.UTF_8));
}
/**
* Title color of the state: the theme's active color (a green) for an enabled playlist channel, its inactive
* color (a blue) for a disabled one, and its plain text color for a radio reference candidate
*/
public static Color getColor(SpectralDisplayTheme theme, State state)
{
return switch(state)
{
case ENABLED -> theme.getChannelActive();
case DISABLED -> theme.getChannelInactive();
case CANDIDATE -> theme.getText();
};
}
/**
* Color moved toward white on a dark background, or black on a light one, until it's readable on the background
*/
public static Color readable(Color color, Color background)
{
Color target = luminance(background) < 0.5 ? Color.WHITE : Color.BLACK;
Color adjusted = color;
for(int step = 1; step <= 10 && contrast(adjusted, background) < MIN_CONTRAST; step++)
{
adjusted = color.interpolate(target, step / 10.0);
}
return adjusted;
}
static double contrast(Color a, Color b)
{
double la = luminance(a);
double lb = luminance(b);
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
}
private static double luminance(Color color)
{
return (0.2126 * linear(color.getRed())) + (0.7152 * linear(color.getGreen())) +
(0.0722 * linear(color.getBlue()));
}
private static double linear(double channel)
{
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
}
/**
* Rules that set the text color of the labels and of their text nodes. The dark application theme fills each
* label's text node, so both are set.
*/
private static String textRules(String color, String... labelSelectors)
{
String labels = String.join(", ", labelSelectors);
String texts = String.join(" .text, ", labelSelectors) + " .text";
return labels + " { -fx-text-fill: " + color + "; }\n" + texts + " { -fx-fill: " + color + "; }\n";
}
private static Color opaque(Color color)
{
return Color.color(color.getRed(), color.getGreen(), color.getBlue());
}
private static String css(Color color)
{
return String.format(Locale.ROOT, "rgba(%d,%d,%d,%.3f)", Math.round(color.getRed() * 255),
Math.round(color.getGreen() * 255), Math.round(color.getBlue() * 255), color.getOpacity());
}
/**
* Values joined with a middle dot, skipping null and empty values
*/
public static String join(String... values)
{
StringBuilder sb = new StringBuilder();
for(String value: values)
{
if(value != null && !value.isEmpty())
{
if(!sb.isEmpty())
{
sb.append(" · ");
}
sb.append(value);
}
}
return sb.isEmpty() ? null : sb.toString();
}
}

View File

@@ -20,6 +20,12 @@
package io.github.dsheirer.gui.spectrum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
@@ -1120,15 +1126,53 @@ public class SpectralDisplay extends StackPane
double xFraction = width > 0 ? event.getX() / width : 0.5;
ContextMenu menu = new ContextMenu();
//Items of the layers grouped by section, in layer order. A layer without a section is a group of its own.
Map<Object,List<MenuItem>> groups = new LinkedHashMap<>();
Map<Object,Map<Object,MenuItem>> listed = new HashMap<>();
for(SpectralDisplayLayer layer: mLayers)
{
List<MenuItem> items = layer.getContextMenuItems(pane.getSection(), frequency);
if(items != null && !items.isEmpty())
if(items == null || items.isEmpty())
{
menu.getItems().addAll(items);
menu.getItems().add(new SeparatorMenuItem());
continue;
}
Object key = layer.getContextMenuSection() != null ? layer.getContextMenuSection() : layer;
List<MenuItem> group = groups.computeIfAbsent(key, k -> new ArrayList<>());
Map<Object,MenuItem> keys = listed.computeIfAbsent(key, k -> new IdentityHashMap<>());
for(MenuItem item: items)
{
MenuItem earlier = item.getUserData() != null ? keys.get(item.getUserData()) : null;
if(earlier != null)
{
//The same channel from another layer is listed once, with the other layer's options added
mergeOptions(earlier, item);
}
else
{
if(item.getUserData() != null)
{
keys.put(item.getUserData(), item);
}
group.add(item);
}
}
}
for(Map.Entry<Object,List<MenuItem>> group: groups.entrySet())
{
if(group.getKey() instanceof String section)
{
menu.getItems().add(SpectralDisplayLayer.createSectionHeader(section));
}
menu.getItems().addAll(group.getValue());
menu.getItems().add(new SeparatorMenuItem());
}
Menu zoomMenu = new Menu("Zoom");
@@ -1154,11 +1198,97 @@ public class SpectralDisplay extends StackPane
menu.getItems().add(pause);
}
alignLabels(menu.getItems());
ChannelMenus.style(menu, getTheme());
mContextMenu = menu;
menu.show(pane, event.getScreenX(), event.getScreenY());
event.consume();
}
/**
* Adds the submenu options of a later entry for the same channel that the earlier entry doesn't have, e.g. the
* radio reference layer's option to view a playlist channel's listing. When the later entry has all of the
* earlier entry's options, the earlier entry takes the later entry's options in their order, otherwise the
* missing options are added after a separator.
*/
private static void mergeOptions(MenuItem earlier, MenuItem later)
{
if(!(earlier instanceof Menu earlierMenu) || !(later instanceof Menu laterMenu))
{
return;
}
Set<String> earlierTexts = getOptionTexts(earlierMenu);
Set<String> laterTexts = getOptionTexts(laterMenu);
if(laterTexts.containsAll(earlierTexts))
{
if(laterTexts.size() > earlierTexts.size())
{
//Items belong to one menu, so they're moved
List<MenuItem> options = new ArrayList<>(laterMenu.getItems());
laterMenu.getItems().clear();
earlierMenu.getItems().setAll(options);
}
return;
}
List<MenuItem> added = new ArrayList<>();
for(MenuItem option: laterMenu.getItems())
{
if(!(option instanceof SeparatorMenuItem) && option.getText() != null &&
!earlierTexts.contains(option.getText()))
{
added.add(option);
}
}
if(!added.isEmpty())
{
laterMenu.getItems().removeAll(added);
earlierMenu.getItems().add(ChannelMenus.createSeparator());
earlierMenu.getItems().addAll(added);
}
}
private static Set<String> getOptionTexts(Menu menu)
{
Set<String> texts = new HashSet<>();
for(MenuItem option: menu.getItems())
{
if(!(option instanceof SeparatorMenuItem) && option.getText() != null)
{
texts.add(option.getText());
}
}
return texts;
}
/**
* A context menu places item text in a column after the widest graphic, so when a layer's items show their
* content as a graphic, the text of the other items is moved into a graphic too, to line up on the left.
*/
private static void alignLabels(List<MenuItem> items)
{
if(items.stream().noneMatch(item -> item.getGraphic() != null && !(item instanceof SeparatorMenuItem)))
{
return;
}
for(MenuItem item: items)
{
if(item.getGraphic() == null && item.getText() != null && !(item instanceof SeparatorMenuItem))
{
item.setGraphic(new Label(item.getText()));
item.setText(null);
}
}
}
/**
* Resizable pane that holds a canvas for one display section.
*/

View File

@@ -147,6 +147,44 @@ public abstract class SpectralDisplayLayer
return Collections.emptyList();
}
/**
* Channels at the mouse position for the display's Channels hover card (see
* {@link io.github.dsheirer.gui.spectrum.layer.ChannelCardLayer}). Called on the JavaFX application thread while
* the mouse rests over the display, so it should be quick.
* @param cursor mouse position
* @param area of the section under the mouse
* @return entries, or an empty list
*/
public List<ChannelCardEntry> getCardEntries(DisplayCursor cursor, RenderArea area)
{
return Collections.emptyList();
}
/**
* Context menu section of this layer's items. The items of layers with the same section are listed together
* under a header with the section name, each item once: an item whose user data is the same object as an earlier
* item's in the section is left out.
* @return section name, or null for items of their own without a header
*/
public String getContextMenuSection()
{
return null;
}
/**
* Section header for context menu items: an inactive item with smaller bold text in the theme's text color,
* slightly faded. Inline styles, since the application theme's stylesheets are added to each popup's scene.
* @param title of the section
*/
public static MenuItem createSectionHeader(String title)
{
MenuItem header = new MenuItem(title);
header.setDisable(true);
header.getStyleClass().add("spectral-menu-section-header");
header.setStyle("-fx-opacity: 0.6; -fx-font-size: 0.85em; -fx-font-weight: bold;");
return header;
}
/**
* Title of this layer's section in the configuration panel, or null to place the layer's rows in the panel's
* Display section instead of a section of their own.

View File

@@ -239,6 +239,74 @@ public enum SpectralDisplayTheme
return mCorrection;
}
/**
* Text color for an active (enabled) playlist channel in the Channels menu and card: a green that reads as
* active on the theme's background, or the theme's own highlight in the monochrome themes. Red/green color
* blind themes use a yellowish green and blue/yellow color blind themes a green that stays distinct from
* {@link #getChannelInactive()}.
*/
public Color getChannelActive()
{
return Color.web(switch(this)
{
case CLASSIC -> "#33E633";
case DARK -> "#66BB6A";
case MEDIUM -> "#81C784";
case LIGHT -> "#2E7D32";
case GREEN_PHOSPHOR -> "#66FF8C";
case AMBER -> "#FFC233";
case GRAYSCALE -> "#FFFFFF";
case HIGH_CONTRAST_DARK -> "#00FF00";
case HIGH_CONTRAST_LIGHT -> "#006400";
case VIRIDIS -> "#6DCD59";
case CIVIDIS -> "#B4DE2C";
case INFERNO -> "#4CC764";
});
}
/**
* Text color for an inactive (disabled) playlist channel in the Channels menu and card: a blue that reads as
* inactive on the theme's background, or a dimmed shade in the monochrome themes. The blue/yellow color blind
* theme uses a pink, since blue and green look alike there.
*/
public Color getChannelInactive()
{
return Color.web(switch(this)
{
case CLASSIC -> "#4D9FFF";
case DARK -> "#64B5F6";
case MEDIUM -> "#90CAF9";
case LIGHT -> "#1565C0";
case GREEN_PHOSPHOR -> "#3FAF5C";
case AMBER -> "#B07A10";
case GRAYSCALE -> "#8C8C8C";
case HIGH_CONTRAST_DARK -> "#00BFFF";
case HIGH_CONTRAST_LIGHT -> "#0000C0";
case VIRIDIS -> "#5B9BF0";
case CIVIDIS -> "#56B4E9";
case INFERNO -> "#E879C6";
});
}
/**
* Plain text color on the theme's background, e.g. for menu entries that aren't highlighted
*/
public Color getText()
{
return Color.web(switch(this)
{
case CLASSIC, HIGH_CONTRAST_DARK -> "#FFFFFF";
case DARK -> "#E6E8EB";
case MEDIUM -> "#F0F4F8";
case LIGHT -> "#212529";
case GREEN_PHOSPHOR -> "#CCFFCC";
case AMBER -> "#FFF0C2";
case GRAYSCALE -> "#D0D0D0";
case HIGH_CONTRAST_LIGHT -> "#000000";
case VIRIDIS, CIVIDIS, INFERNO -> "#E8E8EE";
});
}
/**
* ARGB color for the waterfall intensity index (0 - 255).
*/

View File

@@ -22,6 +22,7 @@ package io.github.dsheirer.gui.spectrum;
import io.github.dsheirer.controller.channel.ChannelModel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.spectrum.layer.ChannelCardLayer;
import io.github.dsheirer.gui.spectrum.layer.ChannelLayer;
import io.github.dsheirer.gui.spectrum.layer.RadioReferenceLayer;
import io.github.dsheirer.playlist.PlaylistManager;
@@ -104,8 +105,8 @@ public class TunerSpectralDisplay extends DftSpectralDisplay implements ISourceE
private TunerSpectralDisplay(ChannelLayer channelLayer, RadioReferenceLayer radioReferenceLayer,
DiscoveredTunerModel discoveredTunerModel, boolean saveSettings)
{
//The radio reference layer draws after the channel layer, so its card is on top
super(SETTINGS_PREFIX, saveSettings, channelLayer, radioReferenceLayer);
//The channels card draws after the other layers, so it's on top
super(SETTINGS_PREFIX, saveSettings, channelLayer, radioReferenceLayer, new ChannelCardLayer());
mChannelLayer = channelLayer;
mRadioReferenceLayer = radioReferenceLayer;
mDiscoveredTunerModel = discoveredTunerModel;

View File

@@ -0,0 +1,430 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum.layer;
import io.github.dsheirer.gui.spectrum.ChannelCardEntry;
import io.github.dsheirer.gui.spectrum.ChannelMenus;
import io.github.dsheirer.gui.spectrum.CursorReadout;
import io.github.dsheirer.gui.spectrum.DisplayCursor;
import io.github.dsheirer.gui.spectrum.DisplaySection;
import io.github.dsheirer.gui.spectrum.RenderArea;
import io.github.dsheirer.gui.spectrum.SpectralDisplayLayer;
import io.github.dsheirer.gui.spectrum.SpectralDisplayModel;
import io.github.dsheirer.gui.spectrum.SpectralDisplayTheme;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import javafx.animation.PauseTransition;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
/**
* Channels hover card. When the mouse rests over the spectrum or the waterfall, shows a card next to the mouse with
* the channels at the mouse position that the other layers provide (see
* {@link SpectralDisplayLayer#getCardEntries}): playlist channels first, then radio reference candidates. The titles
* have the colors of the Channels context menu entries: one for an enabled playlist channel, one for a disabled one
* and one for a candidate. The card replaces the cursor readout and ends with the readout lines.
*
* The card is shown when an entry prompts it, e.g. a playlist channel whose labels don't fit in its box or a
* candidate; the other channels at the mouse position are then listed too.
*/
public class ChannelCardLayer extends SpectralDisplayLayer
{
private static final Duration HOVER_DELAY = Duration.millis(400);
private static final Font FONT = Font.font(11);
private static final Font TITLE_FONT = Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 11);
private static final int MAX_ENTRIES = 6;
private static final double MAX_TEXT_WIDTH = 380;
private static final double PADDING = 6;
private static final double GAP = 5;
//Space beside the text and below the readout lines, as in the cursor readout, so the readout lines stay in place
private static final double PADDING_X = 4;
//Space kept between the card and the edges of the section
private static final double EDGE_MARGIN = 2;
private static final double READOUT_PADDING = 2;
private static final String HEADER = ChannelMenus.SECTION;
private final Text mMeasure = new Text();
private final double mTextHeight;
private PauseTransition mHoverTimer;
private DisplaySection mHoverSection;
private double mHoverX = Double.NaN;
private double mHoverY = Double.NaN;
private boolean mHoverReady;
private List<ChannelCardEntry> mEntries = Collections.emptyList();
private Card mCard;
/**
* Card text, measured when the entries or the room change
* @param entries lines of each shown entry: the title, then the details
* @param states of the shown entries
* @param more line, or null
* @param textWidth of the widest line
* @param lineCount of the header, entry and more lines
* @param source entries the card was made from
* @param maxTextWidth that the lines were shortened to
* @param maxHeight that the card was limited to
* @param readoutLines that the card was sized for
*/
private record Card(List<List<String>> entries, List<ChannelMenus.State> states, String more, double textWidth,
int lineCount, List<ChannelCardEntry> source, double maxTextWidth, double maxHeight,
int readoutLines)
{
}
/**
* Constructs an instance
*/
public ChannelCardLayer()
{
mMeasure.setFont(FONT);
mMeasure.setText("Ag");
mTextHeight = Math.ceil(mMeasure.getLayoutBounds().getHeight());
}
@Override
public void dispose()
{
if(mHoverTimer != null)
{
mHoverTimer.stop();
}
}
@Override
public void renderSpectrumForeground(GraphicsContext gc, RenderArea area)
{
render(gc, area, DisplaySection.SPECTRUM);
}
@Override
public void renderWaterfall(GraphicsContext gc, RenderArea area)
{
render(gc, area, DisplaySection.WATERFALL);
}
/**
* Draws the card in the section under the mouse once the mouse has rested for the hover delay
*/
private void render(GraphicsContext gc, RenderArea area, DisplaySection section)
{
DisplayCursor cursor = getSpectralDisplay() != null ? getSpectralDisplay().getDisplayCursor() : null;
trackHover(cursor);
if(cursor != null && cursor.section() == section && replacesCursorReadout(cursor, area))
{
drawCard(gc, area, cursor, mEntries);
}
}
/**
* The card replaces the cursor readout while it's shown: it ends with the readout lines, in the readout's place.
*/
@Override
public boolean replacesCursorReadout(DisplayCursor cursor, RenderArea area)
{
SpectralDisplayModel model = getModel();
//Only for the position the mouse rested at - the readout comes back as soon as the mouse moves
if(!mHoverReady || model == null || !model.hasSource() || cursor == null || cursor.section() != mHoverSection ||
cursor.x() != mHoverX || cursor.y() != mHoverY || area.width() <= 0)
{
return false;
}
mEntries = getEntries(cursor, area);
return mEntries.stream().anyMatch(ChannelCardEntry::prompts);
}
/**
* Entries of the other layers, each channel once, playlist channels first
*/
private List<ChannelCardEntry> getEntries(DisplayCursor cursor, RenderArea area)
{
List<ChannelCardEntry> entries = new ArrayList<>();
Set<Object> keys = Collections.newSetFromMap(new IdentityHashMap<>());
for(SpectralDisplayLayer layer: getSpectralDisplay().getLayers())
{
if(layer == this)
{
continue;
}
for(ChannelCardEntry entry: layer.getCardEntries(cursor, area))
{
if(entry.key() == null || keys.add(entry.key()))
{
entries.add(entry);
}
}
}
entries.sort(Comparator.comparing(entry -> entry.state() == ChannelMenus.State.CANDIDATE));
return entries;
}
/**
* Restarts the hover delay each time the mouse moves, and hides the card until it passes
*/
private void trackHover(DisplayCursor cursor)
{
if(cursor == null)
{
if(mHoverSection != null)
{
mHoverSection = null;
mHoverReady = false;
getHoverTimer().stop();
}
return;
}
if(cursor.section() != mHoverSection || cursor.x() != mHoverX || cursor.y() != mHoverY)
{
mHoverSection = cursor.section();
mHoverX = cursor.x();
mHoverY = cursor.y();
mHoverReady = false;
getHoverTimer().playFromStart();
}
}
private PauseTransition getHoverTimer()
{
if(mHoverTimer == null)
{
mHoverTimer = new PauseTransition(HOVER_DELAY);
mHoverTimer.setOnFinished(event -> {
mHoverReady = true;
requestRender();
});
}
return mHoverTimer;
}
/**
* Draws the card in place of the cursor readout: beside the mouse and above it, placed like the readout, with the
* channels above the readout lines so the frequency and level stay where the readout showed them. The card fits
* the larger side of the mouse and the height of the section, showing as many channels as fit.
*/
private void drawCard(GraphicsContext gc, RenderArea area, DisplayCursor cursor, List<ChannelCardEntry> entries)
{
//The level line changes with the mouse height while the channels don't
List<String> readout = CursorReadout.lines(cursor, area, getModel());
double readoutWidth = 0;
for(String line: readout)
{
readoutWidth = Math.max(readoutWidth, measure(line, FONT));
}
double room = Math.max(area.width() - cursor.x(), cursor.x()) - CursorReadout.GAP_X - EDGE_MARGIN;
double maxTextWidth = Math.max(readoutWidth, Math.min(MAX_TEXT_WIDTH, room - (PADDING_X * 2)));
//Above the mouse, so the readout lines stay where the readout showed them, when an entry fits there
double above = cursor.y() - CursorReadout.GAP_Y;
double maxHeight = above >= cardHeight(5, 1, true, readout.size()) ? above : area.plotHeight() - EDGE_MARGIN;
if(mCard == null || !mCard.source().equals(entries) || mCard.maxTextWidth() != maxTextWidth ||
mCard.maxHeight() != maxHeight || mCard.readoutLines() != readout.size())
{
mCard = createCard(entries, maxTextWidth, maxHeight, readout.size());
}
Card card = mCard;
SpectralDisplayTheme theme = getSpectralDisplay().getTheme();
Color background = opaque(theme.getBackground());
Color detail = opaque(theme.getLine());
double width = Math.max(card.textWidth(), readoutWidth) + (PADDING_X * 2);
double height = cardHeight(card.lineCount(), card.entries().size(), card.more() != null, readout.size());
double x = Math.max(0, CursorReadout.x(cursor, width, area));
double y = CursorReadout.y(cursor, height, area);
gc.setFill(theme.getBackground(0.92));
gc.fillRoundRect(x, y, width, height, 8, 8);
gc.setStroke(detail);
gc.setLineWidth(1.0);
gc.strokeRoundRect(Math.floor(x) + 0.5, Math.floor(y) + 0.5, width, height, 8, 8);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.TOP);
double textX = x + PADDING_X;
double lineY = y + PADDING;
gc.setFill(detail);
gc.setFont(TITLE_FONT);
gc.fillText(HEADER, textX, lineY);
lineY += mTextHeight + GAP;
for(int index = 0; index < card.entries().size(); index++)
{
List<String> lines = card.entries().get(index);
gc.setFill(ChannelMenus.readable(ChannelMenus.getColor(theme, card.states().get(index)), background));
gc.setFont(TITLE_FONT);
gc.fillText(lines.get(0), textX, lineY);
lineY += mTextHeight;
gc.setFill(detail);
gc.setFont(FONT);
for(int line = 1; line < lines.size(); line++)
{
gc.fillText(lines.get(line), textX, lineY);
lineY += mTextHeight;
}
lineY += GAP;
}
if(card.more() != null)
{
gc.setFill(detail);
gc.setFont(FONT);
gc.fillText(card.more(), textX, lineY);
lineY += mTextHeight + GAP;
}
//The readout lines, separated from the channels, in the readout's style
double separator = Math.floor(lineY - (GAP / 2.0)) + 0.5;
gc.setStroke(theme.getLine(0.5));
gc.strokeLine(textX, separator, x + width - PADDING_X, separator);
gc.setFill(theme.getCursor());
gc.setFont(FONT);
for(String line: readout)
{
gc.fillText(line, textX, lineY);
lineY += mTextHeight;
}
}
/**
* Height of a card with the lines
* @param lineCount of the header, entry and more lines
* @param entries number of entries
* @param more true when the card has a more line
* @param readoutLines number of readout lines
*/
private double cardHeight(int lineCount, int entries, boolean more, int readoutLines)
{
int gaps = 1 + entries + (more ? 1 : 0);
return ((lineCount + readoutLines) * mTextHeight) + (gaps * GAP) + PADDING + READOUT_PADDING;
}
/**
* Card text for as many entries as fit the height, shortened to the width
*/
private Card createCard(List<ChannelCardEntry> source, double maxTextWidth, double maxHeight, int readoutLines)
{
int limit = Math.min(source.size(), MAX_ENTRIES);
List<List<String>> entries = new ArrayList<>();
List<ChannelMenus.State> states = new ArrayList<>();
double textWidth = measure(HEADER, TITLE_FONT);
int lineCount = 1;
for(int index = 0; index < limit; index++)
{
ChannelCardEntry entry = source.get(index);
List<String> lines = new ArrayList<>();
lines.add(fit(entry.title(), TITLE_FONT, maxTextWidth));
for(String detail: entry.details())
{
if(detail != null)
{
lines.add(fit(detail, FONT, maxTextWidth));
}
}
//Keep room for the more line when entries are left out
boolean more = index + 1 < source.size();
if(!entries.isEmpty() && cardHeight(lineCount + lines.size() + (more ? 1 : 0), entries.size() + 1, more,
readoutLines) > maxHeight)
{
break;
}
textWidth = Math.max(textWidth, measure(lines.get(0), TITLE_FONT));
for(int line = 1; line < lines.size(); line++)
{
textWidth = Math.max(textWidth, measure(lines.get(line), FONT));
}
lineCount += lines.size();
entries.add(lines);
states.add(entry.state());
}
String more = source.size() > entries.size() ? "+ " + (source.size() - entries.size()) + " more" : null;
if(more != null)
{
textWidth = Math.max(textWidth, measure(more, FONT));
lineCount++;
}
return new Card(entries, states, more, textWidth, lineCount, source, maxTextWidth, maxHeight, readoutLines);
}
/**
* Text shortened with an ellipsis to fit the width
*/
private String fit(String text, Font font, double maxWidth)
{
if(measure(text, font) <= maxWidth)
{
return text;
}
int length = text.length();
while(length > 1 && measure(text.substring(0, length) + "…", font) > maxWidth)
{
length--;
}
return text.substring(0, length) + "…";
}
private double measure(String text, Font font)
{
mMeasure.setFont(font);
mMeasure.setText(text);
double width = mMeasure.getLayoutBounds().getWidth();
mMeasure.setFont(FONT);
return width;
}
private static Color opaque(Color color)
{
return Color.color(color.getRed(), color.getGreen(), color.getBlue());
}
}

View File

@@ -24,8 +24,8 @@ import io.github.dsheirer.controller.channel.ChannelEvent;
import io.github.dsheirer.controller.channel.ChannelException;
import io.github.dsheirer.controller.channel.ChannelModel;
import io.github.dsheirer.controller.channel.ChannelProcessingManager;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.channel.ViewChannelRequest;
import io.github.dsheirer.gui.spectrum.ChannelCardEntry;
import io.github.dsheirer.gui.spectrum.ChannelMenus;
import io.github.dsheirer.gui.spectrum.ConfigurationRow;
import io.github.dsheirer.gui.spectrum.DisplayCursor;
import io.github.dsheirer.gui.spectrum.DisplaySection;
@@ -56,7 +56,6 @@ import javafx.scene.control.MenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
@@ -66,24 +65,20 @@ import javafx.scene.text.TextAlignment;
* decoder. Processing and selected channels use their own colors. When the decoder applies a frequency correction,
* a bracket at the bottom of the box shows the corrected channel position and the PPM error.
*
* When the zoom level is too low for a channel's labels to fit in its box, moving the mouse over the channel shows a
* popout card near the bottom of the spectrum (or the waterfall) with the channel name, system, site, decoder,
* frequency and state. The popout can be turned off with the hover details setting.
* When the zoom level is too low for a channel's labels to fit in its box, resting the mouse over the channel lists
* it in the Channels hover card (drawn by {@link ChannelCardLayer}) with its system, site, decoder, frequency and
* state. This can be turned off with the hover details setting.
*
* Right-clicking a channel adds a menu item to view or edit the channel in the playlist editor.
* Right-clicking a channel lists it in the Channels context menu, to enable or disable it or view or edit it in the
* playlist editor.
*/
public class ChannelLayer extends SpectralDisplayLayer
{
private static final Font FONT = Font.font(11);
private static final DecimalFormat PPM_FORMAT = new DecimalFormat("0.0");
private static final DecimalFormat FREQUENCY_FORMAT = new DecimalFormat("0.00000");
private static final Font POPOUT_TITLE_FONT = Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 11);
private static final double MIN_LABEL_BOX_WIDTH = 12;
private static final double POPOUT_MIN_HIT_WIDTH = 10;
private static final double POPOUT_PADDING = 6;
private static final double POPOUT_GAP = 5;
private static final double POPOUT_SWATCH = 8;
private static final int POPOUT_MAX_CHANNELS = 4;
private static final double MIN_HIT_WIDTH = 10;
/**
* Which channels the layer shows.
@@ -382,131 +377,23 @@ public class ChannelLayer extends SpectralDisplayLayer
}
}
}
renderPopout(gc, area, DisplaySection.SPECTRUM);
}
@Override
public void renderWaterfall(GraphicsContext gc, RenderArea area)
{
renderPopout(gc, area, DisplaySection.WATERFALL);
}
/**
* Draws a card near the bottom of the section under the mouse with the details of each channel under the mouse
* whose labels don't fit in its box at the current zoom. The card moves to the top of the section when the mouse
* is over the bottom of the section.
* Card entries for the channels under the mouse. A channel whose labels don't fit in its box at the current
* zoom prompts the card. The hit area of a narrow channel is widened so it can be found with the mouse.
*/
private void renderPopout(GraphicsContext gc, RenderArea area, DisplaySection section)
@Override
public List<ChannelCardEntry> getCardEntries(DisplayCursor cursor, RenderArea area)
{
SpectralDisplayModel model = getModel();
DisplayCursor cursor = getSpectralDisplay().getDisplayCursor();
List<ChannelCardEntry> entries = new ArrayList<>();
if(!mHoverDetails.get() || model == null || !model.hasSource() || cursor == null ||
cursor.section() != section || mChannelDisplay.get() == ChannelDisplay.NONE)
if(!mHoverDetails.get() || model == null || mChannelDisplay.get() == ChannelDisplay.NONE)
{
return;
return entries;
}
List<PopoutEntry> entries = getPopoutEntries(model, area, cursor.x());
if(entries.isEmpty())
{
return;
}
SpectralDisplayTheme theme = getSpectralDisplay().getTheme();
int shown = Math.min(entries.size(), POPOUT_MAX_CHANNELS);
String more = entries.size() > shown ? "+ " + (entries.size() - shown) + " more" : null;
//Measure the card
double textWidth = 0;
int lineCount = 0;
for(int x = 0; x < shown; x++)
{
PopoutEntry entry = entries.get(x);
textWidth = Math.max(textWidth, measure(entry.title(), POPOUT_TITLE_FONT) + POPOUT_SWATCH + 5);
for(String line: entry.details())
{
textWidth = Math.max(textWidth, measure(line, FONT));
}
lineCount += 1 + entry.details().size();
}
if(more != null)
{
textWidth = Math.max(textWidth, measure(more, FONT));
lineCount++;
}
double width = textWidth + (POPOUT_PADDING * 2);
double height = (lineCount * mTextHeight) + ((shown - 1) * POPOUT_GAP) + (POPOUT_PADDING * 2);
double bottom = section == DisplaySection.SPECTRUM ? area.plotHeight() : area.height();
double x = Math.max(4, Math.min(area.width() - width - 4, cursor.x() - (width / 2.0)));
double y = bottom - height - 6;
//Keep the card out from under the mouse
if(cursor.y() >= y - 4)
{
y = 6;
}
if(y < 0 || width > area.width())
{
return;
}
gc.setFill(theme.getBackground(0.88));
gc.fillRoundRect(x, y, width, height, 8, 8);
gc.setStroke(opaque(theme.getLine()));
gc.setLineWidth(1.0);
gc.strokeRoundRect(Math.floor(x) + 0.5, Math.floor(y) + 0.5, width, height, 8, 8);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.TOP);
double lineY = y + POPOUT_PADDING;
double textX = x + POPOUT_PADDING;
for(int index = 0; index < shown; index++)
{
PopoutEntry entry = entries.get(index);
double swatchY = lineY + ((mTextHeight - POPOUT_SWATCH) / 2.0);
gc.setFill(opaque(entry.color()));
gc.fillRect(textX, swatchY, POPOUT_SWATCH, POPOUT_SWATCH);
gc.setFill(theme.getCursor());
gc.setFont(POPOUT_TITLE_FONT);
gc.fillText(entry.title(), textX + POPOUT_SWATCH + 5, lineY);
lineY += mTextHeight;
gc.setFill(opaque(theme.getLine()));
gc.setFont(FONT);
for(String line: entry.details())
{
gc.fillText(line, textX, lineY);
lineY += mTextHeight;
}
lineY += POPOUT_GAP;
}
if(more != null)
{
gc.fillText(more, textX, lineY - POPOUT_GAP);
}
}
/**
* Channels under the screen x position whose labels don't fit in the channel box. The hit area of a narrow
* channel is widened so it can be found with the mouse.
*/
private List<PopoutEntry> getPopoutEntries(SpectralDisplayModel model, RenderArea area, double cursorX)
{
List<PopoutEntry> entries = new ArrayList<>();
SpectralDisplayTheme theme = getSpectralDisplay().getTheme();
for(Channel channel: getChannels(model))
{
if(!isShown(channel))
@@ -523,38 +410,14 @@ public class ChannelLayer extends SpectralDisplayLayer
continue;
}
double hitWidth = Math.max(POPOUT_MIN_HIT_WIDTH, box.width());
double hitWidth = Math.max(MIN_HIT_WIDTH, box.width());
double hitStart = box.center() - (hitWidth / 2.0);
if(cursorX < hitStart || cursorX > hitStart + hitWidth || labelsFit(channel, box))
if(cursor.x() >= hitStart && cursor.x() <= hitStart + hitWidth)
{
continue;
entries.add(ChannelMenus.createCardEntry(channel, tunerChannel, !labelsFit(channel, box)));
break;
}
List<String> details = new ArrayList<>();
String systemSite = join(channel.hasSystem() ? channel.getSystem() : null,
channel.hasSite() ? channel.getSite() : null);
if(systemSite != null)
{
details.add(systemSite);
}
String state = channel.isProcessing() ? "Enabled" : "Disabled";
if(channel.isSelected())
{
state += ", Selected";
}
details.add(join(channel.getDecodeConfiguration().getDecoderType().getShortDisplayString(),
FREQUENCY_FORMAT.format(tunerChannel.getFrequency() / 1E6) + " MHz", state));
Color color = channel.isSelected() ? theme.getChannelSelected() :
channel.isProcessing() ? theme.getChannelProcessing() : theme.getChannel();
entries.add(new PopoutEntry(channel.getName() != null ? channel.getName() : "(unnamed)", details,
color));
break;
}
}
@@ -723,14 +586,9 @@ public class ChannelLayer extends SpectralDisplayLayer
frequency <= tunerChannel.getMaxFrequency())
{
//Traffic channels are started and stopped by their decoder, not from the playlist
if(!channel.isTrafficChannel() && mChannelProcessingManager != null)
{
items.add(createEnableItem(channel));
}
MenuItem item = new MenuItem("View/Edit: " + channel.getShortTitle());
item.setOnAction(e -> MyEventBus.getGlobalEventBus().post(new ViewChannelRequest(channel)));
items.add(item);
Runnable toggle = !channel.isTrafficChannel() && mChannelProcessingManager != null ?
() -> toggle(channel) : null;
items.add(ChannelMenus.createChannelEntry(channel, tunerChannel, toggle));
break;
}
}
@@ -739,14 +597,20 @@ public class ChannelLayer extends SpectralDisplayLayer
return items;
}
@Override
public String getContextMenuSection()
{
return ChannelMenus.SECTION;
}
/**
* Menu item that starts the channel when it's disabled, or stops it when it's enabled, in the background
* Stops the channel when it's processing, otherwise starts it
*/
private MenuItem createEnableItem(Channel channel)
private void toggle(Channel channel)
{
boolean processing = channel.isProcessing();
MenuItem item = new MenuItem((processing ? "Disable: " : "Enable: ") + channel.getShortTitle());
item.setOnAction(e -> ThreadPool.CACHED.execute(() -> {
ThreadPool.CACHED.execute(() -> {
try
{
if(processing)
@@ -762,8 +626,7 @@ public class ChannelLayer extends SpectralDisplayLayer
{
showError((processing ? "Can't stop " : "Can't start ") + channel.getShortTitle(), ce.getMessage());
}
}));
return item;
});
}
/**
@@ -792,10 +655,4 @@ public class ChannelLayer extends SpectralDisplayLayer
{
}
/**
* Channel details for the popout card.
*/
private record PopoutEntry(String title, List<String> details, Color color)
{
}
}

View File

@@ -20,24 +20,27 @@
package io.github.dsheirer.gui.spectrum.layer;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.playlist.radioreference.ViewRadioReferenceRequest;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.module.decode.DecoderType;
import io.github.dsheirer.service.radioreference.SiteRecord;
import io.github.dsheirer.source.tuner.channel.TunerChannel;
import java.util.HashSet;
import java.util.Set;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import io.github.dsheirer.gui.spectrum.ChannelCardEntry;
import io.github.dsheirer.gui.spectrum.ChannelMenus;
import io.github.dsheirer.gui.spectrum.ChannelMenus.State;
import io.github.dsheirer.gui.spectrum.ConfigurationRow;
import io.github.dsheirer.gui.spectrum.CursorReadout;
import io.github.dsheirer.gui.spectrum.DisplayCursor;
import io.github.dsheirer.gui.spectrum.DisplaySection;
import io.github.dsheirer.gui.spectrum.RenderArea;
import io.github.dsheirer.gui.spectrum.SpectralDisplayLayer;
import io.github.dsheirer.gui.spectrum.SpectralDisplayModel;
import io.github.dsheirer.gui.spectrum.SpectralDisplayTheme;
import io.github.dsheirer.service.radioreference.DistanceFormat;
import io.github.dsheirer.service.radioreference.FrequencyCandidate;
import io.github.dsheirer.service.radioreference.RadioReferenceFrequencyIndex;
@@ -45,76 +48,37 @@ import io.github.dsheirer.service.radioreference.RadioReferenceFrequencyIndex.Ra
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javafx.animation.PauseTransition;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
/**
* Radio reference candidates layer. When the mouse rests over the spectrum or the waterfall, shows a card next to the
* mouse with the radio reference frequencies near the frequency under the mouse, nearest to the user's location first.
* Radio reference candidates layer. Lists the radio reference frequencies near the frequency under the mouse,
* nearest to the user's location first, in the Channels hover card (drawn by {@link ChannelCardLayer}) and the
* Channels context menu. A candidate that a playlist channel already decodes is listed as that channel.
*
* The candidates come from the radio reference frequency index, which needs a premium account and the user's location.
* Looking up a frequency doesn't call the web service.
*/
public class RadioReferenceLayer extends SpectralDisplayLayer
{
private static final Duration HOVER_DELAY = Duration.millis(400);
private static final Font FONT = Font.font(11);
private static final Font TITLE_FONT = Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 11);
private static final DecimalFormat FREQUENCY_FORMAT = new DecimalFormat("0.00000");
private static final long MIN_TOLERANCE_HZ = 3_000;
private static final double TOLERANCE_PIXELS = 3.0;
private static final int MAX_CANDIDATES = 6;
private static final double MAX_TEXT_WIDTH = 380;
private static final double PADDING = 6;
private static final double GAP = 5;
//Space beside the text and below the readout lines, as in the cursor readout, so the readout lines stay in place
private static final double PADDING_X = 4;
//Space kept between the card and the edges of the section
private static final double EDGE_MARGIN = 2;
private static final double READOUT_PADDING = 2;
private static final String HEADER = "Radio Reference";
private final RadioReferenceFrequencyIndex mIndex;
private final RadioReferencePlaylistActions mActions;
private final BooleanProperty mHoverCandidates = new SimpleBooleanProperty(true);
private final Text mMeasure = new Text();
private final double mTextHeight;
private PauseTransition mHoverTimer;
private DisplaySection mHoverSection;
private double mHoverX = Double.NaN;
private double mHoverY = Double.NaN;
private boolean mHoverReady;
private long mResultsFrequency = Long.MIN_VALUE;
private long mResultsTolerance;
private List<RankedCandidate> mResults = Collections.emptyList();
private Card mCard;
/**
* Candidate text of the card, measured once per lookup
* @param entries lines of each candidate: the title, then the details
* @param more line, or null
* @param textWidth of the widest line
* @param lineCount of the header, candidate and more lines
* @param maxTextWidth that the lines were shortened to
* @param maxHeight that the card was limited to
* @param readoutLines that the card was sized for
*/
private record Card(List<List<String>> entries, String more, double textWidth, int lineCount,
double maxTextWidth, double maxHeight, int readoutLines)
{
}
private List<RankedCandidate> mCardCandidates;
private List<ChannelCardEntry> mCardEntries = Collections.emptyList();
private long mCardEntriesTime;
/**
* Constructs an instance.
@@ -125,9 +89,6 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
{
mIndex = index;
mActions = actions;
mMeasure.setFont(FONT);
mMeasure.setText("Ag");
mTextHeight = Math.ceil(mMeasure.getLayoutBounds().getHeight());
mHoverCandidates.addListener((ob, ov, nv) -> requestRender());
}
@@ -148,15 +109,6 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
}
}
@Override
public void dispose()
{
if(mHoverTimer != null)
{
mHoverTimer.stop();
}
}
@Override
public String getConfigurationTitle()
{
@@ -181,10 +133,17 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
return List.of(hover, new ConfigurationRow("Nearby", status));
}
@Override
public String getContextMenuSection()
{
return ChannelMenus.SECTION;
}
/**
* Context menu items for the candidates at the frequency, in the card's order: add a candidate to the playlist and
* start it, or enable or disable the playlist channel that already decodes it. One item per site, and per
* frequency and protocol, so an item never adds a duplicate channel.
* Channel entries for the candidates at the frequency, in the card's order. A candidate that a playlist channel
* already decodes is listed as that playlist channel, otherwise as a candidate to add to the playlist (and
* start). Both can be viewed in the playlist editor's Radio Reference tab (View in Radio Reference). One entry per site, since the site's
* frequencies share its channel. Adding never duplicates a playlist channel.
*/
@Override
public List<MenuItem> getContextMenuItems(DisplaySection section, long frequency)
@@ -219,139 +178,121 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
if(site != null && offered.add(key))
{
addSiteItem(items, site, candidate, frequency);
items.add(createSiteEntry(site, ranked));
}
}
else
else if(offered.add("frequency:" + candidate.frequencyHz() + ":" + candidate.title() + ":" +
candidate.source()))
{
DecoderType decoderType = RadioReferencePlaylistActions.getDecoderType(candidate);
Set<DecoderType> family = RadioReferencePlaylistActions.getProtocolFamily(decoderType);
String protocol = family.isEmpty() ? String.valueOf(candidate.mode()) : family.iterator().next().name();
if(offered.add("frequency:" + candidate.frequencyHz() + ":" + protocol))
{
addConventionalItem(items, candidate, decoderType, frequency);
}
items.add(createConventionalEntry(ranked, RadioReferencePlaylistActions.getDecoderType(candidate)));
}
}
if(!items.isEmpty())
{
MenuItem header = new MenuItem("Radio Reference");
header.setDisable(true);
items.add(0, header);
}
//Playlist channels first, then the candidates, each in the card's order
items.sort(Comparator.comparing(item -> item.getUserData() == null));
return items;
}
private void addSiteItem(List<MenuItem> items, SiteRecord site, FrequencyCandidate candidate, long frequency)
/**
* Entry for a trunked system site, or for the candidate's repeater of a repeater site (LTR)
*/
private Menu createSiteEntry(SiteRecord site, RankedCandidate ranked)
{
String label = site.systemName() + " \u00B7 Site " + site.siteNumber() +
(site.description() != null ? " " + site.description() : "");
FrequencyCandidate candidate = ranked.candidate();
boolean repeater = RadioReferencePlaylistActions.isRepeaterSite(site);
ViewRadioReferenceRequest view = ViewRadioReferenceRequest.site(site.systemId(), site.siteId());
String unsupported = RadioReferencePlaylistActions.getUnsupportedReason(site);
Channel existing = unsupported != null ? null : repeater ? mActions.findChannel(List.of(candidate.frequencyHz()),
RadioReferencePlaylistActions.getSiteDecoderTypes(site)) : mActions.findSiteChannel(site);
if(existing != null)
{
return createPlaylistEntry(existing, view);
}
String title = site.systemName() + " \u00B7 Site " + site.siteNumber() +
(site.description() != null ? " " + site.description() : "");
if(repeater)
{
title += site.channels().stream().filter(channel -> channel.frequencyHz() == candidate.frequencyHz() &&
channel.logicalChannelNumber() > 0).map(channel -> " LCN " + channel.logicalChannelNumber())
.findFirst().orElse("");
}
Menu menu = ChannelMenus.createEntry(title, describe(ranked), State.CANDIDATE, null);
if(unsupported != null)
{
MenuItem item = new MenuItem(label + " \u2013 " + unsupported);
item.setDisable(true);
items.add(item);
return;
menu.getItems().add(ChannelMenus.createNote(unsupported));
}
if(RadioReferencePlaylistActions.isRepeaterSite(site))
else if(repeater)
{
addRepeaterItem(items, site, candidate.frequencyHz(), label, frequency);
return;
}
Channel existing = mActions.findSiteChannel(site);
if(existing != null)
{
//The channel layer offers the channels at the clicked frequency
if(!covers(existing, frequency))
{
items.add(createEnableItem(existing));
}
menu.getItems().addAll(
ChannelMenus.createItem("Add to Playlist and Start", State.CANDIDATE,
() -> mActions.addRepeater(site, candidate.frequencyHz(), true, this::showError)),
ChannelMenus.createItem("Add to Playlist", State.CANDIDATE,
() -> mActions.addRepeater(site, candidate.frequencyHz(), false, this::showError)));
}
else
{
MenuItem item = new MenuItem("Add and Start: " + label);
//Start on the right-clicked frequency when it's a control or alternate control channel
item.setOnAction(event -> mActions.addSite(site, candidate.frequencyHz(), this::showError));
items.add(item);
//Start on the candidate frequency when it's a control or alternate control channel
menu.getItems().addAll(
ChannelMenus.createItem("Add to Playlist and Start", State.CANDIDATE,
() -> mActions.addSite(site, candidate.frequencyHz(), true, this::showError)),
ChannelMenus.createItem("Add to Playlist", State.CANDIDATE,
() -> mActions.addSite(site, candidate.frequencyHz(), false, this::showError)));
}
addViewItem(menu, State.CANDIDATE, view);
return menu;
}
/**
* Menu item for one repeater of a repeater site (LTR): add and start it, or enable or disable its channel
* Entry for a conventional frequency
*/
private void addRepeaterItem(List<MenuItem> items, SiteRecord site, long repeaterFrequency, String label,
long frequency)
private Menu createConventionalEntry(RankedCandidate ranked, DecoderType decoderType)
{
Channel existing = mActions.findChannel(List.of(repeaterFrequency),
RadioReferencePlaylistActions.getSiteDecoderTypes(site));
FrequencyCandidate candidate = ranked.candidate();
String sourceKey = mIndex.getSourceKey(candidate);
ViewRadioReferenceRequest view = sourceKey != null ?
ViewRadioReferenceRequest.frequency(sourceKey, candidate) : null;
Channel existing = decoderType != null ? mActions.findConventionalChannel(candidate) : null;
if(existing != null)
{
if(!covers(existing, frequency))
{
items.add(createEnableItem(existing));
}
return;
return createPlaylistEntry(existing, view);
}
String lcn = site.channels().stream().filter(channel -> channel.frequencyHz() == repeaterFrequency &&
channel.logicalChannelNumber() > 0).map(channel -> " LCN " + channel.logicalChannelNumber())
.findFirst().orElse("");
MenuItem item = new MenuItem("Add and Start: " + label + lcn + " (" +
FREQUENCY_FORMAT.format(repeaterFrequency / 1E6) + " MHz)");
item.setOnAction(event -> mActions.addRepeater(site, repeaterFrequency, this::showError));
items.add(item);
}
private void addConventionalItem(List<MenuItem> items, FrequencyCandidate candidate, DecoderType decoderType,
long frequency)
{
String label = candidate.title() + " (" + FREQUENCY_FORMAT.format(candidate.frequencyHz() / 1E6) + " MHz" +
(candidate.mode() != null ? " " + candidate.mode() : "") + ")";
Menu menu = ChannelMenus.createEntry(candidate.title() != null ? candidate.title() : "(untitled)",
describe(ranked), State.CANDIDATE, null);
if(decoderType == null)
{
MenuItem item = new MenuItem(label + " \u2013 mode isn't supported");
item.setDisable(true);
items.add(item);
return;
}
Channel existing = mActions.findConventionalChannel(candidate);
if(existing != null)
{
if(!covers(existing, frequency))
{
items.add(createEnableItem(existing));
}
menu.getItems().add(ChannelMenus.createNote("Mode isn't supported"));
}
else
{
MenuItem item = new MenuItem("Add and Start: " + label);
item.setOnAction(event -> mActions.addConventional(candidate, this::showError));
items.add(item);
menu.getItems().addAll(
ChannelMenus.createItem("Add to Playlist and Start", State.CANDIDATE,
() -> mActions.addConventional(candidate, true, this::showError)),
ChannelMenus.createItem("Add to Playlist", State.CANDIDATE,
() -> mActions.addConventional(candidate, false, this::showError)));
}
addViewItem(menu, State.CANDIDATE, view);
return menu;
}
/**
* Menu item that enables the playlist channel when it's disabled, or disables it when it's enabled
* Entry for the playlist channel that decodes a candidate: enable or disable it, view or edit it, and view the
* candidate in the Radio Reference tab
* @param view request for the candidate, or null when its listing isn't known
*/
private MenuItem createEnableItem(Channel channel)
private Menu createPlaylistEntry(Channel channel, ViewRadioReferenceRequest view)
{
boolean processing = channel.isProcessing();
MenuItem item = new MenuItem((processing ? "Disable: " : "Enable: ") + channel.getShortTitle());
item.setOnAction(event -> {
if(processing)
Runnable toggle = channel.isTrafficChannel() ? null : () -> {
if(channel.isProcessing())
{
mActions.disable(channel, this::showError);
}
@@ -359,25 +300,22 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
{
mActions.enable(channel, this::showError);
}
});
return item;
};
Menu menu = ChannelMenus.createChannelEntry(channel, null, toggle);
addViewItem(menu, channel.isProcessing() ? State.ENABLED : State.DISABLED, view);
return menu;
}
/**
* Indicates if one of the channel's tuner channels includes the frequency
* Adds the item that shows the candidate in the playlist editor's Radio Reference tab
* @param request to show the candidate, or null when the candidate's listing isn't known
*/
private static boolean covers(Channel channel, long frequency)
private static void addViewItem(Menu menu, State state, ViewRadioReferenceRequest request)
{
for(TunerChannel tunerChannel: channel.getTunerChannels())
{
if(tunerChannel != null && tunerChannel.getMinFrequency() <= frequency &&
frequency <= tunerChannel.getMaxFrequency())
{
return true;
}
}
return false;
MenuItem view = ChannelMenus.createItem("View in Radio Reference", state,
() -> MyEventBus.getGlobalEventBus().post(request));
view.setDisable(request == null);
menu.getItems().addAll(ChannelMenus.createSeparator(), view);
}
/**
@@ -399,49 +337,88 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
});
}
@Override
public void renderSpectrumForeground(GraphicsContext gc, RenderArea area)
{
render(gc, area, DisplaySection.SPECTRUM);
}
@Override
public void renderWaterfall(GraphicsContext gc, RenderArea area)
{
render(gc, area, DisplaySection.WATERFALL);
}
/**
* Draws the card in the section under the mouse once the mouse has rested for the hover delay
*/
private void render(GraphicsContext gc, RenderArea area, DisplaySection section)
{
DisplayCursor cursor = getSpectralDisplay() != null ? getSpectralDisplay().getDisplayCursor() : null;
trackHover(cursor);
if(cursor != null && cursor.section() == section && replacesCursorReadout(cursor, area))
{
drawCard(gc, area, cursor, getCandidates(cursor.frequency(), getTolerance(getModel(), area)));
}
}
/**
* The card replaces the cursor readout while it's shown: it ends with the readout lines, in the readout's place.
* Card entries for the candidates at the mouse position, in the card's order. A candidate that a playlist
* channel already decodes is listed as that playlist channel.
*/
@Override
public boolean replacesCursorReadout(DisplayCursor cursor, RenderArea area)
public List<ChannelCardEntry> getCardEntries(DisplayCursor cursor, RenderArea area)
{
SpectralDisplayModel model = getModel();
//Only for the position the mouse rested at - the readout comes back as soon as the mouse moves
if(mIndex == null || !mHoverCandidates.get() || !mHoverReady || model == null || !model.hasSource() ||
cursor == null || cursor.section() != mHoverSection || cursor.x() != mHoverX || cursor.y() != mHoverY ||
area.width() <= 0)
if(mIndex == null || !mHoverCandidates.get() || model == null || area.width() <= 0)
{
return false;
return Collections.emptyList();
}
return !getCandidates(cursor.frequency(), getTolerance(model, area)).isEmpty();
List<RankedCandidate> candidates = getCandidates(cursor.frequency(), getTolerance(model, area));
//The playlist channels of the candidates, looked up once per lookup or second, since that copies the playlist
if(candidates != mCardCandidates || System.currentTimeMillis() - mCardEntriesTime > 1000)
{
mCardCandidates = candidates;
mCardEntriesTime = System.currentTimeMillis();
mCardEntries = createCardEntries(candidates);
}
return mCardEntries;
}
private List<ChannelCardEntry> createCardEntries(List<RankedCandidate> candidates)
{
List<ChannelCardEntry> entries = new ArrayList<>();
Set<String> listed = new HashSet<>();
for(RankedCandidate ranked: candidates)
{
FrequencyCandidate candidate = ranked.candidate();
Channel existing = mActions != null ? findChannel(candidate) : null;
if(existing != null)
{
entries.add(ChannelMenus.createCardEntry(existing, null, true));
}
//The same listing in several places (e.g. a county and its agency) is shown once
else if(listed.add(candidate.frequencyHz() + "|" + candidate.title() + "|" + candidate.source()))
{
List<String> details = new ArrayList<>();
details.add(describe(ranked));
String source = source(candidate);
if(source != null)
{
details.add(source);
}
String title = candidate.title() != null ? candidate.title() : "(untitled)";
entries.add(new ChannelCardEntry(title, details, State.CANDIDATE, null, true));
}
}
return entries;
}
/**
* Playlist channel that decodes the candidate, or null
*/
private Channel findChannel(FrequencyCandidate candidate)
{
if(candidate.isSiteFrequency())
{
SiteRecord site = mIndex.getSite(candidate.systemId(), candidate.siteId());
if(site == null || RadioReferencePlaylistActions.getUnsupportedReason(site) != null)
{
return null;
}
return RadioReferencePlaylistActions.isRepeaterSite(site) ?
mActions.findChannel(List.of(candidate.frequencyHz()),
RadioReferencePlaylistActions.getSiteDecoderTypes(site)) : mActions.findSiteChannel(site);
}
return RadioReferencePlaylistActions.getDecoderType(candidate) != null ?
mActions.findConventionalChannel(candidate) : null;
}
/**
@@ -453,47 +430,6 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
return Math.max(MIN_TOLERANCE_HZ, Math.round(Math.max(TOLERANCE_PIXELS * hertzPerPixel, model.getBinWidth())));
}
/**
* Restarts the hover delay each time the mouse moves, and hides the card until it passes
*/
private void trackHover(DisplayCursor cursor)
{
if(cursor == null)
{
if(mHoverSection != null)
{
mHoverSection = null;
mHoverReady = false;
getHoverTimer().stop();
}
return;
}
if(cursor.section() != mHoverSection || cursor.x() != mHoverX || cursor.y() != mHoverY)
{
mHoverSection = cursor.section();
mHoverX = cursor.x();
mHoverY = cursor.y();
mHoverReady = false;
getHoverTimer().playFromStart();
}
}
private PauseTransition getHoverTimer()
{
if(mHoverTimer == null)
{
mHoverTimer = new PauseTransition(HOVER_DELAY);
mHoverTimer.setOnFinished(event -> {
mHoverReady = true;
requestRender();
});
}
return mHoverTimer;
}
/**
* Candidates for the frequency, looked up again only when the frequency or the tolerance changes
*/
@@ -504,172 +440,11 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
mResults = mIndex.lookup(frequency, tolerance);
mResultsFrequency = frequency;
mResultsTolerance = tolerance;
mCard = null;
}
return mResults;
}
/**
* Draws the card in place of the cursor readout: beside the mouse and above it, placed like the readout, with the
* candidates above the readout lines so the frequency and level stay where the readout showed them. The card
* fits the larger side of the mouse and the height of the section, showing as many candidates as fit.
*/
private void drawCard(GraphicsContext gc, RenderArea area, DisplayCursor cursor, List<RankedCandidate> candidates)
{
//The level line changes with the mouse height while the candidates don't
List<String> readout = CursorReadout.lines(cursor, area, getModel());
double readoutWidth = 0;
for(String line: readout)
{
readoutWidth = Math.max(readoutWidth, measure(line, FONT));
}
double room = Math.max(area.width() - cursor.x(), cursor.x()) - CursorReadout.GAP_X - EDGE_MARGIN;
double maxTextWidth = Math.max(readoutWidth, Math.min(MAX_TEXT_WIDTH, room - (PADDING_X * 2)));
//Above the mouse, so the readout lines stay where the readout showed them, when a candidate fits there
double above = cursor.y() - CursorReadout.GAP_Y;
double maxHeight = above >= cardHeight(5, 1, true, readout.size()) ? above : area.plotHeight() - EDGE_MARGIN;
if(mCard == null || mCard.maxTextWidth() != maxTextWidth || mCard.maxHeight() != maxHeight ||
mCard.readoutLines() != readout.size())
{
mCard = createCard(candidates, maxTextWidth, maxHeight, readout.size());
}
Card card = mCard;
SpectralDisplayTheme theme = getSpectralDisplay().getTheme();
double width = Math.max(card.textWidth(), readoutWidth) + (PADDING_X * 2);
double height = cardHeight(card.lineCount(), card.entries().size(), card.more() != null, readout.size());
double x = Math.max(0, CursorReadout.x(cursor, width, area));
double y = CursorReadout.y(cursor, height, area);
gc.setFill(theme.getBackground(0.92));
gc.fillRoundRect(x, y, width, height, 8, 8);
gc.setStroke(opaque(theme.getLine()));
gc.setLineWidth(1.0);
gc.strokeRoundRect(Math.floor(x) + 0.5, Math.floor(y) + 0.5, width, height, 8, 8);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.TOP);
double textX = x + PADDING_X;
double lineY = y + PADDING;
gc.setFill(theme.getCursor());
gc.setFont(TITLE_FONT);
gc.fillText(HEADER, textX, lineY);
lineY += mTextHeight + GAP;
for(List<String> lines: card.entries())
{
gc.setFill(theme.getCursor());
gc.setFont(TITLE_FONT);
gc.fillText(lines.get(0), textX, lineY);
lineY += mTextHeight;
gc.setFill(opaque(theme.getLine()));
gc.setFont(FONT);
for(int line = 1; line < lines.size(); line++)
{
gc.fillText(lines.get(line), textX, lineY);
lineY += mTextHeight;
}
lineY += GAP;
}
if(card.more() != null)
{
gc.setFill(opaque(theme.getLine()));
gc.setFont(FONT);
gc.fillText(card.more(), textX, lineY);
lineY += mTextHeight + GAP;
}
//The readout lines, separated from the candidates, in the readout's style
double separator = Math.floor(lineY - (GAP / 2.0)) + 0.5;
gc.setStroke(theme.getLine(0.5));
gc.strokeLine(textX, separator, x + width - PADDING_X, separator);
gc.setFill(theme.getCursor());
gc.setFont(FONT);
for(String line: readout)
{
gc.fillText(line, textX, lineY);
lineY += mTextHeight;
}
}
/**
* Height of a card with the lines
* @param lineCount of the header, candidate and more lines
* @param entries number of candidates
* @param more true when the card has a more line
* @param readoutLines number of readout lines
*/
private double cardHeight(int lineCount, int entries, boolean more, int readoutLines)
{
int gaps = 1 + entries + (more ? 1 : 0);
return ((lineCount + readoutLines) * mTextHeight) + (gaps * GAP) + PADDING + READOUT_PADDING;
}
/**
* Card text for as many candidates as fit the height: each candidate's title, details and source, shortened to
* the width
*/
private Card createCard(List<RankedCandidate> candidates, double maxTextWidth, double maxHeight,
int readoutLines)
{
int limit = Math.min(candidates.size(), MAX_CANDIDATES);
List<List<String>> entries = new ArrayList<>();
double textWidth = measure(HEADER, TITLE_FONT);
int lineCount = 1;
for(int index = 0; index < limit; index++)
{
RankedCandidate candidate = candidates.get(index);
List<String> lines = new ArrayList<>();
String title = candidate.candidate().title() != null ? candidate.candidate().title() : "(untitled)";
lines.add(fit(title, TITLE_FONT, maxTextWidth));
lines.add(fit(describe(candidate), FONT, maxTextWidth));
String source = source(candidate.candidate());
if(source != null)
{
lines.add(fit(source, FONT, maxTextWidth));
}
//Keep room for the more line when candidates are left out
boolean more = index + 1 < candidates.size();
if(!entries.isEmpty() && cardHeight(lineCount + lines.size() + (more ? 1 : 0), entries.size() + 1, more,
readoutLines) > maxHeight)
{
break;
}
textWidth = Math.max(textWidth, measure(lines.get(0), TITLE_FONT));
for(int line = 1; line < lines.size(); line++)
{
textWidth = Math.max(textWidth, measure(lines.get(line), FONT));
}
lineCount += lines.size();
entries.add(lines);
}
String more = candidates.size() > entries.size() ? "+ " + (candidates.size() - entries.size()) + " more" : null;
if(more != null)
{
textWidth = Math.max(textWidth, measure(more, FONT));
lineCount++;
}
return new Card(entries, more, textWidth, lineCount, maxTextWidth, maxHeight, readoutLines);
}
/**
* Frequency, mode or use, tone, encryption and distance of the candidate
*/
@@ -691,35 +466,6 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
return join(alphaTag, candidate.source());
}
/**
* Text shortened with an ellipsis to fit the width
*/
private String fit(String text, Font font, double maxWidth)
{
if(measure(text, font) <= maxWidth)
{
return text;
}
int length = text.length();
while(length > 1 && measure(text.substring(0, length) + "…", font) > maxWidth)
{
length--;
}
return text.substring(0, length) + "…";
}
private double measure(String text, Font font)
{
mMeasure.setFont(font);
mMeasure.setText(text);
double width = mMeasure.getLayoutBounds().getWidth();
mMeasure.setFont(FONT);
return width;
}
private static String join(String... values)
{
StringBuilder sb = new StringBuilder();
@@ -739,9 +485,4 @@ public class RadioReferenceLayer extends SpectralDisplayLayer
return sb.isEmpty() ? null : sb.toString();
}
private static Color opaque(Color color)
{
return Color.color(color.getRed(), color.getGreen(), color.getBlue());
}
}

View File

@@ -0,0 +1,57 @@
/*
* *****************************************************************************
* 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.table;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.javafx.IconNode;
/**
* Button that opens the column configuration editor for a table.
*/
public class ColumnConfigurationButton extends Button
{
private final TableColumnMonitor<?> mTableColumnMonitor;
private ColumnConfigurationEditor mEditor;
/**
* Constructs an instance
* @param tableColumnMonitor for the table to configure
* @param title for the editor window
*/
public ColumnConfigurationButton(TableColumnMonitor<?> tableColumnMonitor, String title)
{
super("Columns");
mTableColumnMonitor = tableColumnMonitor;
IconNode iconNode = new IconNode(FontAwesome.COLUMNS);
//Follow the themed text color so that the icon is readable in light and dark themes
iconNode.fillProperty().bind(textFillProperty());
setGraphic(iconNode);
setTooltip(new Tooltip("Choose the columns to show and the column order"));
setOnAction(event -> {
if(mEditor == null)
{
mEditor = new ColumnConfigurationEditor(mTableColumnMonitor, title);
}
mEditor.show(this);
});
}
}

View File

@@ -0,0 +1,199 @@
/*
* *****************************************************************************
* 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.table;
import io.github.dsheirer.gui.theme.ThemeManager;
import javafx.collections.ListChangeListener;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.CheckBoxListCell;
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.util.StringConverter;
/**
* Editor window for choosing the columns to show in a table and the order of the columns. Changes apply to the
* table immediately and are stored by the table column monitor.
*/
public class ColumnConfigurationEditor
{
private final TableColumnMonitor<?> mTableColumnMonitor;
private final String mTitle;
private Stage mStage;
private ListView<TableColumn<?,?>> mListView;
private Button mMoveUpButton;
private Button mMoveDownButton;
private Button mResetButton;
/**
* Constructs an instance
* @param tableColumnMonitor for the table
* @param title for the window
*/
public ColumnConfigurationEditor(TableColumnMonitor<?> tableColumnMonitor, String title)
{
mTableColumnMonitor = tableColumnMonitor;
mTitle = title;
}
/**
* Shows the editor next to the node, or brings it to the front when it is already showing.
* @param anchor node for positioning the editor window
*/
public void show(Node anchor)
{
if(mStage == null)
{
mStage = createStage();
}
if(!mStage.isShowing())
{
mListView.getSelectionModel().clearSelection();
if(anchor != null && anchor.getScene() != null)
{
Bounds bounds = anchor.localToScreen(anchor.getBoundsInLocal());
if(bounds != null)
{
mStage.setX(bounds.getMinX());
mStage.setY(bounds.getMaxY());
}
}
mStage.show();
}
mStage.toFront();
}
@SuppressWarnings({"unchecked", "rawtypes"})
private Stage createStage()
{
Stage stage = new Stage();
stage.setTitle(mTitle);
mListView = new ListView<>();
//The list shares the table's column list, so that column header drags in the table show here too
mListView.setItems((javafx.collections.ObservableList)mTableColumnMonitor.getTableView().getColumns());
mListView.setCellFactory(CheckBoxListCell.forListView(TableColumn::visibleProperty,
new StringConverter<>()
{
@Override
public String toString(TableColumn<?,?> column)
{
return column != null ? TableColumnMonitor.getName(column) : null;
}
@Override
public TableColumn<?,?> fromString(String string)
{
return null;
}
}));
mListView.setPrefHeight(300);
mListView.setPrefWidth(220);
mListView.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> updateButtons());
mListView.getItems().addListener((ListChangeListener<TableColumn<?,?>>)c -> updateButtons());
mMoveUpButton = new Button("Move Up");
mMoveUpButton.setTooltip(new Tooltip("Move the selected column toward the left side of the table"));
mMoveUpButton.setOnAction(event -> move(-1));
mMoveDownButton = new Button("Move Down");
mMoveDownButton.setTooltip(new Tooltip("Move the selected column toward the right side of the table"));
mMoveDownButton.setOnAction(event -> move(1));
mResetButton = new Button("Reset");
mResetButton.setTooltip(new Tooltip("Restore the default columns and column order"));
mResetButton.setOnAction(event -> {
mTableColumnMonitor.reset();
mListView.getSelectionModel().clearSelection();
updateButtons();
});
for(Button button: new Button[]{mMoveUpButton, mMoveDownButton, mResetButton})
{
button.setMaxWidth(Double.MAX_VALUE);
}
Region spacer = new Region();
VBox.setVgrow(spacer, Priority.ALWAYS);
Button closeButton = new Button("Close");
closeButton.setMaxWidth(Double.MAX_VALUE);
closeButton.setOnAction(event -> stage.hide());
VBox buttonBox = new VBox(5, mMoveUpButton, mMoveDownButton, mResetButton, spacer, closeButton);
HBox listBox = new HBox(10, mListView, buttonBox);
HBox.setHgrow(mListView, Priority.ALWAYS);
VBox.setVgrow(listBox, Priority.ALWAYS);
Label instructions = new Label("Check the columns to show. You can also drag column headers in the " +
"table to change the column order.");
instructions.setWrapText(true);
instructions.setMaxWidth(320);
VBox content = new VBox(10, instructions, listBox);
content.setPadding(new Insets(10));
content.setAlignment(Pos.TOP_LEFT);
Scene scene = new Scene(content);
ThemeManager.getInstance().register(scene);
stage.setScene(scene);
stage.setOnShown(event -> updateButtons());
//Reset tracks whether the table has the default columns, so update it when visibility changes too
for(TableColumn<?,?> column: mTableColumnMonitor.getDefaultOrder())
{
column.visibleProperty().addListener((observable, oldValue, newValue) -> updateButtons());
}
return stage;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void move(int direction)
{
TableColumn column = mListView.getSelectionModel().getSelectedItem();
if(column != null && ((TableColumnMonitor)mTableColumnMonitor).move(column, direction))
{
mListView.getSelectionModel().select(column);
mListView.scrollTo(column);
}
}
private void updateButtons()
{
int index = mListView.getSelectionModel().getSelectedIndex();
mMoveUpButton.setDisable(index <= 0);
mMoveDownButton.setDisable(index < 0 || index >= mListView.getItems().size() - 1);
mResetButton.setDisable(mTableColumnMonitor.isDefault());
}
}

View File

@@ -0,0 +1,459 @@
/*
* *****************************************************************************
* 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.table;
import io.github.dsheirer.preference.swing.SwingPreference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.prefs.Preferences;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
/**
* Stores and restores the order, visibility and width of the columns of a JavaFX table across application sessions,
* and restores the default column order and visibility on request.
*
* Each column must have a unique, stable ID (TableColumn.setId()), which is the key for its stored settings. The
* order and visibility of the columns when this monitor is constructed are the defaults. A column that is added to
* the table in a later version of the application is shown at its default position.
*
* Use this class only on the JavaFX application thread.
*/
public class TableColumnMonitor<S>
{
/**
* Column property that holds the name shown for the column in the column configuration editor, when the
* column header text doesn't identify the column by itself (e.g. two columns titled 'Alias').
*/
public static final String CONFIGURATION_NAME = "column.configuration.name";
/**
* Column property that holds the column number of the column in the Swing version of the table, for the stored
* Swing column widths.
*/
public static final String LEGACY_INDEX = "column.legacy.index";
private static final String ORDER = ".column.order";
private static final String HIDDEN = ".column.hidden";
private static final String KNOWN = ".column.known";
private static final String WIDTH = ".column.width.";
private static final String SEPARATOR = ",";
private final TableView<S> mTableView;
private final String mKey;
private final Preferences mPreferences;
private final List<TableColumn<S,?>> mDefaultOrder;
private final Map<TableColumn<S,?>,Boolean> mDefaultVisibility = new HashMap<>();
private boolean mRestoring;
/**
* Constructs an instance and applies the stored column settings to the table.
* @param tableView to monitor
* @param key that uniquely identifies the table, used as the prefix for its stored settings
*/
public TableColumnMonitor(TableView<S> tableView, String key)
{
this(tableView, key, Preferences.userNodeForPackage(TableColumnMonitor.class), null, null);
}
/**
* Constructs an instance and applies the stored column settings to the table. Columns that don't have a stored
* width yet use the width stored by the Swing version of the table, so that users keep their column widths.
* @param tableView to monitor
* @param key that uniquely identifies the table, used as the prefix for its stored settings
* @param swingPreference that holds the column widths of the Swing table
* @param swingKey of the Swing table. The Swing column number is the default index of the column.
*/
public TableColumnMonitor(TableView<S> tableView, String key, SwingPreference swingPreference, String swingKey)
{
this(tableView, key, Preferences.userNodeForPackage(TableColumnMonitor.class), swingPreference, swingKey);
}
/**
* Constructs an instance and applies the stored column settings to the table.
* @param tableView to monitor
* @param key that uniquely identifies the table, used as the prefix for its stored settings
* @param preferences node for storing the settings
* @param swingPreference that holds legacy Swing column widths, or null
* @param swingKey for the legacy Swing column widths, or null
*/
TableColumnMonitor(TableView<S> tableView, String key, Preferences preferences, SwingPreference swingPreference,
String swingKey)
{
mTableView = tableView;
mKey = key;
mPreferences = preferences;
mDefaultOrder = List.copyOf(tableView.getColumns());
Set<String> ids = new HashSet<>();
for(TableColumn<S,?> column: mDefaultOrder)
{
if(column.getId() == null || column.getId().isEmpty() || column.getId().contains(SEPARATOR) ||
!ids.add(column.getId()))
{
throw new IllegalArgumentException("Each table column needs a unique ID without commas - column [" +
column.getText() + "] has ID [" + column.getId() + "]");
}
mDefaultVisibility.put(column, column.isVisible());
}
restore(swingPreference, swingKey);
mTableView.getColumns().addListener((ListChangeListener<TableColumn<S,?>>)c -> {
if(!mRestoring)
{
storeOrder();
}
});
for(TableColumn<S,?> column: mDefaultOrder)
{
column.visibleProperty().addListener((observable, wasVisible, visible) -> {
if(!mRestoring)
{
//Don't let the user hide every column, since that leaves no column header for getting them back
if(!visible && getVisibleColumnCount() == 0)
{
column.setVisible(true);
return;
}
storeVisibility();
}
});
column.widthProperty().addListener((observable, oldWidth, width) -> {
if(!mRestoring && column.isVisible() && width.doubleValue() > 0)
{
mPreferences.putDouble(getWidthKey(column), width.doubleValue());
}
});
}
}
/**
* Table that is monitored.
*/
public TableView<S> getTableView()
{
return mTableView;
}
/**
* Columns in their default order.
*/
public List<TableColumn<S,?>> getDefaultOrder()
{
return mDefaultOrder;
}
/**
* Name of the column for display in the column configuration editor.
* @param column to name
* @return configuration name for the column, or the column header text.
*/
public static String getName(TableColumn<?,?> column)
{
Object name = column.getProperties().get(CONFIGURATION_NAME);
return name != null ? name.toString() : column.getText();
}
/**
* Sets the name of the column for display in the column configuration editor
* @param column to name
* @param name to show in the configuration editor
*/
public static void setName(TableColumn<?,?> column, String name)
{
column.getProperties().put(CONFIGURATION_NAME, name);
}
/**
* Sets the column number of the column in the Swing version of the table, for migrating the Swing column width.
* When any column of a table has a legacy index, only those columns use Swing column widths. Otherwise, the
* default column index is the Swing column number.
* @param column to set
* @param index of the column in the Swing table
*/
public static void setLegacyIndex(TableColumn<?,?> column, int index)
{
column.getProperties().put(LEGACY_INDEX, index);
}
/**
* Restores the default column order and visibility and removes the stored order and visibility settings. The
* column widths aren't changed.
*/
public void reset()
{
mRestoring = true;
try
{
if(!mTableView.getColumns().equals(mDefaultOrder))
{
mTableView.getColumns().setAll(mDefaultOrder);
}
for(TableColumn<S,?> column: mDefaultOrder)
{
column.setVisible(mDefaultVisibility.get(column));
}
}
finally
{
mRestoring = false;
}
mPreferences.remove(mKey + ORDER);
mPreferences.remove(mKey + HIDDEN);
mPreferences.remove(mKey + KNOWN);
}
/**
* Indicates if the column order and visibility are the defaults.
*/
public boolean isDefault()
{
if(!mTableView.getColumns().equals(mDefaultOrder))
{
return false;
}
for(TableColumn<S,?> column: mDefaultOrder)
{
if(column.isVisible() != mDefaultVisibility.get(column))
{
return false;
}
}
return true;
}
/**
* Moves the column one position toward the start (-1) or the end (+1) of the table.
* @param column to move
* @param direction -1 or +1
* @return true if the column moved
*/
public boolean move(TableColumn<S,?> column, int direction)
{
ObservableList<TableColumn<S,?>> columns = mTableView.getColumns();
int index = columns.indexOf(column);
int target = index + Integer.signum(direction);
if(index < 0 || direction == 0 || target < 0 || target >= columns.size())
{
return false;
}
//Rearrange a copy and apply it in one change, since a table view can't hold the same column twice
List<TableColumn<S,?>> reordered = new ArrayList<>(columns);
Collections.swap(reordered, index, target);
columns.setAll(reordered);
return true;
}
/**
* Applies the stored column settings to the table.
*/
private void restore(SwingPreference swingPreference, String swingKey)
{
mRestoring = true;
try
{
Map<String,TableColumn<S,?>> columnMap = new LinkedHashMap<>();
for(TableColumn<S,?> column: mDefaultOrder)
{
columnMap.put(column.getId(), column);
}
String order = mPreferences.get(mKey + ORDER, null);
if(order != null)
{
List<TableColumn<S,?>> ordered = new ArrayList<>();
for(String id: order.split(SEPARATOR))
{
TableColumn<S,?> column = columnMap.get(id);
if(column != null && !ordered.contains(column))
{
ordered.add(column);
}
}
//Columns that aren't in the stored order are new, so show them at their default position
for(int x = 0; x < mDefaultOrder.size(); x++)
{
TableColumn<S,?> column = mDefaultOrder.get(x);
if(!ordered.contains(column))
{
ordered.add(Math.min(x, ordered.size()), column);
}
}
mTableView.getColumns().setAll(ordered);
}
String hidden = mPreferences.get(mKey + HIDDEN, null);
if(hidden != null)
{
Set<String> hiddenIds = Set.of(hidden.isEmpty() ? new String[0] : hidden.split(SEPARATOR));
Set<String> knownIds = getKnownIds();
for(TableColumn<S,?> column: mDefaultOrder)
{
//Columns that weren't in the table when the visibility was stored are new, so use the default
column.setVisible(knownIds.contains(column.getId()) ? !hiddenIds.contains(column.getId()) :
mDefaultVisibility.get(column));
}
if(getVisibleColumnCount() == 0)
{
for(TableColumn<S,?> column: mDefaultOrder)
{
column.setVisible(mDefaultVisibility.get(column));
}
}
}
boolean hasLegacyIndexes = mDefaultOrder.stream()
.anyMatch(column -> column.getProperties().containsKey(LEGACY_INDEX));
for(int x = 0; x < mDefaultOrder.size(); x++)
{
TableColumn<S,?> column = mDefaultOrder.get(x);
double width = mPreferences.getDouble(getWidthKey(column), Double.NaN);
Integer legacyIndex = column.getProperties().get(LEGACY_INDEX) instanceof Integer index ? index :
(hasLegacyIndexes ? null : x);
if(Double.isNaN(width) && swingPreference != null && swingKey != null && legacyIndex != null)
{
int swingWidth = swingPreference.getInt(swingKey + ".column." + legacyIndex, Integer.MAX_VALUE);
if(swingWidth != Integer.MAX_VALUE && swingWidth > 0)
{
width = swingWidth;
}
}
if(!Double.isNaN(width) && width > 0)
{
column.setPrefWidth(width);
}
}
}
finally
{
mRestoring = false;
}
}
/**
* IDs of the columns that were in the table when the visibility was stored. Settings stored before the known
* columns were stored only had columns that are shown by default.
*/
private Set<String> getKnownIds()
{
String known = mPreferences.get(mKey + KNOWN, null);
if(known != null)
{
return Set.of(known.isEmpty() ? new String[0] : known.split(SEPARATOR));
}
Set<String> ids = new HashSet<>();
for(TableColumn<S,?> column: mDefaultOrder)
{
if(mDefaultVisibility.get(column))
{
ids.add(column.getId());
}
}
return ids;
}
private int getVisibleColumnCount()
{
int count = 0;
for(TableColumn<S,?> column: mDefaultOrder)
{
if(column.isVisible())
{
count++;
}
}
return count;
}
private void storeOrder()
{
List<String> ids = new ArrayList<>();
for(TableColumn<S,?> column: mTableView.getColumns())
{
ids.add(column.getId());
}
mPreferences.put(mKey + ORDER, String.join(SEPARATOR, ids));
}
private void storeVisibility()
{
List<String> ids = new ArrayList<>();
List<String> known = new ArrayList<>();
for(TableColumn<S,?> column: mDefaultOrder)
{
known.add(column.getId());
if(!column.isVisible())
{
ids.add(column.getId());
}
}
mPreferences.put(mKey + HIDDEN, String.join(SEPARATOR, ids));
mPreferences.put(mKey + KNOWN, String.join(SEPARATOR, known));
}
private String getWidthKey(TableColumn<S,?> column)
{
return mKey + WIDTH + column.getId();
}
}

View File

@@ -502,10 +502,10 @@ public class ThemeManager
.append("-fx-background-color: ").append(accent).append(";")
.append("}");
//URL-encode the body; java.net.URLEncoder is fine for our restricted charset.
String encoded = java.net.URLEncoder.encode(css.toString(),
java.nio.charset.StandardCharsets.UTF_8);
return "data:text/css," + encoded;
//Base64-encode the body. Don't use URLEncoder: it is form encoding and turns spaces
//into '+', which a data URL doesn't decode, so JavaFX silently drops the whole sheet.
return "data:text/css;base64," + java.util.Base64.getEncoder().encodeToString(
css.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
catch(Throwable t)
{

View File

@@ -19,7 +19,9 @@
package io.github.dsheirer.identifier.alias;
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.identifier.MutableIdentifierCollection;
import io.github.dsheirer.identifier.Role;
@@ -29,6 +31,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
/**
* Talker alias cache manager. Collects observed talker aliases and inserts them into an identifier collection when
@@ -39,6 +42,7 @@ import java.util.concurrent.ConcurrentHashMap;
public class TalkerAliasManager
{
private Map<Integer,TalkerAliasIdentifier> mAliasMap = new ConcurrentHashMap<>();
private volatile BiConsumer<RadioIdentifier,TalkerAliasIdentifier> mTalkerAliasListener;
/**
* Constructs an instance
@@ -47,6 +51,16 @@ public class TalkerAliasManager
{
}
/**
* Sets an optional listener to receive each talker alias that is assigned to a radio, e.g. to automatically add
* talker aliases to an alias list. The listener is invoked on the calling decoder thread.
* @param listener to receive radio and talker alias updates, or null to clear the listener.
*/
public void setTalkerAliasListener(BiConsumer<RadioIdentifier,TalkerAliasIdentifier> listener)
{
mTalkerAliasListener = listener;
}
/**
* Updates the alias for the radio identifier
*
@@ -58,6 +72,13 @@ public class TalkerAliasManager
if(identifier.getRole() == Role.FROM)
{
mAliasMap.put(identifier.getValue(), alias);
BiConsumer<RadioIdentifier,TalkerAliasIdentifier> listener = mTalkerAliasListener;
if(listener != null && alias != null)
{
listener.accept(identifier, alias);
}
}
}
@@ -116,6 +137,16 @@ public class TalkerAliasManager
}
}
/**
* Current FROM radio in the identifier collection
* @param identifierCollection to inspect
* @return FROM radio identifier, or null
*/
public static Identifier getFromRadio(IdentifierCollection identifierCollection)
{
return identifierCollection.getIdentifier(IdentifierClass.USER, Form.RADIO, Role.FROM);
}
/**
* Creates a summary listing of talker aliases
* @return summary.

View File

@@ -0,0 +1,323 @@
/*
* *****************************************************************************
* 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.identifier.alias;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.MutableIdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.identifier.radio.RadioIdentifier;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Keeps the talker alias in a decoder's identifier collection matched to the radio that is talking, and assigns each
* received talker alias to the right radio in the talker alias manager. Use one instance for each decoder state (or
* timeslot) on the decoder state's thread.
*
* Talker aliases can arrive:
* <ul>
* <li>During the call, after the talking radio is identified (most protocols).</li>
* <li>During the call, before the talking radio is identified. The alias is shown for the call and stored for
* the radio once the radio is identified.</li>
* <li>Between calls. Depending on the protocol, the alias belongs to the talker of the call that just ended (e.g.
* P25 Phase 1 L3Harris aliases in the TDULC messages) or to the talker of the next call (e.g. P25 Phase 2
* L3Harris aliases that arrive just before the Push-To-Talk). See {@link BetweenCalls}.</li>
* <li>With their own radio identifier (e.g. Motorola), which is stored for that radio.</li>
* </ul>
*
* The decoder state calls {@link #callActivity(long)} after it updates the identifier collection for call activity,
* {@link #callEnded()} when a call ends, before it removes the FROM identifiers, and {@link #received} for each
* talker alias.
*/
public class TalkerAliasTracker
{
/**
* Talker that an alias received between calls belongs to
*/
public enum BetweenCalls
{
/**
* The talker of the call that just ended
*/
PREVIOUS_TALKER,
/**
* The talker of the next call, when it starts within {@link #NEXT_CALL_WINDOW_MS}
*/
NEXT_TALKER
}
/**
* Maximum time from a talker alias received between calls to the start of the next call, for the alias to belong
* to the next call's talker.
*/
public static final long NEXT_CALL_WINDOW_MS = 2000;
/**
* Call that a received talker alias belongs to
*/
public enum Assignment
{
/**
* The call in progress. The alias is shown in the identifier collection.
*/
CURRENT_CALL,
/**
* The call that just ended. The alias isn't shown, since no call is in progress.
*/
ENDED_CALL,
/**
* The next call. The alias is held and shown when the next call starts.
*/
NEXT_CALL,
/**
* Neither, e.g. an alias for a radio that isn't talking. The alias is stored for its radio, if known.
*/
UNASSIGNED
}
private final MutableIdentifierCollection mIdentifierCollection;
private final Supplier<TalkerAliasManager> mTalkerAliasManager;
private final BetweenCalls mBetweenCalls;
private boolean mCallActive;
private TalkerAliasIdentifier mNextCallAlias;
private long mNextCallAliasTimestamp;
private Identifier mTalker;
private RadioIdentifier mEndedCallRadio;
/**
* Constructs an instance
* @param identifierCollection of the decoder state
* @param talkerAliasManager for storing the talker alias of each radio. The supplier can return null when the
* decoder doesn't have a talker alias manager.
* @param betweenCalls talker that an alias received between calls belongs to, for the protocol
*/
public TalkerAliasTracker(MutableIdentifierCollection identifierCollection,
Supplier<TalkerAliasManager> talkerAliasManager, BetweenCalls betweenCalls)
{
mIdentifierCollection = identifierCollection;
mTalkerAliasManager = talkerAliasManager;
mBetweenCalls = betweenCalls;
}
/**
* Signals call activity, after the decoder updates the identifier collection from a call message. Keeps the
* talker alias matched to the talking radio: removes the alias when a different radio talks, stores an alias that
* arrived before the talking radio was identified, and adds the stored alias for the talking radio.
* @param timestamp of the call message
*/
public void callActivity(long timestamp)
{
if(!mCallActive && mNextCallAlias != null && Math.abs(timestamp - mNextCallAliasTimestamp) <= NEXT_CALL_WINDOW_MS)
{
//The alias received just before this call belongs to this call's talker. It's stored for the talker once
//the talker is identified.
mIdentifierCollection.update(mNextCallAlias);
}
mNextCallAlias = null;
mCallActive = true;
mEndedCallRadio = null;
update();
}
/**
* Keeps the talker alias matched to the talking radio after an identifier collection update, without signaling
* call activity.
*/
public void update()
{
Identifier current = getFromRadio();
if(current != null)
{
Identifier alias = getTalkerAlias();
TalkerAliasManager manager = mTalkerAliasManager.get();
if(mTalker != null && !isSameRadio(mTalker, current))
{
//A different radio is talking
mIdentifierCollection.remove(IdentifierClass.USER, Form.TALKER_ALIAS, Role.FROM);
}
else if(mTalker == null && alias instanceof TalkerAliasIdentifier talkerAlias &&
current instanceof RadioIdentifier radio && manager != null)
{
//The alias arrived during this call before the radio was identified
manager.update(radio, talkerAlias);
}
if(manager != null)
{
manager.enrichMutable(mIdentifierCollection);
}
}
mTalker = current;
}
/**
* Signals the end of the call. Call before removing the FROM identifiers from the identifier collection.
* Remembers the talker for an alias that arrives after the call, and removes the talker alias. Can be called
* more than once for the same call.
*/
public void callEnded()
{
Identifier current = getFromRadio();
if(current instanceof RadioIdentifier radio)
{
mEndedCallRadio = radio;
}
else if(mTalker instanceof RadioIdentifier radio)
{
mEndedCallRadio = radio;
}
mCallActive = false;
mTalker = null;
mIdentifierCollection.remove(IdentifierClass.USER, Form.TALKER_ALIAS, Role.FROM);
}
/**
* Resets the tracker, e.g. when the decoder state resets.
*/
public void reset()
{
mCallActive = false;
mTalker = null;
mEndedCallRadio = null;
mNextCallAlias = null;
}
/**
* Processes a received talker alias: stores it for its radio and shows it when the radio is talking.
*
* @param talkerAlias that was received
* @param aliasRadio that the alias identifies itself (e.g. Motorola), or null when the alias belongs to the
* talker of the current call, or of the previous or next call, depending on the protocol.
* @param timestamp of the alias message
* @return the call that the alias belongs to.
*/
public Assignment received(TalkerAliasIdentifier talkerAlias, RadioIdentifier aliasRadio, long timestamp)
{
if(talkerAlias == null)
{
return Assignment.UNASSIGNED;
}
Identifier current = getFromRadio();
RadioIdentifier radio = aliasRadio;
if(radio == null)
{
if(current instanceof RadioIdentifier currentRadio)
{
radio = currentRadio;
}
else if(!mCallActive)
{
if(mBetweenCalls == BetweenCalls.NEXT_TALKER)
{
//Hold the alias for the next call's talker
mNextCallAlias = talkerAlias;
mNextCallAliasTimestamp = timestamp;
return Assignment.NEXT_CALL;
}
radio = mEndedCallRadio;
}
}
TalkerAliasManager manager = mTalkerAliasManager.get();
if(radio != null && manager != null)
{
manager.update(radio, talkerAlias);
}
if(current != null && radio != null && isSameRadio(current, radio))
{
mIdentifierCollection.update(talkerAlias);
return Assignment.CURRENT_CALL;
}
if(radio == null && mCallActive)
{
//The talking radio isn't identified yet. The alias is stored for the radio once it's identified.
mIdentifierCollection.update(talkerAlias);
return Assignment.CURRENT_CALL;
}
if(radio != null && !mCallActive && mEndedCallRadio != null && isSameRadio(radio, mEndedCallRadio))
{
return Assignment.ENDED_CALL;
}
return Assignment.UNASSIGNED;
}
/**
* Talker of the call that just ended, or null.
*/
public RadioIdentifier getEndedCallRadio()
{
return mEndedCallRadio;
}
/**
* Talking radio for the current call, or null.
*/
public RadioIdentifier getCurrentRadio()
{
return getFromRadio() instanceof RadioIdentifier radio ? radio : null;
}
/**
* Indicates if a call is in progress
*/
public boolean isCallActive()
{
return mCallActive;
}
/**
* Indicates if the identifiers are the same radio, comparing radio values so that a radio and its fully qualified
* variant match.
*/
public static boolean isSameRadio(Identifier a, Identifier b)
{
if(a instanceof RadioIdentifier ra && b instanceof RadioIdentifier rb)
{
return Objects.equals(ra.getValue(), rb.getValue());
}
return Objects.equals(a, b);
}
private Identifier getFromRadio()
{
return TalkerAliasManager.getFromRadio(mIdentifierCollection);
}
private Identifier getTalkerAlias()
{
return mIdentifierCollection.getIdentifier(IdentifierClass.USER, Form.TALKER_ALIAS, Role.FROM);
}
}

View File

@@ -26,7 +26,7 @@
* and open the template in the editor.
*/
package org.jdesktop.swingx.mapviewer;
package io.github.dsheirer.map;
/**
* An immutable coordinate in the real (geographic) world,

View File

@@ -1,7 +1,6 @@
/*
* ******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2018 Dennis Sheirer
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -15,13 +14,30 @@
*
* 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.map;
import java.util.List;
/**
* Listener for changes to the plottable entities. Called on the thread that made the change: the decode event thread
* for new locations, or the thread that deleted the entities.
*/
public interface IPlottableUpdateListener
{
void entitiesUpdated();
void addPlottableEntity(PlottableEntityHistory entity);
void removePlottableEntity(PlottableEntityHistory entity);
/**
* A new entity was added
*/
void entityAdded(PlottableEntityHistory entity);
/**
* An existing entity received a new decode event or location
*/
void entityUpdated(PlottableEntityHistory entity);
/**
* Entities were deleted
*/
void entitiesRemoved(List<PlottableEntityHistory> entities);
}

View File

@@ -1,193 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.map;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Point2D;
public class MapMouseListener extends MouseInputAdapter implements MouseWheelListener
{
private JXMapViewer mJXMapViewer;
private Consumer<GeoPosition> mMyLocationListener;
private Function<Point,List<JMenuItem>> mMenuItemProvider;
private Point mPreviousPoint;
private Point mCurrentPoint;
/**
* Constructs an instance
* @param viewer map
* @param myLocationListener receives the location chosen with the 'Set My Location Here' menu item
* @param menuItemProvider of additional context menu items for the point that was right-clicked, listed first
*/
public MapMouseListener( JXMapViewer viewer, Consumer<GeoPosition> myLocationListener,
Function<Point,List<JMenuItem>> menuItemProvider )
{
mJXMapViewer = viewer;
mMyLocationListener = myLocationListener;
mMenuItemProvider = menuItemProvider;
}
@Override
public void mouseDragged( MouseEvent event )
{
if ( !SwingUtilities.isLeftMouseButton( event ) )
{
return;
}
Point current = event.getPoint();
double x = mJXMapViewer.getCenter().getX() -
( current.getX() - mPreviousPoint.getX() );
double y = mJXMapViewer.getCenter().getY() -
(current.getY() - mPreviousPoint.getY() );
if ( !mJXMapViewer.isNegativeYAllowed() )
{
if ( y < 0 )
{
y = 0;
}
}
int maxHeight = (int)( mJXMapViewer.getTileFactory()
.getMapSize( mJXMapViewer.getZoom() ).getHeight() *
mJXMapViewer.getTileFactory()
.getTileSize( mJXMapViewer.getZoom() ) );
if (y > maxHeight)
{
y = maxHeight;
}
mPreviousPoint = current;
mJXMapViewer.setCenter( new Point2D.Double( x, y ) );
mJXMapViewer.repaint();
/* Set cursor to dragging */
mJXMapViewer.setCursor( Cursor.getPredefinedCursor( Cursor.MOVE_CURSOR ) );
}
@Override
public void mouseReleased( MouseEvent event )
{
if ( !SwingUtilities.isLeftMouseButton( event ) )
{
return;
}
mPreviousPoint = null;
/* Reset the curson */
mJXMapViewer.setCursor(
Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) );
}
@Override
public void mouseEntered( MouseEvent event )
{
SwingUtilities.invokeLater( new Runnable()
{
@Override
public void run()
{
mJXMapViewer.requestFocusInWindow();
}
});
}
@Override
public void mousePressed( MouseEvent event )
{
mCurrentPoint = event.getPoint();
mPreviousPoint = event.getPoint();
boolean left = SwingUtilities.isLeftMouseButton( event );
boolean middle = SwingUtilities.isMiddleMouseButton( event );
boolean right = SwingUtilities.isRightMouseButton( event );
boolean doubleClick = ( event.getClickCount() == 2 );
if (middle || ( left && doubleClick ) )
{
recenterMap( event );
}
else if( right )
{
JPopupMenu popup = new JPopupMenu();
if( mMenuItemProvider != null )
{
List<JMenuItem> items = mMenuItemProvider.apply( event.getPoint() );
if( items != null && !items.isEmpty() )
{
items.forEach( popup::add );
popup.addSeparator();
}
}
JMenuItem mapViewItem = new JMenuItem( "Set My Location Here" );
mapViewItem.setToolTipText( "Sets your location, which is also used by the playlist editor's " +
"Radio Reference tab, to this point" );
mapViewItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
mMyLocationListener.accept( mJXMapViewer.convertPointToGeoPosition( mCurrentPoint ) );
}
} );
popup.add( mapViewItem );
popup.show( mJXMapViewer, event.getX(), event.getY() );
}
}
private void recenterMap( MouseEvent event )
{
Rectangle bounds = mJXMapViewer.getViewportBounds();
double x = bounds.getX() + event.getX();
double y = bounds.getY() + event.getY();
mJXMapViewer.setCenter( new Point2D.Double( x, y ) );
mJXMapViewer.setZoom( mJXMapViewer.getZoom() - 1 );
mJXMapViewer.repaint();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -29,7 +29,7 @@ import io.github.dsheirer.module.decode.event.PlottableDecodeEvent;
public class PlottableEntityHistory
{
private final TrackHistoryModel mTrackHistoryModel = new TrackHistoryModel();
private PlottableDecodeEvent mCurrentEvent;
private volatile PlottableDecodeEvent mCurrentEvent;
private final Identifier mIdentifier;
/**

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.map;
import io.github.dsheirer.alias.Alias;
@@ -27,31 +26,24 @@ import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.configuration.AliasListConfigurationIdentifier;
import io.github.dsheirer.module.decode.event.PlottableDecodeEvent;
import io.github.dsheirer.sample.Listener;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Table model for plottable entity history elements.
* Plottable entity histories, one for each FROM identifier and alias list that reported a location. Thread safe:
* listeners are called on the thread that made the change, outside of the model's lock.
*/
public class PlottableEntityModel extends AbstractTableModel implements Listener<PlottableDecodeEvent>
public class PlottableEntityModel implements Listener<PlottableDecodeEvent>
{
private final static Logger LOGGER = LoggerFactory.getLogger(PlottableEntityModel.class);
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALIAS = 1;
private static final int COLUMN_ALIAS_LIST = 2;
private static final String[] COLUMN_NAMES = {"ID", "Alias", "List"};
private static final String KEY_NO_ALIAS_LIST = "(no alias list)";
private Map<String,PlottableEntityHistory> mEntityHistoryMap = new HashMap();
private List<PlottableEntityHistory> mEntityHistories = new ArrayList<>();
private List<IPlottableUpdateListener> mPlottableUpdateListeners = new ArrayList<>();
private AliasModel mAliasModel;
private final Map<String,PlottableEntityHistory> mEntityHistoryMap = new HashMap<>();
private final List<PlottableEntityHistory> mEntityHistories = new ArrayList<>();
private final List<IPlottableUpdateListener> mPlottableUpdateListeners = new CopyOnWriteArrayList<>();
private final AliasModel mAliasModel;
/**
* Constructs an instance
@@ -67,181 +59,144 @@ public class PlottableEntityModel extends AbstractTableModel implements Listener
*/
public void deleteAllTracks()
{
EventQueue.invokeLater(() -> {
if(mEntityHistories.size() > 0)
{
int firstRow = 0;
int lastRow = mEntityHistories.size() - 1;
mEntityHistoryMap.clear();
mEntityHistories.clear();
fireTableRowsDeleted(firstRow, lastRow);
}
});
List<PlottableEntityHistory> removed;
synchronized(this)
{
removed = new ArrayList<>(mEntityHistories);
mEntityHistoryMap.clear();
mEntityHistories.clear();
}
if(!removed.isEmpty())
{
mPlottableUpdateListeners.forEach(listener -> listener.entitiesRemoved(removed));
}
}
/**
* Deletes the tracks from both the map and entity histories and fires a table model changed event.
* Deletes the tracks from the entity histories.
* @param tracksToDelete to delete
*/
public void delete(List<PlottableEntityHistory> tracksToDelete)
{
EventQueue.invokeLater(() ->
List<PlottableEntityHistory> removed = new ArrayList<>();
synchronized(this)
{
for(PlottableEntityHistory track : tracksToDelete)
{
int index = mEntityHistories.indexOf(track);
mEntityHistories.remove(track);
mEntityHistoryMap.entrySet().removeIf(entry -> entry.getValue() == track);
fireTableRowsDeleted(index, index);
if(mEntityHistories.remove(track))
{
mEntityHistoryMap.values().removeIf(value -> value == track);
removed.add(track);
}
}
});
}
if(!removed.isEmpty())
{
mPlottableUpdateListeners.forEach(listener -> listener.entitiesRemoved(removed));
}
}
@Override
public void receive(PlottableDecodeEvent plottableDecodeEvent)
{
if(plottableDecodeEvent.isValidLocation())
if(!plottableDecodeEvent.isValidLocation())
{
//Add or update the event on the swing event thread
EventQueue.invokeLater(() -> {
Identifier from = plottableDecodeEvent.getIdentifierCollection().getFromIdentifier();
if(from != null && from.getForm() != Form.LOCATION)
{
AliasListConfigurationIdentifier aliasList = plottableDecodeEvent.getIdentifierCollection().getAliasListConfiguration();
String key = (aliasList != null ? aliasList.toString() : KEY_NO_ALIAS_LIST) + from;
PlottableEntityHistory entityHistory = mEntityHistoryMap.get(key);
if(entityHistory == null)
{
entityHistory = new PlottableEntityHistory(from, plottableDecodeEvent);
mEntityHistories.add(entityHistory);
mEntityHistoryMap.put(key, entityHistory);
int index = mEntityHistories.indexOf(entityHistory);
fireTableRowsInserted(index, index);
}
else
{
entityHistory.add(plottableDecodeEvent);
int index = mEntityHistories.indexOf(entityHistory);
fireTableRowsUpdated(index, index);
}
for(IPlottableUpdateListener listener : mPlottableUpdateListeners)
{
listener.addPlottableEntity(entityHistory);
}
}
else
{
// LOGGER.warn("Received plottable decode event that does not contain a FROM identifier - cannot plot");
}
});
}
}
@Override
public String getColumnName(int column)
{
if(0 <= column && column < COLUMN_NAMES.length)
{
return COLUMN_NAMES[column];
return;
}
return "error!";
}
Identifier from = plottableDecodeEvent.getIdentifierCollection().getFromIdentifier();
@Override
public int getRowCount()
{
return mEntityHistories.size();
}
if(from == null || from.getForm() == Form.LOCATION)
{
return;
}
@Override
public int getColumnCount()
{
return COLUMN_NAMES.length;
AliasListConfigurationIdentifier aliasList = plottableDecodeEvent.getIdentifierCollection()
.getAliasListConfiguration();
String key = (aliasList != null ? aliasList.toString() : KEY_NO_ALIAS_LIST) + from;
PlottableEntityHistory entityHistory;
boolean added = false;
synchronized(this)
{
entityHistory = mEntityHistoryMap.get(key);
if(entityHistory == null)
{
entityHistory = new PlottableEntityHistory(from, plottableDecodeEvent);
mEntityHistories.add(entityHistory);
mEntityHistoryMap.put(key, entityHistory);
added = true;
}
else
{
entityHistory.add(plottableDecodeEvent);
}
}
for(IPlottableUpdateListener listener : mPlottableUpdateListeners)
{
if(added)
{
listener.entityAdded(entityHistory);
}
else
{
listener.entityUpdated(entityHistory);
}
}
}
/**
* Get the plottable entity history for the specified model index
* @param index in the model
* @return entity history or null.
* Snapshot of all plottable entity histories, in the order they were added.
*/
public PlottableEntityHistory get(int index)
{
if(index >= 0 && index < mEntityHistories.size())
{
return mEntityHistories.get(index);
}
return null;
}
/**
* Get all plottable entity histories.
*/
public List<PlottableEntityHistory> getAll()
public synchronized List<PlottableEntityHistory> getAll()
{
return new ArrayList<>(mEntityHistories);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
/**
* Aliases for the entity's identifier from the entity's alias list
* @param history of the entity
* @return aliases, or an empty list
*/
public List<Alias> getAliases(PlottableEntityHistory history)
{
PlottableEntityHistory history = mEntityHistories.get(rowIndex);
AliasList aliasList = mAliasModel.getAliasList(history.getIdentifierCollection());
if(history != null)
if(aliasList != null && history.getIdentifier() != null)
{
switch(columnIndex)
{
case COLUMN_ID:
Identifier identifier = history.getIdentifier();
if(identifier != null)
{
return identifier.toString();
}
else
{
return "(no ID)";
}
case COLUMN_ALIAS:
Identifier aliasListConfig = history.getIdentifierCollection().getAliasListConfiguration();
if(aliasListConfig != null)
{
AliasList al = mAliasModel.getAliasList(aliasListConfig.toString());
if(al != null)
{
List<Alias> aliases = al.getAliases(history.getIdentifier());
if(!aliases.isEmpty())
{
return aliases.get(0).getName();
}
}
}
break;
case COLUMN_ALIAS_LIST:
Identifier aliasList = history.getIdentifierCollection().getAliasListConfiguration();
if(aliasList != null)
{
return aliasList.toString();
}
else
{
return "(no alias list)";
}
default:
throw new IllegalArgumentException("Unexpected column index");
}
return aliasList.getAliases(history.getIdentifier());
}
return null;
return Collections.emptyList();
}
/**
* Name of the entity's first alias, or null
*/
public String getAliasName(PlottableEntityHistory history)
{
List<Alias> aliases = getAliases(history);
return aliases.isEmpty() ? null : aliases.getFirst().getName();
}
/**
* Name of the entity's alias list
*/
public static String getAliasListName(PlottableEntityHistory history)
{
Identifier aliasList = history.getIdentifierCollection().getAliasListConfiguration();
return aliasList != null ? aliasList.toString() : KEY_NO_ALIAS_LIST;
}
/**
* Adds a listener. New listeners don't receive the existing entities: see {@link #getAll()}.
*/
public void addListener(IPlottableUpdateListener listener)
{
mPlottableUpdateListeners.add(listener);

View File

@@ -1,139 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.map;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.icon.IconModel;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.painter.AbstractPainter;
/**
* Paints plottable entities to the map.
*/
public class PlottableEntityPainter extends AbstractPainter<JXMapViewer>
{
private PlottableEntityRenderer mRenderer;
private Set<PlottableEntityHistory> mEntities = new HashSet<>();
/**
* Constructs an instance
* @param aliasModel to lookup alias for entities
* @param iconModel to lookup icon from alias.
*/
public PlottableEntityPainter(AliasModel aliasModel, IconModel iconModel)
{
mRenderer = new PlottableEntityRenderer(aliasModel, iconModel);
setAntialiasing(true);
setCacheable(false);
}
/**
* Sets the length of the plotted history trails.
* @param length of history trails
*/
public void setTrackHistoryLength(int length)
{
mRenderer.setTrackHistoryLength(length);
}
/**
* Current size of the history trail length.
*/
public int getTrackHistoryLength()
{
return mRenderer.getTrackHistoryLength();
}
/**
* Adds an entity to the map
* @param entity to add
*/
public boolean addEntity(PlottableEntityHistory entity)
{
if(entity != null && !mEntities.contains(entity))
{
mEntities.add(entity);
return true;
}
return false;
}
/**
* Adds all entities to this painter
* @param entities to add.
*/
public boolean addAll(List<PlottableEntityHistory> entities)
{
boolean added = false;
for(PlottableEntityHistory entity : entities)
{
added |= addEntity(entity);
}
return added;
}
/**
* Removes an entity from the map
* @param entity to remove
*/
public void removeEntity(PlottableEntityHistory entity)
{
mEntities.remove(entity);
}
/**
* Clears all entities from the map.
*/
public void clearAllEntities()
{
mEntities.clear();
}
/**
* Clears teh specified entities from the map
* @param toDelete to delete
*/
public void clearEntities(List<PlottableEntityHistory> toDelete)
{
mEntities.removeAll(toDelete);
}
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
Rectangle viewportBounds = map.getViewportBounds();
g.translate(-viewportBounds.getX(), -viewportBounds.getY());
for(PlottableEntityHistory entity : mEntities)
{
mRenderer.paintPlottableEntity(g, map, entity, true);
}
g.translate(viewportBounds.getX(), viewportBounds.getY());
}
}

View File

@@ -1,219 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 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.map;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.icon.IconModel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.util.Collections;
import java.util.List;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import javax.swing.ImageIcon;
/**
* Paints a single plottable entity to the map.
*/
public class PlottableEntityRenderer
{
private AliasModel mAliasModel;
private IconModel mIconModel;
private int mTrackHistoryLength = 3;
/**
* Constructs an instance
* @param aliasModel for alias lookup for the entity to determine plot color and icon
* @param iconModel to retrieve icon for plotting.
*/
public PlottableEntityRenderer(AliasModel aliasModel, IconModel iconModel)
{
mAliasModel = aliasModel;
mIconModel = iconModel;
}
/**
* Sets the length of the plotted history trails.
* @param length of history trails
*/
public void setTrackHistoryLength(int length)
{
mTrackHistoryLength = length;
}
/**
* Current size of the history trail length.
*/
public int getTrackHistoryLength()
{
return mTrackHistoryLength;
}
/**
* Requests the plottable entity be painted to the map viewer.
* @param g graphics
* @param viewer requesting the painting
* @param entity to be painted
* @param antiAliasing for rendering.
*/
public void paintPlottableEntity(Graphics2D g, JXMapViewer viewer, PlottableEntityHistory entity, boolean antiAliasing)
{
List<TimestampedGeoPosition> locationHistory = entity.getTrackHistoryModel().getTrackHistory();
if(!locationHistory.isEmpty() && locationHistory.getLast().isValid())
{
Graphics2D graphics = (Graphics2D)g.create();
if(antiAliasing)
{
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
List<Alias> aliases = getAliases(entity);
Alias alias = aliases.isEmpty() ? null : aliases.get(0);
/**
* Use the entity's preferred color for lines and labels
*/
Color color = (alias != null ? alias.getDisplayColor() : Color.BLUE);
graphics.setColor(color);
/**
* Paint the route first, so the icon and label overlay it
*/
paintRoute(graphics, viewer, entity, color);
/**
* Convert the lat/long geoposition to an x/y point on the viewer
*/
Point2D point = viewer.getTileFactory().geoToPixel(entity.getLatestPosition(), viewer.getZoom());
/**
* Paint the icon at the current location
*/
ImageIcon icon = getIcon(alias);
paintIcon(graphics, point, icon);
/**
* Paint the label offset to the right of the icon
*/
String label = (alias != null ? alias.getName() : entity.getIdentifier().toString());
paintLabel(graphics, point, label, (int)(icon.getIconWidth() / 2), 0);
/**
* Cleanup
*/
graphics.dispose();
}
}
/**
* Optional alias that matches the identifier for the entity history
*/
private List<Alias> getAliases(PlottableEntityHistory entityHistory)
{
AliasList aliasList = mAliasModel.getAliasList(entityHistory.getIdentifierCollection());
if(aliasList != null)
{
return aliasList.getAliases(entityHistory.getIdentifier());
}
return Collections.EMPTY_LIST;
}
private ImageIcon getIcon(Alias alias)
{
String iconName = (alias != null ? alias.getIconName() : null);
return mIconModel.getIcon(iconName, IconModel.DEFAULT_ICON_SIZE);
}
private void paintIcon(Graphics2D graphics, Point2D point, ImageIcon icon)
{
graphics.drawImage(icon.getImage(), (int)point.getX() - (icon.getIconWidth() / 2),
(int)point.getY() - (icon.getIconHeight() / 2), null);
}
private void paintLabel(Graphics2D graphics, Point2D point, String label, int xOffset, int yOffset)
{
graphics.drawString(label, (int)point.getX() + xOffset, (int)point.getY() + yOffset);
}
/**
* Paints a two-tone route from the entity's list of plottables (locations).
* using black as a wider background route, and the entity's preferred color
* as a narrower foreground route.
*/
private void paintRoute(Graphics2D graphics, JXMapViewer viewer, PlottableEntityHistory entity, Color color)
{
List<TimestampedGeoPosition> locations = entity.getTrackHistoryModel().getTrackHistory();
if(!locations.isEmpty())
{
// Draw the route with a black background line
graphics.setColor(Color.BLACK);
graphics.setStroke(new BasicStroke(3));
drawRoute(locations, graphics, viewer);
// Draw the route again, in the entity's preferred color
graphics.setColor(color);
graphics.setStroke(new BasicStroke(1));
drawRoute(locations, graphics, viewer);
}
}
/**
* Draws a route from a list of plottables
*/
private void drawRoute(List<TimestampedGeoPosition> locations, Graphics2D g, JXMapViewer viewer)
{
Point2D previousPoint = null;
int length = Math.min(locations.size(), mTrackHistoryLength);
for(int x = 0; x < length; x++)
{
GeoPosition location = locations.get(x);
// convert geo-coordinate to world bitmap pixel
Point2D currentPoint = viewer.getTileFactory().geoToPixel(location, viewer.getZoom());
if(previousPoint != null)
{
g.drawLine((int)previousPoint.getX(), (int)previousPoint.getY(), (int)currentPoint.getX(), (int)currentPoint.getY());
}
previousPoint = currentPoint;
}
}
}

View File

@@ -1,187 +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.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;
/**
* HTML card with the details of radio reference trunked system sites, shown when the mouse is over a site's tower on
* the map: the system and protocol, the site, and the site's channels.
*/
public final class RadioReferenceSiteCard
{
private static final int MAX_SITES = 3;
private static final int CHANNEL_COLUMNS = 3;
private static final int MAX_CHANNELS = 24;
private static final String SEPARATOR = " &middot; ";
private RadioReferenceSiteCard()
{
}
/**
* Card for the sites
* @param sites under the mouse, nearest first
* @param location of the user, for the distances, or null
* @return HTML for a tooltip
*/
public static String html(List<SiteRecord> sites, RadioReferencePreference.Location location)
{
DecimalFormat frequencyFormat = new DecimalFormat("0.00000");
StringBuilder sb = new StringBuilder("<html><body style='padding:3px'>");
int shown = Math.min(sites.size(), MAX_SITES);
for(int index = 0; index < shown; index++)
{
SiteRecord site = sites.get(index);
if(index > 0)
{
sb.append("<hr>");
}
sb.append("<div><b>").append(escape(site.systemName() != null ? site.systemName() : "(unnamed system)"))
.append("</b></div>");
appendLine(sb, site.protocol(), site.voice());
String siteName = "Site " + site.siteNumber();
String distance = location != null ? DistanceFormat.format(Coverage.distanceKilometers(
location.latitude(), location.longitude(), site.latitude(), site.longitude())) : null;
appendLine(sb, siteName, site.description(), site.county(), distance);
appendLine(sb, site.nac() != null ? "NAC " + site.nac() : null,
site.rfss() > 0 ? "RFSS " + site.rfss() : null, site.zone() > 0 ? "Zone " + site.zone() : null);
appendChannels(sb, site.channels(), frequencyFormat);
}
if(sites.size() > shown)
{
sb.append("<hr><div>+ ").append(sites.size() - shown).append(" more site")
.append(sites.size() - shown > 1 ? "s" : "").append(" here</div>");
}
sb.append("</body></html>");
return sb.toString();
}
/**
* Channels in columns, control channels marked C and alternate control channels marked A
*/
private static void appendChannels(StringBuilder sb, List<SiteRecord.SiteChannel> channels,
DecimalFormat frequencyFormat)
{
if(channels == null || channels.isEmpty())
{
return;
}
int shown = Math.min(channels.size(), MAX_CHANNELS);
boolean control = false;
sb.append("<table cellspacing='0' cellpadding='1'>");
for(int index = 0; index < shown; index++)
{
if(index % CHANNEL_COLUMNS == 0)
{
sb.append("<tr>");
}
SiteRecord.SiteChannel channel = channels.get(index);
sb.append("<td style='padding-right:8px'>").append(frequencyFormat.format(channel.frequencyHz() / 1E6));
if("Control".equals(channel.use()))
{
sb.append(" <b>C</b>");
control = true;
}
else if("Alternate control".equals(channel.use()))
{
sb.append(" <b>A</b>");
control = true;
}
sb.append("</td>");
if(index % CHANNEL_COLUMNS == CHANNEL_COLUMNS - 1)
{
sb.append("</tr>");
}
}
if(shown % CHANNEL_COLUMNS != 0)
{
sb.append("</tr>");
}
sb.append("</table>");
List<String> notes = new ArrayList<>();
if(channels.size() > shown)
{
notes.add("+ " + (channels.size() - shown) + " more channels");
}
if(control)
{
notes.add("C control, A alternate control");
}
if(!notes.isEmpty())
{
appendLine(sb, notes.toArray(new String[0]));
}
}
/**
* Appends a line with the non-empty values separated by dots, or nothing when all are empty
*/
private static void appendLine(StringBuilder sb, String... values)
{
StringBuilder line = new StringBuilder();
for(String value: values)
{
if(value != null && !value.isBlank())
{
if(!line.isEmpty())
{
line.append(SEPARATOR);
}
line.append(escape(value));
}
}
if(!line.isEmpty())
{
sb.append("<div>").append(line).append("</div>");
}
}
private static String escape(String text)
{
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
}

View File

@@ -1,184 +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.map;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.painter.AbstractPainter;
/**
* Paints a radio tower at each radio reference trunked system site, with the base of the tower at the site location.
*/
public class RadioReferenceSitePainter extends AbstractPainter<JXMapViewer>
{
private static final Color TOWER = new Color(240, 128, 32);
private static final Color OUTLINE = new Color(40, 40, 40, 200);
private static final Stroke TOWER_STROKE = new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
private static final Stroke OUTLINE_STROKE = new BasicStroke(3.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
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 Rectangle HIT_AREA = new Rectangle(-10, -24, 20, 28);
private final Supplier<List<SiteRecord>> mSites;
private volatile boolean mShowSites = true;
/**
* Constructs an instance
* @param sites to paint, read each time the map is painted
*/
public RadioReferenceSitePainter(Supplier<List<SiteRecord>> sites)
{
mSites = sites;
setAntialiasing(true);
setCacheable(false);
}
/**
* 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 map viewer
* @param point in the viewer
* @return sites, or an empty list when the sites are hidden or none is under the point
*/
public List<SiteRecord> getSitesAt(JXMapViewer map, Point point)
{
if(!mShowSites)
{
return Collections.emptyList();
}
Rectangle viewport = map.getViewportBounds();
List<SiteRecord> sites = new ArrayList<>();
List<Double> distances = new ArrayList<>();
for(SiteRecord site: mSites.get())
{
Point2D pixel = map.getTileFactory().geoToPixel(new GeoPosition(site.latitude(), site.longitude()),
map.getZoom());
double dx = point.x - (pixel.getX() - viewport.getX());
double dy = point.y - (pixel.getY() - viewport.getY());
if(HIT_AREA.contains(dx, dy))
{
//Nearest to the middle of the tower first
double distance = Math.hypot(dx, dy + (HEIGHT / 2.0));
int index = 0;
while(index < distances.size() && distances.get(index) <= distance)
{
index++;
}
sites.add(index, site);
distances.add(index, distance);
}
}
return sites;
}
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
if(!mShowSites)
{
return;
}
Rectangle viewport = map.getViewportBounds();
for(SiteRecord site: mSites.get())
{
Point2D pixel = map.getTileFactory().geoToPixel(new GeoPosition(site.latitude(), site.longitude()),
map.getZoom());
double x = pixel.getX() - viewport.getX();
double y = pixel.getY() - viewport.getY();
if(x >= -20 && x <= width + 20 && y >= -4 && y <= height + 30)
{
paintTower(g, x, y);
}
}
}
/**
* Paints 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 paintTower(Graphics2D g, double x, double y)
{
double top = y - HEIGHT;
Path2D mast = new Path2D.Double();
mast.moveTo(x - HALF_BASE, y);
mast.lineTo(x, top);
mast.lineTo(x + HALF_BASE, y);
mast.moveTo(x - (HALF_BASE * 0.55), y - (HEIGHT * 0.45));
mast.lineTo(x + (HALF_BASE * 0.55), y - (HEIGHT * 0.45));
Arc2D leftInner = new Arc2D.Double(x - 5, top - 4, 10, 8, 135, 90, Arc2D.OPEN);
Arc2D rightInner = new Arc2D.Double(x - 5, top - 4, 10, 8, -45, 90, Arc2D.OPEN);
Arc2D leftOuter = new Arc2D.Double(x - 9, top - 7, 18, 14, 135, 90, Arc2D.OPEN);
Arc2D rightOuter = new Arc2D.Double(x - 9, top - 7, 18, 14, -45, 90, Arc2D.OPEN);
g.setStroke(OUTLINE_STROKE);
g.setColor(OUTLINE);
g.draw(mast);
g.draw(leftInner);
g.draw(rightInner);
g.draw(leftOuter);
g.draw(rightOuter);
g.setStroke(TOWER_STROKE);
g.setColor(TOWER);
g.draw(mast);
g.draw(leftInner);
g.draw(rightInner);
g.draw(leftOuter);
g.draw(rightOuter);
g.fill(new Ellipse2D.Double(x - 2, top - 2, 4, 4));
}
}

View File

@@ -1,104 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.map;
import org.apache.commons.math3.util.FastMath;
import org.jdesktop.swingx.JXMapViewer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
/**
* Creates a selection rectangle based on mouse input
* Also triggers repaint events in the viewer
* @author Martin Steiger
*/
public class SelectionAdapter extends MouseAdapter
{
private boolean dragging;
private JXMapViewer viewer;
private Point2D startPos = new Point2D.Double();
private Point2D endPos = new Point2D.Double();
/**
* @param viewer the jxmapviewer
*/
public SelectionAdapter(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent e)
{
if (e.getButton() != MouseEvent.BUTTON3)
return;
startPos.setLocation(e.getX(), e.getY());
endPos.setLocation(e.getX(), e.getY());
dragging = true;
}
@Override
public void mouseDragged(MouseEvent e)
{
if (!dragging)
return;
endPos.setLocation(e.getX(), e.getY());
viewer.repaint();
}
@Override
public void mouseReleased(MouseEvent e)
{
if (!dragging)
return;
if (e.getButton() != MouseEvent.BUTTON3)
return;
viewer.repaint();
dragging = false;
}
/**
* @return the selection rectangle
*/
public Rectangle getRectangle()
{
if (dragging)
{
int x1 = (int) FastMath.min(startPos.getX(), endPos.getX());
int y1 = (int) FastMath.min(startPos.getY(), endPos.getY());
int x2 = (int) FastMath.max(startPos.getX(), endPos.getX());
int y2 = (int) FastMath.max(startPos.getY(), endPos.getY());
return new Rectangle(x1, y1, x2-x1, y2-y1);
}
return null;
}
}

View File

@@ -1,56 +0,0 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.map;
import org.jdesktop.swingx.painter.Painter;
import java.awt.*;
/**
* Paints a selection rectangle
* @author Martin Steiger
*/
public class SelectionPainter implements Painter<Object>
{
private Color fillColor = new Color(128, 192, 255, 128);
private Color frameColor = new Color(0, 0, 255, 128);
private SelectionAdapter adapter;
/**
* @param adapter the selection adapter
*/
public SelectionPainter(SelectionAdapter adapter)
{
this.adapter = adapter;
}
@Override
public void paint(Graphics2D g, Object t, int width, int height)
{
Rectangle rc = adapter.getRectangle();
if (rc != null)
{
g.setColor(frameColor);
g.draw(rc);
g.setColor(fillColor);
g.fill(rc);
}
}
}

View File

@@ -1,6 +1,5 @@
package io.github.dsheirer.map;
import org.jdesktop.swingx.mapviewer.GeoPosition;
/**
* Timestamped geo position

View File

@@ -36,7 +36,6 @@ import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.jdesktop.swingx.mapviewer.GeoPosition;
/**
* Map test track data generator.

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,23 +19,16 @@
package io.github.dsheirer.map;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
* Track history table model.
* Location history of a plottable entity, newest first. Thread safe: positions are added on the decode event thread
* and read on the JavaFX thread.
*/
public class TrackHistoryModel extends AbstractTableModel
public class TrackHistoryModel
{
public static final int MAX_LOCATION_HISTORY = 10;
private static final String[] COLUMNS = new String[]{"Time", "Latitude", "Longitude"};
private final SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final DecimalFormat mDegreeFormat = new DecimalFormat("0.00000");
private final List<TimestampedGeoPosition> mTimestampedGeoPositions = new ArrayList<>();
/**
@@ -46,48 +39,46 @@ public class TrackHistoryModel extends AbstractTableModel
}
/**
* Complete history for this entity.
* Snapshot of the history for this entity, newest first.
*/
public List<TimestampedGeoPosition> getTrackHistory()
public synchronized List<TimestampedGeoPosition> getTrackHistory()
{
return Collections.unmodifiableList(mTimestampedGeoPositions);
return List.copyOf(mTimestampedGeoPositions);
}
/**
* Adds the position to the history if it is unique and trims the history to MAX_LOCATION_HISTORY size.
* @param latest position to add.
* @return true if the position was added
*/
public void add(TimestampedGeoPosition latest)
public synchronized boolean add(TimestampedGeoPosition latest)
{
TimestampedGeoPosition mostRecentPosition = null;
if(!mTimestampedGeoPositions.isEmpty())
{
mostRecentPosition = mTimestampedGeoPositions.getFirst();
}
TimestampedGeoPosition mostRecentPosition = mTimestampedGeoPositions.isEmpty() ? null :
mTimestampedGeoPositions.getFirst();
if(isUnique(latest, mostRecentPosition))
{
mTimestampedGeoPositions.addFirst(latest);
fireTableRowsInserted(0, 0);
while(mTimestampedGeoPositions.size() > MAX_LOCATION_HISTORY)
{
int index = mTimestampedGeoPositions.size() - 1;
mTimestampedGeoPositions.removeLast();
fireTableRowsDeleted(index, index);
}
return true;
}
return false;
}
/**
* Indicates if the latest time and position is at least 30 seconds newer than the previous position and either the
* latitude or longitude differs by at least 0.00001 degrees.
* Indicates if the latest time is more than 2 seconds newer than the previous position or either the latitude or
* longitude differs by more than 0.00001 degrees.
* @param latest location
* @param previous location
* @return indication of uniqueness.
*/
private boolean isUnique(TimestampedGeoPosition latest, TimestampedGeoPosition previous)
private static boolean isUnique(TimestampedGeoPosition latest, TimestampedGeoPosition previous)
{
if(latest != null && previous == null)
{
@@ -106,10 +97,10 @@ public class TrackHistoryModel extends AbstractTableModel
/**
* Get the geo position at the specified index
* @param index to retrieve
* @param index to retrieve, 0 for the newest
* @return geo or null.
*/
public TimestampedGeoPosition get(int index)
public synchronized TimestampedGeoPosition get(int index)
{
if(index >= 0 && index < mTimestampedGeoPositions.size())
{
@@ -119,38 +110,11 @@ public class TrackHistoryModel extends AbstractTableModel
return null;
}
@Override
public int getRowCount()
/**
* Number of positions in the history
*/
public synchronized int size()
{
return mTimestampedGeoPositions.size();
}
@Override
public int getColumnCount()
{
return COLUMNS.length;
}
@Override
public String getColumnName(int column)
{
return COLUMNS[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
TimestampedGeoPosition geoPosition = mTimestampedGeoPositions.get(rowIndex);
switch (columnIndex)
{
case 0:
return mSimpleDateFormat.format(geoPosition.getTimestamp());
case 1:
return mDegreeFormat.format(geoPosition.getLatitude());
case 2:
return mDegreeFormat.format(geoPosition.getLongitude());
}
return null;
}
}

View File

@@ -1,109 +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.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.painter.AbstractPainter;
/**
* Paints a push-pin at the user's location, with the tip of the pin at the location.
*/
public class UserLocationPainter extends AbstractPainter<JXMapViewer>
{
private static final Color NEEDLE = new Color(90, 90, 90);
private static final Color HEAD = new Color(220, 40, 40);
private static final Color HEAD_OUTLINE = new Color(110, 0, 0);
private static final Color HIGHLIGHT = new Color(255, 255, 255, 170);
private static final Color SHADOW = new Color(0, 0, 0, 70);
private static final double NEEDLE_LENGTH = 14.0;
private static final double HEAD_RADIUS = 7.0;
private volatile GeoPosition mPosition;
/**
* Constructs an instance
*/
public UserLocationPainter()
{
setAntialiasing(true);
setCacheable(false);
}
/**
* 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
* @return position, or null
*/
public GeoPosition getPosition()
{
return mPosition;
}
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
GeoPosition position = mPosition;
if(position == null)
{
return;
}
Rectangle viewportBounds = map.getViewportBounds();
Point2D point = map.getTileFactory().geoToPixel(position, map.getZoom());
double x = point.getX() - viewportBounds.getX();
double y = point.getY() - viewportBounds.getY();
double headY = y - NEEDLE_LENGTH - HEAD_RADIUS;
//Shadow where the needle enters the map, so the tip reads as the location
g.setColor(SHADOW);
g.fill(new Ellipse2D.Double(x - 4, y - 2, 8, 4));
g.setColor(NEEDLE);
g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.draw(new Line2D.Double(x, y, x, headY));
Ellipse2D head = new Ellipse2D.Double(x - HEAD_RADIUS, headY - HEAD_RADIUS, HEAD_RADIUS * 2, HEAD_RADIUS * 2);
g.setColor(HEAD);
g.fill(head);
g.setColor(HEAD_OUTLINE);
g.setStroke(new BasicStroke(1.0f));
g.draw(head);
g.setColor(HIGHLIGHT);
g.fill(new Ellipse2D.Double(x - HEAD_RADIUS / 2 - 1, headY - HEAD_RADIUS / 2 - 1, 4, 4));
}
}

View File

@@ -20,6 +20,7 @@ package io.github.dsheirer.module.decode;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.alias.TalkerAliasAutoAdder;
import io.github.dsheirer.alias.action.AliasActionManager;
import io.github.dsheirer.audio.*;
import io.github.dsheirer.audio.codec.mbe.JmbeAudioModule;
@@ -210,9 +211,37 @@ public class DecoderFactory
throw new IllegalArgumentException("Unknown decoder type [" + decodeConfig.getDecoderType().toString() + "]");
}
configureTalkerAliasAutoAdd(channel, modules, aliasModel);
return modules;
}
/**
* Configures the traffic channel manager of a standard (control) channel to automatically add talker aliases to
* the channel's alias list, when the channel is configured for it. Traffic channels share the talker alias manager
* of their control channel, so they use the control channel's setting.
* @param channel configuration
* @param modules for the channel
* @param aliasModel to add aliases to
*/
private static void configureTalkerAliasAutoAdd(Channel channel, List<Module> modules, AliasModel aliasModel)
{
if(channel.isStandardChannel() && channel.isAutoAddTalkerAliases() &&
channel.getDecodeConfiguration().getDecoderType().providesTalkerAlias() &&
channel.getAliasListName() != null && !channel.getAliasListName().isEmpty())
{
TalkerAliasAutoAdder autoAdder = new TalkerAliasAutoAdder(aliasModel, channel.getAliasListName());
for(Module module: modules)
{
if(module instanceof TrafficChannelManager tcm && tcm.getTalkerAliasManager() != null)
{
tcm.getTalkerAliasManager().setTalkerAliasListener(autoAdder);
}
}
}
}
/**
* Creates decoder modules for APCO-25 Phase 2 decoder
* @param channel configuration

View File

@@ -78,6 +78,11 @@ public enum DecoderType
*/
public static final EnumSet<DecoderType> MBE_AUDIO_CODEC_DECODERS = EnumSet.of(DMR, NXDN, P25_PHASE1, P25_PHASE2);
/**
* Decoders that produce talker aliases
*/
public static final EnumSet<DecoderType> TALKER_ALIAS_DECODERS = EnumSet.of(DMR, NXDN, P25_PHASE1, P25_PHASE2);
public Protocol getProtocol()
{
return mProtocol;
@@ -114,4 +119,12 @@ public enum DecoderType
{
return MBE_AUDIO_CODEC_DECODERS.contains(this);
}
/**
* Indicates if the decoder type produces talker aliases
*/
public boolean providesTalkerAlias()
{
return TALKER_ALIAS_DECODERS.contains(this);
}
}

View File

@@ -20,12 +20,12 @@ package io.github.dsheirer.module.decode.dmr;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.channel.state.ChangeChannelTimeoutEvent;
import io.github.dsheirer.channel.state.DecoderStateEvent;
import io.github.dsheirer.channel.state.DecoderStateEvent.Event;
import io.github.dsheirer.channel.state.DecoderStateEvent;
import io.github.dsheirer.channel.state.State;
import io.github.dsheirer.channel.state.TimeslotDecoderState;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.Channel.ChannelType;
import io.github.dsheirer.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelConfigurationChangeNotification;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
@@ -33,9 +33,10 @@ import io.github.dsheirer.identifier.IdentifierClass;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.MutableIdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.identifier.alias.DmrTalkerAliasIdentifier;
import io.github.dsheirer.identifier.alias.TalkerAliasIdentifier;
import io.github.dsheirer.identifier.alias.TalkerAliasManager;
import io.github.dsheirer.identifier.alias.TalkerAliasTracker;
import io.github.dsheirer.identifier.integer.IntegerIdentifier;
import io.github.dsheirer.identifier.radio.RadioIdentifier;
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
import io.github.dsheirer.log.LoggingSuppressor;
import io.github.dsheirer.message.EmptyTimeslotPlaceholderMessage;
@@ -107,7 +108,7 @@ import io.github.dsheirer.source.tuner.channel.rotation.AddChannelRotationActive
import io.github.dsheirer.util.PacketUtil;
import java.util.List;
import java.util.Map;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import io.github.dsheirer.map.GeoPosition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -126,6 +127,11 @@ public class DMRDecoderState extends TimeslotDecoderState
private DMRNetworkConfigurationMonitor mNetworkConfigurationMonitor;
private DMRTrafficChannelManager mTrafficChannelManager;
private DecodeEvent mCurrentCallEvent;
//Call event of the call that just ended, for a talker alias that completes after the call ends
private DecodeEvent mEndedCallEvent;
//Keeps the talker alias matched to the talking radio and assigns received talker aliases to the right radio
private final TalkerAliasTracker mTalkerAliasTracker = new TalkerAliasTracker(getIdentifierCollection(),
this::getTalkerAliasManager, TalkerAliasTracker.BetweenCalls.PREVIOUS_TALKER);
private boolean mIgnoreCRCChecksums;
private DMRDecoderState mSisterDecoderState;
@@ -1315,24 +1321,54 @@ public class DMRDecoderState extends TimeslotDecoderState
case FULL_STANDARD_TALKER_ALIAS_COMPLETE:
if(message instanceof TalkerAliasComplete tac && tac.hasTalkerAliasIdentifier())
{
getIdentifierCollection().update(tac.getTalkerAliasIdentifier());
Identifier fromRadio = getIdentifierCollection().getFromIdentifier();
if(hasTrafficChannelManager() && fromRadio instanceof RadioIdentifier radio)
{
mTrafficChannelManager.getTalkerAliasManager().update(radio, tac.getTalkerAliasIdentifier());
}
if(mCurrentCallEvent != null)
{
broadcast(mCurrentCallEvent);
}
processTalkerAlias(tac.getTalkerAliasIdentifier(), tac.getTimestamp());
}
break;
}
}
/**
* Talker alias manager shared with the traffic channel manager, or null when there's no traffic channel manager.
*/
private TalkerAliasManager getTalkerAliasManager()
{
return hasTrafficChannelManager() ? mTrafficChannelManager.getTalkerAliasManager() : null;
}
/**
* Processes a talker alias: stores it for the talking radio and adds it to the call that it belongs to.
* @param talkerAlias that was received
* @param timestamp of the message
*/
private void processTalkerAlias(TalkerAliasIdentifier talkerAlias, long timestamp)
{
switch(mTalkerAliasTracker.received(talkerAlias, null, timestamp))
{
case CURRENT_CALL ->
{
if(mCurrentCallEvent != null)
{
mCurrentCallEvent.setIdentifierCollection(getIdentifierCollection().copyOf());
broadcast(mCurrentCallEvent);
}
}
case ENDED_CALL ->
{
//Alias completed after the call ended: add it to that call's event when it's the same talker
if(mEndedCallEvent != null && TalkerAliasTracker.isSameRadio(mTalkerAliasTracker.getEndedCallRadio(),
mEndedCallEvent.getIdentifierCollection().getIdentifier(IdentifierClass.USER, Form.RADIO, Role.FROM)))
{
MutableIdentifierCollection mic = new MutableIdentifierCollection(
mEndedCallEvent.getIdentifierCollection().getIdentifiers());
mic.update(talkerAlias);
mEndedCallEvent.setIdentifierCollection(mic);
broadcast(mEndedCallEvent);
}
}
default -> {} //Stored for the radio, for the radio's next call
}
}
/**
* Updates the current call with encryption information.
* @param embeddedEncryptionParameters decoded from the Voice Frame F
@@ -1340,6 +1376,8 @@ public class DMRDecoderState extends TimeslotDecoderState
*/
private void updateEncryptedCall(EmbeddedEncryptionParameters embeddedEncryptionParameters, boolean isGroup, long timestamp)
{
mTalkerAliasTracker.callActivity(timestamp);
if(mCurrentCallEvent != null)
{
String details = mCurrentCallEvent.getDetails();;
@@ -1377,6 +1415,9 @@ public class DMRDecoderState extends TimeslotDecoderState
*/
private void updateCurrentCall(DecodeEventType type, String details, long timestamp)
{
//Keep the talker alias matched to the talking radio before the call event copies the identifiers
mTalkerAliasTracker.callActivity(timestamp);
Event event = (mCurrentCallEvent == null ? Event.START : Event.CONTINUATION);
//Create a repeater channel descriptor if we don't have one
@@ -1428,10 +1469,12 @@ public class DMRDecoderState extends TimeslotDecoderState
{
mCurrentCallEvent.end(timestamp);
broadcast(mCurrentCallEvent);
mEndedCallEvent = mCurrentCallEvent;
mCurrentCallEvent = null;
}
getIdentifierCollection().remove(IdentifierClass.USER, Form.TALKER_ALIAS, Role.FROM);
//Remembers the talker for a talker alias that completes after the call, and removes the talker alias
mTalkerAliasTracker.callEnded();
getIdentifierCollection().remove(IdentifierClass.USER, Form.TONE, Role.FROM);
}

View File

@@ -135,6 +135,7 @@ public class DMRTrafficChannelManager extends TrafficChannelManager implements I
/**
* Talker alias manager
*/
@Override
public TalkerAliasManager getTalkerAliasManager()
{
return mTalkerAliasManager;
@@ -381,6 +382,9 @@ public class DMRTrafficChannelManager extends TrafficChannelManager implements I
public void processChannelGrant(DMRChannel channel, IdentifierCollection identifierCollection,
Opcode opcode, long timestamp, boolean encrypted)
{
//Apply the stored talker alias for the radio, learned from the radio's earlier calls
identifierCollection = mTalkerAliasManager.enrich(identifierCollection);
mLock.lock();
try
@@ -419,11 +423,11 @@ public class DMRTrafficChannelManager extends TrafficChannelManager implements I
}
else if(event != null) //Update current event
{
Identifier from = getIdentifier(identifierCollection, Role.FROM);
Identifier from = getFrom(identifierCollection);
if(from != null)
{
Identifier currentFrom = getIdentifier(event.getIdentifierCollection(), Role.FROM);
Identifier currentFrom = getFrom(event.getIdentifierCollection());
if(currentFrom != null && !Objects.equals(from, currentFrom))
{
event.end(timestamp);
@@ -660,6 +664,15 @@ public class DMRTrafficChannelManager extends TrafficChannelManager implements I
* @param collection containing a TO identifier
* @return TO identifier or null
*/
/**
* FROM identifier of the collection, preferring the radio over other FROM identifiers such as a talker alias.
*/
private Identifier getFrom(IdentifierCollection collection)
{
Identifier radio = TalkerAliasManager.getFromRadio(collection);
return radio != null ? radio : getIdentifier(collection, Role.FROM);
}
private Identifier getIdentifier(IdentifierCollection collection, Role role)
{
List<Identifier> identifiers = collection.getIdentifiers(role);

View File

@@ -28,7 +28,7 @@ import io.github.dsheirer.module.decode.dmr.message.type.PositionError;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.util.FastMath;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import io.github.dsheirer.map.GeoPosition;
/**
* GPS Information

View File

@@ -1,126 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.module.decode.event;
import java.awt.EventQueue;
import java.util.LinkedList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
* AbstractTableModel implementation supporting clearable method options.
*/
public abstract class ClearableHistoryModel<T> extends AbstractTableModel
{
public static final int DEFAULT_HISTORY_SIZE = 200;
private LinkedList<T> mItems = new LinkedList<>();
private int mHistorySize = DEFAULT_HISTORY_SIZE;
/**
* Access an item/row by the model index value.
* @param index to retrieve
* @return item or null
*/
public T getItem(int index)
{
if(index < mItems.size())
{
return mItems.get(index);
}
return null;
}
/**
* Adds the item to the top of the item list and removes any tail items while the item list size exceeds the
* maximum history size for this model.
* @param item to add
*/
public void add(T item)
{
if(mItems.contains(item))
{
int itemRow = mItems.indexOf(item);
fireTableRowsUpdated(itemRow, itemRow);
}
else
{
mItems.addFirst(item);
fireTableRowsInserted(0, 0);
while(mItems.size() > mHistorySize)
{
mItems.removeLast();
fireTableRowsDeleted(mItems.size() - 1, mItems.size() - 1);
}
}
}
/**
* Clears all messages from history
*/
public void clear()
{
EventQueue.invokeLater(() -> {
mItems.clear();
fireTableDataChanged();
});
}
/**
* Clears the current messages and loads the messages argument
*/
public void clearAndSet(List<T> items)
{
EventQueue.invokeLater(() -> {
mItems.clear();
fireTableDataChanged();
for(T item: items)
{
add(item);
}
});
}
/**
* Current history size
* @return history size
*/
public int getHistorySize()
{
return mHistorySize;
}
/**
* Sets the history size
* @param historySize
*/
public void setHistorySize(int historySize)
{
mHistorySize = historySize;
}
@Override
public int getRowCount()
{
return mItems.size();
}
}

View File

@@ -1,171 +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.module.decode.event;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.channel.IChannelDescriptor;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.sample.Listener;
import java.awt.EventQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Decode event table model
*/
public class DecodeEventModel extends ClearableHistoryModel<IDecodeEvent> implements Listener<IDecodeEvent>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(DecodeEventModel.class);
public static final int COLUMN_TIME = 0;
public static final int COLUMN_DURATION = 1;
public static final int COLUMN_EVENT = 2;
public static final int COLUMN_FROM_ID = 3;
public static final int COLUMN_FROM_ALIAS = 4;
public static final int COLUMN_TO_ID = 5;
public static final int COLUMN_TO_ALIAS = 6;
public static final int COLUMN_CHANNEL = 7;
public static final int COLUMN_FREQUENCY = 8;
public static final int COLUMN_DETAILS = 9;
protected String[] mHeaders = new String[]{"Time", "Duration", "Event", "From", "Alias", "To", "Alias", "Channel", "Frequency", "Details"};
public DecodeEventModel()
{
MyEventBus.getGlobalEventBus().register(this);
}
/**
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.DECODE_EVENT || preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
fireTableDataChanged();
}
}
/**
* Adds, updates or deletes the event from the model. Producers can send
* the same call event multiple times to indicate that information in the
* event is updated. Producers can also mark the event as invalid and the
* event will be removed from the model.
*/
public void receive(final IDecodeEvent event)
{
EventQueue.invokeLater(() -> add(event));
}
@Override
public int getColumnCount()
{
return mHeaders.length;
}
public String getColumnName(int column)
{
return mHeaders[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
IDecodeEvent event = getItem(rowIndex);
if(event != null)
{
switch(columnIndex)
{
case COLUMN_TIME:
return event.getTimeStart();
case COLUMN_DURATION:
return event.getDuration();
case COLUMN_EVENT:
return event.getEventType().getLabel();
case COLUMN_FROM_ID:
return event.getIdentifierCollection();
case COLUMN_FROM_ALIAS:
return event.getIdentifierCollection();
case COLUMN_TO_ID:
return event.getIdentifierCollection();
case COLUMN_TO_ALIAS:
return event.getIdentifierCollection();
case COLUMN_CHANNEL:
IChannelDescriptor channelDescriptor = event.getChannelDescriptor();
if(channelDescriptor != null)
{
if(event.hasTimeslot() && !event.toString().contains("TS"))
{
return channelDescriptor + " TS" + event.getTimeslot();
}
else
{
return channelDescriptor.toString();
}
}
else
{
if(event.hasTimeslot() && !event.toString().contains("TS"))
{
return "TS" + event.getTimeslot();
}
else
{
return null;
}
}
case COLUMN_FREQUENCY:
return event.getChannelDescriptor();
case COLUMN_DETAILS:
return event.getDetails();
}
}
return null;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch(columnIndex)
{
case COLUMN_DURATION:
case COLUMN_TIME:
return Long.class;
case COLUMN_DETAILS:
case COLUMN_EVENT:
return String.class;
case COLUMN_FREQUENCY:
case COLUMN_FROM_ALIAS:
case COLUMN_FROM_ID:
case COLUMN_TO_ALIAS:
case COLUMN_TO_ID:
return IdentifierCollection.class;
case COLUMN_CHANNEL:
return String.class;
}
return super.getColumnClass(columnIndex);
}
}

View File

@@ -1,440 +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.module.decode.event;
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.channel.IChannelDescriptor;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.filter.FilterSet;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.identifier.Form;
import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.identifier.Role;
import io.github.dsheirer.module.ProcessingChain;
import io.github.dsheirer.module.decode.event.filter.DecodeEventFilterSet;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
import io.github.dsheirer.sample.Listener;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
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;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
* Decode event table view
*/
public class DecodeEventPanel extends JPanel implements Listener<ProcessingChain>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(DecodeEventPanel.class);
private static final String TABLE_PREFERENCE_KEY = "decode.event.panel";
private final JTable mTable;
private final DecodeEventModel mEventModel = new DecodeEventModel();
private DecodeEventHistory mCurrentEventHistory;
private final IconModel mIconModel;
private final AliasModel mAliasModel;
private final UserPreferences mUserPreferences;
private final TimestampCellRenderer mTimestampCellRenderer;
private final FilterSet<IDecodeEvent> mFilterSet = new DecodeEventFilterSet();
private final HistoryManagementPanel<IDecodeEvent> mHistoryManagementPanel;
/**
* View for call event table
* @param iconModel to display alias icons in table rows
*/
public DecodeEventPanel(IconModel iconModel, UserPreferences userPreferences, AliasModel aliasModel)
{
MyEventBus.getGlobalEventBus().register(this);
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[][grow,fill]"));
mIconModel = iconModel;
mAliasModel = aliasModel;
mUserPreferences = userPreferences;
mTimestampCellRenderer = new TimestampCellRenderer();
mTable = new JTable(mEventModel);
TableRowSorter<TableModel> tableRowSorter = new TableRowSorter<>(mEventModel);
tableRowSorter.setRowFilter(new EventRowFilter());
mTable.setRowSorter(tableRowSorter);
JTableColumnWidthMonitor tableColumnWidthMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTable, TABLE_PREFERENCE_KEY);
updateCellRenderers();
mHistoryManagementPanel = new HistoryManagementPanel<>(mEventModel, "Event Filter Editor");
mHistoryManagementPanel.updateFilterSet(mFilterSet);
add(mHistoryManagementPanel, "span,growx");
JScrollPane emptyScroller = new JScrollPane(mTable);
add(emptyScroller);
//Register filter change listener to refresh the table any time the event filters are changed.
mFilterSet.register(mEventModel::fireTableDataChanged);
}
public void dispose()
{
MyEventBus.getGlobalEventBus().unregister(this);
}
/**
* Receives preference update notifications via the event bus
* @param preferenceType that was updated
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.DECODE_EVENT || preferenceType == PreferenceType.TALKGROUP_FORMAT)
{
EventQueue.invokeLater(mTimestampCellRenderer::updatePreferences);
}
}
private void updateCellRenderers()
{
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_TIME).setCellRenderer(mTimestampCellRenderer);
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_DURATION).setCellRenderer(new DurationCellRenderer());
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_FROM_ID).setCellRenderer(new IdentifierCellRenderer(Role.FROM));
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_FROM_ALIAS).setCellRenderer(new AliasedIdentifierCellRenderer(Role.FROM));
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_TO_ID).setCellRenderer(new IdentifierCellRenderer(Role.TO));
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_TO_ALIAS).setCellRenderer(new AliasedIdentifierCellRenderer(Role.TO));
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_CHANNEL).setCellRenderer(new ChannelDescriptorCellRenderer());
mTable.getColumnModel().getColumn(DecodeEventModel.COLUMN_FREQUENCY).setCellRenderer(new FrequencyCellRenderer());
}
@Override
public void receive(final ProcessingChain processingChain)
{
if(mCurrentEventHistory != null)
{
mCurrentEventHistory.removeListener(mEventModel);
}
EventQueue.invokeLater(() -> {
if(processingChain != null)
{
mCurrentEventHistory = processingChain.getDecodeEventHistory();
mEventModel.clearAndSet(mCurrentEventHistory.getItems());
processingChain.getDecodeEventHistory().addListener(mEventModel);
mHistoryManagementPanel.setEnabled(true);
}
else
{
mCurrentEventHistory = null;
mEventModel.clearAndSet(Collections.emptyList());
mHistoryManagementPanel.setEnabled(false);
}
});
}
/**
* Custom cell renderer for displaying identifiers from an identifier collection
*/
public class IdentifierCellRenderer extends DefaultTableCellRenderer
{
protected Role mRole;
/**
* Constructs an instance of the cell renderer.
*
* @param role of the identifier
*/
public IdentifierCellRenderer(Role role)
{
mRole = role;
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof IdentifierCollection)
{
List<Identifier> identifiers = ((IdentifierCollection)value).getIdentifiers(mRole);
label.setText(format(identifiers));
}
else
{
label.setText(null);
}
return label;
}
/**
* Formats a list of identifiers as a comma separated list of values
* @param identifiers to format
* @return formatted list or null
*/
protected String format(List<Identifier> identifiers)
{
if(identifiers == null || identifiers.isEmpty())
{
return null;
}
StringBuilder sb = new StringBuilder();
for(Identifier identifier: identifiers)
{
if(!sb.isEmpty())
{
sb.append(",");
}
if(identifier.getForm() == Form.TALKGROUP || identifier.getForm() == Form.RADIO || identifier.getForm() == Form.PATCH_GROUP)
{
sb.append(mUserPreferences.getTalkgroupFormatPreference().format(identifier));
}
else
{
sb.append(identifier);
}
}
return sb.toString();
}
}
/**
* Cell renderer for identifier aliases
*/
public class AliasedIdentifierCellRenderer extends DefaultTableCellRenderer
{
private Role mRole;
/**
* Constructs an instance of the cell renderer.
*
* @param role of the identifier
*/
public AliasedIdentifierCellRenderer(Role role)
{
mRole = role;
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Color color = mTable.getForeground();
ImageIcon icon = null;
String text = null;
if(value instanceof IdentifierCollection identifierCollection)
{
List<Identifier> identifiers = identifierCollection.getIdentifiers(mRole);
if(identifiers != null && !identifiers.isEmpty())
{
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
if(aliasList != null)
{
StringBuilder sb = new StringBuilder();
for(Identifier identifier: identifiers)
{
List<Alias> aliases = aliasList.getAliases(identifier);
if(!aliases.isEmpty())
{
if(!sb.isEmpty())
{
sb.append(",");
}
sb.append(Joiner.on(", ").skipNulls().join(aliases));
color = ThemeManager.getInstance().getReadableColor(
aliases.getFirst().getDisplayColor(), label.getBackground());
icon = mIconModel.getIcon(aliases.getFirst().getIconName(), IconModel.DEFAULT_ICON_SIZE);
}
}
text = sb.toString();
}
}
}
label.setText(text);
label.setForeground(color);
label.setIcon(icon);
return label;
}
}
public class TimestampCellRenderer extends DefaultTableCellRenderer
{
private SimpleDateFormat mTimestampFormatter;
public TimestampCellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
updatePreferences();
}
public void updatePreferences()
{
mTimestampFormatter = mUserPreferences.getDecodeEventPreference().getTimestampFormat().getFormatter();
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof Long)
{
label.setText(mTimestampFormatter.format(new Date((long)value)));
}
else
{
label.setText(null);
}
return label;
}
}
public static class DurationCellRenderer extends DefaultTableCellRenderer
{
private final DecimalFormat mDecimalFormat = new DecimalFormat("0.0");
public DurationCellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
String formatted = null;
if(value instanceof Long)
{
long duration = (long)value;
if(duration > 0)
{
formatted = mDecimalFormat.format((double)duration / 1e3d);
}
}
label.setText(formatted);
return label;
}
}
/**
* Frequency value cell renderer
*/
public static class FrequencyCellRenderer extends DefaultTableCellRenderer
{
private final DecimalFormat mFrequencyFormatter = new DecimalFormat("0.00000");
public FrequencyCellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
String formatted = null;
if(value instanceof IChannelDescriptor channelDescriptor)
{
long frequency = channelDescriptor.getDownlinkFrequency();
if(frequency > 0)
{
formatted = mFrequencyFormatter.format(frequency / 1e6d);
}
}
label.setText(formatted);
return label;
}
}
/**
* Channel descriptor value cell renderer
*/
public static class ChannelDescriptorCellRenderer extends DefaultTableCellRenderer
{
public ChannelDescriptorCellRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
}
/**
* Row filter for decode events
*/
public class EventRowFilter extends RowFilter<TableModel, Integer>
{
@Override
public boolean include(Entry<? extends TableModel, ? extends Integer> entry)
{
if(entry.getModel() instanceof DecodeEventModel model)
{
IDecodeEvent event = model.getItem(entry.getIdentifier());
if(event != null)
{
return mFilterSet.canProcess(event) && mFilterSet.passes(event);
}
}
return false;
}
}
}

View File

@@ -1,212 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.module.decode.event;
import io.github.dsheirer.filter.FilterEditor;
import io.github.dsheirer.filter.FilterSet;
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import net.miginfocom.swing.MigLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
/**
* History management panel with controls for managing item histories.
*/
public class HistoryManagementPanel<T> extends JPanel
{
private ClearableHistoryModel mModel;
private FilterSet<T> mFilterSet;
private FilterEditor<T> mFilterEditor;
private JButton mClearButton;
private JButton mFilterButton;
private JSlider mHistorySlider;
private JLabel mHistoryTitleLabel;
private JLabel mHistoryValueLabel;
private String mFilterEditorTitle;
/**
* Constructs an instance
* @param model to manage
*/
public HistoryManagementPanel(ClearableHistoryModel model, String filterEditorTitle)
{
mModel = model;
mFilterEditorTitle = filterEditorTitle;
setLayout(new MigLayout("insets 6 1 5 5", "[]5[]10[]5[]5[][grow]", ""));
add(getFilterButton());
add(getClearButton());
add(getHistoryTitleLabel());
add(getHistorySlider());
add(getHistoryValueLabel());
setEnabled(false);
}
/**
* Updates the filter set
* @param filterSet to use
*/
public void updateFilterSet(FilterSet<T> filterSet)
{
mFilterSet = filterSet;
if(mFilterEditor != null)
{
getFilterEditor().updateFilterSet(filterSet);
}
}
/**
* Overrides the panel method to also set the enabled state for the child controls.
* @param enabled true if this component should be enabled, false otherwise
*/
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
getClearButton().setEnabled(enabled);
getFilterButton().setEnabled(enabled);
getHistoryValueLabel().setEnabled(enabled);
getHistoryTitleLabel().setEnabled(enabled);
getHistorySlider().setEnabled(enabled);
}
/**
* Filter editor
* @return editor lazily constructed
*/
private FilterEditor<T> getFilterEditor()
{
if(mFilterEditor == null)
{
mFilterEditor = new FilterEditor<>(mFilterEditorTitle, getFilterButton(), mFilterSet);
}
return mFilterEditor;
}
/**
* Filter button for accessing the filter editor
* @return filter button
*/
private JButton getFilterButton()
{
if(mFilterButton == null)
{
mFilterButton = new JButton("Filters");
mFilterButton.setToolTipText("Edit filters");
mFilterButton.addActionListener(arg0 -> EventQueue.invokeLater(() -> getFilterEditor().setVisible(true)));
}
return mFilterButton;
}
/**
* Clear button
* @return clear button
*/
private JButton getClearButton()
{
if(mClearButton == null)
{
mClearButton = new JButton("Clear");
mClearButton.addActionListener(e -> mModel.clear());
mClearButton.setToolTipText("Clears the history");
}
return mClearButton;
}
/**
* History value label.
* @return label
*/
private JLabel getHistoryValueLabel()
{
if(mHistoryValueLabel == null)
{
mHistoryValueLabel = new JLabel(String.valueOf(ClearableHistoryModel.DEFAULT_HISTORY_SIZE));
}
return mHistoryValueLabel;
}
/**
* History title label
* @return label
*/
private JLabel getHistoryTitleLabel()
{
if(mHistoryTitleLabel == null)
{
mHistoryTitleLabel = new JLabel("History:");
}
return mHistoryTitleLabel;
}
/**
* History value slider control
* @return slider
*/
private JSlider getHistorySlider()
{
if(mHistorySlider == null)
{
mHistorySlider = new JSlider();
mHistorySlider.setToolTipText("Adjust history size. Double-click to reset to default 200");
mHistorySlider.setMinimum(0);
mHistorySlider.setMaximum(2000);
mHistorySlider.setMinorTickSpacing(25);
mHistorySlider.setMajorTickSpacing(500);
mHistorySlider.setPaintTicks(false);
mHistorySlider.setPaintLabels(false);
mHistorySlider.addMouseListener(new MouseListener()
{
@Override
public void mouseClicked(MouseEvent arg0)
{
if(SwingUtilities.isLeftMouseButton(arg0) && arg0.getClickCount() == 2)
{
mHistorySlider.setValue(ClearableHistoryModel.DEFAULT_HISTORY_SIZE);
}
}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
});
mHistorySlider.setValue(mModel.getHistorySize());
mHistorySlider.addChangeListener(e -> {
mModel.setHistorySize(mHistorySlider.getValue());
getHistoryValueLabel().setText(String.valueOf(mHistorySlider.getValue()));
});
}
return mHistorySlider;
}
}

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