Compare commits

..

31 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
Denny Sheirer
c93d099742 #2658 DMR additional error detection and correction enhancements (#2659)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 04:04:34 -05:00
Denny Sheirer
be0966653b #2656 DMR Hamming and BPTC error detection and correction algorithm enhancements (#2657)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 03:46:55 -05:00
jpmetal
26a24fc6ad Fix the DMR EMB QR(16,7,6) codeword table (#2645)
All 64 entries with bit 15 set differed by an XOR of 0x0060 from the
codewords derived from the generator matrix in TS 102 361-1 table B.12, so
error-free EMBs for colour codes 8-15 were flagged invalid by the hard
decoder and "corrected" by the soft decoder.  Single bit errors in those
codewords, though within the correction capability, were reported as
uncorrectable for 13 of the 15 bit positions (87 %).

Co-authored-by: modificaz <jpmetal@freemail.gr>
2026-11-15 03:46:24 -05:00
Jared Szechy
9deabd0dcc Network tuner support - rtl_tcp (#2471)
* Add network tuner dialog

* wip: network tuner configs

* wip stash

* working tcp solution

* fix copyright headers

* fix: resolve rebase conflicts from jRTL library changeover

- Drop redundant JFrequencyControl digit-sizing fix now that upstream
  fixes the same issue via setColumns(1)
- Mark SUPPORTED_NETWORK_TUNERS final to match the new EnumSet style
- Replace removed SampleRate.getClosest() with a local nearest-match
  helper in NetworkTunerEditor

* Add mise config
2026-11-15 03:32:02 -05:00
Denny Sheirer
2db41393dc #2654 NXDN Audio Removes Additive Non-Clipping Gain and uses JMBE AGC only (#2655)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 02:15:33 -05:00
Denny Sheirer
29a10edf03 #2652 DMR audio module checks voice messages for at least one CRC-valid audio frame before processing audio and purges any enqueued audio on voice header to prepare for the upcoming call (#2653)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-15 01:47:46 -05:00
Denny Sheirer
5bce541631 #2641 Enhanced radio reference integration. With a premium subscription and when you set your location on the map, the Spectral display includes radio reference layer that presents popup card in the spectrum that shows candidate systems or frequencies ordered by distance from your location. Background thread builds an offline cache of data to support this. Map plots this cache as tower pins on the map and you can hover and active site frequencies from the map. (#2642)
Updates sdrtrunk to use latest radio reference api jar.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-14 09:37:29 -05:00
Denny Sheirer
9641d2ef59 #736 New JavaFX spectral display and waterfall for both tuner and channel spectrums. (#2637)
* Popout configuration panel (top-left of display)
* Themed color support
* Reworked signal averating/smoothing
* Optional decibel overlay with corrected decibel calculations
* Integrated noise floor slider in  channel view
* Traffic channel overlays
* Popup channel information when hovering over playlist channels.
* Removes legacy swing components.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 07:30:31 -05:00
Denny Sheirer
73fc85aa76 #1045 P25 encrypted call ignore setting. Cleanup several other errors. (#2636)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 05:14:45 -05:00
Thinline Dynamic Solutions
aad971db9c Add Thinline Radio completed-call upload stream type (#2626)
Same /api/call-upload flow as Rdio Scanner, with its own configuration and
playlist editor. Reuses RdioScannerBroadcaster.

Co-authored-by: Michael Chambers <michaelchambers@Michaels-Mac-mini.local>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-13 04:54:08 -05:00
Denny Sheirer
73d3238644 #2634 Gradle build now uses git tag for versioning (#2635)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 03:32:08 -05:00
farewell-ladmin
4626d56730 #2392 P25P1: trust HDU/LDU2 algorithm ID over LC service options encryption flag (#2477)
Some radios set the encryption flag in the service options of the LDU1 Group
Voice Channel User link control while transmitting clear voice; the HDU and
LDU2 encryption sync parameters report ALGID 0x80 (unencrypted) for the same
call. Example (CoMIRS Boston, TG 2217, valid LCs from several radios):

  HDU   TALKGROUP:2217 UNENCRYPTED
  LDU1  GROUP VOICE CHANNEL USER FM:64008 TO:2217 SERVICE OPTIONS:PRI4 ENCRYPTED CIRCUIT
  LDU2  UNENCRYPTED

P25P1DecoderState broadcast State.ENCRYPTED for each such LDU1 and State.CALL
for each LDU2, so the channel state flapped between CALL and ENCRYPTED (and on
upstream, where ENCRYPTED cannot change back to CALL, the call stays muted).

Track the per-call encryption state from the HDU header and LDU2 algorithm ID
(reset at TDU/TDULC). When it is known to be unencrypted, clear the encryption
flag on the LC service options before using them for the channel state and
traffic channel call event. Genuinely encrypted calls are unaffected, and when
the algorithm ID is not yet known (late entry before the first LDU2) the LC
service options are used as before.

Adds VoiceServiceOptions.createUnencrypted(ServiceOptions) to copy service
options with only the encryption flag cleared.

Verified by driving P25P1DecoderState with HDU/LDU1/LDU2/TDU sequences
reproducing the field logs: state events go from C C C E C E C to all CALL;
encrypted calls (ALGID 0x84) still report ENCRYPTED throughout.


Claude-Session: https://claude.ai/code/session_01FRdfTvgcdBvwkipdfP8qxy
(cherry picked from commit 2ef3c9d02176871577d38f8afd0fa3c32fb92a58)

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-13 02:56:00 -05:00
Christopher Smith
1a90eaf6c6 P25P1: decode unconfirmed data PDUs with a packet data SAP as IP packets (#2506)
PDU header format 0x15 is the generic unconfirmed data header; unconfirmed
multi-block trunking control (UMBTC) is only its trunking control SAP
(61/63) use.  PDUHeaderFactory built a plain PDUHeader for every 0x15
header and PDUMessageFactory sent every such sequence to createUMBTC(), so
outbound unconfirmed IP data (SNDCP RF UNCONFIRMED DATA with SAP 0, 4 or
6) was logged raw as

  PDU HEADER FORMAT:UNCONFIRMED MBTC UNCONFIRMED VENDOR:STANDARD TO LLID:n
  DATA BLOCKS:4 MSG:4100450000...

while the confirmed equivalent (format 0x16) was decoded as IPPKT with
its LRRP / ARS payload.

- PDUHeaderFactory: build a PacketHeader for a 0x15 header whose SAP is
  UNENCRYPTED_USER_DATA, PACKET_DATA or SNDCP_PACKET_DATA_CONTROL.  Other
  SAPs, including trunking control 61/63, keep the plain PDUHeader.
- PDUMessageFactory: route a 0x15 sequence whose header is a PacketHeader
  through createPacketData(); everything else stays on the UMBTC path.

No payload changes are needed: PacketMessage already sizes unconfirmed
data blocks at 12 octets, and the header fields it uses (SAP, pad octet
count, data header offset) sit at the same bit positions in the confirmed
and unconfirmed headers.  The ARS RegistrationAcknowledgement parser only
reads the extension octet, so the 5-octet trailer (0x04 + 32-bit time)
some systems append does not affect it.

Adds PDUMessageFactoryTest, built from two unconfirmed PDUs captured on a
Motorola P25 Phase 1 system (ARS registration acknowledgements to UDP
port 4005, one with the trailer), plus header routing checks for SAP
0/4/6, SAP 61/63 and the confirmed 0x16 header.

Co-authored-by: csmith_ai <carrottop@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 02:42:53 -05:00
Christopher Smith
fbc54a38dd LRRP: decode request token values as 7-bit varints and correct request token names (#2507)
Motorola LRRP request tokens that carry an integer (trigger interval
0x31, trigger distance 0x78 and the unknown parameters 0x42 / 0x44)
encode it as a 7-bit variable length integer: each byte holds seven
value bits, most significant group first, and the high bit of a byte
flags a continuation byte.  The parser read a single byte, so a real
triggered location start request

  09 11 22 03 FF FF EE 52 44 64 42 9C 10 62 57 34 31 84 58

was logged as

  ID:15663103 TRIGGER ON GPIO TRIGGER EVERY:132 SECS REQUESTED TOKENS
  [TIME,REQUEST-64,REQUEST-62,HORIZONTAL DIRECTION,TIMESTAMP,
  UNRECOGNIZED(10,44,58,9C)]

and now decodes to

  ID:FFFFEE PERIODIC INTERVAL:600 SECS PARAM-42:3600 PARAM-44:100
  REQUESTED TOKENS [TIME,HORIZONTAL SPEED,HORIZONTAL DIRECTION]

The encoding and the token names follow node-dmr-lib (LRRP.js
parseLRRPInt/toLRRPInt and its quoted TRBONet captures, DMRConst.js)
and Moto.Net (LRRPPacket.cs "using VLQ for most of the fields").

- Add VarInt, a shared 7-bit varint reader, and VarIntToken, a token
  base class whose byte length is measured from the value and bounded
  by the remaining payload.  Use them for 0x31, 0x78, 0x42 and 0x44.
- Add TokenType.fromRequestValue(): 0x34 is the periodic trigger flag
  in a request and the timestamp in a response.  TokenFactory accepts
  the resolved TokenType so the request path is not re-resolved.
- Rename request tokens: 0x31 TRIGGER_INTERVAL (TriggerInterval),
  0x4A TRIGGER_CONDITION (TriggerCondition: 02 emergency, 42 pin
  status change, 50 PTT, 51 PTT emergency), 0x78 TRIGGER_DISTANCE
  (TriggerDistance), 0x62 HORIZONTAL_SPEED.  0x42 and 0x44 become
  REQUEST_PARAMETER_42/44 (RequestParameter) with an optional varint
  value; their meaning is unknown (observed 3600 and 100).  Remove
  TriggerGpio and TriggerOnMove.
- Identity: assemble the request id big-endian (it was accumulated
  LSB-first), render it in hex, and clamp the read to the message.
- RequestedTokens: keep a list that holds only unrecognized ids; add
  getters for the recognized and unrecognized lists.
- Remove leftover debug locals from LRRPPacket.parseTokens().
- Add LRRPPacketTest (both captured bodies plus two copies with a
  corrupted type byte) and VarIntTest.

Built with the project's Gradle build (JDK 27 toolchain, in Docker);
compileJava, compileTestJava and the 9 new tests pass.

Co-authored-by: csmith_ai <carrottop@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-13 02:33:52 -05:00
Denny Sheirer
07b61be257 #2632 Detect on startup if multiple versions of any library are on the classpath and warn user to cleanup and reinstall (#2633)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-13 01:59:38 -05:00
Steve Pinkham
74dc32538f P25 Phase 1: fix typo in HDU Golay word starts (278 -> 378) (#2630)
GOLAY_WORD_STARTS listed 278 where it should list 378. The word at 378 was
never corrected, and the decoder ran a correction over bits 278-295 that
straddle the already corrected words at 270 and 288.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:31:08 -05:00
Steve Pinkham
7fcf035337 edac: correct Golay(24,12) words that are not at the start of the message (#2631)
Golay24.checkAndCorrect indexed the word from bit 0 (getInt(0, 22), xor(12, ...),
flip(index)) and took the parity over the whole message, so it was only right for a
message that is exactly one 24-bit word. P25 TDULC words 2-12 and the DMR voice
superframe words at 24 and 48 were "corrected" in the wrong bits. Decode any other
word in a 24-bit copy and write it back.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:29:50 -05:00
358 changed files with 33298 additions and 20751 deletions

View File

@@ -14,6 +14,9 @@ jobs:
steps:
- uses: actions/checkout@v7
with:
# Full history and tags, so the build can describe the commit relative to the latest version tag
fetch-depth: 0
- name: Set up JDK 27
uses: actions/setup-java@v6
@@ -34,7 +37,7 @@ jobs:
- name: Create Build Info file
run: |
echo -e "ref: $GITHUB_REF \ncommit: $GITHUB_SHA\nbuild: $(date +"%Y-%m-%dT%H:%M:%SZ")" > build/image/build_info.txt
echo -e "ref: $GITHUB_REF \ncommit: $GITHUB_SHA\ndescribe: $(git describe --tags --match 'v[0-9]*' --dirty)\nbuild: $(date +"%Y-%m-%dT%H:%M:%SZ")" > build/image/build_info.txt
- name: Add build artifacts to nightly release
uses: softprops/action-gh-release@v3

View File

@@ -1,6 +1,6 @@
# Publishes a release when a version tag is pushed. The tag has to match
# projectVersion in gradle.properties with a leading 'v': v0.6.2 for a final
# release, or v0.6.2-beta-1 / v0.6.2-alpha-1 for a pre-release.
# Publishes a release when a version tag is pushed: v0.6.2 for a final release,
# or v0.6.2-beta-1 / v0.6.2-alpha-1 for a pre-release. The build derives the
# version from the tag (see build.gradle).
name: Release
on:
@@ -22,15 +22,6 @@ jobs:
# Full history and tags, to find the previous release tag for the release notes
fetch-depth: 0
- id: version
run: |
expected="v$(sed -n 's/^projectVersion=//p' gradle.properties | tr -d '[:space:]')"
if [ "$GITHUB_REF_NAME" != "$expected" ]; then
echo "::error::Tag $GITHUB_REF_NAME does not match projectVersion in gradle.properties ($expected)"
exit 1
fi
echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
# Release notes list the PRs since the previous version tag (never 'nightly'). A final release
# starts from the previous final release, so it covers every alpha and beta in between.
- id: previous
@@ -54,6 +45,17 @@ jobs:
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v6
# The version comes from 'git describe', which can pick a different tag when more than one
# version tag points at the same commit. Fail rather than publish zips with the wrong version.
- id: version
run: |
version="$(./gradlew -q printVersion --console=plain | tail -n 1)"
if [ "v$version" != "$GITHUB_REF_NAME" ]; then
echo "::error::Build version $version does not match tag $GITHUB_REF_NAME"
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
- name: Build and test
run: ./gradlew clean build --console=plain

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.
@@ -54,17 +66,19 @@ committed to the code base, so it's not really 'nightly' as much as it is 'curre
Releases are built and published automatically by the [Release](.github/workflows/release.yml) GitHub workflow
whenever a version tag is pushed to the repository.
1. Update `projectVersion` in `gradle.properties` to the new version, following the naming convention described in
that file (e.g. `0.6.2-alpha-1`, `0.6.2-beta-1` or `0.6.2`).
2. Commit and push the change to `master`.
3. Create and push a tag that matches the version with a leading `v`:
The version is taken from the tag, so there is no version number to update in the code. Create and push a tag
with a leading `v`, following the naming convention described in `gradle.properties` (e.g. `v0.6.2-alpha-1`,
`v0.6.2-beta-1` or `v0.6.2`):
```
git tag v0.6.2-beta-1
git push origin v0.6.2-beta-1
```
Builds made from an untagged commit get a version like `0.6.2-beta-1-14-g4626d567` (14 commits after the
`v0.6.2-beta-1` tag, at commit `4626d567`), with `-dirty` appended when there are uncommitted changes.
The workflow then:
* Verifies that the tag matches `projectVersion` in `gradle.properties` and fails if it does not.
* Verifies that the version the build derives from git matches the tag and fails if it does not.
* Builds and tests the code, then creates the release zips for Linux, Mac and Windows (x86-64 and aarch64).
* Creates a GitHub release titled `Version <version>` with auto-generated release notes (a "What's Changed" list of
the PRs merged since the previous version tag), and attaches the six zip

View File

@@ -52,8 +52,44 @@ plugins {
id 'org.beryx.runtime' version '2.0.1'
}
//Version is defined in gradle.properties so that we can CLI override it for nightly builds.
version = project.findProperty('projectVersion')
/**
* Version is derived from the most recent 'v<version>' git tag (e.g. v1.0.0-beta-1 -> 1.0.0-beta-1). Commits after
* the tag produce a version like 1.0.0-beta-1-14-g4626d567 and uncommitted changes append '-dirty'. The moving
* 'nightly' tag is ignored. Override with -PprojectVersion=<version> (the nightly build uses 'nightly' so that the
* nightly release asset names stay the same). Falls back to 'unknown' when built outside a git checkout.
*/
String gitDescribe = describeGitVersion()
version = project.findProperty('projectVersion') ?: (gitDescribe ? gitDescribe.substring(1) : 'unknown')
String describeGitVersion()
{
try
{
def describe = providers.exec {
commandLine 'git', 'describe', '--tags', '--match', 'v[0-9]*', '--dirty'
ignoreExitValue = true
}
if(describe.result.get().exitValue == 0)
{
return describe.standardOutput.asText.get().trim()
}
}
catch(Exception e)
{
logger.warn("Unable to determine version from git tags: " + e.message)
}
return null
}
tasks.register('printVersion') {
description = 'Prints the project version'
def projectVersion = version
doLast {
println projectVersion
}
}
//Java 27 is required for this version of the Project Panama preview/incubator feature
java {
@@ -132,8 +168,7 @@ dependencies {
implementation 'io.github.dsheirer:jlimesdr:25.1.0.2' //LimeSDR tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jrtl:1.4.0.3' //RTL-SDR tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jsdrplay:3.15.3' //SDRplay RSP tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:jsignalhound:2026.10.05' //Signal Hound tuners - GitHub release, see settings.gradle
implementation 'io.github.dsheirer:radio-reference-api:18.0.0'
implementation 'io.github.dsheirer:radio-reference-api:18.1.0' //RadioReference SOAP API - GitHub release, see settings.gradle
implementation 'org.apache.commons:commons-compress:1.28.0' //Not used directly - overrides the vulnerable 1.21 version from jarchivelib
implementation 'org.apache.commons:commons-lang3:3.21.0'
implementation 'org.apache.commons:commons-math3:3.6.1'
@@ -203,6 +238,7 @@ jar {
attributes (
'Implementation-Title' : 'sdrtrunk project',
'Implementation-Version' : archiveVersion,
'Git-Describe' : gitDescribe ?: 'unknown',
'Created-By' : "Gradle ${gradle.gradleVersion}",
'Build-Timestamp' : new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(new Date()),
'Build-JDK' : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']}",

View File

@@ -17,15 +17,16 @@
# *****************************************************************************
#
# Version naming conventions:
# Alpha: maj.min.patch-alpha-build
# Beta: maj.min.patch-beta-build
# Release: maj.min.patch
# The project version is no longer defined here. It is derived from the most recent 'v<version>' git tag (see
# build.gradle) and can be overridden with -PprojectVersion=<version>.
#
# Example: 0.6.0-beta-5
# Version tag naming conventions:
# Alpha: vmaj.min.patch-alpha-build
# Beta: vmaj.min.patch-beta-build
# Release: vmaj.min.patch
#
# Note: this is so that the file names for the resultant release build products match the GitLab release asset
# Example: v0.6.0-beta-5
#
# Note: this is so that the file names for the resultant release build products match the GitHub release asset
# tag name, specifically the dashes inserted before and after the alpha/beta labels.
# See: https://github.com/DSheirer/sdrtrunk/issues/1651
projectVersion=1.0.0-beta-1

2
mise.toml Normal file
View File

@@ -0,0 +1,2 @@
[tools]
java = "liberica-javafx-27"

View File

@@ -75,15 +75,6 @@ dependencyResolutionManagement {
content { includeModule 'io.github.dsheirer', 'jsdrplay' }
}
//jSignalHound is published as a GitHub release. The jar does not contain the Signal Hound API native libraries,
//which users install separately from the Signal Hound SDK
ivy {
url = 'https://github.com/DSheirer/jSignalHound/releases/download'
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'jsignalhound' }
}
//jBladeRF is published as a GitHub release, with the native libraries for all platforms in the jar
ivy {
url = 'https://github.com/DSheirer/jBladeRF/releases/download'
@@ -91,5 +82,14 @@ dependencyResolutionManagement {
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'jbladerf' }
}
//radio-reference-api is published as a GitHub release. Its dependencies (jackson-dataformat-xml, slf4j-api)
//are not pulled in transitively and are declared directly in build.gradle
ivy {
url = 'https://github.com/DSheirer/radio-reference-api/releases/download'
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
metadataSources { artifact() }
content { includeModule 'io.github.dsheirer', 'radio-reference-api' }
}
}
}

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

@@ -25,6 +25,7 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyCallConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration;
import io.github.dsheirer.audio.broadcast.thinline.ThinlineRadioConfiguration;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzConfiguration;
import io.github.dsheirer.audio.broadcast.icecast.IcecastConfiguration;
import io.github.dsheirer.audio.broadcast.shoutcast.v1.ShoutcastV1Configuration;
@@ -49,6 +50,7 @@ import java.net.SocketAddress;
@JsonSubTypes({
@JsonSubTypes.Type(value = BroadcastifyCallConfiguration.class, name="broadcastifyCallConfiguration"),
@JsonSubTypes.Type(value = RdioScannerConfiguration.class, name="RdioScannerConfiguration"),
@JsonSubTypes.Type(value = ThinlineRadioConfiguration.class, name="ThinlineRadioConfiguration"),
@JsonSubTypes.Type(value = OpenMHzConfiguration.class, name="OpenMHzConfiguration"),
@JsonSubTypes.Type(value = IcecastConfiguration.class, name="icecastConfiguration"),
@JsonSubTypes.Type(value = ShoutcastV1Configuration.class, name="shoutcastV1Configuration"),

View File

@@ -24,6 +24,7 @@ import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyCallConfigura
import io.github.dsheirer.audio.broadcast.broadcastify.BroadcastifyFeedConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerBroadcaster;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration;
import io.github.dsheirer.audio.broadcast.thinline.ThinlineRadioConfiguration;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerFeedConfiguration;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzBroadcaster;
import io.github.dsheirer.audio.broadcast.openmhz.OpenMHzConfiguration;
@@ -68,6 +69,7 @@ public class BroadcastFactory
return new BroadcastifyCallBroadcaster((BroadcastifyCallConfiguration)configuration,
inputAudioFormat, mp3Setting, aliasModel);
case RDIOSCANNER_CALL:
case THINLINE_RADIO:
return new RdioScannerBroadcaster((RdioScannerConfiguration)configuration,
inputAudioFormat, mp3Setting, aliasModel);
case OPENMHZ:
@@ -113,6 +115,8 @@ public class BroadcastFactory
return new BroadcastifyCallConfiguration(format);
case RDIOSCANNER_CALL:
return new RdioScannerConfiguration(format);
case THINLINE_RADIO:
return new ThinlineRadioConfiguration(format);
case BROADCASTIFY:
return new BroadcastifyFeedConfiguration(format);
case OPENMHZ:

View File

@@ -32,6 +32,7 @@ public enum BroadcastServerType
ICECAST_HTTP("Icecast 2 (v2.4+)", "images/icecast.png"),
RDIOSCANNER_CALL("Rdio Scanner", "images/rdioscanner.png"),
THINLINE_RADIO("Thinline Radio", "images/rdioscanner.png"),
OPENMHZ("OpenMHz", "images/openmhz.png"),
ICECAST_TCP("Icecast (v2.3)", "images/icecast.png"),
SHOUTCAST_V1("Shoutcast v1.x", "images/shoutcast.png"),

View File

@@ -113,7 +113,8 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
}
else
{
mLog.error("Error connecting to Rdio Scanner server on startup [" + response + "]");
mLog.error("Error connecting to " + getBroadcastConfiguration().getServiceName() +
" server on startup [" + response + "]");
setBroadcastState(BroadcastState.ERROR);
}
@@ -249,7 +250,8 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
}
catch(IOException e)
{
mLog.error("Rdio Scanner API - audio recording file not found - ignoring upload");
mLog.error(getBroadcastConfiguration().getServiceName() +
" API - audio recording file not found - ignoring upload");
}
if(audioBytes != null)
@@ -286,14 +288,14 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
//We get socket reset exceptions occasionally when the remote server doesn't
//fully read our request and immediately responds.
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error("Rdio Scanner API file upload fail [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
else
{
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error("Rdio Scanner API file upload fail [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
@@ -321,7 +323,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else
{
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
mLog.error("Rdio Scanner API file upload fail [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
fileResponse.statusCode() + "] response [" +
fileResponse.body() + "]");
}
@@ -334,7 +336,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
else
{
//Register an error for the file not found exception
mLog.error("Rdio Scanner API - upload file not found [" +
mLog.error(getBroadcastConfiguration().getServiceName() + " API - upload file not found [" +
audioRecording.getPath().toString() + "]");
incrementErrorAudioCount();
broadcast(new BroadcastEvent(RdioScannerBroadcaster.this,

View File

@@ -19,6 +19,7 @@
package io.github.dsheirer.audio.broadcast.rdioscanner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.audio.broadcast.BroadcastConfiguration;
import io.github.dsheirer.audio.broadcast.BroadcastFormat;
@@ -125,6 +126,15 @@ public class RdioScannerConfiguration extends BroadcastConfiguration
return BroadcastServerType.RDIOSCANNER_CALL;
}
/**
* Product name written to connection and upload logs.
*/
@JsonIgnore
public String getServiceName()
{
return "Rdio Scanner";
}
@Override
public BroadcastConfiguration copyOf()
{

View File

@@ -0,0 +1,75 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.audio.broadcast.thinline;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.audio.broadcast.BroadcastConfiguration;
import io.github.dsheirer.audio.broadcast.BroadcastFormat;
import io.github.dsheirer.audio.broadcast.BroadcastServerType;
import io.github.dsheirer.audio.broadcast.rdioscanner.RdioScannerConfiguration;
/**
* Call upload configuration for Thinline Radio.
*
* Thinline Radio accepts the same completed-call upload used by Rdio Scanner, including the system id, API key,
* and /api/call-upload path.
*/
public class ThinlineRadioConfiguration extends RdioScannerConfiguration
{
/**
* Constructor for Jackson
*/
public ThinlineRadioConfiguration()
{
this(BroadcastFormat.MP3);
}
/**
* Public constructor.
* @param format to use for audio recording (MP3)
*/
public ThinlineRadioConfiguration(BroadcastFormat format)
{
super(format);
}
@JacksonXmlProperty(isAttribute = true, localName = "type", namespace = "http://www.w3.org/2001/XMLSchema-instance")
@Override
public BroadcastServerType getBroadcastServerType()
{
return BroadcastServerType.THINLINE_RADIO;
}
@JsonIgnore
@Override
public String getServiceName()
{
return "Thinline Radio";
}
@Override
public BroadcastConfiguration copyOf()
{
ThinlineRadioConfiguration copy = new ThinlineRadioConfiguration();
copy.setSystemID(getSystemID());
return copy;
}
}

View File

@@ -41,11 +41,11 @@ public abstract class AmbeAudioModule extends JmbeAudioModule
{
if(getAudioCodec() != null)
{
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio will be available");
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio can be processed");
}
else
{
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be available");
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be processed");
}
sLibraryStatusLogged = true;

View File

@@ -57,10 +57,11 @@ public class ByteNativeBuffer extends AbstractNativeBuffer
public ByteNativeBuffer(byte[] samples, long timestamp, float averageDc, float samplesPerMillisecond)
{
super(timestamp, samplesPerMillisecond);
//Ensure we're an even multiple of the fragment size. Typically, this will be 64k or 128k
if(samples.length % FRAGMENT_SIZE != 0)
//Ensure we're an even multiple of the fragment size in bytes (2 bytes per I/Q sample). Typically, this
//will be 64k or 128k
if(samples.length % (FRAGMENT_SIZE * 2) != 0)
{
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + FRAGMENT_SIZE);
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + (FRAGMENT_SIZE * 2));
}
mSamples = samples;

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, settingsManager);
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,11 +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.map.MapPanel;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.map.MapPanel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
@@ -62,8 +63,10 @@ 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, settingsManager);
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, detailTabsVisible);
mMapPanel = new MapPanel(mapService, iconModel, userPreferences,
playlistManager.getRadioReference() != null ? playlistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(playlistManager));
mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences);
init();

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

@@ -153,6 +153,14 @@ public class ChannelProcessingManager implements Listener<ChannelEvent>
return !mProcessingChainsMap.isEmpty();
}
/**
* Channels that currently have a processing chain, including temporary traffic channels.
*/
public List<Channel> getProcessingChannels()
{
return new ArrayList<>(mProcessingChainsMap.keySet());
}
/**
* Returns the current processing chain associated with the channel, or
* null if a processing chain is not currently setup for the channel

View File

@@ -1,51 +0,0 @@
package io.github.dsheirer.dsp.gain;
public class NonClippingGain
{
private float mGain;
private float mMaxValue;
/**
* Applies a fixed gain value to the float samples.
*
* @param gain value
* @param maxValue max absolute value to prevent clipping ( 0.0 to 1.0 )
*/
public NonClippingGain( float gain, float maxValue )
{
mGain = gain;
mMaxValue = maxValue;
}
/**
* Applies gain to the sample
*/
public float apply( float sample )
{
float adjusted = sample * mGain;
if( adjusted > mMaxValue )
{
adjusted = mMaxValue;
}
if( adjusted < -mMaxValue )
{
adjusted = -mMaxValue;
}
return adjusted;
}
/**
* Applies gain to the sample array
*/
public float[] apply( float[] samples )
{
for( int x = 0; x < samples.length; x++ )
{
samples[ x ] = apply( samples[ x ]);
}
return samples;
}
}

View File

@@ -68,6 +68,29 @@ public class Golay24
*/
public static int checkAndCorrect(CorrectedBinaryMessage message, int startIndex)
{
//The correction below indexes the word from bit 0 and takes the parity over the whole message, so it is only
//correct for a message that is exactly the 24-bit word. Decode any other word in a 24-bit copy.
if(startIndex != 0 || message.size() != 24)
{
CorrectedBinaryMessage word = new CorrectedBinaryMessage(24);
int original = message.getInt(startIndex, startIndex + 23);
word.load(0, 24, original);
int result = checkAndCorrectWord(word);
int corrected = word.getInt(0, 23);
message.load(startIndex, 24, corrected);
message.incrementCorrectedBitCount(Integer.bitCount(original ^ corrected));
return result;
}
return checkAndCorrectWord(message);
}
/**
* Error detection and correction of a message that is exactly one 24-bit word.
*/
private static int checkAndCorrectWord(CorrectedBinaryMessage message)
{
int startIndex = 0;
boolean parityError = message.cardinality() % 2 != 0;
int syndrome = getSyndrome(message, startIndex);

View File

@@ -37,7 +37,8 @@ public class Hamming13
*
* @param message containing a Hamming protected word
* @param offset to the start of the protected word
* @return message index for an error bit or -1 if no errors are detected.
* @return message index for an error bit, -1 if no errors are detected, or 1000 if more than one bit error is
* detected.
*/
public static int getErrorIndex(BinaryMessage message, int offset)
{
@@ -45,7 +46,8 @@ public class Hamming13
if(syndrome > 0)
{
return offset + ERROR_INDEX[syndrome];
int errorIndex = ERROR_INDEX[syndrome];
return errorIndex >= 0 ? offset + errorIndex : IHamming.MULTIPLE_ERRORS;
}
return IHamming.NO_ERRORS;

View File

@@ -47,13 +47,6 @@ public class Hamming16 implements IHamming
return NO_ERRORS;
}
//If the syndrome indicates the error is in the final parity bit position, and we already have odd parity, then
//flag it as invalid for multiple errors.
if(syndrome == 1 && message.getSubMessage(offset, offset + 16).cardinality() % 2 == 1) //check final parity bit
{
return MULTIPLE_ERRORS;
}
for(int index = 0; index < CHECKSUMS.length; index++)
{
if(syndrome == CHECKSUMS[index])

View File

@@ -46,13 +46,6 @@ public class Hamming17 implements IHamming
return NO_ERRORS;
}
//If the syndrome indicates the error is in the final parity bit position, and we already have odd parity, then
//flag it as invalid for multiple errors.
if(syndrome == 1 && message.getSubMessage(offset, offset + 17).cardinality() % 2 == 1) //check final parity bit
{
return MULTIPLE_ERRORS;
}
for(int index = 0; index < CHECKSUMS.length; index++)
{
if(syndrome == CHECKSUMS[index])

View File

@@ -0,0 +1,421 @@
/*
* *****************************************************************************
* 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.edac;
import io.github.dsheirer.bits.BinaryMessage;
import java.util.function.ToIntFunction;
/**
* Hard decision minimum distance decoder for binary product codes, where each row is a codeword of a short row code
* and each column is a codeword of a systematic column code with the column parity bits in the final rows.
*
* Finds the minimum weight error pattern that produces the received row and column syndromes, using an iterative
* deepening search over the error patterns (coset) of each information row syndrome. The column parity row errors
* are fully determined by the column syndromes and the information row error choices, and the column parity rows then
* also match their row syndromes, so only the information rows are searched.
*
* Corrects every error pattern up to half the product code minimum distance, and most patterns up to the maximum
* error count. When more than one error pattern has the minimum weight, the received word is equidistant from more
* than one codeword and is treated as uncorrectable.
*
* Row words are integers where bit i (LSB = 0) holds the bit in column i. Instances are thread safe.
*/
public class ProductCodeDecoder
{
public static final int UNCORRECTABLE = -1;
//Bounds the decode time for pathological inputs (~20 ms). Error injection testing with random error patterns of
//each weight: the largest search was 630k nodes (3 ms) for BPTC(196,96) with a maximum error count of 12.
private static final long MAXIMUM_SEARCH_NODES = 4_000_000;
private final int mColumnCount;
private final int mRowCount;
private final int mInformationRowCount;
private final int[] mRowChecks;
private final int[] mColumnChecks;
private final int mColumnCheckBits;
private final long mColumnGroupMask;
private final int mMaximumErrors;
private final int[][] mCosets;
private final int[] mMinimumWeights;
/**
* Constructs an instance.
* @param rowChecks parity check matrix column (syndrome of a single bit error) for each row code bit position, where
* the array length is the column count (maximum 20).
* @param columnChecks parity check matrix column for each column code bit position, where the array length is the
* row count. The column code must be systematic, with distinct single bit parity checks for the final (parity)
* rows. For a single (even) parity check column code, each value is 1.
* @param maximumErrors maximum number of bit errors to correct.
*/
public ProductCodeDecoder(int[] rowChecks, int[] columnChecks, int maximumErrors)
{
mColumnCount = rowChecks.length;
mRowCount = columnChecks.length;
mRowChecks = rowChecks.clone();
mColumnChecks = columnChecks.clone();
mMaximumErrors = maximumErrors;
mColumnCheckBits = bitLength(mColumnChecks);
mInformationRowCount = mRowCount - mColumnCheckBits;
if(mColumnCount < 1 || mColumnCount > 20)
{
throw new IllegalArgumentException("Column count must be in range 1 - 20");
}
if(mColumnCount * mColumnCheckBits > Long.SIZE || mInformationRowCount < 1)
{
throw new IllegalArgumentException("Unsupported column code dimensions");
}
//Verify the final rows are the systematic parity rows
int parityChecks = 0;
for(int row = mInformationRowCount; row < mRowCount; row++)
{
int check = mColumnChecks[row];
if(Integer.bitCount(check) != 1 || (parityChecks & check) != 0)
{
throw new IllegalArgumentException("Column code parity rows must have distinct single bit checks");
}
parityChecks |= check;
}
long groupMask = 0;
for(int column = 0; column < mColumnCount; column++)
{
groupMask |= 1L << (column * mColumnCheckBits);
}
mColumnGroupMask = groupMask;
//Coset lists: the error patterns for each row syndrome, up to the maximum error count, ordered by weight
int syndromeCount = 1 << bitLength(mRowChecks);
int maximumWeight = Math.min(maximumErrors, mColumnCount);
int wordCount = 1 << mColumnCount;
int[] syndromes = new int[wordCount];
int[] sizes = new int[syndromeCount];
for(int word = 0; word < wordCount; word++)
{
syndromes[word] = getSyndrome(word, mRowChecks);
if(Integer.bitCount(word) <= maximumWeight)
{
sizes[syndromes[word]]++;
}
}
mCosets = new int[syndromeCount][];
mMinimumWeights = new int[syndromeCount];
for(int syndrome = 0; syndrome < syndromeCount; syndrome++)
{
mCosets[syndrome] = new int[sizes[syndrome]];
}
int[] filled = new int[syndromeCount];
for(int weight = 0; weight <= maximumWeight; weight++)
{
for(int word = 0; word < wordCount; word++)
{
if(Integer.bitCount(word) == weight)
{
int syndrome = syndromes[word];
mCosets[syndrome][filled[syndrome]++] = word;
}
}
}
for(int syndrome = 0; syndrome < syndromeCount; syndrome++)
{
mMinimumWeights[syndrome] = mCosets[syndrome].length > 0 ? Integer.bitCount(mCosets[syndrome][0]) :
maximumWeight + 1;
}
}
/**
* Number of bits needed to represent the largest value.
*/
private static int bitLength(int[] values)
{
int combined = 0;
for(int value: values)
{
combined |= value;
}
return Integer.SIZE - Integer.numberOfLeadingZeros(combined);
}
/**
* Calculates the parity check matrix columns for a code from a syndrome calculator, as the syndrome of each single
* bit error.
* @param length of the code in bits
* @param syndrome calculator for a binary message of the code length.
* @return parity check matrix column for each bit position.
*/
public static int[] getParityChecks(int length, ToIntFunction<BinaryMessage> syndrome)
{
int[] checks = new int[length];
for(int i = 0; i < length; i++)
{
BinaryMessage message = new BinaryMessage(length);
message.set(i);
checks[i] = syndrome.applyAsInt(message);
}
return checks;
}
/**
* Calculates the syndrome of the word.
* @param word where bit i (LSB = 0) is code bit position i
* @param checks parity check matrix column for each bit position
* @return syndrome, zero for a valid codeword.
*/
public static int getSyndrome(int word, int[] checks)
{
int syndrome = 0;
while(word != 0)
{
syndrome ^= checks[Integer.numberOfTrailingZeros(word)];
word &= word - 1;
}
return syndrome;
}
/**
* Indicates if all rows and columns are valid codewords.
* @param rows to check
* @return true if valid.
*/
public boolean isValid(int[] rows)
{
long columnSyndromes = 0;
for(int row = 0; row < mRowCount; row++)
{
if(getSyndrome(rows[row], mRowChecks) != 0)
{
return false;
}
columnSyndromes ^= getColumnContribution(row, rows[row]);
}
return columnSyndromes == 0;
}
/**
* Corrects the rows to the nearest valid product codeword when the number of bit errors doesn't exceed the
* maximum error count and the nearest codeword is unique.
* @param rows to correct, where bit i of each row is the bit in column i. Unchanged when uncorrectable.
* @return number of corrected bit errors, or UNCORRECTABLE.
*/
public int decode(int[] rows)
{
if(rows.length != mRowCount)
{
throw new IllegalArgumentException("Expected " + mRowCount + " rows");
}
Search search = new Search();
boolean rowErrors = false;
for(int row = 0; row < mRowCount; row++)
{
search.mRowSyndromes[row] = getSyndrome(rows[row], mRowChecks);
rowErrors |= search.mRowSyndromes[row] != 0;
search.mColumnSyndromes ^= getColumnContribution(row, rows[row]);
}
if(!rowErrors && search.mColumnSyndromes == 0)
{
return 0;
}
//Lower bound on the error count of the remaining rows, including the column parity rows, at each search depth
int lowerBound = 0;
for(int row = mInformationRowCount; row < mRowCount; row++)
{
lowerBound += mMinimumWeights[search.mRowSyndromes[row]];
}
search.mLowerBounds[mInformationRowCount] = lowerBound;
for(int row = mInformationRowCount - 1; row >= 0; row--)
{
search.mLowerBounds[row] = search.mLowerBounds[row + 1] + mMinimumWeights[search.mRowSyndromes[row]];
}
int start = Math.max(search.mLowerBounds[0], getErrorColumnCount(search.mColumnSyndromes));
for(search.mBudget = start; search.mBudget <= mMaximumErrors; search.mBudget++)
{
search(search, 0, 0, 0L);
if(search.mAborted || search.mSolutionCount > 1)
{
return UNCORRECTABLE;
}
if(search.mSolutionCount == 1)
{
for(int row = 0; row < mInformationRowCount; row++)
{
rows[row] ^= search.mSolution[row];
}
long residual = search.mColumnSyndromes ^ search.mSolutionContribution;
for(int row = mInformationRowCount; row < mRowCount; row++)
{
int check = mColumnChecks[row];
for(int column = 0; column < mColumnCount; column++)
{
if(((residual >>> (column * mColumnCheckBits)) & check) != 0)
{
rows[row] ^= 1 << column;
}
}
}
return search.mBudget;
}
}
return UNCORRECTABLE;
}
/**
* Depth first search over the information row error patterns, for solutions that don't exceed the error budget.
* @param search state
* @param row to choose an error pattern for
* @param used error count of the error patterns chosen for the preceding rows
* @param contribution to the column syndromes from the error patterns chosen for the preceding rows
*/
private void search(Search search, int row, int used, long contribution)
{
if(++search.mNodes > MAXIMUM_SEARCH_NODES)
{
search.mAborted = true;
return;
}
//The remaining column syndromes must be resolved by the remaining rows
long residual = search.mColumnSyndromes ^ contribution;
if(row == mInformationRowCount)
{
//Each remaining column syndrome bit is a column parity row error
if(used + Long.bitCount(residual) <= search.mBudget && ++search.mSolutionCount == 1)
{
System.arraycopy(search.mChosen, 0, search.mSolution, 0, mInformationRowCount);
search.mSolutionContribution = contribution;
}
return;
}
if(used + Math.max(search.mLowerBounds[row], getErrorColumnCount(residual)) > search.mBudget)
{
return;
}
int remainingLowerBound = search.mLowerBounds[row + 1];
for(int error: mCosets[search.mRowSyndromes[row]])
{
int weight = Integer.bitCount(error);
if(used + weight + remainingLowerBound > search.mBudget)
{
break; //Error patterns are ordered by weight
}
search.mChosen[row] = error;
search(search, row + 1, used + weight, contribution ^ getColumnContribution(row, error));
if(search.mAborted || search.mSolutionCount > 1)
{
return;
}
}
}
/**
* Calculates the contribution of a row word to the column syndromes, where the syndrome for each column occupies
* a group of column check bits, starting with column 0 in the LSBs.
*/
private long getColumnContribution(int row, int word)
{
long contribution = 0;
long check = mColumnChecks[row];
while(word != 0)
{
contribution ^= check << (Integer.numberOfTrailingZeros(word) * mColumnCheckBits);
word &= word - 1;
}
return contribution;
}
/**
* Number of columns with a non-zero syndrome, where each requires at least one more bit error.
*/
private int getErrorColumnCount(long columnSyndromes)
{
long folded = columnSyndromes;
for(int shift = 1; shift < mColumnCheckBits; shift++)
{
folded |= columnSyndromes >>> shift;
}
return Long.bitCount(folded & mColumnGroupMask);
}
/**
* Search state for a single decode.
*/
private final class Search
{
private final int[] mRowSyndromes = new int[mRowCount];
private final int[] mLowerBounds = new int[mInformationRowCount + 1];
private final int[] mChosen = new int[mInformationRowCount];
private final int[] mSolution = new int[mInformationRowCount];
private long mColumnSyndromes;
private long mSolutionContribution;
private int mBudget;
private int mSolutionCount;
private long mNodes;
private boolean mAborted;
}
}

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
@@ -51,6 +51,7 @@ import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.record.AudioRecordingManager;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.settings.MapViewSetting;
import io.github.dsheirer.settings.SettingsManager;
import io.github.dsheirer.source.tuner.Tuner;
import io.github.dsheirer.source.tuner.TunerEvent;
@@ -59,7 +60,8 @@ import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerSpectralDisplayManager;
import io.github.dsheirer.spectrum.DisableSpectrumWaterfallMenuItem;
import io.github.dsheirer.spectrum.ShowTunerMenuItem;
import io.github.dsheirer.spectrum.SpectralDisplayPanel;
import io.github.dsheirer.gui.spectrum.SpectralDisplayPanel;
import io.github.dsheirer.util.DuplicateLibraryDetector;
import io.github.dsheirer.util.ThreadPool;
import io.github.dsheirer.util.TimeStamp;
import io.github.dsheirer.vector.calibrate.CalibrationManager;
@@ -81,6 +83,7 @@ import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.prefs.Preferences;
import javafx.application.Platform;
@@ -153,6 +156,17 @@ public class SDRTrunk implements Listener<TunerEvent>
mApplicationLog = new ApplicationLog(mUserPreferences);
mApplicationLog.start();
Map<String,List<String>> duplicateLibraries = DuplicateLibraryDetector.findDuplicates();
if(!duplicateLibraries.isEmpty())
{
mLog.warn("More than one version of these libraries is in the library folder [" +
DuplicateLibraryDetector.getFolder(duplicateLibraries) + "]. This happens when a new version of " +
"sdrtrunk is unzipped over an older one, and it can load the older library code. Delete the " +
"sdrtrunk folder and unzip the release into an empty folder.\n" +
DuplicateLibraryDetector.describe(duplicateLibraries));
}
mResourceMonitor = new ResourceMonitor(mUserPreferences);
ThreadPool.logSettings();
@@ -171,6 +185,15 @@ public class SDRTrunk implements Listener<TunerEvent>
mSettingsManager = new SettingsManager();
//Older versions stored the map view in the settings file. Move it to the map preferences once.
MapViewSetting legacyMapView = mSettingsManager.getLegacyMapView();
if(legacyMapView != null)
{
mUserPreferences.getMapPreference().migrateLegacyView(legacyMapView.getLatitude(),
legacyMapView.getLongitude(), legacyMapView.getZoom());
}
AliasModel aliasModel = new AliasModel();
EventLogManager eventLogManager = new EventLogManager(aliasModel, mUserPreferences);
mPlaylistManager = new PlaylistManager(mUserPreferences, mTunerManager, aliasModel, eventLogManager, mIconModel);
@@ -219,10 +242,13 @@ public class SDRTrunk implements Listener<TunerEvent>
mSettingsManager, mTunerManager, mUserPreferences, mNowPlayingDetailsVisible);
}
mSpectralPanel = new SpectralDisplayPanel(mPlaylistManager, mSettingsManager, mTunerManager.getDiscoveredTunerModel());
if(!headless)
{
mSpectralPanel = new SpectralDisplayPanel(mPlaylistManager, mTunerManager.getDiscoveredTunerModel());
}
TunerSpectralDisplayManager tunerSpectralDisplayManager = new TunerSpectralDisplayManager(mSpectralPanel,
mPlaylistManager, mSettingsManager, mTunerManager.getDiscoveredTunerModel());
mPlaylistManager, mTunerManager.getDiscoveredTunerModel());
mTunerManager.getDiscoveredTunerModel().addListener(tunerSpectralDisplayManager);
mTunerManager.getDiscoveredTunerModel().addListener(this);
@@ -253,6 +279,11 @@ public class SDRTrunk implements Listener<TunerEvent>
{
updateTitle(tuner.getPreferredName());
}
if(!duplicateLibraries.isEmpty())
{
showDuplicateLibrariesDialog(duplicateLibraries);
}
}
if(calibrating && !GraphicsEnvironment.isHeadless())
@@ -622,14 +653,14 @@ public class SDRTrunk implements Listener<TunerEvent>
(mMainGui.getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH);
mUserPreferences.getSwingPreference().setDimension(SPECTRAL_PANEL_IDENTIFIER, mSpectralPanel.getSize());
mUserPreferences.getSwingPreference().setDimension(CONTROLLER_PANEL_IDENTIFIER, mControllerPanel.getSize());
mLog.info("Stopping spectral display ...");
mSpectralPanel.dispose();
mJavaFxWindowManager.shutdown();
mLog.info("Stopping channels ...");
mPlaylistManager.getChannelProcessingManager().shutdown();
mAudioRecordingManager.stop();
mResourceMonitor.stop();
mLog.info("Stopping spectral display ...");
mSpectralPanel.clearTuner();
mLog.info("Stopping tuners ...");
mTunerManager.stop();
mLog.info("Shutdown complete.");
@@ -798,7 +829,7 @@ public class SDRTrunk implements Listener<TunerEvent>
updateTitle(null);
break;
case NOTIFICATION_SHUTTING_DOWN:
Tuner currentTuner = mSpectralPanel.getTuner();
Tuner currentTuner = mSpectralPanel != null ? mSpectralPanel.getTuner() : null;
if(event.hasTuner() && event.getTuner().equals(currentTuner) || currentTuner == null)
{
@@ -809,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);
@@ -909,6 +945,28 @@ public class SDRTrunk implements Listener<TunerEvent>
}
/**
* Warns the user that the library folder holds more than one version of some libraries, which happens when a new
* release is unzipped over an older one. The launch scripts put every jar in the library folder on the class
* path, so the older library code can load instead of the newer code.
* @param duplicates library name to jar paths, from DuplicateLibraryDetector
*/
private void showDuplicateLibrariesDialog(Map<String,List<String>> duplicates)
{
String message = "<html><body style='width: 450px'>" +
"<p>The sdrtrunk library folder has more than one version of these libraries:</p><br>" +
"<pre>" + DuplicateLibraryDetector.describe(duplicates) + "</pre>" +
"<p>This happens when a new version of sdrtrunk is unzipped over an older one. sdrtrunk can load " +
"the older library code, which can cause crashes or errors that the newer version fixed.</p><br>" +
"<p>Close sdrtrunk, delete the sdrtrunk folder that contains this library folder and unzip the " +
"release into a new, empty folder:</p><br>" +
"<p><b>" + DuplicateLibraryDetector.getFolder(duplicates) + "</b></p><br>" +
"<p>Your playlist and settings are stored in your user folder and won't be affected.</p>" +
"</body></html>";
JOptionPane.showMessageDialog(mMainGui, message, "Duplicate Library Versions", JOptionPane.WARNING_MESSAGE);
}
/**
* Launch the application.
*/

View File

@@ -1,546 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.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.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.settings.SettingsManager;
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 io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.FrequencyOverlayPanel;
import io.github.dsheirer.spectrum.SpectrumPanel;
import io.github.dsheirer.spectrum.converter.ComplexDecibelConverter;
import io.github.dsheirer.spectrum.converter.DFTResultsConverter;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
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.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.MouseInputAdapter;
/**
* 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 ComplexDftProcessor mComplexDftProcessor = new ComplexDftProcessor();
private SpectrumPanel mSpectrumPanel;
private final FrequencyOverlayPanel mFrequencyOverlayPanel;
private final SourceEventProcessor mSourceEventProcessor = new SourceEventProcessor();
private final SpinnerNumberModel mNoiseFloorSpinnerModel;
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 boolean mDftProcessing = 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, SettingsManager settingsManager)
{
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);
mNoiseFloorSpinnerModel = new SpinnerNumberModel(18, 8, 36, 1);
mNoiseFloorSpinnerModel.addChangeListener(e -> {
Number number = mNoiseFloorSpinnerModel.getNumber();
mSpectrumPanel.setSampleSize(number.doubleValue());
});
JSpinner noiseFloorSpinner = new JSpinner(mNoiseFloorSpinnerModel);
labelPanel.add(new JLabel("Noise Floor:"));
labelPanel.add(noiseFloorSpinner);
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");
mFrequencyOverlayPanel = new FrequencyOverlayPanel(settingsManager);
mSpectrumPanel = new SpectrumPanel(settingsManager);
mSpectrumPanel.setSampleSize(18.0);
/**
* The layered pane holds the overlapping spectrum and channel panels
* and manages the sizing of each panel with the resize listener
*/
JLayeredPane layeredPanel = new JLayeredPane();
layeredPanel.addComponentListener(new ResizeListener());
/**
* Create a mouse adapter to handle mouse events over the spectrum
* and waterfall panels
*/
MouseEventProcessor mouser = new MouseEventProcessor();
mFrequencyOverlayPanel.addMouseListener(mouser);
mFrequencyOverlayPanel.addMouseMotionListener(mouser);
mFrequencyOverlayPanel.addMouseWheelListener(mouser);
//Add the spectrum and channel panels to the layered panel
layeredPanel.add(mSpectrumPanel, 0, 0);
layeredPanel.add(mFrequencyOverlayPanel, 1, 0);
fftPanel.add(layeredPanel);
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);
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);
mSampleStreamTapModule.setListener(mComplexDftProcessor);
DFTResultsConverter DFTResultsConverter = new ComplexDecibelConverter();
mComplexDftProcessor.addConverter(DFTResultsConverter);
DFTResultsConverter.addListener(mSpectrumPanel);
mSpectrumPanel.clearSpectrum();
}
/**
* 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 DFT processor. 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 void updateFFTProcessing()
{
if(mPanelVisible && mProcessingChain != null)
{
startDftProcessing();
}
else
{
stopDftProcessing();
}
}
/**
* Starts DFT processing
*/
private void startDftProcessing()
{
if(!mDftProcessing)
{
mDftProcessing = true;
mSampleStreamTapModule.setListener(mComplexDftProcessor);
mComplexDftProcessor.start();
}
}
/**
* Stops DFT processing
*/
private void stopDftProcessing()
{
if(mDftProcessing)
{
mSampleStreamTapModule.removeListener();
mComplexDftProcessor.stop();
mSpectrumPanel.clearSpectrum();
mDftProcessing = false;
}
}
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);
mFrequencyOverlayPanel.process(SourceEvent.frequencyChange(null, 0));
mFrequencyOverlayPanel.process(SourceEvent.sampleRateChange(0));
mFrequencyOverlayPanel.setEstimatedCarrierOffsetFrequency(0);
mFrequencyOverlayPanel.setChannelBandwidth(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();
if(source instanceof TunerChannelSource tcs)
{
mFrequencyOverlayPanel.process(SourceEvent.frequencyChange(null, tcs.getFrequency()));
mFrequencyOverlayPanel.process(SourceEvent.sampleRateChange(tcs.getSampleRate()));
}
Channel channel = mPlaylistManager.getChannelProcessingManager().getChannel(mProcessingChain);
if(channel != null)
{
List<TunerChannel> tunerChannels = channel.getTunerChannels();
if(!tunerChannels.isEmpty())
{
mFrequencyOverlayPanel.setChannelBandwidth(tunerChannels.getFirst().getBandwidth());
}
}
}
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.
mFrequencyOverlayPanel.setEstimatedCarrierOffsetFrequency(-status.getDecoderCorrection());
});
}
}
//TODO: is this still needed?
mSignalPowerView.receive(sourceEvent);
}
}
/**
* Monitors the sizing of the layered pane and resizes the spectrum and
* channel panels whenever the layered pane is resized
*/
public class ResizeListener implements ComponentListener
{
@Override public void componentResized(ComponentEvent e)
{
Component c = e.getComponent();
mSpectrumPanel.setBounds(0, 0, c.getWidth(), c.getHeight());
mFrequencyOverlayPanel.setBounds(0, 0, c.getWidth(), c.getHeight());
}
@Override public void componentHidden(ComponentEvent arg0) {}
@Override public void componentMoved(ComponentEvent arg0) {}
@Override public void componentShown(ComponentEvent arg0) {}
}
/**
* Mouse event handler for the spectral display panel.
*/
public class MouseEventProcessor extends MouseInputAdapter
{
@Override public void mouseMoved(MouseEvent event)
{
update(event);
}
/**
* Updates the cursor display while the mouse is performing actions
*/
private void update(MouseEvent event)
{
mFrequencyOverlayPanel.setCursorLocation(event.getPoint());
}
@Override public void mouseEntered(MouseEvent e)
{
mFrequencyOverlayPanel.setCursorVisible(true);
}
@Override public void mouseExited(MouseEvent e)
{
mFrequencyOverlayPanel.setCursorVisible(false);
}
}
}

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

@@ -17,18 +17,19 @@
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.signalhound;
package io.github.dsheirer.gui.map;
import javafx.scene.canvas.GraphicsContext;
/**
* Signal Hound device details for display.
* @param model such as BB60D, SM200B or SP145
* @param serial number
* @param firmware version
* @param library name of the Signal Hound API library, such as bb_api
* @param libraryVersion of the Signal Hound API library
* @param libraryLocation where the Signal Hound API library was loaded from
* Overlay drawn over the map tiles, in the order the layers were added to the {@link TileMapView}.
*/
public record SignalHoundDeviceInformation(String model, int serial, String firmware, String library,
String libraryVersion, String libraryLocation)
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

@@ -73,6 +73,7 @@ public class P25P1ConfigurationEditor extends ChannelConfigurationEditor
private EventLogConfigurationEditor mEventLogConfigurationEditor;
private RecordConfigurationEditor mRecordConfigurationEditor;
private ToggleSwitch mIgnoreDataCallsButton;
private ToggleSwitch mIgnoreEncryptedCallsButton;
private Spinner<Integer> mTrafficChannelPoolSizeSpinner;
private SegmentedButton mModulationSegmentedButton;
private ToggleButton mC4FMToggleButton;
@@ -157,6 +158,15 @@ public class P25P1ConfigurationEditor extends ChannelConfigurationEditor
GridPane.setConstraints(directionLabel, 5, row);
gridPane.getChildren().add(directionLabel);
GridPane.setConstraints(getIgnoreEncryptedCallsButton(), 6, row);
gridPane.getChildren().add(getIgnoreEncryptedCallsButton());
Label ignoreEncryptedLabel = new Label("Ignore Encrypted Calls");
ignoreEncryptedLabel.setLabelFor(getIgnoreEncryptedCallsButton());
GridPane.setHalignment(ignoreEncryptedLabel, HPos.LEFT);
GridPane.setConstraints(ignoreEncryptedLabel, 7, row);
gridPane.getChildren().add(ignoreEncryptedLabel);
row++;
Label modulationHelpLabel = new Label("C4FM: repeaters and non-simulcast trunked systems. LSM: simulcast trunked systems.");
@@ -343,6 +353,21 @@ public class P25P1ConfigurationEditor extends ChannelConfigurationEditor
return mLSMToggleButton;
}
private ToggleSwitch getIgnoreEncryptedCallsButton()
{
if(mIgnoreEncryptedCallsButton == null)
{
mIgnoreEncryptedCallsButton = new AccessibleToggleSwitch();
mIgnoreEncryptedCallsButton.setDisable(true);
mIgnoreEncryptedCallsButton.setTooltip(new Tooltip("Don't tune a traffic channel when the channel grant indicates the call is encrypted. " +
"Phase 2: the channel is still tuned when the other timeslot has a clear call."));
mIgnoreEncryptedCallsButton.selectedProperty()
.addListener((observable, oldValue, newValue) -> modifiedProperty().set(true));
}
return mIgnoreEncryptedCallsButton;
}
private ToggleSwitch getIgnoreDataCallsButton()
{
if(mIgnoreDataCallsButton == null)
@@ -398,11 +423,13 @@ public class P25P1ConfigurationEditor extends ChannelConfigurationEditor
protected void setDecoderConfiguration(DecodeConfiguration config)
{
getIgnoreDataCallsButton().setDisable(config == null);
getIgnoreEncryptedCallsButton().setDisable(config == null);
getTrafficChannelPoolSizeSpinner().setDisable(config == null);
if(config instanceof DecodeConfigP25Phase1 decodeConfig)
{
getIgnoreDataCallsButton().setSelected(decodeConfig.getIgnoreDataCalls());
getIgnoreEncryptedCallsButton().setSelected(decodeConfig.getIgnoreEncryptedCalls());
getTrafficChannelPoolSizeSpinner().getValueFactory().setValue(decodeConfig.getTrafficChannelPoolSize());
if(decodeConfig.getModulation() == Modulation.C4FM)
{
@@ -427,6 +454,7 @@ public class P25P1ConfigurationEditor extends ChannelConfigurationEditor
else
{
getIgnoreDataCallsButton().setSelected(false);
getIgnoreEncryptedCallsButton().setSelected(false);
getTrafficChannelPoolSizeSpinner().getValueFactory().setValue(0);
getJmbeAGCButton().setDisable(true);
getJmbeNoiseGainSlider().setDisable(true);
@@ -454,6 +482,7 @@ public class P25P1ConfigurationEditor extends ChannelConfigurationEditor
}
config.setIgnoreDataCalls(getIgnoreDataCallsButton().isSelected());
config.setIgnoreEncryptedCalls(getIgnoreEncryptedCallsButton().isSelected());
config.setTrafficChannelPoolSize(getTrafficChannelPoolSizeSpinner().getValue());
config.setModulation(getC4FMToggleButton().isSelected() ? Modulation.C4FM : Modulation.CQPSK);
config.setAGC(getJmbeAGCButton().selectedProperty().getValue());

View File

@@ -71,6 +71,7 @@ public class P25P2ConfigurationEditor extends ChannelConfigurationEditor
private IntegerTextField mSystemTextField;
private IntegerTextField mNacTextField;
private ToggleSwitch mIgnoreDataCallsButton;
private ToggleSwitch mIgnoreEncryptedCallsButton;
private Spinner<Integer> mTrafficChannelPoolSizeSpinner;
private ToggleSwitch mJmbeAGCButton;
private Slider mJmbeToneGainSlider;
@@ -142,6 +143,15 @@ public class P25P2ConfigurationEditor extends ChannelConfigurationEditor
GridPane.setConstraints(directionLabel, 3, row);
gridPane.getChildren().add(directionLabel);
GridPane.setConstraints(getIgnoreEncryptedCallsButton(), 4, row);
gridPane.getChildren().add(getIgnoreEncryptedCallsButton());
Label ignoreEncryptedLabel = new Label("Ignore Encrypted Calls");
ignoreEncryptedLabel.setLabelFor(getIgnoreEncryptedCallsButton());
GridPane.setHalignment(ignoreEncryptedLabel, HPos.LEFT);
GridPane.setConstraints(ignoreEncryptedLabel, 5, row);
gridPane.getChildren().add(ignoreEncryptedLabel);
Label wacnLabel = new Label("WACN");
wacnLabel.setLabelFor(getWacnTextField());
GridPane.setHalignment(wacnLabel, HPos.RIGHT);
@@ -300,6 +310,21 @@ public class P25P2ConfigurationEditor extends ChannelConfigurationEditor
return mEventLogConfigurationEditor;
}
private ToggleSwitch getIgnoreEncryptedCallsButton()
{
if(mIgnoreEncryptedCallsButton == null)
{
mIgnoreEncryptedCallsButton = new AccessibleToggleSwitch();
mIgnoreEncryptedCallsButton.setDisable(true);
mIgnoreEncryptedCallsButton.setTooltip(new Tooltip("Don't tune a traffic channel when the channel grant indicates the call is encrypted. " +
"Phase 2: the channel is still tuned when the other timeslot has a clear call."));
mIgnoreEncryptedCallsButton.selectedProperty()
.addListener((observable, oldValue, newValue) -> modifiedProperty().set(true));
}
return mIgnoreEncryptedCallsButton;
}
private ToggleSwitch getIgnoreDataCallsButton()
{
if(mIgnoreDataCallsButton == null)
@@ -417,6 +442,8 @@ public class P25P2ConfigurationEditor extends ChannelConfigurationEditor
getIgnoreDataCallsButton().setDisable(false);
getIgnoreDataCallsButton().setSelected(decodeConfig.getIgnoreDataCalls());
getIgnoreEncryptedCallsButton().setDisable(false);
getIgnoreEncryptedCallsButton().setSelected(decodeConfig.getIgnoreEncryptedCalls());
getTrafficChannelPoolSizeSpinner().setDisable(false);
getTrafficChannelPoolSizeSpinner().getValueFactory().setValue(decodeConfig.getTrafficChannelPoolSize());
getJmbeAGCButton().setSelected(decodeConfig.isAGC());
@@ -433,6 +460,8 @@ public class P25P2ConfigurationEditor extends ChannelConfigurationEditor
getSystemTextField().setDisable(true);
getNacTextField().setDisable(true);
getIgnoreDataCallsButton().setDisable(true);
getIgnoreEncryptedCallsButton().setDisable(true);
getIgnoreEncryptedCallsButton().setSelected(false);
getTrafficChannelPoolSizeSpinner().setDisable(true);
getJmbeAGCButton().setDisable(true);
getJmbeNoiseGainSlider().setDisable(true);
@@ -465,6 +494,7 @@ public class P25P2ConfigurationEditor extends ChannelConfigurationEditor
int nac = getNacTextField().get();
config.setScrambleParameters(new ScrambleParameters(wacn, system, nac));
config.setIgnoreDataCalls(getIgnoreDataCallsButton().isSelected());
config.setIgnoreEncryptedCalls(getIgnoreEncryptedCallsButton().isSelected());
config.setTrafficChannelPoolSize(getTrafficChannelPoolSizeSpinner().getValue());
config.setAGC(getJmbeAGCButton().selectedProperty().getValue());
config.setComfortNoiseGain((float)getJmbeNoiseGainSlider().getValue());

View File

@@ -39,7 +39,6 @@ import javafx.scene.layout.VBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@@ -56,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
@@ -92,8 +93,9 @@ public class AgencyEditor extends VBox
if(agencies != null && !agencies.isEmpty())
{
Collections.sort(agencies, new AgencyComparator());
//The agencies list belongs to a cached state or county info shared with other callers, so sort the items
getAgencyListView().getItems().addAll(agencies);
getAgencyListView().getItems().sort(new AgencyComparator());
int preferredAgencyId = mUserPreferences.getRadioReferencePreference().getPreferredAgencyId(mLevel);
@@ -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

@@ -21,6 +21,7 @@ package io.github.dsheirer.gui.playlist.radioreference;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.rrapi.RadioReferenceException;
import io.github.dsheirer.rrapi.type.Category;
import io.github.dsheirer.rrapi.type.Frequency;
import io.github.dsheirer.rrapi.type.Mode;
@@ -67,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;
@@ -153,19 +169,22 @@ public class AgencyFrequencyEditor extends GridPane
{
clear();
if(categories != null)
{
Collections.sort(categories, new CategoryComparator());
}
if(categories != null && !categories.isEmpty())
{
//The categories list belongs to a cached agency or county info shared with other callers, so change a copy
List<Category> sorted = new ArrayList<>(categories);
sorted.sort(new CategoryComparator());
// Only allow the combined list of all categories if there aren't that many
if (categories.size() < 10) {
categories.add(0, ALL_CATEGORIES);
if (sorted.size() < 10) {
sorted.add(0, ALL_CATEGORIES);
}
getCategoryComboBox().getItems().addAll(sorted);
if(mPendingFrequency == null || !selectPendingFrequency())
{
getCategoryComboBox().getSelectionModel().select(sorted.get(0));
}
getCategoryComboBox().getItems().addAll(categories);
getCategoryComboBox().getSelectionModel().select(categories.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)
{
@@ -441,15 +570,38 @@ public class AgencyFrequencyEditor extends GridPane
Collections.sort(frequencies, new FrequencyComparator());
//Load the cached modes map here so that the mode column doesn't call the service on the FX
//thread. On failure, the mode column shows an error and the frequencies are still listed.
try
{
mRadioReference.getService().getModesMap();
}
catch(RadioReferenceException rre)
{
mLog.warn("Unable to retrieve radio reference modes - " + rre.getMessage());
}
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(() -> new RadioReferenceUnavailableAlert(getSubCategoryComboBox()).showAndWait());
Platform.runLater(() -> {
mLoadingFrequencies = false;
setLoading(false);
new RadioReferenceUnavailableAlert(getSubCategoryComboBox()).showAndWait();
});
}
});
}

View File

@@ -204,7 +204,7 @@ public class FrequencyEditor extends VBox
if(item != null)
{
mFrequency = (long)(item.getDownlink() * 1E6);
mFrequency = item.getDownlinkHz();
getAlphaTagTextField().setText(item.getAlphaTag());
getFrequencyTextField().setText(FREQUENCY_FORMATTER.format(item.getDownlink()));
getToneTextField().setText(item.getTone());
@@ -413,46 +413,7 @@ public class FrequencyEditor extends VBox
*/
private Channel createChannel(ModeDecoderType modeDecoderType, long frequency, String system, String site, String name)
{
if(modeDecoderType.hasDecoderType())
{
Channel channel = new Channel();
channel.setSystem(system);
channel.setSite(site);
channel.setName(name);
SourceConfigTuner sourceConfigTuner = new SourceConfigTuner();
sourceConfigTuner.setFrequency(frequency);
channel.setSourceConfiguration(sourceConfigTuner);
DecodeConfiguration decodeConfiguration = DecoderFactory.getDecodeConfiguration(modeDecoderType.getDecoderType());
if(decodeConfiguration instanceof DecodeConfigNBFM && modeDecoderType == ModeDecoderType.FM)
{
((DecodeConfigNBFM)decodeConfiguration).setBandwidth(DecodeConfigNBFM.Bandwidth.BW_25_0);
}
else if(decodeConfiguration instanceof DecodeConfigP25Phase1)
{
((DecodeConfigP25Phase1)decodeConfiguration).setModulation(Modulation.C4FM);
}
else if(decodeConfiguration instanceof DecodeConfigNXDN nxdn)
{
if(modeDecoderType == ModeDecoderType.NXDN48)
{
nxdn.setTransmissionMode(TransmissionMode.M4800);
}
else if(modeDecoderType == ModeDecoderType.NXDN96)
{
nxdn.setTransmissionMode(TransmissionMode.M9600);
}
}
channel.setDecodeConfiguration(decodeConfiguration);
return channel;
}
else
{
mLog.warn("Can't create channel configuration for [" + modeDecoderType.name() + "] no supported decoder type");
}
return null;
return RadioReferenceChannelFactory.conventional(modeDecoderType, frequency, system, site, name);
}
private TextField getSystemTextField()

View File

@@ -0,0 +1,436 @@
/*
* *****************************************************************************
* 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 com.google.common.annotations.VisibleForTesting;
import io.github.dsheirer.preference.radioreference.RadioReferencePreference.Location;
import io.github.dsheirer.rrapi.RadioReferenceException;
import io.github.dsheirer.service.radioreference.RadioReference;
import io.github.dsheirer.util.ThreadPool;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Window;
/**
* Dialog to set the user's location, used to rank radio reference results by distance. The location can be looked
* up from a United States zip code (premium radio reference account) or entered as decimal degrees.
*/
public class LocationDialog extends Dialog<LocationDialog.Result>
{
/**
* Button to clear the location
*/
public static final ButtonType CLEAR = new ButtonType("Clear", ButtonBar.ButtonData.LEFT);
private static final String COORDINATE = "([-+]?\\d+(?:[.,]\\d+)?)\\s*°?\\s*([NSEWnsew])?";
/**
* A latitude and longitude pair, e.g. "43.0481, -76.1474" as copied from Google Maps, or "43.0481° N, 76.1474° W".
* A comma separator must be followed by whitespace, so that a decimal comma isn't taken for a separator.
*/
private static final Pattern COORDINATE_PAIR = Pattern.compile("^\\s*" + COORDINATE + "\\s*(?:,\\s+|;\\s*|\\s+)" +
COORDINATE + "\\s*$");
private static final Pattern SINGLE_COORDINATE = Pattern.compile("^\\s*" + COORDINATE + "\\s*$");
private final RadioReference mRadioReference;
private final TextField mZipcodeText = new TextField();
private final Button mLookupButton = new Button("Look Up");
private final Label mLookupStatus = new Label();
private final TextField mLatitudeText = new TextField();
private final TextField mLongitudeText = new TextField();
private final Label mValidationText = new Label();
private String mLabel;
private boolean mUpdatingFields;
/**
* Result of the dialog
* @param location to store, or null to clear the location
*/
public record Result(Location location)
{
}
/**
* Constructs an instance
* @param radioReference service, for zip code lookups
* @param current location, or null
* @param owner window
*/
public LocationDialog(RadioReference radioReference, Location current, Window owner)
{
mRadioReference = radioReference;
setTitle("sdrtrunk - Location");
setHeaderText("Your location is shown on the map and used to find nearby Radio Reference frequencies");
if(owner != null)
{
initOwner(owner);
}
getDialogPane().setContent(createContent());
getDialogPane().getButtonTypes().addAll(CLEAR, ButtonType.OK, ButtonType.CANCEL);
if(current != null)
{
mUpdatingFields = true;
mLatitudeText.setText(format(current.latitude()));
mLongitudeText.setText(format(current.longitude()));
mUpdatingFields = false;
mLabel = current.label();
}
else
{
getDialogPane().lookupButton(CLEAR).setDisable(true);
}
BooleanBinding valid = Bindings.createBooleanBinding(() -> getLocation() != null,
mLatitudeText.textProperty(), mLongitudeText.textProperty());
getDialogPane().lookupButton(ButtonType.OK).disableProperty().bind(valid.not());
updateValidationText();
setResultConverter(buttonType -> {
if(buttonType == ButtonType.OK)
{
return new Result(getLocation());
}
else if(buttonType == CLEAR)
{
return new Result(null);
}
return null;
});
}
private Node createContent()
{
GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(10, 10, 5, 10));
gridPane.setHgap(5.0);
gridPane.setVgap(5.0);
Label zipcodeLabel = new Label("Zip Code:");
zipcodeLabel.setLabelFor(mZipcodeText);
GridPane.setHalignment(zipcodeLabel, HPos.RIGHT);
gridPane.add(zipcodeLabel, 0, 0);
mZipcodeText.setPrefColumnCount(6);
mZipcodeText.setOnAction(event -> lookup());
gridPane.add(mZipcodeText, 1, 0);
mLookupButton.setOnAction(event -> lookup());
gridPane.add(mLookupButton, 2, 0);
//Zip code lookups need a premium account
boolean premium = mRadioReference.premiumAccountProperty().get();
mZipcodeText.setDisable(!premium);
mLookupButton.setDisable(!premium);
mLookupStatus.setText(premium ? "United States zip codes only" :
"Zip code lookup requires a premium Radio Reference login");
mLookupStatus.setWrapText(true);
gridPane.add(mLookupStatus, 1, 1, 4, 1);
Label latitudeLabel = new Label("Latitude:");
latitudeLabel.setLabelFor(mLatitudeText);
GridPane.setHalignment(latitudeLabel, HPos.RIGHT);
gridPane.add(latitudeLabel, 0, 2);
mLatitudeText.setPrefColumnCount(10);
mLatitudeText.setPromptText("43.0481");
GridPane.setHgrow(mLatitudeText, Priority.ALWAYS);
gridPane.add(mLatitudeText, 1, 2, 2, 1);
Label longitudeLabel = new Label("Longitude:");
longitudeLabel.setLabelFor(mLongitudeText);
GridPane.setHalignment(longitudeLabel, HPos.RIGHT);
gridPane.add(longitudeLabel, 3, 2);
mLongitudeText.setPrefColumnCount(10);
mLongitudeText.setPromptText("-76.1474");
GridPane.setHgrow(mLongitudeText, Priority.ALWAYS);
gridPane.add(mLongitudeText, 4, 2);
Label hint = new Label("Decimal degrees. You can paste \"latitude, longitude\" from a map into either field.");
hint.setWrapText(true);
gridPane.add(hint, 1, 3, 4, 1);
mValidationText.setWrapText(true);
//Inline style, because the theme stylesheets override a label's text fill
mValidationText.setStyle("-fx-text-fill: orangered;");
gridPane.add(mValidationText, 1, 4, 4, 1);
mLatitudeText.textProperty().addListener((observable, oldValue, newValue) -> coordinatesEdited(newValue));
mLongitudeText.textProperty().addListener((observable, oldValue, newValue) -> coordinatesEdited(newValue));
return gridPane;
}
/**
* Handles an edit of either coordinate field: splits a pasted pair into both fields and forgets the zip code label
* because the location no longer comes from the zip code.
*/
private void coordinatesEdited(String text)
{
if(mUpdatingFields)
{
return;
}
mLabel = null;
double[] pair = parsePair(text);
if(pair != null)
{
//Changing a text field from its own change listener isn't allowed, so split the pair afterwards
Platform.runLater(() -> setCoordinates(pair[0], pair[1]));
}
updateValidationText();
}
private void setCoordinates(double latitude, double longitude)
{
mUpdatingFields = true;
mLatitudeText.setText(format(latitude));
mLongitudeText.setText(format(longitude));
mUpdatingFields = false;
updateValidationText();
}
private void updateValidationText()
{
String latitudeText = mLatitudeText.getText();
String longitudeText = mLongitudeText.getText();
if(isBlank(latitudeText) && isBlank(longitudeText))
{
mValidationText.setText(null);
}
else if(isBlank(latitudeText) || isBlank(longitudeText))
{
mValidationText.setText("Enter both a latitude and a longitude");
}
else if(Double.isNaN(parseCoordinate(latitudeText, true)))
{
mValidationText.setText("Latitude must be a number from -90 to 90");
}
else if(Double.isNaN(parseCoordinate(longitudeText, false)))
{
mValidationText.setText("Longitude must be a number from -180 to 180");
}
else
{
mValidationText.setText(null);
}
}
/**
* Location from the fields
* @return location, or null if the fields aren't valid
*/
private Location getLocation()
{
double latitude = parseCoordinate(mLatitudeText.getText(), true);
double longitude = parseCoordinate(mLongitudeText.getText(), false);
if(Location.isValid(latitude, longitude))
{
return new Location(latitude, longitude, mLabel);
}
return null;
}
/**
* Looks up the zip code in the background and fills the coordinates
*/
private void lookup()
{
String zipcode = mZipcodeText.getText() != null ? mZipcodeText.getText().trim() : "";
if(!zipcode.matches("\\d{5}"))
{
mLookupStatus.setText("Enter a five digit zip code");
return;
}
mLookupButton.setDisable(true);
mLookupStatus.setText("Looking up " + zipcode + "...");
ThreadPool.CACHED.execute(() -> {
Location location = null;
String error = null;
try
{
location = mRadioReference.lookupZipcode(Integer.parseInt(zipcode));
}
catch(RadioReferenceException rre)
{
error = switch(rre.getErrorType())
{
case NETWORK, TIMEOUT -> "Unable to reach Radio Reference";
case INVALID_REQUEST -> "Radio Reference has no location for zip code " + zipcode;
default -> "Lookup failed: " + rre.getMessage();
};
}
catch(RuntimeException re)
{
error = "Lookup failed: " + re.getMessage();
}
final Location result = location;
final String message = error;
Platform.runLater(() -> {
mLookupButton.setDisable(false);
if(result != null)
{
setCoordinates(result.latitude(), result.longitude());
mLabel = result.label();
mLookupStatus.setText(result.label());
}
else
{
mLookupStatus.setText(message);
}
});
});
}
/**
* Parses a latitude and longitude pair
* @param text to parse
* @return latitude and longitude, or null if the text isn't a valid pair
*/
@VisibleForTesting
static double[] parsePair(String text)
{
if(text == null)
{
return null;
}
Matcher matcher = COORDINATE_PAIR.matcher(text);
if(matcher.matches())
{
double latitude = toDegrees(matcher.group(1), matcher.group(2), true);
double longitude = toDegrees(matcher.group(3), matcher.group(4), false);
if(Location.isValid(latitude, longitude))
{
return new double[]{latitude, longitude};
}
}
return null;
}
/**
* Parses one coordinate in decimal degrees, with an optional degree sign and hemisphere letter
* @param text to parse
* @param latitude true for a latitude, false for a longitude
* @return degrees, or NaN if the text isn't a valid coordinate
*/
@VisibleForTesting
static double parseCoordinate(String text, boolean latitude)
{
if(text == null)
{
return Double.NaN;
}
Matcher matcher = SINGLE_COORDINATE.matcher(text);
if(matcher.matches())
{
double degrees = toDegrees(matcher.group(1), matcher.group(2), latitude);
if(Math.abs(degrees) <= (latitude ? 90.0 : 180.0))
{
return degrees;
}
}
return Double.NaN;
}
/**
* Converts a number and an optional hemisphere letter to signed degrees
* @return degrees, or NaN if the hemisphere letter doesn't match the coordinate type
*/
private static double toDegrees(String number, String hemisphere, boolean latitude)
{
//Accept a decimal comma
double degrees = Double.parseDouble(number.replace(',', '.'));
if(hemisphere != null)
{
char letter = Character.toUpperCase(hemisphere.charAt(0));
boolean latitudeLetter = letter == 'N' || letter == 'S';
if(latitudeLetter != latitude || degrees < 0)
{
return Double.NaN;
}
if(letter == 'S' || letter == 'W')
{
degrees = -degrees;
}
}
return degrees;
}
/**
* Formats degrees with up to six decimal places (about 0.1 meter)
*/
@VisibleForTesting
static String format(double degrees)
{
return BigDecimal.valueOf(degrees).setScale(6, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
}
private static boolean isBlank(String text)
{
return text == null || text.isBlank();
}
}

View File

@@ -24,6 +24,7 @@ import io.github.dsheirer.rrapi.RadioReferenceException;
import io.github.dsheirer.rrapi.response.Fault;
import io.github.dsheirer.rrapi.type.AuthorizationInformation;
import io.github.dsheirer.service.radioreference.RadioReference;
import io.github.dsheirer.util.ThreadPool;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.event.ActionEvent;
@@ -49,7 +50,6 @@ import jiconfont.javafx.IconNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.ConnectException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
@@ -60,6 +60,8 @@ import java.util.Date;
public class LoginDialog extends Dialog<AuthorizationInformation>
{
private final static Logger mLog = LoggerFactory.getLogger(LoginDialog.class);
private static final String TEST_CONNECTION = "Test Connection";
private static final String TESTING_CONNECTION = "Testing...";
private UserPreferences mUserPreferences;
private TextField mUserNameText;
private PasswordField mPasswordField;
@@ -278,7 +280,7 @@ public class LoginDialog extends Dialog<AuthorizationInformation>
{
if(mTestConnectionButton == null)
{
mTestConnectionButton = new Button("Test Connection");
mTestConnectionButton = new Button(TEST_CONNECTION);
mTestConnectionButton.setMaxWidth(Double.MAX_VALUE);
mTestConnectionButton.setOnAction(new EventHandler<ActionEvent>()
{
@@ -316,98 +318,26 @@ public class LoginDialog extends Dialog<AuthorizationInformation>
return;
}
Platform.runLater(new Runnable()
{
@Override
public void run()
getTestConnectionButton().setText(TESTING_CONNECTION);
//The test calls the web service, which can take up to the connect and request timeouts, so it runs
//off the FX thread and the result is shown on the FX thread
ThreadPool.CACHED.execute(() -> {
RadioReference.LoginStatus loginStatus = null;
Exception error = null;
try
{
boolean success = false;
RadioReference.LoginStatus loginStatus;
try
{
loginStatus = RadioReference.testConnectionWithExp(userName, password);
if(loginStatus == RadioReference.LoginStatus.VALID_PREMIUM)
{
getTestPassIcon().setVisible(true);
getTestFailIcon().setVisible(false);
getTestExpiredIcon().setVisible(false);
//Success is only shown as an icon, so report it in the button's accessible name
getTestConnectionButton().setAccessibleText("Test Connection: login successful");
}
else if (loginStatus == RadioReference.LoginStatus.EXPIRED_PREMIUM)
{
getTestPassIcon().setVisible(false);
getTestFailIcon().setVisible(false);
getTestExpiredIcon().setVisible(true);
Alert alert = new Alert(Alert.AlertType.WARNING, "You do not have a valid Radio Reference Premium Subscription (it may have expired).", ButtonType.OK);
alert.setHeaderText("Expired Premium Account");
alert.setTitle("Radio Reference Account issue");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
}
else if (loginStatus == RadioReference.LoginStatus.INVALID_LOGIN)
{
getTestPassIcon().setVisible(false);
getTestFailIcon().setVisible(true);
getTestExpiredIcon().setVisible(false);
Alert alert = new Alert(Alert.AlertType.ERROR, "Please verify username and password", ButtonType.OK);
alert.setHeaderText("Login Failed");
alert.setTitle("Test Failed");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
mLog.error("Login failed. Invalid username or password. Can't login to radioreference.com");
}
else
{
// Only way to get here is via an exception
}
}
catch(RadioReferenceException rre)
{
// Set an error state
getTestPassIcon().setVisible(false);
getTestFailIcon().setVisible(true);
getTestExpiredIcon().setVisible(false);
if(rre.getCause() instanceof ConnectException)
{
Alert alert = new Alert(Alert.AlertType.ERROR, "Please check network or radio reference availability", ButtonType.OK);
alert.setHeaderText("No Network Connection");
alert.setTitle("Test Failed");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
mLog.error("No network connection to radioreference.com");
}
else if(rre.hasFault())
{
Fault fault = rre.getFault();
Alert alert = new Alert(Alert.AlertType.ERROR, fault.getFaultString(), ButtonType.OK);
alert.setHeaderText(fault.getFaultCode());
alert.setTitle("Test Failed");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
mLog.error("Test failed. Fault [" + fault.toString() + "] Can't login to radioreference.com");
}
else
{
Alert alert = new Alert(Alert.AlertType.ERROR, "Error: " + rre.getMessage(), ButtonType.OK);
alert.setHeaderText("Unknown Error");
alert.setTitle("Test Failed");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
mLog.error("Error testing connection to radioreference.com", rre);
}
}
getTestConnectionButton().setDisable(false);
loginStatus = RadioReference.testConnectionWithExp(userName, password);
}
catch(Exception e)
{
error = e;
}
final RadioReference.LoginStatus status = loginStatus;
final Exception exception = error;
Platform.runLater(() -> showTestConnectionResult(status, exception));
});
}
});
@@ -416,6 +346,111 @@ public class LoginDialog extends Dialog<AuthorizationInformation>
return mTestConnectionButton;
}
/**
* Shows the result of a connection test. Must be called on the FX thread.
* @param loginStatus from the test, or null if the test failed with an error
* @param error from the test, or null
*/
private void showTestConnectionResult(RadioReference.LoginStatus loginStatus, Exception error)
{
getTestConnectionButton().setText(TEST_CONNECTION);
getTestConnectionButton().setDisable(false);
//Results that arrive after the dialog closes are only logged
boolean showing = isShowing();
if(error != null)
{
// Set an error state
getTestPassIcon().setVisible(false);
getTestFailIcon().setVisible(true);
getTestExpiredIcon().setVisible(false);
RadioReferenceException.ErrorType errorType = error instanceof RadioReferenceException rre ?
rre.getErrorType() : RadioReferenceException.ErrorType.UNKNOWN;
//The service has a 10 second connect timeout, so an unreachable service is reported as TIMEOUT as well
//as NETWORK
if(errorType == RadioReferenceException.ErrorType.NETWORK ||
errorType == RadioReferenceException.ErrorType.TIMEOUT)
{
mLog.error("No network connection to radioreference.com - " + error.getMessage());
if(showing)
{
showTestFailedAlert(Alert.AlertType.ERROR, "No Network Connection",
"Please check network or radio reference availability");
}
}
else if(error instanceof RadioReferenceException rre && rre.hasFault())
{
Fault fault = rre.getFault();
mLog.error("Test failed. Fault [" + fault.toString() + "] Can't login to radioreference.com");
if(showing)
{
showTestFailedAlert(Alert.AlertType.ERROR, fault.getFaultCode(), fault.getFaultString());
}
}
else
{
mLog.error("Error testing connection to radioreference.com", error);
if(showing)
{
showTestFailedAlert(Alert.AlertType.ERROR, "Unknown Error", "Error: " + error.getMessage());
}
}
}
else if(loginStatus == RadioReference.LoginStatus.VALID_PREMIUM)
{
getTestPassIcon().setVisible(true);
getTestFailIcon().setVisible(false);
getTestExpiredIcon().setVisible(false);
//Success is only shown as an icon, so report it in the button's accessible name
getTestConnectionButton().setAccessibleText("Test Connection: login successful");
}
else if(loginStatus == RadioReference.LoginStatus.EXPIRED_PREMIUM)
{
getTestPassIcon().setVisible(false);
getTestFailIcon().setVisible(false);
getTestExpiredIcon().setVisible(true);
if(showing)
{
Alert alert = new Alert(Alert.AlertType.WARNING, "You do not have a valid Radio Reference Premium Subscription (it may have expired).", ButtonType.OK);
alert.setHeaderText("Expired Premium Account");
alert.setTitle("Radio Reference Account issue");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
}
}
else if(loginStatus == RadioReference.LoginStatus.INVALID_LOGIN)
{
getTestPassIcon().setVisible(false);
getTestFailIcon().setVisible(true);
getTestExpiredIcon().setVisible(false);
mLog.error("Login failed. Invalid username or password. Can't login to radioreference.com");
if(showing)
{
showTestFailedAlert(Alert.AlertType.ERROR, "Login Failed", "Please verify username and password");
}
}
}
/**
* Shows an alert for a failed connection test. Must be called on the FX thread.
*/
private void showTestFailedAlert(Alert.AlertType alertType, String header, String content)
{
Alert alert = new Alert(alertType, content, ButtonType.OK);
alert.setHeaderText(header);
alert.setTitle("Test Failed");
alert.initOwner(((Node)getTestConnectionButton()).getScene().getWindow());
alert.showAndWait();
}
private IconNode getTestPassIcon()
{
if(mTestPassIcon == null)

View File

@@ -70,8 +70,28 @@ public enum ModeDecoderType
}
/**
* Lookup the entry that matches the mode
*
* Lookup the matching entry for a radio reference mode name, e.g. FMN
* @param name of the mode
* @return matching entry or UNKNOWN
*/
public static ModeDecoderType fromName(String name)
{
if(name != null)
{
for(ModeDecoderType modeDecoderType : ModeDecoderType.values())
{
if(modeDecoderType.getValue().contentEquals(name.trim().toLowerCase()))
{
return modeDecoderType;
}
}
}
return UNKNOWN;
}
/**
* Lookup the matching entry for the radio reference mode
* @param mode to match
* @return matching entry or UNKNOWN
*/

View File

@@ -0,0 +1,268 @@
/*
* *****************************************************************************
* 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.controller.channel.Channel;
import io.github.dsheirer.module.decode.DecoderFactory;
import io.github.dsheirer.module.decode.DecoderType;
import io.github.dsheirer.module.decode.config.DecodeConfiguration;
import io.github.dsheirer.module.decode.nbfm.DecodeConfigNBFM;
import io.github.dsheirer.module.decode.nxdn.DecodeConfigNXDN;
import io.github.dsheirer.module.decode.nxdn.layer3.type.TransmissionMode;
import io.github.dsheirer.module.decode.p25.phase1.DecodeConfigP25Phase1;
import io.github.dsheirer.module.decode.p25.phase1.Modulation;
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.source.config.SourceConfigTuner;
import io.github.dsheirer.source.config.SourceConfigTunerMultipleFrequency;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Creates playlist channels from radio reference frequencies and trunked system sites.
*/
public final class RadioReferenceChannelFactory
{
private static final Logger mLog = LoggerFactory.getLogger(RadioReferenceChannelFactory.class);
private RadioReferenceChannelFactory()
{
}
/**
* Creates a conventional channel for a radio reference frequency
* @param modeDecoderType of the frequency's radio reference mode
* @param frequency in Hertz
* @param system name for the channel
* @param site name for the channel
* @param name of the channel
* @return channel, or null when sdrtrunk has no decoder for the mode
*/
public static Channel conventional(ModeDecoderType modeDecoderType, long frequency, String system, String site,
String name)
{
if(modeDecoderType.hasDecoderType())
{
Channel channel = new Channel();
channel.setSystem(system);
channel.setSite(site);
channel.setName(name);
SourceConfigTuner sourceConfigTuner = new SourceConfigTuner();
sourceConfigTuner.setFrequency(frequency);
channel.setSourceConfiguration(sourceConfigTuner);
DecodeConfiguration decodeConfiguration = DecoderFactory.getDecodeConfiguration(modeDecoderType.getDecoderType());
if(decodeConfiguration instanceof DecodeConfigNBFM && modeDecoderType == ModeDecoderType.FM)
{
((DecodeConfigNBFM)decodeConfiguration).setBandwidth(DecodeConfigNBFM.Bandwidth.BW_25_0);
}
else if(decodeConfiguration instanceof DecodeConfigP25Phase1)
{
((DecodeConfigP25Phase1)decodeConfiguration).setModulation(Modulation.C4FM);
}
else if(decodeConfiguration instanceof DecodeConfigNXDN nxdn)
{
if(modeDecoderType == ModeDecoderType.NXDN48)
{
nxdn.setTransmissionMode(TransmissionMode.M4800);
}
else if(modeDecoderType == ModeDecoderType.NXDN96)
{
nxdn.setTransmissionMode(TransmissionMode.M9600);
}
}
channel.setDecodeConfiguration(decodeConfiguration);
return channel;
}
mLog.warn("Can't create channel configuration for [" + modeDecoderType.name() + "] no supported decoder type");
return null;
}
/**
* Decoder type for a trunked system site's control channel. A P25 Phase II site with an FDMA control channel
* uses the Phase 1 decoder, which follows the Phase II traffic channels.
* @return decoder type, or null when sdrtrunk can't decode the site's control channel
*/
public static DecoderType getControlDecoderType(RadioReferenceDecoder decoder, System system, Site site)
{
//Motorola Type II control channels with P25 voice channels aren't supported
if(decoder.isHybridMotorolaP25(system))
{
return null;
}
DecoderType decoderType = decoder.getDecoderType(system, site);
if(decoderType == DecoderType.P25_PHASE2 && (site == null || site.getTdmaControlChannel() == 0))
{
return DecoderType.P25_PHASE1;
}
return decoderType;
}
/**
* Control and alternate control channel frequencies of the site, control channels first
*/
public static List<Long> getControlFrequencies(Site site)
{
List<Long> frequencies = new ArrayList<>();
if(site != null && site.getSiteFrequencies() != null)
{
for(SiteFrequency siteFrequency: site.getSiteFrequencies())
{
if(SiteEditor.isControl(siteFrequency) && siteFrequency.getFrequencyHz() > 0)
{
frequencies.add(siteFrequency.getFrequencyHz());
}
}
for(SiteFrequency siteFrequency: site.getSiteFrequencies())
{
if(SiteEditor.isAlternate(siteFrequency) && siteFrequency.getFrequencyHz() > 0)
{
frequencies.add(siteFrequency.getFrequencyHz());
}
}
}
return frequencies;
}
/**
* Creates a channel for each of the site's repeaters on the frequencies, for systems without a control channel
* (LTR), where each repeater carries its own trunking data. The channels are named by logical channel number,
* like the playlist editor's site editor does.
* @param decoder for the radio reference system details
* @param system of the site
* @param systemInformation of the system
* @param site of the repeaters
* @param frequencies of the repeaters to create channels for
* @return channels, or an empty list when sdrtrunk can't decode the system
*/
public static List<Channel> repeaters(RadioReferenceDecoder decoder, System system,
SystemInformation systemInformation, Site site, List<Long> frequencies)
{
List<Channel> channels = new ArrayList<>();
DecoderType decoderType = decoder.getDecoderType(system, site);
if(decoderType == null || site == null || site.getSiteFrequencies() == null)
{
return channels;
}
for(SiteFrequency siteFrequency: site.getSiteFrequencies())
{
if(frequencies.contains(siteFrequency.getFrequencyHz()))
{
Channel channel = new Channel();
channel.setSystem(system.getName());
channel.setSite(site.getDescription() != null && !site.getDescription().isBlank() ?
site.getDescription().trim() : "Site " + site.getSiteNumber());
channel.setName("LCN " + siteFrequency.getLogicalChannelNumber());
channel.setDecodeConfiguration(decoder.getDecodeConfiguration(decoderType, site, systemInformation));
SourceConfigTuner sourceConfigTuner = new SourceConfigTuner();
sourceConfigTuner.setFrequency(siteFrequency.getFrequencyHz());
channel.setSourceConfiguration(sourceConfigTuner);
channels.add(channel);
}
}
return channels;
}
/**
* Creates a channel for a trunked system site: the site's control channel decoder, tuned to its control and
* alternate control channels.
* @param decoder for the radio reference system details
* @param system of the site
* @param systemInformation of the system
* @param site to create a channel for
* @return channel, or null when sdrtrunk can't decode the site's control channel or it has none listed
*/
public static Channel trunkedSite(RadioReferenceDecoder decoder, System system, SystemInformation systemInformation,
Site site)
{
return trunkedSite(decoder, system, systemInformation, site, null);
}
/**
* Creates a channel for a trunked system site: the site's control channel decoder, tuned to its control and
* alternate control channels, starting with the first frequency when it's one of them.
* @param decoder for the radio reference system details
* @param system of the site
* @param systemInformation of the system
* @param site to create a channel for
* @param firstFrequency to list first, so the channel starts on it, or null for control channels first
* @return channel, or null when sdrtrunk can't decode the site's control channel or it has none listed
*/
public static Channel trunkedSite(RadioReferenceDecoder decoder, System system, SystemInformation systemInformation,
Site site, Long firstFrequency)
{
DecoderType decoderType = getControlDecoderType(decoder, system, site);
List<Long> frequencies = getControlFrequencies(site);
//A multi-frequency channel starts on its first frequency
if(firstFrequency != null && frequencies.remove(firstFrequency))
{
frequencies.add(0, firstFrequency);
}
if(decoderType == null || frequencies.isEmpty())
{
return null;
}
Channel channel = new Channel();
channel.setSystem(system.getName());
String siteName = "Site " + site.getSiteNumber();
channel.setSite(site.getDescription() != null && !site.getDescription().isBlank() ?
site.getDescription().trim() : siteName);
channel.setName(siteName);
channel.setDecodeConfiguration(decoder.getDecodeConfiguration(decoderType, site, systemInformation));
if(frequencies.size() == 1)
{
SourceConfigTuner sourceConfigTuner = new SourceConfigTuner();
sourceConfigTuner.setFrequency(frequencies.get(0));
channel.setSourceConfiguration(sourceConfigTuner);
}
else
{
SourceConfigTunerMultipleFrequency sourceConfig = new SourceConfigTunerMultipleFrequency();
for(long frequency: frequencies)
{
sourceConfig.addFrequency(frequency);
}
channel.setSourceConfiguration(sourceConfig);
}
return channel;
}
}

View File

@@ -19,6 +19,16 @@
package io.github.dsheirer.gui.playlist.radioreference;
import io.github.dsheirer.module.decode.DecoderFactory;
import io.github.dsheirer.module.decode.config.DecodeConfiguration;
import io.github.dsheirer.module.decode.dmr.DecodeConfigDMR;
import io.github.dsheirer.module.decode.nxdn.DecodeConfigNXDN;
import io.github.dsheirer.module.decode.nxdn.layer3.type.TransmissionMode;
import io.github.dsheirer.module.decode.p25.phase1.DecodeConfigP25Phase1;
import io.github.dsheirer.module.decode.p25.phase1.Modulation;
import io.github.dsheirer.module.decode.p25.phase2.DecodeConfigP25Phase2;
import io.github.dsheirer.module.decode.p25.phase2.enumeration.ScrambleParameters;
import io.github.dsheirer.rrapi.type.RadioNetwork;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.identifier.talkgroup.LTRTalkgroup;
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
@@ -382,7 +392,7 @@ public class RadioReferenceDecoder
TimeslotFrequency timeslotFrequency = new TimeslotFrequency();
timeslotFrequency.setNumber(lcn);
timeslotFrequency.setDownlinkFrequency((long)(siteFrequency.getFrequency() * 1E6));
timeslotFrequency.setDownlinkFrequency(siteFrequency.getFrequencyHz());
frequencies.add(timeslotFrequency);
}
@@ -432,7 +442,7 @@ public class RadioReferenceDecoder
}
}
frequencies.add(new ChannelFrequency(lcn, (long)(siteFrequency.getFrequency() * 1E6), 0));
frequencies.add(new ChannelFrequency(lcn, siteFrequency.getFrequencyHz(), 0));
}
return frequencies;
@@ -577,4 +587,126 @@ public class RadioReferenceDecoder
return null;
}
/**
* Creates a channel decode configuration for the specified site.
* @param decoderType to create
* @param site information and frequencies
* @param systemInformation with frequency mapping
* @return decode configuration
*/
public DecodeConfiguration getDecodeConfiguration(DecoderType decoderType, Site site, SystemInformation systemInformation)
{
if(decoderType == null)
{
return null;
}
switch(decoderType)
{
case DMR:
DecodeConfigDMR dmr = new DecodeConfigDMR();
List<TimeslotFrequency> timeslotFrequencies = getTimeslotFrequencies(systemInformation, site);
dmr.setTimeslotMap(timeslotFrequencies);
return dmr;
case NXDN:
Flavor flavor = getFlavor(systemInformation);
TransmissionMode mode = TransmissionMode.M4800;
/**
* 9600 bps Flavors
* ----------------------------
* 29 - NEXEDGE 9600
* 45 - Conventional Networked
*
* 4800 bps Flavors
* ---------------------------
* 11 - Narrowband Networked
* 42 - NEXEDGE 4800
* 44 - Icom IDAS Type C
*
* Type-D (also 4800 bps) Flavors
* ---------------------------
* 36 - Icom IDAS Type D
* 47 - Kenwood Type D
*/
mode = switch(flavor.getName())
{
case "NEXEDGE 9600", "Conventional Networked" -> TransmissionMode.M9600;
case "Icom IDAS Type D", "Kenwood Type D" -> TransmissionMode.TYPE_D;
default -> TransmissionMode.M4800;
};
DecodeConfigNXDN nxdn = new DecodeConfigNXDN(mode);
List<ChannelFrequency> channelMap = getChannelMap(systemInformation, site);
nxdn.setChannelMap(channelMap);
return nxdn;
case P25_PHASE1:
DecodeConfiguration p1config = DecoderFactory.getDecodeConfiguration(decoderType);
if(isLSM(site))
{
if(p1config instanceof DecodeConfigP25Phase1)
{
((DecodeConfigP25Phase1)p1config).setModulation(Modulation.CQPSK);
}
}
return p1config;
case P25_PHASE2:
DecodeConfigP25Phase2 config = new DecodeConfigP25Phase2();
int nac = 0;
if(site != null && site.getNac() != null)
{
try
{
nac = Integer.parseInt(site.getNac(), 16);
}
catch(Exception e)
{
//Do nothing
}
}
int wacn = 0;
int system = 0;
if(systemInformation != null && systemInformation.getRadioNetworks() != null &&
!systemInformation.getRadioNetworks().isEmpty())
{
RadioNetwork radioNetwork = systemInformation.getRadioNetworks().get(0);
if(radioNetwork.getWacn() != null)
{
try
{
wacn = Integer.parseInt(radioNetwork.getWacn(), 16);
}
catch(Exception e)
{
//Do nothing
}
}
if(radioNetwork.getSystemId() != null)
{
try
{
system = Integer.parseInt(radioNetwork.getSystemId(), 16);
}
catch(Exception e)
{
//Do nothing
}
}
}
config.setScrambleParameters(new ScrambleParameters(wacn, system, nac));
return config;
default:
return DecoderFactory.getDecodeConfiguration(decoderType);
}
}
}

View File

@@ -20,34 +20,46 @@
package io.github.dsheirer.gui.playlist.radioreference;
import io.github.dsheirer.playlist.PlaylistManager;
import com.google.common.eventbus.Subscribe;
import io.github.dsheirer.eventbus.MyEventBus;
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;
import io.github.dsheirer.service.radioreference.UserLocation;
import io.github.dsheirer.util.ThreadPool;
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;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
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.util.StringConverter;
@@ -57,7 +69,10 @@ 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;
public class RadioReferenceEditor extends BorderPane implements Consumer<AuthorizationInformation>
@@ -68,6 +83,10 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
private PlaylistManager mPlaylistManager;
private VBox mTopBox;
private HBox mCredentialsBox;
private HBox mLocationBox;
private Label mLocationText;
private final AtomicLong mLocationRequest = new AtomicLong();
private volatile String mLocationKey;
private Label mRRStatusText;
private TextField mUserNameText;
private TextField mAccountExpiresText;
@@ -113,20 +132,41 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
{
refreshCountries();
}
//The preferred county fallback location needs a premium login
refreshLocation();
});
refreshLocation();
//Updates the location when it's changed elsewhere, e.g. from the map
MyEventBus.getGlobalEventBus().register(this);
}
/**
* Refreshes the location text when the location or the preferred county changes
* @param preferenceType that was updated
*/
@Subscribe
public void preferenceUpdated(PreferenceType preferenceType)
{
if(preferenceType == PreferenceType.RADIO_REFERENCE)
{
RadioReferencePreference preference = mUserPreferences.getRadioReferencePreference();
String key = preference.getLocation() + "/" + preference.getPreferredCountyId();
if(!key.equals(mLocationKey))
{
mLocationKey = key;
Platform.runLater(this::refreshLocation);
}
}
}
private void login()
{
if(mUserPreferences.getRadioReferencePreference().hasStoredCredentials())
{
AuthorizationInformation credentials = mUserPreferences.getRadioReferencePreference().getAuthorizationInformation();
if(credentials != null)
{
ThreadPool.CACHED.execute(() -> accept(credentials));
}
}
//Logs in on a background thread, unless the spectral display has already logged in
mRadioReference.loginWithStoredCredentials();
}
/**
@@ -137,8 +177,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
{
getCountryComboBox().getItems().clear();
final int preferredCountryId = mUserPreferences.getRadioReferencePreference().getPreferredCountryId();
ThreadPool.CACHED.execute(() -> {
try
{
@@ -146,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)
{
@@ -168,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)
@@ -354,7 +730,7 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
mTopBox = new VBox();
mTopBox.setSpacing(5);
mTopBox.setPadding(new Insets(10,10,10,10));
mTopBox.getChildren().addAll(getCredentialsBox(), getComboBoxPane());
mTopBox.getChildren().addAll(getCredentialsBox(), getLocationBox(), getComboBoxPane());
}
return mTopBox;
@@ -416,13 +792,7 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
mCredentialsBox = new HBox();
mCredentialsBox.setAlignment(Pos.CENTER_RIGHT);
mCredentialsBox.setSpacing(5.0);
Region leftFiller = new Region();
HBox.setHgrow(leftFiller, Priority.ALWAYS);
mCredentialsBox.getChildren().add(leftFiller);
mCredentialsBox.getChildren().add(getRRPremiumReqText());
Region rightFiller = new Region();
HBox.setHgrow(rightFiller, Priority.ALWAYS);
mCredentialsBox.getChildren().add(rightFiller);
mCredentialsBox.getChildren().add(new Label("User Name:"));
mCredentialsBox.getChildren().add(getUserNameText());
mCredentialsBox.getChildren().add(new Label("Expires:"));
@@ -446,8 +816,8 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
Bindings.and(
mRadioReference.availableProperty(),
mRadioReference.premiumAccountProperty().not()));
mRRStatusText.setTextFill(Color.ORANGERED);
mRRStatusText.setStyle("-fx-font-weight: bold;"); // I guess
//Inline style, because the theme stylesheets override a label's text fill
mRRStatusText.setStyle("-fx-text-fill: orangered; -fx-font-weight: bold;");
}
return mRRStatusText;
@@ -571,8 +941,6 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
if(country != null)
{
int preferredStateId = mUserPreferences.getRadioReferencePreference().getPreferredStateId();
ThreadPool.CACHED.execute(() -> {
try
{
@@ -581,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())
{
@@ -627,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(() -> {
@@ -640,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())
{
@@ -725,6 +1093,7 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
if(selected != null)
{
mUserPreferences.getRadioReferencePreference().setPreferredCountyId(selected.getCountyId());
refreshLocation();
}
});
}
@@ -732,6 +1101,111 @@ public class RadioReferenceEditor extends BorderPane implements Consumer<Authori
return mCountyComboBox;
}
/**
* Row that shows the user's location and a button to change it
*/
private HBox getLocationBox()
{
if(mLocationBox == null)
{
mLocationBox = new HBox();
mLocationBox.setAlignment(Pos.CENTER_LEFT);
mLocationBox.setSpacing(5.0);
Button setLocationButton = new Button("My Location:");
setLocationButton.setOnAction(event -> {
LocationDialog dialog = new LocationDialog(mRadioReference,
mUserPreferences.getRadioReferencePreference().getLocation(), getScene().getWindow());
//The map follows the location through the preference update
dialog.showAndWait().ifPresent(result -> {
mUserPreferences.getRadioReferencePreference().setLocation(result.location());
refreshLocation();
});
});
mLocationBox.getChildren().addAll(setLocationButton, getLocationText());
}
return mLocationBox;
}
private Label getLocationText()
{
if(mLocationText == null)
{
mLocationText = new Label();
mLocationText.setTooltip(new Tooltip("Your location is shown on the map and used to find nearby Radio " +
"Reference frequencies. When it isn't set, the center of the selected county is used."));
}
return mLocationText;
}
/**
* Updates the location text: the user's location, or else the preferred county fallback, which is looked up in
* the background.
*/
private void refreshLocation()
{
long request = mLocationRequest.incrementAndGet();
RadioReferencePreference.Location location = mUserPreferences.getRadioReferencePreference().getLocation();
if(location != null)
{
getLocationText().setText(location.describe());
return;
}
String notRanked = "Not set";
if(mUserPreferences.getRadioReferencePreference().getPreferredCountyId() <= 0 ||
!mRadioReference.premiumAccountProperty().get())
{
getLocationText().setText(notRanked);
return;
}
getLocationText().setText("Not set");
ThreadPool.CACHED.execute(() -> {
String text;
try
{
UserLocation userLocation = mRadioReference.getUserLocation();
if(userLocation == null)
{
text = notRanked;
}
else if(userLocation.source() == UserLocation.Source.PREFERRED_COUNTY)
{
text = "Not set - using the center of " + userLocation.description();
}
else
{
//Set in the meantime - a newer refresh shows it
return;
}
}
catch(RadioReferenceException rre)
{
mLog.warn("Unable to look up the preferred county location - " + rre.getMessage());
text = "Not set - unable to look up the selected county";
}
final String locationText = text;
Platform.runLater(() -> {
//A newer refresh supersedes this one
if(mLocationRequest.get() == request)
{
getLocationText().setText(locationText);
}
});
});
}
/**
* Consumer interface method for receiving login credentials

View File

@@ -0,0 +1,660 @@
/*
* *****************************************************************************
* 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.controller.channel.Channel;
import io.github.dsheirer.controller.channel.ChannelException;
import io.github.dsheirer.module.decode.DecoderType;
import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.rrapi.RadioReferenceException;
import io.github.dsheirer.rrapi.RadioReferenceService;
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.service.radioreference.RadioReference;
import io.github.dsheirer.service.radioreference.SiteRecord;
import io.github.dsheirer.source.config.SourceConfigTuner;
import io.github.dsheirer.source.config.SourceConfigTunerMultipleFrequency;
import io.github.dsheirer.source.config.SourceConfiguration;
import io.github.dsheirer.util.ThreadPool;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Playlist actions for radio reference frequencies and trunked system sites: find the playlist channel that already
* decodes a frequency or site, enable or disable it, or add a channel and optionally start it. A frequency or site that already
* 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
* calling thread pool: the handler shows the message on its own UI thread.
*/
public class RadioReferencePlaylistActions
{
private static final Logger mLog = LoggerFactory.getLogger(RadioReferencePlaylistActions.class);
private final PlaylistManager mPlaylistManager;
/**
* Constructs an instance
* @param playlistManager for the channels, channel processing and the radio reference service
*/
public RadioReferencePlaylistActions(PlaylistManager playlistManager)
{
mPlaylistManager = playlistManager;
}
/**
* Decoder types that count as the same protocol when looking for an existing channel: P25 Phase 1 and Phase 2
* (a Phase 2 system's control channel is often decoded with the Phase 1 decoder), and the LTR variants.
*/
public static Set<DecoderType> getProtocolFamily(DecoderType decoderType)
{
if(decoderType == null)
{
return EnumSet.noneOf(DecoderType.class);
}
return switch(decoderType)
{
case P25_PHASE1, P25_PHASE2 -> EnumSet.of(DecoderType.P25_PHASE1, DecoderType.P25_PHASE2);
case LTR, LTR_NET, PASSPORT -> EnumSet.of(DecoderType.LTR, DecoderType.LTR_NET, DecoderType.PASSPORT);
default -> EnumSet.of(decoderType);
};
}
/**
* Decoder types for a site's control channel, from the site's radio reference protocol
* @return decoder types, or an empty set when sdrtrunk can't decode the site's control channel
*/
public static Set<DecoderType> getSiteDecoderTypes(SiteRecord site)
{
String protocol = site.protocol() != null ? site.protocol().toLowerCase() : "";
if(protocol.startsWith("project 25"))
{
return getProtocolFamily(DecoderType.P25_PHASE1);
}
else if(protocol.startsWith("dmr"))
{
return EnumSet.of(DecoderType.DMR);
}
else if(protocol.startsWith("nxdn"))
{
return EnumSet.of(DecoderType.NXDN);
}
else if(protocol.startsWith("ltr"))
{
return getProtocolFamily(DecoderType.LTR);
}
else if(protocol.startsWith("mpt"))
{
return EnumSet.of(DecoderType.MPT1327);
}
//Motorola Type II, EDACS and other control channels aren't supported
return EnumSet.noneOf(DecoderType.class);
}
/**
* Indicates if the site's system has no control channel, so each repeater has its own channel: LTR, where every
* repeater carries its own trunking data
*/
public static boolean isRepeaterSite(SiteRecord site)
{
return getSiteDecoderTypes(site).contains(DecoderType.LTR);
}
/**
* Indicates if sdrtrunk can decode the site: its control channel, which radio reference lists, or its repeaters
*/
public static boolean isSupported(SiteRecord site)
{
return getUnsupportedReason(site) == null;
}
/**
* Why sdrtrunk can't decode the site
* @return reason, or null when the site is supported
*/
public static String getUnsupportedReason(SiteRecord site)
{
if(getSiteDecoderTypes(site).isEmpty())
{
return (site.protocol() != null ? site.protocol() : "The protocol") + " isn't supported";
}
if(isRepeaterSite(site) ? site.channels().isEmpty() : getControlFrequencies(site).isEmpty())
{
return isRepeaterSite(site) ? "Radio Reference lists no repeaters" :
"Radio Reference lists no control channel";
}
return null;
}
/**
* Frequencies of all of the site's channels
*/
public static List<Long> getSiteFrequencies(SiteRecord site)
{
List<Long> frequencies = new ArrayList<>();
for(SiteRecord.SiteChannel channel: site.channels())
{
frequencies.add(channel.frequencyHz());
}
return frequencies;
}
/**
* Control and alternate control channel frequencies of the site, control channels first
*/
public static List<Long> getControlFrequencies(SiteRecord site)
{
List<Long> frequencies = new ArrayList<>();
for(String use: List.of("Control", "Alternate control"))
{
for(SiteRecord.SiteChannel channel: site.channels())
{
if(use.equals(channel.use()))
{
frequencies.add(channel.frequencyHz());
}
}
}
return frequencies;
}
/**
* Decoder type for a conventional candidate's radio reference mode, or null when sdrtrunk has no decoder for it
*/
public static DecoderType getDecoderType(FrequencyCandidate candidate)
{
ModeDecoderType mode = ModeDecoderType.fromName(candidate.mode());
return mode.hasDecoderType() ? mode.getDecoderType() : null;
}
/**
* Playlist channel, not a temporary traffic channel, tuned to any of the frequencies with one of the decoder types
* @return channel, or null
*/
public Channel findChannel(Collection<Long> frequencies, Set<DecoderType> decoderTypes)
{
return findChannel(getChannels(), frequencies, decoderTypes);
}
/**
* Channel in the list, not a temporary traffic channel, tuned to any of the frequencies with one of the decoder
* types
* @return channel, or null
*/
static Channel findChannel(List<Channel> channels, Collection<Long> frequencies, Set<DecoderType> decoderTypes)
{
if(frequencies.isEmpty() || decoderTypes.isEmpty())
{
return null;
}
for(Channel channel: channels)
{
if(channel.isTrafficChannel() || channel.getDecodeConfiguration() == null ||
!decoderTypes.contains(channel.getDecodeConfiguration().getDecoderType()))
{
continue;
}
for(long frequency: getFrequencies(channel.getSourceConfiguration()))
{
if(frequencies.contains(frequency))
{
return channel;
}
}
}
return null;
}
/**
* Playlist channel that decodes the site, tuned to one of its control channels
* @return channel, or null
*/
public Channel findSiteChannel(SiteRecord site)
{
return findChannel(getControlFrequencies(site), getSiteDecoderTypes(site));
}
/**
* Playlist channels that decode the site: its control channel, or each of its repeaters that has a channel
*/
public List<Channel> findSiteChannels(SiteRecord site)
{
List<Channel> channels = new ArrayList<>();
if(isRepeaterSite(site))
{
List<Channel> playlist = getChannels();
for(long frequency: getSiteFrequencies(site))
{
Channel channel = findChannel(playlist, List.of(frequency), getSiteDecoderTypes(site));
if(channel != null && !channels.contains(channel))
{
channels.add(channel);
}
}
}
else
{
Channel channel = findSiteChannel(site);
if(channel != null)
{
channels.add(channel);
}
}
return channels;
}
/**
* Frequencies of a repeater site that don't have a playlist channel yet
*/
public List<Long> getMissingRepeaterFrequencies(SiteRecord site)
{
List<Long> missing = new ArrayList<>();
List<Channel> playlist = getChannels();
for(long frequency: getSiteFrequencies(site))
{
if(findChannel(playlist, List.of(frequency), getSiteDecoderTypes(site)) == null)
{
missing.add(frequency);
}
}
return missing;
}
/**
* Starts the channels that aren't decoding, in the background
*/
public void enableAll(List<Channel> channels, Consumer<String> onError)
{
for(Channel channel: channels)
{
if(!channel.isProcessing())
{
enable(channel, onError);
}
}
}
/**
* Stops the channels that are decoding, in the background
*/
public void disableAll(List<Channel> channels, Consumer<String> onError)
{
for(Channel channel: channels)
{
if(channel.isProcessing())
{
disable(channel, onError);
}
}
}
/**
* Playlist channel that decodes the conventional frequency with the same protocol
* @return channel, or null
*/
public Channel findConventionalChannel(FrequencyCandidate candidate)
{
return findChannel(List.of(candidate.frequencyHz()), getProtocolFamily(getDecoderType(candidate)));
}
/**
* Starts decoding the playlist channel, in the background
*/
public void enable(Channel channel, Consumer<String> onError)
{
ThreadPool.CACHED.execute(() -> {
try
{
if(!channel.isProcessing())
{
mPlaylistManager.getChannelProcessingManager().start(channel);
}
}
catch(ChannelException ce)
{
mLog.error("Error starting channel [" + channel.getName() + "] - " + ce.getMessage());
onError.accept("Can't start " + channel.getShortTitle() + ": " + ce.getMessage());
}
});
}
/**
* Stops decoding the playlist channel, in the background
*/
public void disable(Channel channel, Consumer<String> onError)
{
ThreadPool.CACHED.execute(() -> {
try
{
mPlaylistManager.getChannelProcessingManager().stop(channel);
}
catch(ChannelException ce)
{
mLog.error("Error stopping channel [" + channel.getName() + "] - " + ce.getMessage());
onError.accept("Can't stop " + channel.getShortTitle() + ": " + ce.getMessage());
}
});
}
/**
* Radio reference details of a site, for creating its channels
*/
private record SiteDetails(RadioReferenceDecoder decoder, io.github.dsheirer.rrapi.type.System system,
SystemInformation systemInformation, Site site)
{
}
/**
* Fetches the site's system details from radio reference. Call from a background thread.
* @return details, or null after reporting the error
*/
private SiteDetails getSiteDetails(SiteRecord siteRecord, Consumer<String> onError)
{
try
{
RadioReference radioReference = mPlaylistManager.getRadioReference();
RadioReferenceService service = radioReference.getService();
SystemInformation systemInformation = service.getSystemInformation(siteRecord.systemId());
Site site = null;
for(Site candidate: service.getSites(siteRecord.systemId()))
{
if(candidate.getSiteId() == siteRecord.siteId())
{
site = candidate;
}
}
if(systemInformation == null || site == null)
{
onError.accept("Radio Reference didn't provide the details of " + siteRecord.systemName() + " site " +
siteRecord.siteNumber());
return null;
}
RadioReferenceDecoder decoder = new RadioReferenceDecoder(radioReference.getUserPreferences(),
service.getTypesMap(), service.getFlavorsMap(), service.getVoicesMap(), service.getTagsMap());
io.github.dsheirer.rrapi.type.System system = new io.github.dsheirer.rrapi.type.System();
system.setSystemId(siteRecord.systemId());
system.setName(systemInformation.getName() != null ? systemInformation.getName() : siteRecord.systemName());
system.setTypeId(systemInformation.getTypeId());
system.setFlavorId(systemInformation.getFlavorId());
system.setVoiceId(systemInformation.getVoiceId());
return new SiteDetails(decoder, system, systemInformation, site);
}
catch(RadioReferenceException rre)
{
mLog.error("Error getting radio reference site details - " + rre.getMessage());
onError.accept("Can't get the site details from Radio Reference: " + rre.getMessage());
return null;
}
}
/**
* Adds playlist channels for the trunked system site and starts them, or starts the site's existing channels.
* A site with a control channel gets one channel for its control channels. A repeater site (LTR) gets a channel
* for each repeater that doesn't have one yet, and all of its channels are started. Fetches the system details
* from radio reference in the background.
*/
public void addSite(SiteRecord siteRecord, Consumer<String> onError)
{
addSite(siteRecord, null, onError);
}
/**
* Adds playlist channels for the trunked system site and starts them, or starts the site's existing channels, like
* {@link #addSite(SiteRecord, Consumer)}. A new control channel starts on the first frequency when it's one of the
* site's control or alternate control channels.
* @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);
if(details == null)
{
return;
}
if(isRepeaterSite(siteRecord))
{
List<Channel> channels = RadioReferenceChannelFactory.repeaters(details.decoder(), details.system(),
details.systemInformation(), details.site(), getMissingRepeaterFrequencies(siteRecord));
List<Channel> existing = findSiteChannels(siteRecord);
if(channels.isEmpty() && existing.isEmpty())
{
onError.accept("sdrtrunk can't decode " + siteRecord.systemName() + " site " +
siteRecord.siteNumber() + (siteRecord.protocol() != null ? " (" + siteRecord.protocol() +
")" : ""));
return;
}
if(start)
{
enableAll(existing, onError);
}
//The channel model's list backs the playlist editor, so it's changed on the JavaFX thread
Platform.runLater(() -> {
for(Channel channel: channels)
{
mPlaylistManager.getChannelModel().addChannel(channel);
if(start)
{
enable(channel, onError);
}
}
});
return;
}
Channel channel = RadioReferenceChannelFactory.trunkedSite(details.decoder(), details.system(),
details.systemInformation(), details.site(), firstFrequency);
if(channel == null)
{
onError.accept("sdrtrunk can't decode the control channel of " + siteRecord.systemName() +
" site " + siteRecord.siteNumber() + (siteRecord.protocol() != null ? " (" +
siteRecord.protocol() + ")" : ""));
return;
}
add(channel, start, onError);
});
}
/**
* 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);
if(details == null)
{
return;
}
List<Channel> channels = RadioReferenceChannelFactory.repeaters(details.decoder(), details.system(),
details.systemInformation(), details.site(), List.of(frequency));
if(channels.isEmpty())
{
onError.accept("sdrtrunk can't decode " + siteRecord.systemName() + (siteRecord.protocol() != null ?
" (" + siteRecord.protocol() + ")" : ""));
return;
}
add(channels.get(0), start, onError);
});
}
/**
* 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];
//The source is owner, category and subcategory: the channel's system is the owner, the site the subcategory
String system = source.length > 0 ? source[0] : null;
String site = source.length > 2 ? source[2] : source.length > 1 ? source[1] : null;
String name = candidate.alphaTag() != null ? candidate.alphaTag() : candidate.title();
Channel channel = RadioReferenceChannelFactory.conventional(mode, candidate.frequencyHz(), system, site, name);
if(channel == null)
{
onError.accept("sdrtrunk can't decode " + (candidate.mode() != null ? candidate.mode() : "the mode of") +
" " + candidate.title());
return;
}
add(channel, start, onError);
}
/**
* Adds the channel to the playlist and optionally starts it, unless the playlist already has a channel for its
* frequencies and protocol, which is started instead when starting
*/
private void add(Channel channel, boolean start, Consumer<String> onError)
{
Channel existing = findChannel(getFrequencies(channel.getSourceConfiguration()),
getProtocolFamily(channel.getDecodeConfiguration().getDecoderType()));
if(existing != null)
{
if(start)
{
enable(existing, onError);
}
return;
}
//The channel model's list backs the playlist editor, so it's changed on the JavaFX thread
Platform.runLater(() -> {
mPlaylistManager.getChannelModel().addChannel(channel);
if(start)
{
enable(channel, onError);
}
});
}
/**
* Copy of the playlist channels, safe to read from any thread
*/
private List<Channel> getChannels()
{
for(int attempt = 0; attempt < 3; attempt++)
{
try
{
return new ArrayList<>(mPlaylistManager.getChannelModel().getChannels());
}
catch(ConcurrentModificationException e)
{
//The playlist changed while copying - try again
}
}
return new ArrayList<>();
}
/**
* Tuned frequencies of a channel source
*/
public static List<Long> getFrequencies(SourceConfiguration sourceConfiguration)
{
if(sourceConfiguration instanceof SourceConfigTuner tuner)
{
return List.of(tuner.getFrequency());
}
else if(sourceConfiguration instanceof SourceConfigTunerMultipleFrequency multiple)
{
return new ArrayList<>(multiple.getFrequencies());
}
return List.of();
}
}

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);
@@ -247,118 +256,7 @@ public class SiteEditor extends GridPane
*/
private DecodeConfiguration getDecodeConfiguration(DecoderType decoderType, Site site, SystemInformation systemInformation)
{
if(decoderType == null)
{
return null;
}
switch(decoderType)
{
case DMR:
DecodeConfigDMR dmr = new DecodeConfigDMR();
List<TimeslotFrequency> timeslotFrequencies = mRadioReferenceDecoder
.getTimeslotFrequencies(systemInformation, site);
dmr.setTimeslotMap(timeslotFrequencies);
return dmr;
case NXDN:
Flavor flavor = mRadioReferenceDecoder.getFlavor(systemInformation);
TransmissionMode mode = TransmissionMode.M4800;
/**
* 9600 bps Flavors
* ----------------------------
* 29 - NEXEDGE 9600
* 45 - Conventional Networked
*
* 4800 bps Flavors
* ---------------------------
* 11 - Narrowband Networked
* 42 - NEXEDGE 4800
* 44 - Icom IDAS Type C
*
* Type-D (also 4800 bps) Flavors
* ---------------------------
* 36 - Icom IDAS Type D
* 47 - Kenwood Type D
*/
mode = switch(flavor.getName())
{
case "NEXEDGE 9600", "Conventional Networked" -> TransmissionMode.M9600;
case "Icom IDAS Type D", "Kenwood Type D" -> TransmissionMode.TYPE_D;
default -> TransmissionMode.M4800;
};
DecodeConfigNXDN nxdn = new DecodeConfigNXDN(mode);
List<ChannelFrequency> channelMap = mRadioReferenceDecoder.getChannelMap(systemInformation, site);
nxdn.setChannelMap(channelMap);
return nxdn;
case P25_PHASE1:
DecodeConfiguration p1config = DecoderFactory.getDecodeConfiguration(decoderType);
if(mRadioReferenceDecoder.isLSM(site))
{
if(p1config instanceof DecodeConfigP25Phase1)
{
((DecodeConfigP25Phase1)p1config).setModulation(Modulation.CQPSK);
}
}
return p1config;
case P25_PHASE2:
DecodeConfigP25Phase2 config = new DecodeConfigP25Phase2();
int nac = 0;
if(site != null && site.getNac() != null)
{
try
{
nac = Integer.parseInt(site.getNac(), 16);
}
catch(Exception e)
{
//Do nothing
}
}
int wacn = 0;
int system = 0;
if(systemInformation != null && systemInformation.getRadioNetworks() != null &&
!systemInformation.getRadioNetworks().isEmpty())
{
RadioNetwork radioNetwork = systemInformation.getRadioNetworks().get(0);
if(radioNetwork.getWacn() != null)
{
try
{
wacn = Integer.parseInt(radioNetwork.getWacn(), 16);
}
catch(Exception e)
{
//Do nothing
}
}
if(radioNetwork.getSystemId() != null)
{
try
{
system = Integer.parseInt(radioNetwork.getSystemId(), 16);
}
catch(Exception e)
{
//Do nothing
}
}
}
config.setScrambleParameters(new ScrambleParameters(wacn, system, nac));
return config;
default:
return DecoderFactory.getDecodeConfiguration(decoderType);
}
return mRadioReferenceDecoder.getDecodeConfiguration(decoderType, site, systemInformation);
}
/**
@@ -389,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);
@@ -621,7 +531,7 @@ public class SiteEditor extends GridPane
if(controls.size() == 1)
{
SourceConfigTuner sourceConfigTuner = new SourceConfigTuner();
sourceConfigTuner.setFrequency((long)(controls.get(0).getFrequency() * 1E6));
sourceConfigTuner.setFrequency(controls.get(0).getFrequencyHz());
channel.setSourceConfiguration(sourceConfigTuner);
}
else
@@ -630,7 +540,7 @@ public class SiteEditor extends GridPane
for(SiteFrequency control: controls)
{
sourceConfig.addFrequency((long)(control.getFrequency() * 1E6));
sourceConfig.addFrequency(control.getFrequencyHz());
}
channel.setSourceConfiguration(sourceConfig);
@@ -856,7 +766,7 @@ public class SiteEditor extends GridPane
private static long getFrequency(SiteFrequency siteFrequency)
{
return (long)(siteFrequency.getFrequency() * 1E6);
return siteFrequency.getFrequencyHz();
}
/**
@@ -989,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

@@ -139,8 +139,9 @@ public class SystemEditor extends VBox
if(systems != null && !systems.isEmpty())
{
Collections.sort(systems, new SystemComparator());
//The systems list belongs to a cached state or county info shared with other callers, so sort the items
getSystemComboBox().getItems().addAll(systems);
getSystemComboBox().getItems().sort(new SystemComparator());
int preferredSystemId = mUserPreferences.getRadioReferencePreference().getPreferredSystemId(mLevel);
@@ -155,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)
@@ -302,7 +338,16 @@ public class SystemEditor extends VBox
//have a county ID of 99,999 as observed from API (undocumented).
if(countyId > 0 && countyId != 99999)
{
countyInfo = mRadioReference.getService().getCountyInfo(site.getCountyId());
//The county name is only for display, so a failed lookup shouldn't fail the system load
try
{
countyInfo = mRadioReference.getService().getCountyInfo(site.getCountyId());
}
catch(RadioReferenceException rre)
{
mLog.warn("Unable to retrieve county [" + countyId + "] for site [" +
site.getSiteNumber() + "] of system [" + system.getSystemId() + "] - " + rre.getMessage());
}
}
enrichedSites.add(new EnrichedSite(site, countyInfo));

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

@@ -264,9 +264,11 @@ public class SystemTalkgroupSelectionEditor extends GridPane
if(talkgroups != null && !talkgroups.isEmpty())
{
Collections.sort(talkgroups, Comparator.comparingInt(Talkgroup::getDecimalValue));
//The talkgroup list is shared by the caching service and is read-only, so sort a copy
List<Talkgroup> sorted = new ArrayList<>(talkgroups);
sorted.sort(Comparator.comparingInt(Talkgroup::getDecimalValue));
for(Talkgroup talkgroup: talkgroups)
for(Talkgroup talkgroup: sorted)
{
mTalkgroupList.add(new AliasedTalkgroup(talkgroup, getAlias(talkgroup)));
}

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

@@ -119,6 +119,22 @@ public class RdioScannerEditor extends AbstractBroadcastEditor<RdioScannerConfig
return BroadcastServerType.RDIOSCANNER_CALL;
}
/**
* Label for the server URL field. Subclasses can override this for another product that uses the same API.
*/
protected String getHostLabel()
{
return "RdioScanner URL";
}
/**
* Label for the credential field.
*/
protected String getApiKeyLabel()
{
return "API Key";
}
protected GridPane getEditorPane()
{
if(mEditorPane == null)
@@ -157,7 +173,7 @@ public class RdioScannerEditor extends AbstractBroadcastEditor<RdioScannerConfig
GridPane.setConstraints(getNameTextField(), 1, row);
mEditorPane.getChildren().add(getNameTextField());
Label apiKeyLabel = new Label("API Key");
Label apiKeyLabel = new Label(getApiKeyLabel());
apiKeyLabel.setLabelFor(getApiKeyTextField());
GridPane.setHalignment(apiKeyLabel, HPos.RIGHT);
GridPane.setConstraints(apiKeyLabel, 0, ++row);
@@ -175,7 +191,7 @@ public class RdioScannerEditor extends AbstractBroadcastEditor<RdioScannerConfig
GridPane.setConstraints(getSystemIdTextField(), 1, row);
mEditorPane.getChildren().add(getSystemIdTextField());
Label hostLabel = new Label("RdioScanner URL");
Label hostLabel = new Label(getHostLabel());
hostLabel.setLabelFor(getHostTextField());
GridPane.setHalignment(hostLabel, HPos.RIGHT);
GridPane.setConstraints(hostLabel, 0, ++row);

View File

@@ -41,6 +41,8 @@ public class StreamEditorFactory
return new BroadcastifyStreamEditor(playlistManager);
case RDIOSCANNER_CALL:
return new RdioScannerEditor(playlistManager);
case THINLINE_RADIO:
return new ThinlineRadioEditor(playlistManager);
case OPENMHZ:
return new OpenMHzEditor(playlistManager);
case BROADCASTIFY_CALL:

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,35 +17,36 @@
* ****************************************************************************
*/
/*
* WaypointRenderer.java
*
* Created on March 30, 2006, 5:56 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package io.github.dsheirer.gui.playlist.streaming;
package org.jdesktop.swingx.mapviewer;
import org.jdesktop.swingx.JXMapViewer;
import java.awt.Graphics2D;
import io.github.dsheirer.audio.broadcast.BroadcastServerType;
import io.github.dsheirer.playlist.PlaylistManager;
/**
* A interface that draws waypoints. Implementations of WaypointRenderer can
* be set on a WayPointPainter to draw waypoints on a JXMapViewer
* @param <W> the waypoint type
* @author joshua.marinacci@sun.com
* Thinline Radio call upload configuration editor.
*
* The form and upload path match the Rdio Scanner editor.
*/
public interface WaypointRenderer<W>
public class ThinlineRadioEditor extends RdioScannerEditor
{
/**
* paint the specified waypoint on the specified map and graphics context
* @param g the graphics2D object
* @param map the map
* @param waypoint the waypoint
* Constructs an instance
* @param playlistManager for accessing the broadcast model
*/
public void paintWaypoint(Graphics2D g, JXMapViewer map, W waypoint);
public ThinlineRadioEditor(PlaylistManager playlistManager)
{
super(playlistManager);
}
@Override
public BroadcastServerType getBroadcastServerType()
{
return BroadcastServerType.THINLINE_RADIO;
}
@Override
protected String getHostLabel()
{
return "Thinline Radio URL";
}
}

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

@@ -0,0 +1,207 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.gui.spectrum.layer.ChannelTuningLayer;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.sample.Listener;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
/**
* Spectral display for a single decoding channel's sample stream, centered on the channel frequency. The channel
* tuning layer marks the channel passband and the decoder's estimated carrier position (PLL).
*
* Construct on the JavaFX application thread. The other methods can be called from any thread. Feed the channel's
* complex sample buffers to getSampleListener() and turn processing on with setActive(true) while the display is
* showing.
*/
public class ChannelSpectralDisplay extends DftSpectralDisplay
{
public static final String SETTINGS_PREFIX = "channel.spectral.display";
public static final double DEFAULT_SAMPLE_SIZE = 18.0;
public static final double MINIMUM_SAMPLE_SIZE = 8.0;
public static final double MAXIMUM_SAMPLE_SIZE = 36.0;
private static final String NOISE_FLOOR = "noise.floor";
private static final String MESSAGE_NO_CHANNEL = "Select a decoding channel to view its spectrum";
private final ChannelTuningLayer mTuningLayer;
private final EdgeSlider mNoiseFloorSlider;
private final Object mLock = new Object();
private boolean mActive;
private boolean mHasChannel;
/**
* Constructs an instance.
*/
public ChannelSpectralDisplay()
{
this(new ChannelTuningLayer());
}
private ChannelSpectralDisplay(ChannelTuningLayer tuningLayer)
{
super(SETTINGS_PREFIX, true, tuningLayer);
mTuningLayer = tuningLayer;
SpectralDisplayModel model = getSpectralDisplay().getModel();
getSpectralDisplay().messageProperty().set(MESSAGE_NO_CHANNEL);
//Noise floor slider along the right edge, below the configuration panel tab
mNoiseFloorSlider = new EdgeSlider("Floor", "Noise floor: moves the bottom of the spectrum's dB range. " +
"Higher settings show a deeper range and move the noise floor up the display.",
MINIMUM_SAMPLE_SIZE, MAXIMUM_SAMPLE_SIZE, 1, this::formatPlotBottom);
double sampleSize = SystemProperties.getInstance().get(key(NOISE_FLOOR), (int)DEFAULT_SAMPLE_SIZE);
sampleSize = Math.max(MINIMUM_SAMPLE_SIZE, Math.min(MAXIMUM_SAMPLE_SIZE, sampleSize));
model.sampleSizeProperty().set(sampleSize);
mNoiseFloorSlider.valueProperty().set(sampleSize);
mNoiseFloorSlider.valueProperty().addListener((ob, ov, nv) -> {
int value = (int)Math.round(nv.doubleValue());
model.sampleSizeProperty().set(value);
save(NOISE_FLOOR, value);
});
//The value shows the plot bottom in dBFS, which also depends on the DFT size and window
model.binCountProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
model.noiseBandwidthProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
mNoiseFloorSlider.refreshLabel();
StackPane.setAlignment(mNoiseFloorSlider, Pos.CENTER_RIGHT);
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
getChildren().add(mNoiseFloorSlider);
installConfigPanel();
}
/**
* Listener for the channel's complex sample buffers.
*/
public Listener<INativeBuffer> getSampleListener()
{
return getDftProcessor();
}
/**
* Shows a channel.
* @param frequency of the channel center in Hertz
* @param sampleRate of the channel sample stream in Hertz
* @param bandwidth of the channel in Hertz, or zero to hide the passband markers
*/
public void setChannel(long frequency, int sampleRate, int bandwidth)
{
synchronized(mLock)
{
mHasChannel = sampleRate > 0;
updateProcessing();
}
getSpectralDisplay().clear();
runOnFxThread(() -> {
SpectralDisplayModel model = getSpectralDisplay().getModel();
model.resetZoom();
model.centerFrequencyProperty().set(frequency);
model.sampleRateProperty().set(sampleRate);
mTuningLayer.channelBandwidthProperty().set(bandwidth);
mTuningLayer.carrierOffsetValidProperty().set(false);
mTuningLayer.carrierOffsetProperty().set(0);
getSpectralDisplay().messageProperty().set(sampleRate > 0 ? null : MESSAGE_NO_CHANNEL);
});
}
/**
* Stops showing the channel.
*/
public void clearChannel()
{
setChannel(0, 0, 0);
}
/**
* Sets the estimated carrier offset from the channel center, from the decoder's frequency correction.
* @param offset in Hertz: where the signal is relative to the channel center
*/
public void setCarrierOffset(long offset)
{
runOnFxThread(() -> {
mTuningLayer.carrierOffsetProperty().set(offset);
mTuningLayer.carrierOffsetValidProperty().set(true);
});
}
/**
* Noise floor slider along the right edge of the display.
*/
public EdgeSlider getNoiseFloorSlider()
{
return mNoiseFloorSlider;
}
/**
* Formats the bottom of the spectrum plot in dBFS for the noise floor slider value.
*/
private String formatPlotBottom(double sampleSize)
{
double range = (20.0 * Math.log10(Math.pow(2.0, sampleSize - 1.0))) +
getSpectralDisplay().getModel().getProcessingGain();
return Math.round(-range) + " dB";
}
/**
* Turns DFT processing on while the display is showing, and off when it's hidden.
*/
public void setActive(boolean active)
{
synchronized(mLock)
{
mActive = active;
updateProcessing();
}
}
@Override
protected void processingEnabledChanged()
{
synchronized(mLock)
{
updateProcessing();
}
}
/**
* Starts or stops the DFT processor. Hold the lock when calling.
*/
private void updateProcessing()
{
if(mActive && mHasChannel && isProcessingEnabled())
{
startDft();
}
else
{
stopDft();
}
}
@Override
public void dispose()
{
setActive(false);
super.dispose();
}
}

View File

@@ -0,0 +1,49 @@
/*
* *****************************************************************************
* 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 javafx.beans.property.BooleanProperty;
import javafx.scene.Node;
import org.controlsfx.control.ToggleSwitch;
/**
* Labeled control that a display layer adds to its section of the configuration panel.
*
* @param label shown to the left of the control
* @param control to change the setting
*/
public record ConfigurationRow(String label, Node control)
{
private static final double SWITCH_WIDTH = 40;
/**
* Creates a row with an on/off switch bound to the property.
*/
public static ConfigurationRow toggle(String label, BooleanProperty property)
{
ToggleSwitch toggleSwitch = new ToggleSwitch();
toggleSwitch.selectedProperty().bindBidirectional(property);
//The switch skin reserves space for its text even when there is none, so size it to the thumb track
toggleSwitch.setMinWidth(SWITCH_WIDTH);
toggleSwitch.setPrefWidth(SWITCH_WIDTH);
toggleSwitch.setMaxWidth(SWITCH_WIDTH);
return new ConfigurationRow(label, toggleSwitch);
}
}

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.spectrum;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Text and placement of the cursor readout: the frequency under the mouse, and the level in the spectrum, in a box
* beside the mouse. The frequency layer draws the readout. A layer that replaces the readout with a larger callout
* (see {@link SpectralDisplayLayer#replacesCursorReadout}) uses the same text and placement, so the readout appears to
* grow into the callout.
*/
public final class CursorReadout
{
/**
* Horizontal distance between the mouse and the box
*/
public static final double GAP_X = 8;
/**
* Vertical distance between the box and the mouse below it
*/
public static final double GAP_Y = 4;
private static final DecimalFormat FREQUENCY_FORMAT = new DecimalFormat("0.00000");
private static final DecimalFormat LEVEL_FORMAT = new DecimalFormat("0.0");
private CursorReadout()
{
}
/**
* Readout lines: the frequency under the mouse, and the level when the mouse is over the spectrum plot
*/
public static List<String> lines(DisplayCursor cursor, RenderArea area, SpectralDisplayModel model)
{
List<String> lines = new ArrayList<>(2);
lines.add(FREQUENCY_FORMAT.format(cursor.frequency() / 1E6) + " MHz");
if(cursor.section() == DisplaySection.SPECTRUM && cursor.y() <= area.plotHeight() && area.plotHeight() > 0)
{
double decibels = -(cursor.y() / area.plotHeight()) * model.getDynamicRange();
lines.add(LEVEL_FORMAT.format(decibels) + " dBFS");
}
return lines;
}
/**
* Left edge of a box beside the mouse: to the right of the mouse, or to the left when it doesn't fit
*/
public static double x(DisplayCursor cursor, double width, RenderArea area)
{
double x = cursor.x() + GAP_X;
if(x + width > area.width())
{
x = cursor.x() - GAP_X - width;
}
return x;
}
/**
* Top edge of a box above the mouse, kept inside the plot
*/
public static double y(DisplayCursor cursor, double height, RenderArea area)
{
return Math.max(0, Math.min(area.plotHeight() - height, cursor.y() - height - GAP_Y));
}
}

View File

@@ -0,0 +1,423 @@
/*
* *****************************************************************************
* 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.dsp.window.WindowType;
import io.github.dsheirer.gui.spectrum.layer.DecibelLayer;
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.layout.StackPane;
/**
* Base class for a spectral display fed by DFT processing of a complex sample stream: the spectral display with the
* decibel and frequency layers plus any layers the subclass adds, the DFT processor and dBFS converter, the
* collapsible configuration panel, and saving the display settings under a property key prefix.
*
* The color theme is shared by all spectral displays in the application.
*
* Construct on the JavaFX application thread. Subclasses call installConfigPanel() at the end of their constructor.
*/
public abstract class DftSpectralDisplay extends StackPane
{
public static final int[] FRAME_RATES = {10, 14, 16, 18, 20, 25, 30, 40, 50, 60};
public static final String PROPERTY_THEME = "spectral.display.theme";
private static final String DFT_SIZE = "dft.size";
private static final String WINDOW_TYPE = "window.type";
private static final String FRAME_RATE = "frame.rate";
private static final String AVERAGING = "averaging";
private static final String PEAK_HOLD = "peak.hold";
private static final String SPECTRUM_ENABLED = "spectrum.enabled";
private static final String WATERFALL_ENABLED = "waterfall.enabled";
private static final String DIVIDER_POSITION = "divider.position";
private static final String DECIBEL_SCALE = "decibel.scale";
private static final String CONFIG_PINNED = "config.pinned";
private static ObjectProperty<SpectralDisplayTheme> sSharedTheme;
private final SpectralDisplay mSpectralDisplay;
private final DecibelLayer mDecibelLayer = new DecibelLayer();
private final ComplexDftProcessor mDftProcessor = new ComplexDftProcessor();
private final FullScaleDecibelConverter mDecibelConverter = new FullScaleDecibelConverter();
private final String mSettingsPrefix;
private final boolean mSaveSettings;
private final ObjectProperty<DFTSize> mDftSize = new SimpleObjectProperty<>(DFTSize.FFT04096);
private final ObjectProperty<WindowType> mWindowType = new SimpleObjectProperty<>(WindowType.BLACKMAN_HARRIS_7);
private final IntegerProperty mFrameRate = new SimpleIntegerProperty(20);
private SpectralDisplayConfigPanel mConfigPanel;
private volatile boolean mProcessingEnabled;
private volatile boolean mDftRunning;
/**
* Constructs an instance.
* @param settingsPrefix for the saved setting keys, for example "spectral.display"
* @param saveSettings true to save setting changes, false to load the saved settings but not change them
* @param layers to draw after the decibel scale and frequency layers
*/
protected DftSpectralDisplay(String settingsPrefix, boolean saveSettings, SpectralDisplayLayer... layers)
{
mSettingsPrefix = settingsPrefix;
mSaveSettings = saveSettings;
SpectralDisplayLayer[] all = new SpectralDisplayLayer[layers.length + 2];
all[0] = mDecibelLayer;
all[1] = new FrequencyLayer();
System.arraycopy(layers, 0, all, 2, layers.length);
mSpectralDisplay = new SpectralDisplay(all);
mDftProcessor.setUnityGainWindow(true);
mDftProcessor.addConverter(mDecibelConverter);
mDecibelConverter.addListener(mSpectralDisplay::receive);
//The processor starts its timer on construction - leave it stopped until there is a sample source
mDftProcessor.stop();
loadSettings();
mDftSize.addListener((ob, ov, nv) -> {
mDftProcessor.setDFTSize(nv);
mSpectralDisplay.getModel().resetZoom();
save(DFT_SIZE, nv.name());
});
mWindowType.addListener((ob, ov, nv) -> {
mDftProcessor.setWindowType(nv);
mSpectralDisplay.getModel().noiseBandwidthProperty().set(ComplexDftProcessor.getNoiseBandwidth(nv));
save(WINDOW_TYPE, nv.name());
});
mFrameRate.addListener((ob, ov, nv) -> {
mDftProcessor.setFrameRateNoSave(nv.intValue());
if(!mDftRunning)
{
//Changing the frame rate restarts the timer - keep it stopped while not processing
mDftProcessor.stop();
}
save(FRAME_RATE, nv.intValue());
});
mSpectralDisplay.averagingProperty().addListener((ob, ov, nv) -> save(AVERAGING, nv.intValue()));
mSpectralDisplay.peakHoldProperty().addListener((ob, ov, nv) -> save(PEAK_HOLD, nv));
mSpectralDisplay.dividerPositionProperty().addListener((ob, ov, nv) ->
save(DIVIDER_POSITION, String.valueOf(nv.doubleValue())));
mDecibelLayer.visibleProperty().addListener((ob, ov, nv) -> save(DECIBEL_SCALE, nv));
mSpectralDisplay.spectrumEnabledProperty().addListener((ob, ov, nv) -> {
save(SPECTRUM_ENABLED, nv);
updateProcessingEnabled();
});
mSpectralDisplay.waterfallEnabledProperty().addListener((ob, ov, nv) -> {
save(WATERFALL_ENABLED, nv);
updateProcessingEnabled();
});
mProcessingEnabled = mSpectralDisplay.spectrumEnabledProperty().get() ||
mSpectralDisplay.waterfallEnabledProperty().get();
mSpectralDisplay.themeProperty().bindBidirectional(getSharedTheme());
getChildren().add(mSpectralDisplay);
setMinSize(0, 0);
}
/**
* Creates the configuration panel. Subclasses call this at the end of their constructor, after their own
* settings are loaded, since the panel reads the subclass's controls.
*/
protected void installConfigPanel()
{
mConfigPanel = new SpectralDisplayConfigPanel(this);
mConfigPanel.pinnedProperty().set(SystemProperties.getInstance().get(key(CONFIG_PINNED), false));
mConfigPanel.pinnedProperty().addListener((ob, ov, nv) -> save(CONFIG_PINNED, nv));
StackPane.setAlignment(mConfigPanel, Pos.TOP_RIGHT);
StackPane.setMargin(mConfigPanel, new Insets(6));
getChildren().add(mConfigPanel);
}
/**
* Color theme shared by all spectral displays, loaded from and saved to the theme setting. JavaFX thread only.
*/
public static ObjectProperty<SpectralDisplayTheme> getSharedTheme()
{
if(sSharedTheme == null)
{
SpectralDisplayTheme theme = parse(SpectralDisplayTheme.class, SystemProperties.getInstance()
.get(PROPERTY_THEME, SpectralDisplayTheme.getDefault().name()), SpectralDisplayTheme.getDefault());
sSharedTheme = new SimpleObjectProperty<>(theme);
sSharedTheme.addListener((ob, ov, nv) -> {
if(nv != null)
{
SystemProperties.getInstance().set(PROPERTY_THEME, nv.name());
}
});
}
return sSharedTheme;
}
private void loadSettings()
{
SystemProperties properties = SystemProperties.getInstance();
DFTSize dftSize = parse(DFTSize.class, properties.get(key(DFT_SIZE), DFTSize.FFT04096.name()),
DFTSize.FFT04096);
mDftSize.set(dftSize);
mDftProcessor.setDFTSize(dftSize);
WindowType windowType = parse(WindowType.class, properties.get(key(WINDOW_TYPE),
WindowType.BLACKMAN_HARRIS_7.name()), WindowType.BLACKMAN_HARRIS_7);
if(!isWindowSupported(windowType))
{
windowType = WindowType.BLACKMAN_HARRIS_7;
}
mWindowType.set(windowType);
mDftProcessor.setWindowType(windowType);
mSpectralDisplay.getModel().noiseBandwidthProperty().set(ComplexDftProcessor.getNoiseBandwidth(windowType));
int frameRate = Math.max(1, Math.min(100, properties.get(key(FRAME_RATE), mDftProcessor.getFrameRate())));
mFrameRate.set(frameRate);
mDftProcessor.setFrameRateNoSave(frameRate);
mDftProcessor.stop();
int averaging = properties.get(key(AVERAGING), SpectralDisplay.AVERAGING_DEFAULT);
mSpectralDisplay.averagingProperty().set(Math.max(SpectralDisplay.AVERAGING_MINIMUM,
Math.min(SpectralDisplay.AVERAGING_MAXIMUM, averaging)));
mSpectralDisplay.peakHoldProperty().set(properties.get(key(PEAK_HOLD), false));
mDecibelLayer.visibleProperty().set(properties.get(key(DECIBEL_SCALE), true));
try
{
double divider = Double.parseDouble(properties.get(key(DIVIDER_POSITION), "0.5"));
mSpectralDisplay.dividerPositionProperty().set(Math.max(0.05, Math.min(0.95, divider)));
}
catch(NumberFormatException nfe)
{
mSpectralDisplay.dividerPositionProperty().set(0.5);
}
mSpectralDisplay.spectrumEnabledProperty().set(properties.get(key(SPECTRUM_ENABLED), true));
mSpectralDisplay.waterfallEnabledProperty().set(properties.get(key(WATERFALL_ENABLED), true));
}
/**
* Full property key for the setting name.
*/
protected String key(String name)
{
return mSettingsPrefix + "." + name;
}
/**
* Indicates if the window type can be used for the spectral display. Kaiser windows need extra parameters.
*/
public static boolean isWindowSupported(WindowType windowType)
{
return windowType != null && windowType != WindowType.KAISER;
}
/**
* Parses an enum setting value, or returns the default for a missing or unrecognized value.
*/
protected static <E extends Enum<E>> E parse(Class<E> type, String value, E defaultValue)
{
if(value != null)
{
try
{
return Enum.valueOf(type, value);
}
catch(IllegalArgumentException iae)
{
//Fall through to the default
}
}
return defaultValue;
}
protected void save(String name, String value)
{
if(mSaveSettings)
{
SystemProperties.getInstance().set(key(name), value);
}
}
protected void save(String name, int value)
{
if(mSaveSettings)
{
SystemProperties.getInstance().set(key(name), value);
}
}
protected void save(String name, boolean value)
{
if(mSaveSettings)
{
SystemProperties.getInstance().set(key(name), value);
}
}
/**
* The spectral display.
*/
public SpectralDisplay getSpectralDisplay()
{
return mSpectralDisplay;
}
/**
* Collapsible configuration panel, or null before installConfigPanel() is called.
*/
public SpectralDisplayConfigPanel getConfigPanel()
{
return mConfigPanel;
}
/**
* DFT processor. Register it with the sample source to feed the display.
*/
protected ComplexDftProcessor getDftProcessor()
{
return mDftProcessor;
}
/**
* DFT size.
*/
public ObjectProperty<DFTSize> dftSizeProperty()
{
return mDftSize;
}
/**
* DFT window type.
*/
public ObjectProperty<WindowType> windowTypeProperty()
{
return mWindowType;
}
/**
* DFT frames per second.
*/
public IntegerProperty frameRateProperty()
{
return mFrameRate;
}
/**
* Indicates if the spectrum or the waterfall is turned on. Safe to read from any thread.
*/
protected boolean isProcessingEnabled()
{
return mProcessingEnabled;
}
private void updateProcessingEnabled()
{
mProcessingEnabled = mSpectralDisplay.spectrumEnabledProperty().get() ||
mSpectralDisplay.waterfallEnabledProperty().get();
processingEnabledChanged();
}
/**
* Called on the JavaFX thread when the spectrum and waterfall are both turned off, or one is turned back on.
* Subclasses start or stop their sample source with isProcessingEnabled().
*/
protected abstract void processingEnabledChanged();
/**
* Starts the DFT processor timer.
*/
protected void startDft()
{
if(!mDftRunning)
{
mDftRunning = true;
mDftProcessor.clearBuffer();
mDftProcessor.start();
}
}
/**
* Stops the DFT processor timer and clears the display.
*/
protected void stopDft()
{
if(mDftRunning)
{
mDftRunning = false;
mDftProcessor.stop();
mDftProcessor.clearBuffer();
mSpectralDisplay.clear();
}
}
/**
* Indicates if the DFT processor timer is running.
*/
protected boolean isDftRunning()
{
return mDftRunning;
}
/**
* Runs the runnable on the JavaFX application thread, ignoring the request after the JavaFX toolkit has exited
* during application shutdown.
*/
protected static void runOnFxThread(Runnable runnable)
{
try
{
Platform.runLater(runnable);
}
catch(IllegalStateException ise)
{
//JavaFX toolkit has exited
}
}
/**
* Releases the DFT processing and the display. Subclasses disconnect their sample source first.
*/
public void dispose()
{
stopDft();
mDftProcessor.dispose();
mDecibelConverter.dispose();
runOnFxThread(() -> {
mSpectralDisplay.themeProperty().unbindBidirectional(getSharedTheme());
if(mConfigPanel != null)
{
mConfigPanel.dispose();
}
mSpectralDisplay.dispose();
});
}
}

View File

@@ -0,0 +1,32 @@
/*
* *****************************************************************************
* 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;
/**
* Mouse cursor position over the spectral display.
*
* @param section under the mouse
* @param x position in pixels within the section
* @param y position in pixels within the section
* @param frequency under the mouse in Hertz
*/
public record DisplayCursor(DisplaySection section, double x, double y, long frequency)
{
}

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