mirror of
https://github.com/DSheirer/sdrtrunk.git
synced 2026-11-21 13:05:43 -05:00
Compare commits
1 Commits
2742-datab
...
signal-hou
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66c5727145 |
5
.github/workflows/nightly.yml
vendored
5
.github/workflows/nightly.yml
vendored
@@ -14,9 +14,6 @@ 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
|
||||
@@ -37,7 +34,7 @@ jobs:
|
||||
|
||||
- name: Create Build Info file
|
||||
run: |
|
||||
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
|
||||
echo -e "ref: $GITHUB_REF \ncommit: $GITHUB_SHA\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
|
||||
|
||||
26
.github/workflows/release.yml
vendored
26
.github/workflows/release.yml
vendored
@@ -1,6 +1,6 @@
|
||||
# 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).
|
||||
# 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.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
@@ -22,6 +22,15 @@ 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
|
||||
@@ -45,17 +54,6 @@ 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
|
||||
|
||||
|
||||
48
README.md
48
README.md
@@ -1,29 +1,35 @@
|
||||

|
||||

|
||||
[](https://github.com/DSheirer/sdrtrunk/releases/latest)
|
||||
[](https://github.com/DSheirer/sdrtrunk/releases)
|
||||
[](LICENSE)
|
||||
[](https://discord.gg/HJQaKYE)
|
||||
[](https://groups.google.com/g/sdrtrunk)
|
||||
|
||||
# MacOS Tahoe 26.1 Users - Attention:
|
||||
Changes to USB support in Tahoe version 26.x cause sdrtrunk to fail to launch. Do the following to install the latest libusb and create a symbolic link and then use the nightly build which includes an updated usb4java native library for Tahoe with ARM processor. There may still be issue(s) with MacOS accessing your USB SDR tuners.
|
||||
|
||||
```
|
||||
brew install libusb --HEAD
|
||||
cd /opt
|
||||
sudo mkdir local
|
||||
cd local
|
||||
sudo mkdir lib
|
||||
```
|
||||
Next, find where brew installed the libusb library, for example: ```/opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib``` Note: the folder "HEAD-9ceaa52" is the version stamp for HEAD when you installed from it.
|
||||
|
||||
Finally, create a symbolic link from the installed library to the place where usb4java is expecting to find libusb (/opt/local/lib/libusb-1.0.0.dylib)
|
||||
|
||||
```
|
||||
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
|
||||
```
|
||||
|
||||
# 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)
|
||||
* [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)
|
||||
|
||||

|
||||
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
|
||||

|
||||
**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.
|
||||
@@ -48,19 +54,17 @@ 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.
|
||||
|
||||
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`):
|
||||
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`:
|
||||
```
|
||||
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 version the build derives from git matches the tag and fails if it does not.
|
||||
* Verifies that the tag matches `projectVersion` in `gradle.properties` 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
|
||||
|
||||
100
build.gradle
100
build.gradle
@@ -52,44 +52,8 @@ plugins {
|
||||
id 'org.beryx.runtime' version '2.0.1'
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
}
|
||||
//Version is defined in gradle.properties so that we can CLI override it for nightly builds.
|
||||
version = project.findProperty('projectVersion')
|
||||
|
||||
//Java 27 is required for this version of the Project Panama preview/incubator feature
|
||||
java {
|
||||
@@ -138,34 +102,38 @@ dependencies {
|
||||
|
||||
//Jitpack imports
|
||||
implementation 'com.github.dnault:libresample4j:master'
|
||||
implementation 'com.github.DSheirer.jmbe:api:v2.1.1'
|
||||
implementation 'com.github.nwaldispuehl:java-lame:v3.98.4'
|
||||
|
||||
//mavenCentral/jcenter imports
|
||||
implementation 'ch.qos.logback:logback-classic:1.6.6'
|
||||
implementation 'ch.qos.logback:logback-core:1.6.6'
|
||||
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.23.0'
|
||||
implementation 'com.formdev:flatlaf:3.8'
|
||||
implementation 'com.formdev:flatlaf-intellij-themes:3.8' //Not imported - Theme.java loads these themes by class name
|
||||
implementation 'com.github.jiconfont:jiconfont-font_awesome:4.7.0.1'
|
||||
implementation 'com.github.jiconfont:jiconfont-javafx:1.0.0'
|
||||
implementation 'com.github.jiconfont:jiconfont-swing:1.0.1'
|
||||
implementation('com.github.wendykierp:JTransforms:3.2') {
|
||||
exclude group: 'junit' //JLargeArrays 1.7 declares junit as a compile dependency
|
||||
}
|
||||
implementation 'com.google.code.gson:gson:2.15.0'
|
||||
implementation 'com.google.guava:guava:33.8.0-jre'
|
||||
implementation 'com.h2database:h2:2.5.252' //Built-in call database
|
||||
implementation 'com.zaxxer:HikariCP:7.1.0' //Database connection pool
|
||||
implementation 'com.jidesoft:jide-oss:3.6.18'
|
||||
implementation 'com.miglayout:miglayout-swing:11.5.2'
|
||||
implementation 'com.mpatric:mp3agic:0.9.1'
|
||||
implementation 'commons-io:commons-io:2.22.0'
|
||||
implementation 'io.github.dsheirer:jairspy:1.0.12.1' //Airspy tuners - GitHub release, see settings.gradle
|
||||
implementation 'io.github.dsheirer:jairspyhf:1.8.1.1' //Airspy HF+ tuners - GitHub release, see settings.gradle
|
||||
implementation 'io.github.dsheirer:jbladerf:2.6.0.1' //bladeRF tuners - GitHub release, see settings.gradle
|
||||
implementation 'io.github.dsheirer:jhackrf:2026.01.3.1' //HackRF tuners - GitHub release, see settings.gradle
|
||||
implementation 'io.github.dsheirer:jmbe-api:3.0.0' //JMBE audio codec interfaces - GitHub release, see settings.gradle
|
||||
implementation 'io.github.dsheirer:jlibusb:1.0.30.1' //libusb and USB hotplug for the tuner libraries - GitHub release; not pulled in transitively
|
||||
implementation 'io.github.dsheirer:jhydrasdr:1.1.4.1' //HydraSDR tuners - GitHub release, see settings.gradle
|
||||
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:radio-reference-api:18.1.0' //RadioReference SOAP API - 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 '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'
|
||||
@@ -173,8 +141,6 @@ dependencies {
|
||||
implementation 'org.apache.mina:mina-core:2.2.10'
|
||||
implementation 'org.apache.mina:mina-http:2.2.10'
|
||||
implementation 'org.controlsfx:controlsfx:11.2.6'
|
||||
implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.11' //Optional MariaDB call database
|
||||
implementation 'org.postgresql:postgresql:42.7.14' //Optional PostgreSQL call database
|
||||
implementation 'org.rauschig:jarchivelib:1.2.0'
|
||||
implementation 'org.slf4j:slf4j-api:2.0.20'
|
||||
}
|
||||
@@ -194,6 +160,7 @@ tasks.withType(JavaCompile).configureEach {
|
||||
*/
|
||||
def jvmArgsWindows =
|
||||
['--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED', //Needed for controls-fx.jar
|
||||
'--add-exports=java.desktop/com.sun.java.swing.plaf.windows=ALL-UNNAMED', //windows users for JIDE
|
||||
'--add-modules=jdk.incubator.vector', //Project Panama vector API is still in incubator
|
||||
'--enable-preview', //Project Panama Vector API is still in incubator
|
||||
'--enable-native-access=ALL-UNNAMED', //Suppress unsafe warnings for FFM API Foreign Memory calls
|
||||
@@ -211,14 +178,6 @@ def jvmArgsLinux =
|
||||
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
|
||||
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
|
||||
|
||||
/**
|
||||
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
|
||||
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
|
||||
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
|
||||
*/
|
||||
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
|
||||
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
|
||||
|
||||
application {
|
||||
mainClass = "io.github.dsheirer.gui.SDRTrunk"
|
||||
|
||||
@@ -230,16 +189,6 @@ application {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the splash screen to the run task through an argument provider. Calling jvmArgs here would replace the
|
||||
* applicationDefaultJvmArgs convention (--add-modules=jdk.incubator.vector, --enable-preview, etc.) instead of adding
|
||||
* to it.
|
||||
*/
|
||||
tasks.named('run') {
|
||||
def splashImage = file(splashResourceDir + '/' + splashImages[0]).absolutePath
|
||||
jvmArgumentProviders.add({ ["-splash:${splashImage}".toString()] } as CommandLineArgumentProvider)
|
||||
}
|
||||
|
||||
test {
|
||||
if(os.isWindows()) {
|
||||
jvmArgs = jvmArgsWindows
|
||||
@@ -254,7 +203,6 @@ 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']}",
|
||||
@@ -304,8 +252,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
|
||||
* @return configured task.
|
||||
*/
|
||||
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
|
||||
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
|
||||
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
|
||||
//Use the correct set of JVM arguments
|
||||
rt.extension.launcherData.get().jvmArgs = jvmArgs
|
||||
|
||||
//Additional modules to include with auto-detected modules.
|
||||
//jdk.charsets - NXDN BIG5 encoding support
|
||||
@@ -313,11 +261,9 @@ def configure(RuntimeZipTask rt, List<String> jvmArgs) {
|
||||
//jdk.incubator.vector - needed for Project Panama foreign function and vector apis
|
||||
//jdk.accessibility is used with assistive technologies like screen readers
|
||||
//java.management for JVM resource monitoring
|
||||
//java.sql, java.naming, java.security.jgss, jdk.net - call database JDBC drivers and connection pool
|
||||
//java.base, java.desktop, java.logging, java.net.http, java.prefs, javafx.controls - required by sdrtrunk (jdeps)
|
||||
//java.base, java.logging, java.net.http, java.prefs, javafx.controls, javafx.swing - required by sdrtrunk (jdeps)
|
||||
rt.extension.addModules('jdk.charsets', 'jdk.crypto.ec', 'jdk.incubator.vector', 'jdk.accessibility', 'java.management',
|
||||
'java.base', 'java.desktop', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'java.sql',
|
||||
'java.naming', 'java.security.jgss', 'jdk.net')
|
||||
'java.base', 'java.logging', 'java.net.http', 'java.prefs', 'javafx.controls', 'javafx.swing')
|
||||
|
||||
//Use only the modules listed above. The runtime plugin's module auto-detection uses a bundled ASM library that
|
||||
//can't read Java 27 class files and logs a 'Failed to scan' error for each sdrtrunk class. The jdeps module check
|
||||
@@ -406,22 +352,6 @@ tasks.named('runtime') {rt ->
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the startup splash screen images into the lib folder of each runtime target image, where the launch scripts
|
||||
* load them from (-splash:{{BIN_DIR}}/../lib/...).
|
||||
*/
|
||||
tasks.named('runtime') {rt ->
|
||||
rt.doLast {
|
||||
rt.targetPlatforms.get().keySet().each { target ->
|
||||
def lib = new File(rt.imageDir.asFile, "${project.name}-${target}/lib")
|
||||
splashImages.each { name ->
|
||||
java.nio.file.Files.copy(file(splashResourceDir + '/' + name).toPath(), new File(lib, name).toPath(),
|
||||
java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that each runtime target image contains every module that the sdrtrunk jar requires, as reported by jdeps.
|
||||
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse
|
||||
|
||||
@@ -17,16 +17,15 @@
|
||||
# *****************************************************************************
|
||||
#
|
||||
|
||||
# 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>.
|
||||
# Version naming conventions:
|
||||
# Alpha: maj.min.patch-alpha-build
|
||||
# Beta: maj.min.patch-beta-build
|
||||
# Release: maj.min.patch
|
||||
#
|
||||
# Version tag naming conventions:
|
||||
# Alpha: vmaj.min.patch-alpha-build
|
||||
# Beta: vmaj.min.patch-beta-build
|
||||
# Release: vmaj.min.patch
|
||||
# Example: 0.6.0-beta-5
|
||||
#
|
||||
# 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
|
||||
# Note: this is so that the file names for the resultant release build products match the GitLab 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
|
||||
@@ -75,6 +75,15 @@ 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'
|
||||
@@ -82,23 +91,5 @@ dependencyResolutionManagement {
|
||||
metadataSources { artifact() }
|
||||
content { includeModule 'io.github.dsheirer', 'jbladerf' }
|
||||
}
|
||||
|
||||
//JMBE API is published as a GitHub release. It holds only the codec interfaces; users create the JMBE codec
|
||||
//library itself with the JMBE creator, which sdrtrunk downloads from the release matching the API major version
|
||||
ivy {
|
||||
url = 'https://github.com/DSheirer/jmbe/releases/download'
|
||||
patternLayout { artifact 'v[revision]/[artifact]-[revision].[ext]' }
|
||||
metadataSources { artifact() }
|
||||
content { includeModule 'io.github.dsheirer', 'jmbe-api' }
|
||||
}
|
||||
|
||||
//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' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package com.sun.java.swing.plaf.windows;
|
||||
|
||||
import javax.swing.LookAndFeel;
|
||||
import javax.swing.UIDefaults;
|
||||
|
||||
/**
|
||||
* No-op stub for the JDK's Windows look-and-feel.
|
||||
*
|
||||
* <p>JIDE 3.6.18's {@code LookAndFeelFactory} contains compile-time
|
||||
* {@code instanceof com.sun.java.swing.plaf.windows.WindowsLookAndFeel} checks throughout its
|
||||
* dispatch logic. On Linux and macOS JDK builds that class is genuinely absent from
|
||||
* {@code java.desktop}, so the JVM throws {@link NoClassDefFoundError} the first time JIDE's
|
||||
* dispatch code executes the {@code instanceof} bytecode. That happens during
|
||||
* {@link com.jidesoft.swing.JideSplitPane#updateUI()} on every LAF change.
|
||||
*
|
||||
* <p>This stub lives in the classpath so the class reference resolves on non-Windows JDKs.
|
||||
* On Windows JDK builds the real {@code WindowsLookAndFeel} is loaded from the
|
||||
* {@code java.desktop} module via the boot class loader and shadows this class.
|
||||
*
|
||||
* <p>The stub reports itself as not native and not supported - JIDE never instantiates this
|
||||
* class, it only uses it for {@code instanceof} comparisons against the active LAF. Since
|
||||
* sdrtrunk never installs this LAF, the {@code instanceof} check always returns false and
|
||||
* JIDE proceeds to its next branch.
|
||||
*/
|
||||
public class WindowsLookAndFeel extends LookAndFeel
|
||||
{
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return "Windows (stub)";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getID()
|
||||
{
|
||||
return "WindowsStub";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription()
|
||||
{
|
||||
return "Compatibility stub for JIDE's instanceof checks on non-Windows JDKs.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNativeLookAndFeel()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSupportedLookAndFeel()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UIDefaults getDefaults()
|
||||
{
|
||||
return new UIDefaults();
|
||||
}
|
||||
}
|
||||
@@ -530,34 +530,6 @@ public class AliasList
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for a talkgroup that is identified by its stored values instead of an identifier instance, for example a
|
||||
* talkgroup from the call database.
|
||||
* @param protocol of the talkgroup
|
||||
* @param value of the talkgroup
|
||||
* @param fullyQualifiedAddress (wacn.system.id) of a fully qualified talkgroup, or null
|
||||
* @return alias or null
|
||||
*/
|
||||
public Alias getTalkgroupAlias(Protocol protocol, int value, String fullyQualifiedAddress)
|
||||
{
|
||||
TalkgroupAliasList talkgroupAliasList = protocol != null ? mTalkgroupProtocolMap.get(protocol) : null;
|
||||
return talkgroupAliasList != null ? talkgroupAliasList.getAlias(value, fullyQualifiedAddress) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for a radio that is identified by its stored values instead of an identifier instance, for example a
|
||||
* radio from the call database.
|
||||
* @param protocol of the radio
|
||||
* @param value of the radio
|
||||
* @param fullyQualifiedAddress (wacn.system.id) of a fully qualified radio, or null
|
||||
* @return alias or null
|
||||
*/
|
||||
public Alias getRadioAlias(Protocol protocol, int value, String fullyQualifiedAddress)
|
||||
{
|
||||
RadioAliasList radioAliasList = protocol != null ? mRadioProtocolMap.get(protocol) : null;
|
||||
return radioAliasList != null ? radioAliasList.getAlias(value, fullyQualifiedAddress) : null;
|
||||
}
|
||||
|
||||
private static List<Alias> toList(Alias alias)
|
||||
{
|
||||
if(alias != null)
|
||||
@@ -698,26 +670,11 @@ public class AliasList
|
||||
//Attempt to do a fully qualified identifier match only
|
||||
if(identifier instanceof FullyQualifiedTalkgroupIdentifier fqti)
|
||||
{
|
||||
return getAlias(fqti.getValue(), fqti.getFullyQualifiedTalkgroupAddress());
|
||||
}
|
||||
|
||||
return getAlias(identifier.getValue(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for a talkgroup value, or for a fully qualified talkgroup address.
|
||||
* @param value of the talkgroup
|
||||
* @param fullyQualifiedAddress (wacn.system.id) for a fully qualified talkgroup, which is matched exclusively,
|
||||
* or null.
|
||||
*/
|
||||
public Alias getAlias(int value, String fullyQualifiedAddress)
|
||||
{
|
||||
if(fullyQualifiedAddress != null)
|
||||
{
|
||||
return mFullyQualifiedTalkgroupAliasMap.get(fullyQualifiedAddress);
|
||||
return mFullyQualifiedTalkgroupAliasMap.get(fqti.getFullyQualifiedTalkgroupAddress());
|
||||
}
|
||||
|
||||
//Attempt to match the talkgroup value
|
||||
int value = identifier.getValue();
|
||||
|
||||
Alias mapValue = mTalkgroupAliasMap.get(value);
|
||||
if (mapValue != null)
|
||||
@@ -833,26 +790,11 @@ public class AliasList
|
||||
//Match fully qualified identifier only.
|
||||
if(identifier instanceof FullyQualifiedRadioIdentifier fqri)
|
||||
{
|
||||
return getAlias(fqri.getValue(), fqri.getFullyQualifiedRadioAddress());
|
||||
}
|
||||
|
||||
return getAlias(identifier.getValue(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for a radio value, or for a fully qualified radio address.
|
||||
* @param value of the radio
|
||||
* @param fullyQualifiedAddress (wacn.system.id) for a fully qualified radio, which is matched exclusively, or
|
||||
* null.
|
||||
*/
|
||||
public Alias getAlias(int value, String fullyQualifiedAddress)
|
||||
{
|
||||
if(fullyQualifiedAddress != null)
|
||||
{
|
||||
return mFullyQualifiedRadioAliasMap.get(fullyQualifiedAddress);
|
||||
return mFullyQualifiedRadioAliasMap.get(fqri.getFullyQualifiedRadioAddress());
|
||||
}
|
||||
|
||||
//Attempt to match against the radio identifier
|
||||
int value = identifier.getValue();
|
||||
|
||||
Alias mapValue = mRadioAliasMap.get(value);
|
||||
if(mapValue != null)
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.alias;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
|
||||
import javafx.beans.Observable;
|
||||
import javafx.beans.property.BooleanProperty;
|
||||
import javafx.beans.property.IntegerProperty;
|
||||
import javafx.beans.property.LongProperty;
|
||||
import javafx.beans.property.SimpleBooleanProperty;
|
||||
import javafx.beans.property.SimpleIntegerProperty;
|
||||
import javafx.beans.property.SimpleLongProperty;
|
||||
import javafx.beans.property.SimpleStringProperty;
|
||||
import javafx.beans.property.StringProperty;
|
||||
import javafx.util.Callback;
|
||||
|
||||
/**
|
||||
* Persisted settings for an alias list. Alias lists are otherwise identified only by the list name that each alias
|
||||
* carries, so settings that belong to the list itself, like tracking a Radio Reference system, are stored here and
|
||||
* saved in the playlist.
|
||||
*
|
||||
* Radio Reference tracking uses two timestamps from the Radio Reference system's last updated value: the last updated
|
||||
* value seen by the most recent check, and the last updated value that the aliases were synchronized to. When the
|
||||
* seen value is newer than the synchronized value, the system changed on Radio Reference and the aliases haven't
|
||||
* been updated yet.
|
||||
*/
|
||||
public class AliasListConfiguration
|
||||
{
|
||||
public static final int NO_SYSTEM = 0;
|
||||
|
||||
private StringProperty mName = new SimpleStringProperty();
|
||||
private IntegerProperty mRadioReferenceSystemId = new SimpleIntegerProperty(NO_SYSTEM);
|
||||
private StringProperty mRadioReferenceSystemName = new SimpleStringProperty();
|
||||
private BooleanProperty mAutoUpdate = new SimpleBooleanProperty();
|
||||
private LongProperty mRadioReferenceLastUpdated = new SimpleLongProperty();
|
||||
private LongProperty mSynchronizedLastUpdated = new SimpleLongProperty();
|
||||
private LongProperty mLastChecked = new SimpleLongProperty();
|
||||
|
||||
/**
|
||||
* Jackson constructor
|
||||
*/
|
||||
public AliasListConfiguration()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param name of the alias list
|
||||
*/
|
||||
public AliasListConfiguration(String name)
|
||||
{
|
||||
setName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extractor so that observable lists of configurations report changes to the persisted properties.
|
||||
*/
|
||||
public static Callback<AliasListConfiguration,Observable[]> extractor()
|
||||
{
|
||||
return (AliasListConfiguration c) -> new Observable[] {c.mName, c.mRadioReferenceSystemId,
|
||||
c.mRadioReferenceSystemName, c.mAutoUpdate, c.mRadioReferenceLastUpdated, c.mSynchronizedLastUpdated,
|
||||
c.mLastChecked};
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias list name
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "name")
|
||||
public String getName()
|
||||
{
|
||||
return mName.get();
|
||||
}
|
||||
|
||||
public void setName(String name)
|
||||
{
|
||||
mName.set(name);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public StringProperty nameProperty()
|
||||
{
|
||||
return mName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this alias list tracks a Radio Reference system.
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isTrackingRadioReferenceSystem()
|
||||
{
|
||||
return getRadioReferenceSystemId() > NO_SYSTEM;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this alias list tracks the specified Radio Reference system.
|
||||
*/
|
||||
public boolean isTracking(int systemId)
|
||||
{
|
||||
return systemId > NO_SYSTEM && getRadioReferenceSystemId() == systemId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Radio Reference system ID tracked by this alias list, or NO_SYSTEM (0).
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "rr_system_id")
|
||||
public int getRadioReferenceSystemId()
|
||||
{
|
||||
return mRadioReferenceSystemId.get();
|
||||
}
|
||||
|
||||
public void setRadioReferenceSystemId(int systemId)
|
||||
{
|
||||
mRadioReferenceSystemId.set(systemId);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public IntegerProperty radioReferenceSystemIdProperty()
|
||||
{
|
||||
return mRadioReferenceSystemId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Radio Reference system name, for display.
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "rr_system_name")
|
||||
public String getRadioReferenceSystemName()
|
||||
{
|
||||
return mRadioReferenceSystemName.get();
|
||||
}
|
||||
|
||||
public void setRadioReferenceSystemName(String name)
|
||||
{
|
||||
mRadioReferenceSystemName.set(name);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public StringProperty radioReferenceSystemNameProperty()
|
||||
{
|
||||
return mRadioReferenceSystemName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if talkgroups are automatically added or updated as aliases when the system changes on Radio Reference.
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "rr_auto_update")
|
||||
public boolean isAutoUpdate()
|
||||
{
|
||||
return mAutoUpdate.get();
|
||||
}
|
||||
|
||||
public void setAutoUpdate(boolean autoUpdate)
|
||||
{
|
||||
mAutoUpdate.set(autoUpdate);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public BooleanProperty autoUpdateProperty()
|
||||
{
|
||||
return mAutoUpdate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Radio Reference last updated timestamp (ms since epoch) for the system, as seen by the most recent check.
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "rr_last_updated")
|
||||
public long getRadioReferenceLastUpdated()
|
||||
{
|
||||
return mRadioReferenceLastUpdated.get();
|
||||
}
|
||||
|
||||
public void setRadioReferenceLastUpdated(long timestamp)
|
||||
{
|
||||
mRadioReferenceLastUpdated.set(timestamp);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public LongProperty radioReferenceLastUpdatedProperty()
|
||||
{
|
||||
return mRadioReferenceLastUpdated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Radio Reference last updated timestamp (ms since epoch) that the aliases were last synchronized to.
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "rr_synchronized")
|
||||
public long getSynchronizedLastUpdated()
|
||||
{
|
||||
return mSynchronizedLastUpdated.get();
|
||||
}
|
||||
|
||||
public void setSynchronizedLastUpdated(long timestamp)
|
||||
{
|
||||
mSynchronizedLastUpdated.set(timestamp);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public LongProperty synchronizedLastUpdatedProperty()
|
||||
{
|
||||
return mSynchronizedLastUpdated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Time (ms since epoch) of the most recent successful check of the system on Radio Reference.
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "rr_last_checked")
|
||||
public long getLastChecked()
|
||||
{
|
||||
return mLastChecked.get();
|
||||
}
|
||||
|
||||
public void setLastChecked(long timestamp)
|
||||
{
|
||||
mLastChecked.set(timestamp);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public LongProperty lastCheckedProperty()
|
||||
{
|
||||
return mLastChecked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the most recent check saw a system change on Radio Reference that the aliases don't include yet.
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isUpdateAvailable()
|
||||
{
|
||||
return isTrackingRadioReferenceSystem() && getRadioReferenceLastUpdated() > getSynchronizedLastUpdated();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts tracking the Radio Reference system. Clears timestamps so that the next refresh synchronizes.
|
||||
*/
|
||||
public void track(int systemId, String systemName)
|
||||
{
|
||||
setRadioReferenceSystemId(systemId);
|
||||
setRadioReferenceSystemName(systemName);
|
||||
setRadioReferenceLastUpdated(0);
|
||||
setSynchronizedLastUpdated(0);
|
||||
setLastChecked(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops tracking any Radio Reference system.
|
||||
*/
|
||||
public void stopTracking()
|
||||
{
|
||||
track(NO_SYSTEM, null);
|
||||
setAutoUpdate(false);
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,6 @@ public class AliasModel
|
||||
private ObservableList<Alias> mAliases = FXCollections.observableArrayList(Alias.extractor());
|
||||
private ObservableList<String> mAliasListNames = FXCollections.observableArrayList();
|
||||
private Map<String,AliasList> mAliasListMap = new HashMap<>();
|
||||
private ObservableList<AliasListConfiguration> mAliasListConfigurations =
|
||||
FXCollections.observableArrayList(AliasListConfiguration.extractor());
|
||||
|
||||
public AliasModel()
|
||||
{
|
||||
@@ -65,99 +63,6 @@ public class AliasModel
|
||||
return mAliasListNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Observable list of persisted alias list configurations. Only alias lists with settings, like Radio Reference
|
||||
* system tracking, have a configuration.
|
||||
*/
|
||||
public ObservableList<AliasListConfiguration> aliasListConfigurations()
|
||||
{
|
||||
return mAliasListConfigurations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk loading of alias list configurations from a playlist. Ignores configurations without a name and
|
||||
* duplicates of an earlier configuration's name.
|
||||
*/
|
||||
public void addAliasListConfigurations(List<AliasListConfiguration> configurations)
|
||||
{
|
||||
if(configurations != null)
|
||||
{
|
||||
for(AliasListConfiguration configuration: configurations)
|
||||
{
|
||||
String name = configuration.getName();
|
||||
|
||||
if(name != null && !name.isEmpty() && getAliasListConfiguration(name) == null)
|
||||
{
|
||||
mAliasListConfigurations.add(configuration);
|
||||
addAliasList(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for the named alias list.
|
||||
* @param aliasListName to find
|
||||
* @return configuration or null if the alias list doesn't have one
|
||||
*/
|
||||
public AliasListConfiguration getAliasListConfiguration(String aliasListName)
|
||||
{
|
||||
if(aliasListName != null)
|
||||
{
|
||||
for(AliasListConfiguration configuration: mAliasListConfigurations)
|
||||
{
|
||||
if(aliasListName.equals(configuration.getName()))
|
||||
{
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for the named alias list, created when the alias list doesn't have one.
|
||||
* @param aliasListName for the configuration, not null or the (No Alias List) name
|
||||
* @return configuration
|
||||
*/
|
||||
public AliasListConfiguration getOrCreateAliasListConfiguration(String aliasListName)
|
||||
{
|
||||
if(aliasListName == null || aliasListName.isEmpty() || aliasListName.equals(NO_ALIAS_LIST))
|
||||
{
|
||||
throw new IllegalArgumentException("Invalid alias list name [" + aliasListName + "]");
|
||||
}
|
||||
|
||||
AliasListConfiguration configuration = getAliasListConfiguration(aliasListName);
|
||||
|
||||
if(configuration == null)
|
||||
{
|
||||
configuration = new AliasListConfiguration(aliasListName);
|
||||
mAliasListConfigurations.add(configuration);
|
||||
addAliasList(aliasListName);
|
||||
}
|
||||
|
||||
return configuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name of the first alias list that tracks the Radio Reference system.
|
||||
* @param systemId of the Radio Reference system
|
||||
* @return alias list name or null
|
||||
*/
|
||||
public String getAliasListNameTracking(int systemId)
|
||||
{
|
||||
for(AliasListConfiguration configuration: mAliasListConfigurations)
|
||||
{
|
||||
if(configuration.isTracking(systemId))
|
||||
{
|
||||
return configuration.getName();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears and reloads the list of alias list names from the current set of aliases.
|
||||
*/
|
||||
@@ -174,15 +79,6 @@ public class AliasModel
|
||||
mAliasListNames.add(aliasListName);
|
||||
}
|
||||
}
|
||||
|
||||
//Alias lists with a configuration exist even before they have any aliases
|
||||
for(AliasListConfiguration configuration: mAliasListConfigurations)
|
||||
{
|
||||
if(!mAliasListNames.contains(configuration.getName()))
|
||||
{
|
||||
mAliasListNames.add(configuration.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -197,22 +93,7 @@ public class AliasModel
|
||||
return;
|
||||
}
|
||||
|
||||
mAliases.stream().filter(alias -> oldName.equals(alias.getAliasListName())).forEach(alias -> alias.setAliasListName(newName));
|
||||
|
||||
AliasListConfiguration configuration = getAliasListConfiguration(oldName);
|
||||
|
||||
if(configuration != null)
|
||||
{
|
||||
//Merging into an existing list keeps that list's configuration
|
||||
if(getAliasListConfiguration(newName) == null)
|
||||
{
|
||||
configuration.setName(newName);
|
||||
}
|
||||
else
|
||||
{
|
||||
mAliasListConfigurations.remove(configuration);
|
||||
}
|
||||
}
|
||||
mAliases.stream().filter(alias -> alias.getAliasListName().equals(oldName)).forEach(alias -> alias.setAliasListName(newName));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,7 +109,6 @@ public class AliasModel
|
||||
|
||||
mAliases.removeIf(alias -> alias.getAliasListName().equals(aliasListName));
|
||||
mAliasListMap.remove(aliasListName);
|
||||
mAliasListConfigurations.removeIf(configuration -> aliasListName.equals(configuration.getName()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -266,7 +146,6 @@ public class AliasModel
|
||||
removeAlias(alias);
|
||||
}
|
||||
|
||||
mAliasListConfigurations.clear();
|
||||
mAliasListNames.clear();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,571 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.alias;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.github.dsheirer.alias.id.AliasID;
|
||||
import io.github.dsheirer.alias.id.radio.NXDNTypeDRadio;
|
||||
import io.github.dsheirer.alias.id.radio.P25FullyQualifiedRadio;
|
||||
import io.github.dsheirer.alias.id.radio.Radio;
|
||||
import io.github.dsheirer.identifier.alias.TalkerAliasIdentifier;
|
||||
import io.github.dsheirer.identifier.radio.FullyQualifiedRadioIdentifier;
|
||||
import io.github.dsheirer.identifier.radio.RadioIdentifier;
|
||||
import io.github.dsheirer.module.decode.nxdn.identifier.NXDNRadioIdentifier;
|
||||
import io.github.dsheirer.protocol.Protocol;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import javafx.application.Platform;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Automatically adds decoded talker aliases to an alias list as radio aliases, using the talker alias as the alias name,
|
||||
* and renames a stored radio alias when the radio's talker alias changes.
|
||||
*
|
||||
* Talker aliases span up to 4 messages, so a decoded talker alias can be a fragment (the leading characters) of the
|
||||
* full alias, even when the decoder reports it as complete. To avoid replacing a full alias with a fragment:
|
||||
* <ul>
|
||||
* <li>A decoded alias that is the start of the stored alias name is a fragment and never replaces it.</li>
|
||||
* <li>A decoded alias that starts with the stored alias name is a longer version of a stored fragment and
|
||||
* replaces it.</li>
|
||||
* <li>Any other decoded alias that differs from the stored alias name replaces it only after it is decoded
|
||||
* {@link #CONFIRMATIONS_REQUIRED} times in a row for the radio.</li>
|
||||
* </ul>
|
||||
*
|
||||
* Only aliases whose only identifier is the radio are created or renamed. An alias that combines the radio with other
|
||||
* identifiers (e.g. several radios or talkgroups) is left alone. The exception is a P25 radio's simple and fully
|
||||
* qualified radio identifiers with the same radio ID: the second form decoded is added to the alias for the first
|
||||
* form, including a user alias outside the managed group, instead of creating a second alias for the same radio.
|
||||
*
|
||||
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
|
||||
* JavaFX application thread.
|
||||
*/
|
||||
public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAliasIdentifier>
|
||||
{
|
||||
private static final Logger mLog = LoggerFactory.getLogger(TalkerAliasAutoAdder.class);
|
||||
|
||||
/**
|
||||
* Group assigned to aliases created from talker aliases.
|
||||
*/
|
||||
public static final String ALIAS_GROUP = "Talker Alias";
|
||||
|
||||
/**
|
||||
* Number of consecutive times a different talker alias must be decoded for a radio before it replaces the stored
|
||||
* alias name.
|
||||
*/
|
||||
public static final int CONFIRMATIONS_REQUIRED = 2;
|
||||
|
||||
/**
|
||||
* Interval for re-checking the stored alias for a talker alias that was already checked, so that a renamed or
|
||||
* deleted alias is restored without checking the alias list for every decoded talker alias.
|
||||
*/
|
||||
private static final long RECHECK_INTERVAL_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Outcome of comparing a decoded talker alias with the stored alias name.
|
||||
*/
|
||||
public enum Decision
|
||||
{
|
||||
/**
|
||||
* The stored alias name matches the talker alias.
|
||||
*/
|
||||
UNCHANGED,
|
||||
/**
|
||||
* The talker alias is a fragment of the stored alias name.
|
||||
*/
|
||||
FRAGMENT,
|
||||
/**
|
||||
* The talker alias differs from the stored alias name and is waiting for more decodes.
|
||||
*/
|
||||
AWAIT_CONFIRMATION,
|
||||
/**
|
||||
* The talker alias replaces the stored alias name.
|
||||
*/
|
||||
UPDATE
|
||||
}
|
||||
|
||||
private final AliasModel mAliasModel;
|
||||
private final String mAliasListName;
|
||||
//Guarded by this
|
||||
private final Map<String,Candidate> mCandidates = new HashMap<>();
|
||||
private final Map<String,Checked> mChecked = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param aliasModel to add aliases to
|
||||
* @param aliasListName of the alias list to add aliases to
|
||||
*/
|
||||
public TalkerAliasAutoAdder(AliasModel aliasModel, String aliasListName)
|
||||
{
|
||||
mAliasModel = aliasModel;
|
||||
mAliasListName = aliasListName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name of the alias list that talker aliases are added to.
|
||||
*/
|
||||
public String getAliasListName()
|
||||
{
|
||||
return mAliasListName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a talker alias that is assigned to a radio.
|
||||
* @param radio that the talker alias belongs to
|
||||
* @param talkerAlias for the radio
|
||||
*/
|
||||
@Override
|
||||
public void accept(RadioIdentifier radio, TalkerAliasIdentifier talkerAlias)
|
||||
{
|
||||
if(radio == null || talkerAlias == null || mAliasListName == null || mAliasListName.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
String value = normalize(talkerAlias.getValue());
|
||||
Radio aliasId = createAliasId(radio);
|
||||
|
||||
if(value == null || aliasId == null || !aliasId.isValid())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
String key = getKey(aliasId);
|
||||
long now = System.currentTimeMillis();
|
||||
int confirmations;
|
||||
|
||||
synchronized(this)
|
||||
{
|
||||
Checked checked = mChecked.get(key);
|
||||
|
||||
if(checked != null && checked.value().equals(value) && (now - checked.timestamp()) < RECHECK_INTERVAL_MS)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
confirmations = confirm(key, value);
|
||||
}
|
||||
|
||||
runOnFxThread(() -> apply(radio, aliasId, key, value, confirmations));
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the consecutive decodes of the talker alias for the radio. A fragment of the talker alias that is
|
||||
* waiting for confirmation doesn't interrupt the count, because fragments are decoded while the full alias is
|
||||
* assembled.
|
||||
* @return number of consecutive decodes of the value, including this one.
|
||||
*/
|
||||
private int confirm(String key, String value)
|
||||
{
|
||||
Candidate candidate = mCandidates.get(key);
|
||||
|
||||
if(candidate != null && candidate.value().equals(value))
|
||||
{
|
||||
candidate = new Candidate(value, candidate.count() + 1);
|
||||
mCandidates.put(key, candidate);
|
||||
return candidate.count();
|
||||
}
|
||||
|
||||
if(candidate != null && isFragment(value, candidate.value()))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
mCandidates.put(key, new Candidate(value, 1));
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates the alias for the radio. Runs on the JavaFX application thread.
|
||||
*/
|
||||
private synchronized void apply(RadioIdentifier radio, Radio aliasId, String key, String value, int confirmations)
|
||||
{
|
||||
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
|
||||
Alias existing = findExactMatch(aliasList.getAliases(radio), aliasId);
|
||||
|
||||
if(existing == null)
|
||||
{
|
||||
existing = findCompanion(aliasList.aliases(), radio, aliasId);
|
||||
|
||||
if(existing != null)
|
||||
{
|
||||
//Add the radio to the alias for the same radio's other identifier form, then continue below to
|
||||
//compare the talker alias with the alias name (only managed aliases are renamed).
|
||||
existing.addAliasID(aliasId);
|
||||
aliasList.updateAlias(existing);
|
||||
mLog.info("Talker alias radio [" + aliasId + "] added to existing alias [" + existing.getName() +
|
||||
"] in alias list [" + mAliasListName + "]");
|
||||
}
|
||||
}
|
||||
|
||||
if(existing == null)
|
||||
{
|
||||
Alias alias = new Alias(value);
|
||||
alias.setAliasListName(mAliasListName);
|
||||
alias.setGroup(ALIAS_GROUP);
|
||||
alias.addAliasID(aliasId);
|
||||
mAliasModel.addAlias(alias);
|
||||
markChecked(key, value);
|
||||
mLog.info("Talker alias [" + value + "] added for radio [" + aliasId + "] to alias list [" +
|
||||
mAliasListName + "]");
|
||||
return;
|
||||
}
|
||||
|
||||
if(!ALIAS_GROUP.equals(existing.getGroup()))
|
||||
{
|
||||
//Only maintain aliases in the managed group. Existing user aliases must not be renamed or duplicated.
|
||||
markChecked(key, value);
|
||||
return;
|
||||
}
|
||||
|
||||
if(getIdentityCount(existing) > 1)
|
||||
{
|
||||
//The alias also identifies other radios or talkgroups - leave it alone.
|
||||
markChecked(key, value);
|
||||
return;
|
||||
}
|
||||
|
||||
String stored = normalize(existing.getName());
|
||||
|
||||
switch(decide(stored, value, confirmations))
|
||||
{
|
||||
case UPDATE:
|
||||
existing.setName(value);
|
||||
markChecked(key, value);
|
||||
mLog.info("Talker alias for radio [" + aliasId + "] in alias list [" + mAliasListName +
|
||||
"] changed from [" + stored + "] to [" + value + "]");
|
||||
break;
|
||||
case UNCHANGED:
|
||||
case FRAGMENT:
|
||||
markChecked(key, value);
|
||||
break;
|
||||
case AWAIT_CONFIRMATION:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void markChecked(String key, String value)
|
||||
{
|
||||
mChecked.put(key, new Checked(value, System.currentTimeMillis()));
|
||||
mCandidates.remove(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the decoded talker alias with the stored alias name.
|
||||
* @param stored alias name, normalized, or null
|
||||
* @param decoded talker alias, normalized
|
||||
* @param confirmations number of consecutive decodes of the talker alias
|
||||
* @return decision
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static Decision decide(String stored, String decoded, int confirmations)
|
||||
{
|
||||
if(stored == null || stored.isEmpty())
|
||||
{
|
||||
return Decision.UPDATE;
|
||||
}
|
||||
|
||||
if(stored.equals(decoded))
|
||||
{
|
||||
return Decision.UNCHANGED;
|
||||
}
|
||||
|
||||
if(isFragment(decoded, stored))
|
||||
{
|
||||
return Decision.FRAGMENT;
|
||||
}
|
||||
|
||||
//A longer version of a stored fragment.
|
||||
if(isFragment(stored, decoded) && !hasUndecodableCharacters(decoded))
|
||||
{
|
||||
return Decision.UPDATE;
|
||||
}
|
||||
|
||||
//A different alias that may be a corrupted or mis-assembled alias. It's replaced only once confirmed, and an
|
||||
//alias that has undecodable characters (e.g. a partial multi-byte character) never replaces a stored alias.
|
||||
if(confirmations >= CONFIRMATIONS_REQUIRED && !hasUndecodableCharacters(decoded))
|
||||
{
|
||||
return Decision.UPDATE;
|
||||
}
|
||||
|
||||
return Decision.AWAIT_CONFIRMATION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the value is a fragment (the leading characters) of the full value.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static boolean isFragment(String value, String full)
|
||||
{
|
||||
return value != null && full != null && value.length() < full.length() && full.startsWith(value);
|
||||
}
|
||||
|
||||
private static boolean hasUndecodableCharacters(String value)
|
||||
{
|
||||
return value.indexOf('<27>') >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes padding, control characters and trailing undecodable characters (e.g. from a partial multi-byte
|
||||
* character at the end of an alias fragment) from the talker alias.
|
||||
* @param value to normalize
|
||||
* @return normalized value or null if the value is empty.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static String normalize(String value)
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder(value.length());
|
||||
|
||||
for(int i = 0; i < value.length(); i++)
|
||||
{
|
||||
char c = value.charAt(i);
|
||||
|
||||
if(!Character.isISOControl(c))
|
||||
{
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
int end = sb.length();
|
||||
|
||||
while(end > 0 && (sb.charAt(end - 1) == '<27>' || Character.isWhitespace(sb.charAt(end - 1))))
|
||||
{
|
||||
end--;
|
||||
}
|
||||
|
||||
String normalized = sb.substring(0, end).trim();
|
||||
return normalized.isEmpty() ? null : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a radio alias identifier that exactly matches the radio.
|
||||
* @param radio identifier
|
||||
* @return alias identifier or null if the radio protocol isn't known.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static Radio createAliasId(RadioIdentifier radio)
|
||||
{
|
||||
if(radio instanceof FullyQualifiedRadioIdentifier fqri && fqri.getProtocol() == Protocol.APCO25)
|
||||
{
|
||||
return new P25FullyQualifiedRadio(fqri.getWacn(), fqri.getSystem(), fqri.getRadio());
|
||||
}
|
||||
|
||||
if(radio instanceof NXDNRadioIdentifier nxdn && nxdn.isTypeD())
|
||||
{
|
||||
return new NXDNTypeDRadio(nxdn.getTypeDHomeRepeater(), nxdn.getTypeDRadio());
|
||||
}
|
||||
|
||||
Protocol protocol = radio.getProtocol();
|
||||
|
||||
if(protocol == null || protocol == Protocol.UNKNOWN || radio.getValue() == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Radio(protocol, radio.getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the alias that has an identifier that exactly matches the radio (i.e. not a radio range).
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static Alias findExactMatch(List<Alias> aliases, Radio aliasId)
|
||||
{
|
||||
if(aliases != null)
|
||||
{
|
||||
for(Alias alias: aliases)
|
||||
{
|
||||
for(AliasID id: alias.getAliasIdentifiers())
|
||||
{
|
||||
if(isExactMatch(id, aliasId))
|
||||
{
|
||||
return alias;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isExactMatch(AliasID id, Radio aliasId)
|
||||
{
|
||||
if(aliasId instanceof P25FullyQualifiedRadio target)
|
||||
{
|
||||
return id instanceof P25FullyQualifiedRadio fqr && fqr.getHashKey().equals(target.getHashKey());
|
||||
}
|
||||
|
||||
return id instanceof Radio radio && !(id instanceof P25FullyQualifiedRadio) &&
|
||||
radio.getProtocol() == aliasId.getProtocol() && radio.getValue() == aliasId.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the alias for the other identifier form of a P25 radio, so that a radio's simple and fully qualified
|
||||
* identifiers share one alias instead of creating an alias for each. This includes user aliases outside the
|
||||
* managed group, so that either identifier maps to the user's alias. The user alias is never renamed.
|
||||
* <ul>
|
||||
* <li>Fully qualified radio: the alias whose only identifier is the simple radio with the same radio
|
||||
* ID. Only when the fully qualified radio isn't using a different local address (e.g. a roaming radio), since
|
||||
* the radio ID then belongs to the home system and doesn't identify the radio on this system.</li>
|
||||
* <li>Simple radio: the alias whose only identifier is a fully qualified radio with the same radio ID. None
|
||||
* when more than one fully qualified radio alias matches.</li>
|
||||
* </ul>
|
||||
* @param aliases to search
|
||||
* @param radio decoded radio identifier
|
||||
* @param aliasId created from the decoded radio
|
||||
* @return companion alias or null.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
|
||||
{
|
||||
if(aliases == null || aliasId.getProtocol() != Protocol.APCO25)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
boolean fullyQualified = aliasId instanceof P25FullyQualifiedRadio;
|
||||
|
||||
if(fullyQualified && !(radio instanceof FullyQualifiedRadioIdentifier fqri &&
|
||||
fqri.getValue() != null && fqri.getValue() == fqri.getRadio()))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Alias match = null;
|
||||
|
||||
for(Alias alias: aliases)
|
||||
{
|
||||
if(getSoleIdentity(alias) instanceof Radio candidate &&
|
||||
(candidate instanceof P25FullyQualifiedRadio) != fullyQualified &&
|
||||
candidate.getProtocol() == Protocol.APCO25 && candidate.getValue() == aliasId.getValue())
|
||||
{
|
||||
if(match != null)
|
||||
{
|
||||
//Ambiguous - more than one candidate.
|
||||
return null;
|
||||
}
|
||||
|
||||
match = alias;
|
||||
}
|
||||
}
|
||||
|
||||
return match;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifier of an alias that has exactly one identifier, excluding audio settings.
|
||||
* @return identifier or null if the alias has none or more than one.
|
||||
*/
|
||||
private static AliasID getSoleIdentity(Alias alias)
|
||||
{
|
||||
AliasID sole = null;
|
||||
|
||||
for(AliasID id: alias.getAliasIdentifiers())
|
||||
{
|
||||
if(!id.isAudioIdentifier())
|
||||
{
|
||||
if(sole != null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
sole = id;
|
||||
}
|
||||
}
|
||||
|
||||
return sole;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of identities (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
|
||||
* streaming. A P25 radio's simple and fully qualified radio identifiers with the same radio ID count as one
|
||||
* identity.
|
||||
*/
|
||||
private static int getIdentityCount(Alias alias)
|
||||
{
|
||||
List<AliasID> ids = alias.getAliasIdentifiers().stream().filter(id -> !id.isAudioIdentifier()).toList();
|
||||
|
||||
if(ids.size() == 2 && isRadioPair(ids.get(0), ids.get(1)))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return ids.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the identifiers are the simple and fully qualified forms of the same P25 radio ID.
|
||||
*/
|
||||
private static boolean isRadioPair(AliasID a, AliasID b)
|
||||
{
|
||||
if(a instanceof P25FullyQualifiedRadio)
|
||||
{
|
||||
AliasID swap = a;
|
||||
a = b;
|
||||
b = swap;
|
||||
}
|
||||
|
||||
return a instanceof Radio simple && !(a instanceof P25FullyQualifiedRadio) &&
|
||||
b instanceof P25FullyQualifiedRadio fqr && simple.getProtocol() == Protocol.APCO25 &&
|
||||
simple.getValue() == fqr.getValue();
|
||||
}
|
||||
|
||||
private static String getKey(Radio aliasId)
|
||||
{
|
||||
if(aliasId instanceof P25FullyQualifiedRadio fqr)
|
||||
{
|
||||
return aliasId.getProtocol() + ":" + fqr.getHashKey();
|
||||
}
|
||||
|
||||
return aliasId.getProtocol() + ":" + aliasId.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs on the FX thread, or on this thread when the FX toolkit isn't running (headless).
|
||||
*/
|
||||
private static void runOnFxThread(Runnable runnable)
|
||||
{
|
||||
if(Platform.isFxApplicationThread())
|
||||
{
|
||||
runnable.run();
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Platform.runLater(runnable);
|
||||
}
|
||||
catch(IllegalStateException ise)
|
||||
{
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
|
||||
private record Candidate(String value, int count) {}
|
||||
private record Checked(String value, long timestamp) {}
|
||||
}
|
||||
@@ -19,16 +19,14 @@
|
||||
|
||||
package io.github.dsheirer.alias.action;
|
||||
|
||||
import io.github.dsheirer.gui.FxToolkit;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.Alert;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
|
||||
import io.github.dsheirer.alias.Alias;
|
||||
import io.github.dsheirer.message.IMessage;
|
||||
import io.github.dsheirer.util.ThreadPool;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -64,28 +62,23 @@ public abstract class RecurringAction extends AliasAction
|
||||
mPerpetualAction = ThreadPool.SCHEDULED.scheduleAtFixedRate(
|
||||
new PerformActionTask(alias, message), 0, mPeriod, TimeUnit.SECONDS);
|
||||
|
||||
String text = "Alias [" + alias.getName() + "] is active in message [" + message + "]";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("<html><div width='250'>Alias [");
|
||||
sb.append(alias.getName());
|
||||
sb.append("] is active in message [");
|
||||
sb.append(message.toString());
|
||||
sb.append("]</div></html>");
|
||||
|
||||
final String text = sb.toString();
|
||||
|
||||
EventQueue.invokeLater(() -> {
|
||||
JOptionPane.showMessageDialog(null, text,
|
||||
"Alias Alert", JOptionPane.INFORMATION_MESSAGE);
|
||||
|
||||
Runnable dismissed = () -> {
|
||||
dismiss(false);
|
||||
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
|
||||
};
|
||||
|
||||
if(FxToolkit.isStarted())
|
||||
{
|
||||
//The action repeats until the user closes the alert
|
||||
Platform.runLater(() -> {
|
||||
Alert alert = new Alert(Alert.AlertType.INFORMATION, text);
|
||||
alert.setTitle("Alias Alert");
|
||||
alert.setHeaderText(null);
|
||||
alert.setOnHidden(event -> dismissed.run());
|
||||
alert.show();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
dismissed.run();
|
||||
}
|
||||
ThreadPool.SCHEDULED.schedule(new ResetTask(), 15, TimeUnit.SECONDS);
|
||||
});
|
||||
break;
|
||||
default:
|
||||
}
|
||||
|
||||
@@ -31,8 +31,6 @@ public class AudioEvent
|
||||
AUDIO_STOPPED,
|
||||
AUDIO_CONTINUATION,
|
||||
AUDIO_CONFIGURATION_CHANGE_STARTED,
|
||||
AUDIO_CONFIGURATION_CHANGE_COMPLETE,
|
||||
REPLAY_STARTED,
|
||||
REPLAY_STOPPED;
|
||||
AUDIO_CONFIGURATION_CHANGE_COMPLETE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import javafx.beans.property.BooleanProperty;
|
||||
import javafx.beans.property.IntegerProperty;
|
||||
import javafx.beans.property.SimpleBooleanProperty;
|
||||
@@ -68,8 +67,6 @@ import org.slf4j.LoggerFactory;
|
||||
public class AudioSegment implements Listener<IdentifierUpdateNotification>
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(AudioSegment.class);
|
||||
private static final AtomicLong ID_GENERATOR = new AtomicLong();
|
||||
private final long mId = ID_GENERATOR.incrementAndGet();
|
||||
private BooleanProperty mComplete = new SimpleBooleanProperty(false);
|
||||
private BooleanProperty mDuplicate = new SimpleBooleanProperty(false);
|
||||
private BooleanProperty mEncrypted = new SimpleBooleanProperty(false);
|
||||
@@ -99,15 +96,6 @@ public class AudioSegment implements Listener<IdentifierUpdateNotification>
|
||||
mIdentifierCollection.setTimeslot(timeslot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unique identifier of this audio segment for the current application session. The call manager uses it as the
|
||||
* call key, which links a call that is playing on an audio channel to the call in the Calls tab.
|
||||
*/
|
||||
public long getId()
|
||||
{
|
||||
return mId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeslot for this audio segment
|
||||
*/
|
||||
|
||||
@@ -25,7 +25,6 @@ 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;
|
||||
@@ -50,7 +49,6 @@ 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"),
|
||||
|
||||
@@ -24,7 +24,6 @@ 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;
|
||||
@@ -69,7 +68,6 @@ 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:
|
||||
@@ -115,8 +113,6 @@ 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:
|
||||
|
||||
@@ -46,8 +46,9 @@ import javafx.collections.ObservableList;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.swing.table.AbstractTableModel;
|
||||
|
||||
public class BroadcastModel implements Listener<AudioRecording>
|
||||
public class BroadcastModel extends AbstractTableModel implements Listener<AudioRecording>
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(BroadcastModel.class);
|
||||
|
||||
@@ -56,6 +57,18 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
|
||||
private static final String UNIQUE_NAME_REGEX = "(.*)\\((\\d*)\\)";
|
||||
|
||||
public static final int COLUMN_BROADCAST_SERVER_TYPE = 0;
|
||||
public static final int COLUMN_STREAM_NAME = 1;
|
||||
public static final int COLUMN_BROADCASTER_STATUS = 2;
|
||||
public static final int COLUMN_BROADCASTER_QUEUE_SIZE = 3;
|
||||
public static final int COLUMN_BROADCASTER_STREAMED_COUNT = 4;
|
||||
public static final int COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT = 5;
|
||||
public static final int COLUMN_BROADCASTER_AGED_OFF_COUNT = 6;
|
||||
public static final int COLUMN_BROADCASTER_ERROR_COUNT = 7;
|
||||
|
||||
public static final String[] COLUMN_NAMES = new String[]
|
||||
{"Stream Type", "Name", "Status", "Queued", "Streamed/Uploaded", "Duplicate Rejected", "Aged Off", "Upload Error"};
|
||||
|
||||
private ObservableList<ConfiguredBroadcast> mConfiguredBroadcasts =
|
||||
FXCollections.observableArrayList(ConfiguredBroadcast.extractor());
|
||||
private List<AudioRecording> mRecordingQueue = new CopyOnWriteArrayList<>();
|
||||
@@ -158,6 +171,8 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
{
|
||||
configuredBroadcast = new ConfiguredBroadcast(configuration);
|
||||
mConfiguredBroadcasts.add(configuredBroadcast);
|
||||
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
|
||||
fireTableRowsInserted(index, index);
|
||||
process(new BroadcastEvent(configuration, BroadcastEvent.Event.CONFIGURATION_ADD));
|
||||
return configuredBroadcast;
|
||||
}
|
||||
@@ -259,6 +274,8 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
|
||||
if(configuredBroadcast != null)
|
||||
{
|
||||
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
|
||||
|
||||
mConfiguredBroadcasts.remove(configuredBroadcast);
|
||||
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
@@ -269,6 +286,8 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
}
|
||||
|
||||
process(new BroadcastEvent(broadcastConfiguration, BroadcastEvent.Event.CONFIGURATION_DELETE));
|
||||
|
||||
fireTableRowsDeleted(index, index);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,6 +354,13 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
audioBroadcaster.setListener(mBroadcastEventListener);
|
||||
mBroadcasterMap.put(audioBroadcaster.getBroadcastConfiguration().getId(), audioBroadcaster);
|
||||
|
||||
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
|
||||
|
||||
if(index >= 0)
|
||||
{
|
||||
fireTableRowsUpdated(index, index);
|
||||
}
|
||||
|
||||
broadcast(new BroadcastEvent(audioBroadcaster, BroadcastEvent.Event.BROADCASTER_ADD));
|
||||
ThreadPool.CACHED.submit(() -> audioBroadcaster.start());
|
||||
}
|
||||
@@ -357,6 +383,13 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
broadcaster.removeListener();
|
||||
broadcaster.dispose();
|
||||
|
||||
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
|
||||
|
||||
if(index >= 0)
|
||||
{
|
||||
fireTableRowsUpdated(index, index);
|
||||
}
|
||||
|
||||
broadcast(new BroadcastEvent(broadcaster, BroadcastEvent.Event.BROADCASTER_DELETE));
|
||||
}
|
||||
}
|
||||
@@ -465,17 +498,186 @@ public class BroadcastModel implements Listener<AudioRecording>
|
||||
ThreadPool.SCHEDULED.schedule(new DelayedBroadcasterStartup(broadcastConfiguration),
|
||||
1, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
int index = mConfiguredBroadcasts.indexOf(configuredBroadcast);
|
||||
fireTableRowsUpdated(index, index);
|
||||
break;
|
||||
case CONFIGURATION_DELETE:
|
||||
deleteBroadcaster(getConfiguredBroadcast(broadcastEvent.getBroadcastConfiguration()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if(broadcastEvent.isAudioBroadcasterEvent())
|
||||
{
|
||||
ConfiguredBroadcast configuredBroadcast = getConfiguredBroadcast(broadcastEvent.getAudioBroadcaster());
|
||||
int row = mConfiguredBroadcasts.indexOf(configuredBroadcast);
|
||||
|
||||
switch(broadcastEvent.getEvent())
|
||||
{
|
||||
case BROADCASTER_QUEUE_CHANGE:
|
||||
if(row >= 0)
|
||||
{
|
||||
fireTableCellUpdated(row, COLUMN_BROADCASTER_QUEUE_SIZE);
|
||||
}
|
||||
break;
|
||||
case BROADCASTER_STATE_CHANGE:
|
||||
if(row >= 0)
|
||||
{
|
||||
fireTableCellUpdated(row, COLUMN_BROADCASTER_STATUS);
|
||||
}
|
||||
break;
|
||||
case BROADCASTER_STREAMED_COUNT_CHANGE:
|
||||
if(row >= 0)
|
||||
{
|
||||
fireTableCellUpdated(row, COLUMN_BROADCASTER_STREAMED_COUNT);
|
||||
}
|
||||
break;
|
||||
case BROADCASTER_DUPLICATE_REJECTED_COUNT_CHANGE:
|
||||
if(row >= 0)
|
||||
{
|
||||
fireTableCellUpdated(row, COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT);
|
||||
}
|
||||
break;
|
||||
case BROADCASTER_AGED_OFF_COUNT_CHANGE:
|
||||
if(row >= 0)
|
||||
{
|
||||
fireTableCellUpdated(row, COLUMN_BROADCASTER_AGED_OFF_COUNT);
|
||||
}
|
||||
case BROADCASTER_ERROR_COUNT_CHANGE:
|
||||
if(row >= 0)
|
||||
{
|
||||
fireTableCellUpdated(row, COLUMN_BROADCASTER_ERROR_COUNT);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//Rebroadcast the event to any listeners of this model
|
||||
broadcast(broadcastEvent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRowCount()
|
||||
{
|
||||
return mConfiguredBroadcasts.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColumnCount()
|
||||
{
|
||||
return COLUMN_NAMES.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValueAt(int rowIndex, int columnIndex)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(rowIndex <= mConfiguredBroadcasts.size())
|
||||
{
|
||||
ConfiguredBroadcast configuredBroadcast = mConfiguredBroadcasts.get(rowIndex);
|
||||
|
||||
if(configuredBroadcast != null)
|
||||
{
|
||||
switch(columnIndex)
|
||||
{
|
||||
case COLUMN_BROADCAST_SERVER_TYPE:
|
||||
return configuredBroadcast.getBroadcastServerType();
|
||||
case COLUMN_STREAM_NAME:
|
||||
return configuredBroadcast.getBroadcastConfiguration().getName();
|
||||
case COLUMN_BROADCASTER_STATUS:
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
{
|
||||
return configuredBroadcast.getAudioBroadcaster().getBroadcastState();
|
||||
}
|
||||
else if(!configuredBroadcast.getBroadcastConfiguration().isEnabled())
|
||||
{
|
||||
return BroadcastState.DISABLED;
|
||||
}
|
||||
else if(!configuredBroadcast.getBroadcastConfiguration().isValid())
|
||||
{
|
||||
return BroadcastState.INVALID_SETTINGS;
|
||||
}
|
||||
else
|
||||
{
|
||||
return BroadcastState.ERROR;
|
||||
}
|
||||
case COLUMN_BROADCASTER_QUEUE_SIZE:
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
{
|
||||
return configuredBroadcast.getAudioBroadcaster().getAudioQueueSize();
|
||||
}
|
||||
break;
|
||||
case COLUMN_BROADCASTER_STREAMED_COUNT:
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
{
|
||||
return configuredBroadcast.getAudioBroadcaster().getStreamedAudioCount();
|
||||
}
|
||||
break;
|
||||
case COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT:
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
{
|
||||
return configuredBroadcast.getAudioBroadcaster().getDuplicateRejectedAudioCount();
|
||||
}
|
||||
break;
|
||||
case COLUMN_BROADCASTER_AGED_OFF_COUNT:
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
{
|
||||
return configuredBroadcast.getAudioBroadcaster().getAgedOffAudioCount();
|
||||
}
|
||||
break;
|
||||
case COLUMN_BROADCASTER_ERROR_COUNT:
|
||||
if(configuredBroadcast.hasAudioBroadcaster())
|
||||
{
|
||||
return configuredBroadcast.getAudioBroadcaster().getAudioErrorCount();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.error("Error accessing data in broadcast model", e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getColumnClass(int columnIndex)
|
||||
{
|
||||
switch(columnIndex)
|
||||
{
|
||||
case COLUMN_BROADCASTER_STATUS:
|
||||
return BroadcastState.class;
|
||||
case COLUMN_BROADCASTER_AGED_OFF_COUNT:
|
||||
case COLUMN_BROADCASTER_QUEUE_SIZE:
|
||||
case COLUMN_BROADCASTER_STREAMED_COUNT:
|
||||
case COLUMN_BROADCASTER_DUPLICATE_REJECTED_COUNT:
|
||||
case COLUMN_BROADCASTER_ERROR_COUNT:
|
||||
return Integer.class;
|
||||
case COLUMN_BROADCAST_SERVER_TYPE:
|
||||
return BroadcastServerType.class;
|
||||
case COLUMN_STREAM_NAME:
|
||||
default:
|
||||
return String.class;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnName(int column)
|
||||
{
|
||||
if(0 <= column && column < COLUMN_NAMES.length)
|
||||
{
|
||||
return COLUMN_NAMES[column];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup method to remove a temporary recording file from disk.
|
||||
*
|
||||
|
||||
@@ -32,7 +32,6 @@ 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"),
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2022 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.broadcast;
|
||||
|
||||
import io.github.dsheirer.icon.Icon;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
|
||||
import java.awt.Color;
|
||||
import java.awt.Component;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
|
||||
import javax.swing.ImageIcon;
|
||||
import javax.swing.JLabel;
|
||||
import javax.swing.JPanel;
|
||||
import javax.swing.JScrollPane;
|
||||
import javax.swing.JTable;
|
||||
import javax.swing.SwingConstants;
|
||||
import javax.swing.table.DefaultTableCellRenderer;
|
||||
|
||||
/**
|
||||
* Table of broadcast streams and statuses.
|
||||
*/
|
||||
public class BroadcastStatusPanel extends JPanel
|
||||
{
|
||||
private JTable mTable;
|
||||
private JTableColumnWidthMonitor mColumnWidthMonitor;
|
||||
private JScrollPane mScrollPane;
|
||||
private BroadcastModel mBroadcastModel;
|
||||
private UserPreferences mUserPreferences;
|
||||
private String mPreferenceKey;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param broadcastModel to access the streams
|
||||
* @param userPreferences for configuring the panel
|
||||
* @param preferenceKey to store column preferences for this panel.
|
||||
*/
|
||||
public BroadcastStatusPanel(BroadcastModel broadcastModel, UserPreferences userPreferences, String preferenceKey)
|
||||
{
|
||||
mBroadcastModel = broadcastModel;
|
||||
mUserPreferences = userPreferences;
|
||||
mPreferenceKey = preferenceKey;
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
public JTable getTable()
|
||||
{
|
||||
return mTable;
|
||||
}
|
||||
|
||||
private void init()
|
||||
{
|
||||
setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));
|
||||
|
||||
mTable = new JTable(mBroadcastModel);
|
||||
|
||||
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)mTable.getDefaultRenderer(String.class);
|
||||
renderer.setHorizontalAlignment(SwingConstants.CENTER);
|
||||
|
||||
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCASTER_STATUS).setCellRenderer(new StatusCellRenderer());
|
||||
mTable.getColumnModel().getColumn(BroadcastModel.COLUMN_BROADCAST_SERVER_TYPE).setCellRenderer(new ServerTypeRenderer());
|
||||
mColumnWidthMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTable, mPreferenceKey);
|
||||
|
||||
mScrollPane = new JScrollPane(mTable);
|
||||
|
||||
add(mScrollPane);
|
||||
}
|
||||
|
||||
public class ServerTypeRenderer extends DefaultTableCellRenderer
|
||||
{
|
||||
public ServerTypeRenderer()
|
||||
{
|
||||
setOpaque(true);
|
||||
setHorizontalAlignment(SwingConstants.CENTER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
|
||||
{
|
||||
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
|
||||
|
||||
if(value instanceof BroadcastServerType broadcastServerType)
|
||||
{
|
||||
component.setText(broadcastServerType.toString());
|
||||
Icon icon = new Icon("empty", broadcastServerType.getIconPath());
|
||||
ImageIcon imageIcon = icon.getIcon();
|
||||
ImageIcon scaledIcon = IconModel.getScaledIcon(imageIcon, 13);
|
||||
component.setIcon(scaledIcon);
|
||||
}
|
||||
else
|
||||
{
|
||||
component.setText(null);
|
||||
component.setIcon(null);
|
||||
}
|
||||
|
||||
return component;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom cell renderer for the broadcast state column.
|
||||
*/
|
||||
public class StatusCellRenderer extends DefaultTableCellRenderer
|
||||
{
|
||||
public StatusCellRenderer()
|
||||
{
|
||||
setOpaque(true);
|
||||
setHorizontalAlignment(SwingConstants.CENTER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
|
||||
boolean hasFocus, int row, int column)
|
||||
{
|
||||
JLabel component = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
|
||||
|
||||
if(isSelected)
|
||||
{
|
||||
setBackground(table.getSelectionBackground());
|
||||
setForeground(table.getSelectionForeground());
|
||||
}
|
||||
else
|
||||
{
|
||||
if(value instanceof BroadcastState)
|
||||
{
|
||||
BroadcastState state = (BroadcastState)value;
|
||||
|
||||
if(state == BroadcastState.CONNECTED)
|
||||
{
|
||||
setBackground(Color.GREEN);
|
||||
setForeground(table.getForeground());
|
||||
}
|
||||
else if(state == BroadcastState.DISABLED)
|
||||
{
|
||||
setBackground(table.getBackground());
|
||||
//Use the LAF's disabled-foreground so the cell reads correctly on any
|
||||
//theme - LIGHT_GRAY is invisible on a light background.
|
||||
Color disabled = javax.swing.UIManager.getColor("Label.disabledForeground");
|
||||
setForeground(disabled != null ? disabled : table.getForeground());
|
||||
}
|
||||
else if(state == BroadcastState.INVALID_SETTINGS ||
|
||||
state == BroadcastState.NETWORK_UNAVAILABLE)
|
||||
{
|
||||
setBackground(Color.YELLOW);
|
||||
setForeground(table.getForeground());
|
||||
}
|
||||
else if(state.isErrorState())
|
||||
{
|
||||
setBackground(Color.RED);
|
||||
setForeground(table.getForeground());
|
||||
}
|
||||
else
|
||||
{
|
||||
setBackground(table.getBackground());
|
||||
setForeground(table.getForeground());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
setForeground(table.getForeground());
|
||||
setBackground(table.getBackground());
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,30 +151,6 @@ public class ConfiguredBroadcast
|
||||
return mAudioBroadcaster != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current status for display: the broadcaster's state when there is a broadcaster, otherwise the reason that
|
||||
* there isn't one.
|
||||
*/
|
||||
public BroadcastState getStatus()
|
||||
{
|
||||
AbstractAudioBroadcaster broadcaster = mAudioBroadcaster;
|
||||
|
||||
if(broadcaster != null)
|
||||
{
|
||||
return broadcaster.getBroadcastState();
|
||||
}
|
||||
else if(!mBroadcastConfiguration.isEnabled())
|
||||
{
|
||||
return BroadcastState.DISABLED;
|
||||
}
|
||||
else if(!mBroadcastConfiguration.isValid())
|
||||
{
|
||||
return BroadcastState.INVALID_SETTINGS;
|
||||
}
|
||||
|
||||
return BroadcastState.ERROR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an observable property extractor for use with observable lists to detect changes internal to this object.
|
||||
*/
|
||||
|
||||
@@ -113,8 +113,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
|
||||
}
|
||||
else
|
||||
{
|
||||
mLog.error("Error connecting to " + getBroadcastConfiguration().getServiceName() +
|
||||
" server on startup [" + response + "]");
|
||||
mLog.error("Error connecting to Rdio Scanner server on startup [" + response + "]");
|
||||
setBroadcastState(BroadcastState.ERROR);
|
||||
}
|
||||
|
||||
@@ -250,8 +249,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
mLog.error(getBroadcastConfiguration().getServiceName() +
|
||||
" API - audio recording file not found - ignoring upload");
|
||||
mLog.error("Rdio Scanner API - audio recording file not found - ignoring upload");
|
||||
}
|
||||
|
||||
if(audioBytes != null)
|
||||
@@ -288,14 +286,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(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
|
||||
mLog.error("Rdio Scanner API file upload fail [" +
|
||||
fileResponse.statusCode() + "] response [" +
|
||||
fileResponse.body() + "]");
|
||||
}
|
||||
else
|
||||
{
|
||||
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
|
||||
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
|
||||
mLog.error("Rdio Scanner API file upload fail [" +
|
||||
fileResponse.statusCode() + "] response [" +
|
||||
fileResponse.body() + "]");
|
||||
}
|
||||
@@ -323,7 +321,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
|
||||
else
|
||||
{
|
||||
setBroadcastState(BroadcastState.TEMPORARY_BROADCAST_ERROR);
|
||||
mLog.error(getBroadcastConfiguration().getServiceName() + " API file upload fail [" +
|
||||
mLog.error("Rdio Scanner API file upload fail [" +
|
||||
fileResponse.statusCode() + "] response [" +
|
||||
fileResponse.body() + "]");
|
||||
}
|
||||
@@ -336,7 +334,7 @@ public class RdioScannerBroadcaster extends AbstractAudioBroadcaster<RdioScanner
|
||||
else
|
||||
{
|
||||
//Register an error for the file not found exception
|
||||
mLog.error(getBroadcastConfiguration().getServiceName() + " API - upload file not found [" +
|
||||
mLog.error("Rdio Scanner API - upload file not found [" +
|
||||
audioRecording.getPath().toString() + "]");
|
||||
incrementErrorAudioCount();
|
||||
broadcast(new BroadcastEvent(RdioScannerBroadcaster.this,
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
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;
|
||||
@@ -126,15 +125,6 @@ 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()
|
||||
{
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.audio.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;
|
||||
}
|
||||
}
|
||||
@@ -41,11 +41,11 @@ public abstract class AmbeAudioModule extends JmbeAudioModule
|
||||
{
|
||||
if(getAudioCodec() != null)
|
||||
{
|
||||
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio can be processed");
|
||||
mLog.info("AMBE CODEC successfully loaded - P25-2/DMR/NXDN audio will be available");
|
||||
}
|
||||
else
|
||||
{
|
||||
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be processed");
|
||||
mLog.warn("AMBE CODEC not loaded - P25-2/DMR/NXDN audio will NOT be available");
|
||||
}
|
||||
|
||||
sLibraryStatusLogged = true;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
* Copyright (C) 2014-2024 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@@ -37,14 +37,10 @@ import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import jmbe.frame.ICorrectedFrame;
|
||||
import jmbe.iface.IAudioCodec;
|
||||
import jmbe.iface.IAudioCodecLibrary;
|
||||
import jmbe.iface.IAudioCodecLibraryV2;
|
||||
import jmbe.iface.IAudioCodecLibraryV3;
|
||||
import jmbe.iface.IAudioCodecV2;
|
||||
import jmbe.iface.IAudioCodecV3;
|
||||
import jmbe.iface.IAudioWithMetadata;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@@ -56,13 +52,6 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
|
||||
{
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JmbeAudioModule.class);
|
||||
private static final String JMBE_AUDIO_LIBRARY = "JMBE";
|
||||
|
||||
/**
|
||||
* JMBE library entry point class names, newest first. The loader uses the newest version that the library
|
||||
* provides, falling back to older versions for libraries created by older JMBE releases.
|
||||
*/
|
||||
private static final List<String> JMBE_LIBRARY_CLASS_NAMES = List.of("jmbe.JMBEAudioLibraryV3",
|
||||
"jmbe.JMBEAudioLibraryV2", "jmbe.JMBEAudioLibrary");
|
||||
private static final List<String> mLibraryLoadStatusLogged = new ArrayList<>();
|
||||
private IAudioCodec mAudioCodec;
|
||||
private final UserPreferences mUserPreferences;
|
||||
@@ -139,56 +128,6 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
|
||||
return getAudioCodec() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the loaded audio codec can synthesize audio from a voice frame that sdrtrunk has already error
|
||||
* corrected. Only JMBE version 3 libraries support this. Version 1 and 2 libraries only accept the raw voice
|
||||
* frame bytes and perform the error detection and correction themselves.
|
||||
*
|
||||
* Callers can use this to skip creating corrected frames when the codec can't use them.
|
||||
*/
|
||||
protected boolean isCorrectedFrameSupported()
|
||||
{
|
||||
return mAudioCodec instanceof IAudioCodecV3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesizes audio for the voice frame. When the codec supports it (JMBE version 3), the audio is synthesized
|
||||
* from the corrected frame so the codec doesn't repeat the error detection and correction. Otherwise, the raw
|
||||
* frame bytes are passed to the codec (JMBE version 1 and 2).
|
||||
*
|
||||
* @param frame bytes for the voice frame as transmitted
|
||||
* @param correctedFrame for the same voice frame, or null to let the codec perform the error correction
|
||||
* @return audio samples
|
||||
*/
|
||||
protected float[] getAudio(byte[] frame, ICorrectedFrame correctedFrame)
|
||||
{
|
||||
if(correctedFrame != null && mAudioCodec instanceof IAudioCodecV3 v3)
|
||||
{
|
||||
return v3.getAudio(correctedFrame);
|
||||
}
|
||||
|
||||
return mAudioCodec.getAudio(frame);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesizes audio with optional metadata (tones, DTMF, etc.) for the voice frame. When the codec supports it
|
||||
* (JMBE version 3), the audio is synthesized from the corrected frame so the codec doesn't repeat the error
|
||||
* detection and correction. Otherwise, the raw frame bytes are passed to the codec (JMBE version 1 and 2).
|
||||
*
|
||||
* @param frame bytes for the voice frame as transmitted
|
||||
* @param correctedFrame for the same voice frame, or null to let the codec perform the error correction
|
||||
* @return audio samples with optional metadata
|
||||
*/
|
||||
protected IAudioWithMetadata getAudioWithMetadata(byte[] frame, ICorrectedFrame correctedFrame)
|
||||
{
|
||||
if(correctedFrame != null && mAudioCodec instanceof IAudioCodecV3 v3)
|
||||
{
|
||||
return v3.getAudioWithMetadata(correctedFrame);
|
||||
}
|
||||
|
||||
return mAudioCodec.getAudioWithMetadata(frame);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Listener<IMessage> getMessageListener()
|
||||
{
|
||||
@@ -238,25 +177,26 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
|
||||
URLClassLoader childClassLoader = new URLClassLoader(new URL[]{path.toUri().toURL()},
|
||||
this.getClass().getClassLoader());
|
||||
|
||||
for(String className: JMBE_LIBRARY_CLASS_NAMES)
|
||||
try
|
||||
{
|
||||
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibraryV2", true, childClassLoader);
|
||||
}
|
||||
catch(ClassNotFoundException legacyLibrary)
|
||||
{
|
||||
try
|
||||
{
|
||||
sLoadedJmbeAudioConverterClass = Class.forName(className, true, childClassLoader);
|
||||
break;
|
||||
sLoadedJmbeAudioConverterClass = Class.forName("jmbe.JMBEAudioLibrary", true, childClassLoader);
|
||||
}
|
||||
catch(ClassNotFoundException notFound)
|
||||
catch(ClassNotFoundException missingLibrary)
|
||||
{
|
||||
//Library doesn't contain this version of the library class - try the next older version
|
||||
if(!mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
|
||||
{
|
||||
LOG.error("Couldn't load JMBE audio conversion library from [" + path +
|
||||
"] - neither V2 nor V1 library class was found");
|
||||
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(sLoadedJmbeAudioConverterClass == null && !mLibraryLoadStatusLogged.contains(JMBE_AUDIO_LIBRARY))
|
||||
{
|
||||
LOG.error("Couldn't load JMBE audio conversion library from [" + path +
|
||||
"] - none of the library classes " + JMBE_LIBRARY_CLASS_NAMES + " were found");
|
||||
mLibraryLoadStatusLogged.add(JMBE_AUDIO_LIBRARY);
|
||||
}
|
||||
}
|
||||
catch(IllegalArgumentException iae)
|
||||
{
|
||||
@@ -289,18 +229,9 @@ public abstract class JmbeAudioModule extends AbstractAudioModule implements Lis
|
||||
if((library.getMajorVersion() == 1 && library.getMinorVersion() >= 0 &&
|
||||
library.getBuildVersion() >= 0) || library.getMajorVersion() >= 1)
|
||||
{
|
||||
if(library instanceof IAudioCodecLibraryV3 libraryV3)
|
||||
{
|
||||
audioConverter = libraryV3.getAudioConverterV3(getCodecName());
|
||||
}
|
||||
else if(library instanceof IAudioCodecLibraryV2 libraryV2)
|
||||
{
|
||||
audioConverter = libraryV2.getAudioConverterV2(getCodecName());
|
||||
}
|
||||
else
|
||||
{
|
||||
audioConverter = library.getAudioConverter(getCodecName());
|
||||
}
|
||||
audioConverter = library instanceof IAudioCodecLibraryV2 libraryV2 ?
|
||||
libraryV2.getAudioConverterV2(getCodecName()) :
|
||||
library.getAudioConverter(getCodecName());
|
||||
|
||||
String codecStatusKey = JMBE_AUDIO_LIBRARY + ":codec:" + getCodecName();
|
||||
if(!mLibraryLoadStatusLogged.contains(codecStatusKey))
|
||||
|
||||
@@ -36,7 +36,7 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Collection;
|
||||
import jmbe.frame.CorrectedIMBEFrame;
|
||||
import jmbe.iface.IAudioCodec;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.filefilter.DirectoryFileFilter;
|
||||
import org.apache.commons.io.filefilter.SuffixFileFilter;
|
||||
@@ -111,15 +111,12 @@ public class MBECallSequenceConverter
|
||||
}
|
||||
}
|
||||
|
||||
boolean correctFrames = audioModule.isCorrectedFrameSupported();
|
||||
IAudioCodec codec = audioModule.getAudioCodec();
|
||||
|
||||
for(VoiceFrame voiceFrame: callSequence.getVoiceFrames())
|
||||
{
|
||||
byte[] frameBytes = voiceFrame.getFrameBytes();
|
||||
|
||||
//Only error correct the frame in sdrtrunk when the JMBE library (version 3+) can synthesize from it
|
||||
float[] audio = audioModule.getAudio(frameBytes,
|
||||
correctFrames ? CorrectedIMBEFrame.correct(frameBytes) : null);
|
||||
float[] audio = codec.getAudio(frameBytes);
|
||||
audioModule.addAudio(audio);
|
||||
}
|
||||
|
||||
|
||||
@@ -97,114 +97,41 @@ public class MP3AudioConverter implements IAudioConverter
|
||||
audioPackets = mResampler.resample(audioPackets);
|
||||
}
|
||||
|
||||
for(float[] audioPacket: audioPackets)
|
||||
for(int x = 0; x < audioPackets.size(); x++)
|
||||
{
|
||||
encodePacket(audioPacket, converted);
|
||||
}
|
||||
byte[] bytesToEncode = null;
|
||||
|
||||
int finalChunkSize = mEncoder.encodeFinish(mOutputFramesBuffer);
|
||||
|
||||
if(finalChunkSize > 0)
|
||||
{
|
||||
converted.add(Arrays.copyOf(mOutputFramesBuffer, finalChunkSize));
|
||||
}
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the PCM audio packet (already resampled) and adds any encoded MP3 frames to the list.
|
||||
*/
|
||||
private void encodePacket(float[] audioPacket, List<byte[]> converted)
|
||||
{
|
||||
byte[] bytesToEncode;
|
||||
|
||||
if(mInputAudioFormat.getAudioFormat().getSampleSizeInBits() == 16)
|
||||
{
|
||||
bytesToEncode = ConversionUtils.convertToSigned16BitSamples(audioPacket).array();
|
||||
}
|
||||
else
|
||||
{
|
||||
bytesToEncode = ConversionUtils.convertToSigned32BitSamples(audioPacket).array();
|
||||
}
|
||||
|
||||
int bytesToEncodePointer = 0;
|
||||
|
||||
int inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length);
|
||||
int outputChunkSize = 0;
|
||||
|
||||
try
|
||||
{
|
||||
while(bytesToEncodePointer < bytesToEncode.length)
|
||||
if(mInputAudioFormat.getAudioFormat().getSampleSizeInBits() == 16)
|
||||
{
|
||||
outputChunkSize = mEncoder.encodeBuffer(bytesToEncode, bytesToEncodePointer, inputChunkSize, mOutputFramesBuffer);
|
||||
bytesToEncodePointer += inputChunkSize;
|
||||
inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length - bytesToEncodePointer);
|
||||
bytesToEncode = ConversionUtils.convertToSigned16BitSamples(audioPackets.get(x)).array();
|
||||
}
|
||||
else
|
||||
{
|
||||
bytesToEncode = ConversionUtils.convertToSigned32BitSamples(audioPackets.get(x)).array();
|
||||
}
|
||||
|
||||
if(outputChunkSize > 0)
|
||||
int bytesToEncodePointer = 0;
|
||||
|
||||
int inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length);
|
||||
int outputChunkSize = 0;
|
||||
|
||||
try
|
||||
{
|
||||
while(bytesToEncodePointer < bytesToEncode.length)
|
||||
{
|
||||
converted.add(Arrays.copyOf(mOutputFramesBuffer, outputChunkSize));
|
||||
outputChunkSize = mEncoder.encodeBuffer(bytesToEncode, bytesToEncodePointer, inputChunkSize, mOutputFramesBuffer);
|
||||
bytesToEncodePointer += inputChunkSize;
|
||||
inputChunkSize = FastMath.min(mOutputFramesBuffer.length, bytesToEncode.length - bytesToEncodePointer);
|
||||
|
||||
if(outputChunkSize > 0)
|
||||
{
|
||||
converted.add(Arrays.copyOf(mOutputFramesBuffer, outputChunkSize));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.error("There was an error converting audio to MP3: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a chunk of a continuing audio stream to MP3. Unlike {@link #convert(List)}, the encoder and resampler
|
||||
* keep their state between invocations, so the chunks of a call are encoded as one continuous stream. Invoke
|
||||
* {@link #finishStream()} after the last chunk. Note: audio normalization is not applied.
|
||||
*
|
||||
* @param audioPackets of PCM audio sampled at 8 kHz
|
||||
* @return encoded MP3 frames, possibly empty
|
||||
*/
|
||||
public List<byte[]> encodeStream(List<float[]> audioPackets)
|
||||
{
|
||||
List<byte[]> converted = new ArrayList<>();
|
||||
|
||||
if(mResampler != null)
|
||||
{
|
||||
List<float[]> resampled = new ArrayList<>();
|
||||
mResampler.setListener(resampled::add);
|
||||
|
||||
for(float[] audioPacket: audioPackets)
|
||||
catch(Exception e)
|
||||
{
|
||||
mResampler.resample(audioPacket);
|
||||
}
|
||||
|
||||
mResampler.setListener(null);
|
||||
audioPackets = resampled;
|
||||
}
|
||||
|
||||
for(float[] audioPacket: audioPackets)
|
||||
{
|
||||
encodePacket(audioPacket, converted);
|
||||
}
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes the resampler and the encoder at the end of a stream encoded with {@link #encodeStream(List)}.
|
||||
* @return final encoded MP3 frames
|
||||
*/
|
||||
public List<byte[]> finishStream()
|
||||
{
|
||||
List<byte[]> converted = new ArrayList<>();
|
||||
|
||||
if(mResampler != null)
|
||||
{
|
||||
List<float[]> resampled = new ArrayList<>();
|
||||
mResampler.setListener(resampled::add);
|
||||
mResampler.flush();
|
||||
mResampler.setListener(null);
|
||||
|
||||
for(float[] audioPacket: resampled)
|
||||
{
|
||||
encodePacket(audioPacket, converted);
|
||||
mLog.error("There was an error converting audio to MP3: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ import io.github.dsheirer.sample.Broadcaster;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.LinkedTransferQueue;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import org.slf4j.Logger;
|
||||
@@ -59,19 +58,13 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
private final LinkedTransferQueue<AudioSegment> mAudioSegmentQueue = new LinkedTransferQueue<>();
|
||||
private final UserPreferences mUserPreferences;
|
||||
private final String mChannelName;
|
||||
private final AtomicInteger mPeakLevelBits = new AtomicInteger();
|
||||
|
||||
private volatile AudioSegment mCurrentAudioSegment;
|
||||
private AudioSegment mCurrentAudioSegment;
|
||||
private Listener<IdentifierCollection> mIdentifierCollectionListener;
|
||||
private boolean mDropDuplicates;
|
||||
private boolean mMetadataSent = false;
|
||||
private boolean mMuted;
|
||||
private boolean mDisabled;
|
||||
private volatile TalkgroupHold mHold;
|
||||
private Listener<TalkgroupHold> mHoldListener;
|
||||
private volatile Runnable mPlaybackListener;
|
||||
private volatile ReplaySource mPendingReplay;
|
||||
private volatile ReplaySource mReplay;
|
||||
private float[] mAudioSegmentStartTone;
|
||||
private float[] mAudioSegmentDropTone;
|
||||
private int mCurrentBufferIndex = -1;
|
||||
@@ -112,114 +105,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold talkgroup for this channel, or null. While a talkgroup is held, only calls to the talkgroup play on this
|
||||
* channel, including calls that are otherwise flagged as do-not-monitor. The audio playback manager is
|
||||
* responsible for steering calls to the channel; use {@link AudioPlaybackManager#setHold(int, TalkgroupHold)}.
|
||||
*/
|
||||
public TalkgroupHold getHold()
|
||||
{
|
||||
return mHold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or clears (null) the hold talkgroup. A call that is playing and doesn't match the hold talkgroup stops
|
||||
* at the next audio interval.
|
||||
*/
|
||||
void setHold(TalkgroupHold hold)
|
||||
{
|
||||
mHold = hold;
|
||||
|
||||
Listener<TalkgroupHold> listener = mHoldListener;
|
||||
|
||||
if(listener != null)
|
||||
{
|
||||
listener.receive(hold);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a single listener to be notified when the hold talkgroup is set (non-null) or cleared (null).
|
||||
*/
|
||||
public void setHoldListener(Listener<TalkgroupHold> listener)
|
||||
{
|
||||
mHoldListener = listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the audio segment is allowed on this channel by the hold talkgroup.
|
||||
*/
|
||||
public boolean isAllowedByHold(AudioSegment audioSegment)
|
||||
{
|
||||
TalkgroupHold hold = mHold;
|
||||
return hold == null || hold.matches(audioSegment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this channel is currently playing (or about to play) a call to its hold talkgroup.
|
||||
*/
|
||||
boolean isPlayingHeldTalkgroup()
|
||||
{
|
||||
TalkgroupHold hold = mHold;
|
||||
AudioSegment current = mCurrentAudioSegment;
|
||||
return hold != null && current != null && hold.matches(current);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a single listener to be notified when this channel starts or stops playing a call audio segment or a
|
||||
* replay. The listener reads the state from {@link #getCurrentAudioSegment()} and {@link #getReplay()}. Notified
|
||||
* on the audio playback thread. Used by the audio playback manager.
|
||||
*/
|
||||
void setPlaybackListener(Runnable listener)
|
||||
{
|
||||
mPlaybackListener = listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays the recorded call on this channel. The replay takes over the channel at the next audio interval: a
|
||||
* call that is playing is dropped and a replay that is playing is stopped. Calls queued for the channel play
|
||||
* after the replay finishes. Use {@link AudioPlaybackManager#replay(ReplaySource)}.
|
||||
*/
|
||||
void startReplay(ReplaySource replay)
|
||||
{
|
||||
mPendingReplay = replay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay that is playing on this channel, or null.
|
||||
*/
|
||||
public ReplaySource getReplay()
|
||||
{
|
||||
return mReplay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this channel is replaying (or about to replay) a recorded call.
|
||||
*/
|
||||
public boolean isReplaying()
|
||||
{
|
||||
ReplaySource replay = mReplay;
|
||||
return mPendingReplay != null || (replay != null && !replay.isFinished());
|
||||
}
|
||||
|
||||
/**
|
||||
* Audio segment that this channel is currently playing, or null.
|
||||
*/
|
||||
public AudioSegment getCurrentAudioSegment()
|
||||
{
|
||||
return mCurrentAudioSegment;
|
||||
}
|
||||
|
||||
private void notifyPlayback()
|
||||
{
|
||||
Runnable listener = mPlaybackListener;
|
||||
|
||||
if(listener != null)
|
||||
{
|
||||
listener.run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this audio channel is enabled.
|
||||
*/
|
||||
@@ -268,7 +153,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
*/
|
||||
public boolean hasAudioSegment()
|
||||
{
|
||||
return mCurrentAudioSegment != null || mReplay != null;
|
||||
return mCurrentAudioSegment != null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,75 +174,20 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
*/
|
||||
public float[] getAudio()
|
||||
{
|
||||
float[] audio = getNextAudio();
|
||||
|
||||
if(audio != null)
|
||||
if(mAudioBuffer.isFull())
|
||||
{
|
||||
updatePeakLevel(audio);
|
||||
float[] audio = mAudioBuffer.get();
|
||||
|
||||
//Muted channels return silence. The peak level is measured before muting so that the display can still
|
||||
//show that the muted channel has audio.
|
||||
if(isMuted())
|
||||
{
|
||||
return new float[SAMPLES_PER_INTERVAL];
|
||||
}
|
||||
}
|
||||
|
||||
return audio;
|
||||
}
|
||||
|
||||
/**
|
||||
* Peak absolute sample value of the audio provided by this channel since the last call to this method, measured
|
||||
* before muting. The audio output pulls audio ahead of playback, so this leads what is heard by the playback
|
||||
* device buffer latency. Thread safe.
|
||||
* @return peak level in the range 0.0 to 1.0 (or higher, if the audio is clipping) and resets it to zero.
|
||||
*/
|
||||
public float getAndResetPeakLevel()
|
||||
{
|
||||
return Float.intBitsToFloat(mPeakLevelBits.getAndSet(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the peak level with the maximum absolute sample value of the audio buffer.
|
||||
*/
|
||||
private void updatePeakLevel(float[] audio)
|
||||
{
|
||||
float peak = 0.0f;
|
||||
|
||||
for(float sample: audio)
|
||||
{
|
||||
float magnitude = Math.abs(sample);
|
||||
|
||||
if(magnitude > peak)
|
||||
else
|
||||
{
|
||||
peak = magnitude;
|
||||
return audio;
|
||||
}
|
||||
}
|
||||
|
||||
final float bufferPeak = peak;
|
||||
|
||||
//Non-negative float bit patterns sort the same as the float values
|
||||
mPeakLevelBits.accumulateAndGet(Float.floatToIntBits(bufferPeak), Math::max);
|
||||
}
|
||||
|
||||
/**
|
||||
* Next interval of audio from the audio buffer or the current audio segment, before muting.
|
||||
* @return audio or null
|
||||
*/
|
||||
private float[] getNextAudio()
|
||||
{
|
||||
float[] replayAudio = getReplayAudio();
|
||||
|
||||
if(replayAudio != null)
|
||||
{
|
||||
return replayAudio;
|
||||
}
|
||||
|
||||
if(mAudioBuffer.isFull())
|
||||
{
|
||||
return mAudioBuffer.get();
|
||||
}
|
||||
|
||||
if(mCurrentAudioSegment == null)
|
||||
{
|
||||
loadNextAudioSegment();
|
||||
@@ -419,54 +249,10 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
audio = mAudioBuffer.flush();
|
||||
}
|
||||
|
||||
return audio;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a pending replay and provides the next replay audio. Audio thread.
|
||||
* @return replay audio, or null when no replay is playing (normal call playback continues)
|
||||
*/
|
||||
private float[] getReplayAudio()
|
||||
{
|
||||
ReplaySource pending = mPendingReplay;
|
||||
|
||||
if(pending != null)
|
||||
//Finally, if we have buffer audio and we're muted, return silence
|
||||
if(isMuted() && audio != null)
|
||||
{
|
||||
mPendingReplay = null;
|
||||
|
||||
if(mReplay != null)
|
||||
{
|
||||
mReplay.stop();
|
||||
}
|
||||
|
||||
//The replay takes over the channel: drop the buffered audio and the call that is playing
|
||||
mAudioBuffer.flush();
|
||||
|
||||
if(mCurrentAudioSegment != null)
|
||||
{
|
||||
disposeCurrentAudioSegment();
|
||||
clearMetadata();
|
||||
}
|
||||
|
||||
mReplay = pending;
|
||||
notifyPlayback();
|
||||
notify(AudioEvent.Type.REPLAY_STARTED);
|
||||
}
|
||||
|
||||
ReplaySource replay = mReplay;
|
||||
|
||||
if(replay == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
float[] audio = replay.next();
|
||||
|
||||
if(audio == null)
|
||||
{
|
||||
mReplay = null;
|
||||
notifyPlayback();
|
||||
notify(AudioEvent.Type.REPLAY_STOPPED);
|
||||
audio = new float[SAMPLES_PER_INTERVAL];
|
||||
}
|
||||
|
||||
return audio;
|
||||
@@ -512,20 +298,7 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
*/
|
||||
private boolean isThrowaway(AudioSegment audioSegment)
|
||||
{
|
||||
if(audioSegment == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
TalkgroupHold hold = mHold;
|
||||
|
||||
if(hold != null)
|
||||
{
|
||||
//A held talkgroup plays even when do-not-monitor, and nothing else plays on a held channel
|
||||
return !hold.matches(audioSegment) || (mDropDuplicates && audioSegment.isDuplicate());
|
||||
}
|
||||
|
||||
return audioSegment.isDoNotMonitor() || mDropDuplicates && (audioSegment.isDuplicate());
|
||||
return audioSegment != null && (audioSegment.isDoNotMonitor() || mDropDuplicates && (audioSegment.isDuplicate()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -571,18 +344,9 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
{
|
||||
|
||||
MyEventBus.getGlobalEventBus().unregister(this);
|
||||
ReplaySource replay = mReplay;
|
||||
|
||||
if(replay != null)
|
||||
{
|
||||
replay.stop();
|
||||
}
|
||||
|
||||
disposeCurrentAudioSegment();
|
||||
mAudioEventBroadcaster.clear();
|
||||
mIdentifierCollectionListener = null;
|
||||
mHoldListener = null;
|
||||
mPlaybackListener = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -693,7 +457,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
mCurrentAudioSegment.decrementConsumerCount();
|
||||
mCurrentAudioSegment.removeIdentifierUpdateNotificationListener(this);
|
||||
mCurrentAudioSegment = null;
|
||||
notifyPlayback();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -731,7 +494,6 @@ public class AudioChannel implements Listener<IdentifierUpdateNotification>
|
||||
|
||||
if(audioSegment != null)
|
||||
{
|
||||
notifyPlayback();
|
||||
mCurrentAudioSegment.addIdentifierUpdateNotificationListener(this);
|
||||
broadcast(mCurrentAudioSegment.getIdentifierCollection());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.playback;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.eventbus.Subscribe;
|
||||
import io.github.dsheirer.alias.Alias;
|
||||
import io.github.dsheirer.alias.AliasList;
|
||||
import io.github.dsheirer.alias.AliasModel;
|
||||
import io.github.dsheirer.audio.AudioEvent;
|
||||
import io.github.dsheirer.eventbus.MyEventBus;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.identifier.Identifier;
|
||||
import io.github.dsheirer.identifier.IdentifierClass;
|
||||
import io.github.dsheirer.identifier.IdentifierCollection;
|
||||
import io.github.dsheirer.identifier.Role;
|
||||
import io.github.dsheirer.preference.PreferenceType;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.preference.identifier.TalkgroupFormatPreference;
|
||||
import io.github.dsheirer.properties.SystemProperties;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import io.github.dsheirer.settings.ColorSetting;
|
||||
import io.github.dsheirer.settings.Setting;
|
||||
import io.github.dsheirer.settings.SettingChangeListener;
|
||||
import io.github.dsheirer.settings.SettingsManager;
|
||||
import java.awt.Color;
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.Font;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.swing.ImageIcon;
|
||||
import javax.swing.JLabel;
|
||||
import javax.swing.JPanel;
|
||||
|
||||
/**
|
||||
* UI to wrap an audio channel and provide display of metadata and playback state information.
|
||||
*/
|
||||
public class AudioChannelPanel extends JPanel implements Listener<AudioEvent>, SettingChangeListener
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Logger mLog = LoggerFactory.getLogger(AudioChannelPanel.class);
|
||||
|
||||
public static final String PROPERTY_PREFIX = "audio.channel.panel.color.";
|
||||
public static final String PROPERTY_COLOR_BACKGROUND = PROPERTY_PREFIX + "background";
|
||||
public static final String PROPERTY_COLOR_LABEL = PROPERTY_PREFIX + "label";
|
||||
public static final String PROPERTY_COLOR_MUTED = PROPERTY_PREFIX + "muted";
|
||||
public static final String PROPERTY_COLOR_VALUE = PROPERTY_PREFIX + "value";
|
||||
|
||||
private final AudioChannel mAudioChannel;
|
||||
private final AliasModel mAliasModel;
|
||||
private final IconModel mIconModel;
|
||||
private final SettingsManager mSettingsManager;
|
||||
private final UserPreferences mUserPreferences;
|
||||
private final TalkgroupFormatPreference mTalkgroupFormatPreference;
|
||||
private Identifier mIdentifier;
|
||||
private List<Alias> mAliases = Collections.EMPTY_LIST;
|
||||
private final Lock mLock = new ReentrantLock();
|
||||
|
||||
private final Font mFont = new Font(Font.MONOSPACED, Font.PLAIN, 16);
|
||||
private final Color mBackgroundColor;
|
||||
private final Color mLabelColor;
|
||||
private final Color mMutedColor;
|
||||
private final Color mValueColor;
|
||||
private final JLabel mMutedLabel = new JLabel("M");
|
||||
private JLabel mChannelName = new JLabel(" ");
|
||||
private final JLabel mIconLabel = new JLabel(" ");
|
||||
private final JLabel mIdentifierLabel = new JLabel("-----");
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param audioChannel to wrap by this panel
|
||||
* @param aliasModel for alias lookup
|
||||
* @param iconModel for icon lookup
|
||||
* @param settingsManager for monitoring changes to tone insertion
|
||||
* @param userPreferences for lookup of tone and other preferences
|
||||
*/
|
||||
public AudioChannelPanel(AudioChannel audioChannel, AliasModel aliasModel, IconModel iconModel,
|
||||
SettingsManager settingsManager, UserPreferences userPreferences)
|
||||
{
|
||||
mIconModel = iconModel;
|
||||
mSettingsManager = settingsManager;
|
||||
mSettingsManager.addListener(this);
|
||||
mAliasModel = aliasModel;
|
||||
mUserPreferences = userPreferences;
|
||||
mTalkgroupFormatPreference = mUserPreferences.getTalkgroupFormatPreference();
|
||||
mAudioChannel = audioChannel;
|
||||
|
||||
if(mAudioChannel != null)
|
||||
{
|
||||
mAudioChannel.addAudioEventListener(this);
|
||||
mAudioChannel.setIdentifierCollectionListener(new AudioMetadataProcessor());
|
||||
}
|
||||
|
||||
mBackgroundColor = SystemProperties.getInstance().get(PROPERTY_COLOR_BACKGROUND, Color.BLACK);
|
||||
mLabelColor = SystemProperties.getInstance().get(PROPERTY_COLOR_LABEL, Color.LIGHT_GRAY);
|
||||
mMutedColor = SystemProperties.getInstance().get(PROPERTY_COLOR_MUTED, Color.RED);
|
||||
mValueColor = SystemProperties.getInstance().get(PROPERTY_COLOR_VALUE, Color.GREEN);
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Receives preference update notifications via the event bus
|
||||
* @param preferenceType that was updated
|
||||
*/
|
||||
@Subscribe
|
||||
public void preferenceUpdated(PreferenceType preferenceType)
|
||||
{
|
||||
if(preferenceType == PreferenceType.TALKGROUP_FORMAT)
|
||||
{
|
||||
updateLabels();
|
||||
}
|
||||
}
|
||||
|
||||
public void dispose()
|
||||
{
|
||||
//Deregister from receiving preference update notifications
|
||||
MyEventBus.getGlobalEventBus().unregister(this);
|
||||
|
||||
if(mAudioChannel != null)
|
||||
{
|
||||
mAudioChannel.removeAudioEventListener(this);
|
||||
mAudioChannel.removeAudioMetadataListener();
|
||||
}
|
||||
}
|
||||
|
||||
private void init()
|
||||
{
|
||||
//Register to receive preference updates
|
||||
MyEventBus.getGlobalEventBus().register(this);
|
||||
|
||||
setLayout(new MigLayout("align center center, insets 0 0 0 0",
|
||||
"[][][align right]0[grow,fill]", ""));
|
||||
setBackground(mBackgroundColor);
|
||||
|
||||
mMutedLabel.setFont(mFont);
|
||||
mMutedLabel.setForeground(mMutedColor);
|
||||
mMutedLabel.setVisible(false);
|
||||
add(mMutedLabel);
|
||||
|
||||
mChannelName = new JLabel(mAudioChannel != null ? mAudioChannel.getChannelName() : " ");
|
||||
mChannelName.setFont(mFont);
|
||||
mChannelName.setForeground(mLabelColor);
|
||||
add(mChannelName);
|
||||
|
||||
mIconLabel.setFont(mFont);
|
||||
mIconLabel.setForeground(mValueColor);
|
||||
add(mIconLabel);
|
||||
|
||||
mIdentifierLabel.setFont(mFont);
|
||||
mIdentifierLabel.setForeground(mValueColor);
|
||||
add(mIdentifierLabel, "wmin 10lp");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receive(final AudioEvent audioEvent)
|
||||
{
|
||||
switch(audioEvent.getType())
|
||||
{
|
||||
case AUDIO_STOPPED:
|
||||
EventQueue.invokeLater(this::resetLabels);
|
||||
break;
|
||||
case AUDIO_MUTED:
|
||||
case AUDIO_UNMUTED:
|
||||
EventQueue.invokeLater(() -> mMutedLabel.setVisible(mAudioChannel.isMuted()));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the from and to labels.
|
||||
*/
|
||||
private void resetLabels()
|
||||
{
|
||||
//Protect access to mIdentifier and mAliases
|
||||
mLock.lock();
|
||||
|
||||
try
|
||||
{
|
||||
boolean updated = mIdentifier != null;
|
||||
mIdentifier = null;
|
||||
mAliases = Collections.EMPTY_LIST;
|
||||
|
||||
//Hold the lock through the label update
|
||||
if(updated)
|
||||
{
|
||||
updateLabels();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
mLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateIdentifiers(IdentifierCollection identifierCollection)
|
||||
{
|
||||
if(identifierCollection == null || identifierCollection.isEmpty())
|
||||
{
|
||||
resetLabels();
|
||||
return;
|
||||
}
|
||||
|
||||
List<Identifier> toIds = identifierCollection.getIdentifiers(IdentifierClass.USER, Role.TO);
|
||||
|
||||
if(toIds.isEmpty())
|
||||
{
|
||||
resetLabels();
|
||||
return;
|
||||
}
|
||||
|
||||
boolean updated = false;
|
||||
|
||||
//Protect access to mIdentifier and mAliases
|
||||
mLock.lock();
|
||||
|
||||
try
|
||||
{
|
||||
if(toIds.size() == 1)
|
||||
{
|
||||
Identifier currentIdentifier = mIdentifier;
|
||||
|
||||
if(currentIdentifier == null || currentIdentifier != toIds.get(0))
|
||||
{
|
||||
mIdentifier = toIds.get(0);
|
||||
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
|
||||
|
||||
if(aliasList != null)
|
||||
{
|
||||
mAliases = aliasList.getAliases(mIdentifier);
|
||||
}
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
mIdentifier = toIds.get(0);
|
||||
AliasList aliasList = mAliasModel.getAliasList(identifierCollection);
|
||||
|
||||
if(aliasList != null)
|
||||
{
|
||||
mAliases = aliasList.getAliases(mIdentifier);
|
||||
}
|
||||
updated = true;
|
||||
}
|
||||
|
||||
//Hold the lock through the label update
|
||||
if(updated)
|
||||
{
|
||||
updateLabels();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
mLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the alias label with text and icon from the alias.
|
||||
*/
|
||||
private void updateLabels()
|
||||
{
|
||||
String identifier = null;
|
||||
String iconName = null;
|
||||
|
||||
//Protect access to mIdentifier and mAliases
|
||||
mLock.lock();
|
||||
|
||||
try
|
||||
{
|
||||
if(mAliases.size() == 1)
|
||||
{
|
||||
identifier = mAliases.get(0).getName();
|
||||
iconName = mAliases.get(0).getIconName();
|
||||
}
|
||||
else if(mAliases.size() > 1)
|
||||
{
|
||||
identifier = Joiner.on(", ").skipNulls().join(mAliases);
|
||||
}
|
||||
|
||||
if(identifier == null && mIdentifier != null)
|
||||
{
|
||||
identifier = mTalkgroupFormatPreference.format(mIdentifier);
|
||||
}
|
||||
|
||||
if(identifier == null)
|
||||
{
|
||||
identifier = "-----";
|
||||
}
|
||||
|
||||
final ImageIcon icon = iconName != null ? mIconModel.getIcon(iconName, 18) : null;
|
||||
final String identifierText = identifier;
|
||||
|
||||
EventQueue.invokeLater(() -> {
|
||||
mIdentifierLabel.setText(identifierText);
|
||||
mIconLabel.setIcon(icon);
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
mLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes audio metadata to update this panel's display values
|
||||
*/
|
||||
public class AudioMetadataProcessor implements Listener<IdentifierCollection>
|
||||
{
|
||||
@Override
|
||||
public void receive(final IdentifierCollection identifierCollection)
|
||||
{
|
||||
updateIdentifiers(identifierCollection);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void settingChanged(Setting setting)
|
||||
{
|
||||
if(setting instanceof ColorSetting)
|
||||
{
|
||||
ColorSetting colorSetting = (ColorSetting)setting;
|
||||
|
||||
switch(colorSetting.getColorSettingName())
|
||||
{
|
||||
case CHANNEL_STATE_LABEL_DECODER:
|
||||
EventQueue.invokeLater(() -> {
|
||||
if(mIdentifierLabel != null)
|
||||
{
|
||||
mIdentifierLabel.setForeground(mLabelColor);
|
||||
}
|
||||
if(mIconLabel != null)
|
||||
{
|
||||
mIconLabel.setForeground(mLabelColor);
|
||||
}
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void settingDeleted(Setting setting)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.playback;
|
||||
|
||||
import io.github.dsheirer.alias.AliasModel;
|
||||
import io.github.dsheirer.audio.IAudioController;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.settings.SettingsManager;
|
||||
import java.awt.Color;
|
||||
import java.awt.Component;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
|
||||
import javax.swing.JPanel;
|
||||
import javax.swing.JSeparator;
|
||||
|
||||
/**
|
||||
* Displays one or more audio channel panels.
|
||||
*/
|
||||
public class AudioChannelsPanel extends JPanel
|
||||
{
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param iconModel for icon access
|
||||
* @param userPreferences to monitor for audio playback changes
|
||||
* @param settingsManager for tone insertion settings
|
||||
* @param controller for the audio channels
|
||||
* @param aliasModel for accessing aliases
|
||||
*/
|
||||
public AudioChannelsPanel(IconModel iconModel, UserPreferences userPreferences, SettingsManager settingsManager,
|
||||
IAudioController controller, AliasModel aliasModel)
|
||||
{
|
||||
setLayout(new MigLayout("insets 0 0 0 0",
|
||||
"[][sizegroup abc,grow,fill][][sizegroup abc,grow,fill]", "[grow,fill]"));
|
||||
|
||||
setBackground(Color.BLACK);
|
||||
|
||||
addSeparator();
|
||||
|
||||
for(int x = 0; x < controller.getAudioChannels().size(); x++)
|
||||
{
|
||||
add(new AudioChannelPanel(controller.getAudioChannels().get(x), aliasModel, iconModel, settingsManager, userPreferences));
|
||||
|
||||
if(x < controller.getAudioChannels().size() - 1)
|
||||
{
|
||||
addSeparator();
|
||||
}
|
||||
}
|
||||
|
||||
/* Add an empty channel panel so that the panel is sized appropriately
|
||||
* for either a single channel or two channels */
|
||||
if(controller.getAudioChannels().size() == 1)
|
||||
{
|
||||
addSeparator();
|
||||
add(new AudioChannelPanel(null, aliasModel, iconModel, settingsManager, userPreferences), "growx");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares for dispose to allow deregistering from services
|
||||
*/
|
||||
public void dispose()
|
||||
{
|
||||
for(Component component: getComponents())
|
||||
{
|
||||
if(component instanceof AudioChannelPanel)
|
||||
{
|
||||
((AudioChannelPanel)component).dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a separator to this panel.
|
||||
*/
|
||||
private void addSeparator()
|
||||
{
|
||||
JSeparator separator = new JSeparator(JSeparator.VERTICAL);
|
||||
separator.setBackground(Color.DARK_GRAY);
|
||||
add(separator);
|
||||
}
|
||||
}
|
||||
305
src/main/java/io/github/dsheirer/audio/playback/AudioPanel.java
Normal file
305
src/main/java/io/github/dsheirer/audio/playback/AudioPanel.java
Normal file
@@ -0,0 +1,305 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.playback;
|
||||
|
||||
import io.github.dsheirer.alias.AliasModel;
|
||||
import io.github.dsheirer.audio.AudioEvent;
|
||||
import io.github.dsheirer.eventbus.MyEventBus;
|
||||
import io.github.dsheirer.gui.preference.PreferenceEditorType;
|
||||
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import io.github.dsheirer.settings.SettingsManager;
|
||||
import java.awt.Color;
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.MouseEvent;
|
||||
import java.awt.event.MouseListener;
|
||||
import jiconfont.icons.font_awesome.FontAwesome;
|
||||
import io.github.dsheirer.gui.theme.ThemedFontIcon;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
|
||||
import javax.sound.sampled.FloatControl;
|
||||
import javax.swing.Icon;
|
||||
import javax.swing.ImageIcon;
|
||||
import javax.swing.JButton;
|
||||
import javax.swing.JMenuItem;
|
||||
import javax.swing.JPanel;
|
||||
import javax.swing.JPopupMenu;
|
||||
import javax.swing.JSlider;
|
||||
import javax.swing.SwingUtilities;
|
||||
|
||||
/**
|
||||
* Audio playback panel
|
||||
*/
|
||||
public class AudioPanel extends JPanel implements Listener<AudioEvent>
|
||||
{
|
||||
private static final ImageIcon MUTED_ICON = IconModel.getScaledIcon("images/audio_muted.png", 20);
|
||||
private static final ImageIcon UNMUTED_ICON = IconModel.getScaledIcon("images/audio_unmuted.png", 20);
|
||||
private final AliasModel mAliasModel;
|
||||
private final AudioPlaybackManager mAudioPlaybackManager;
|
||||
private final IconModel mIconModel;
|
||||
private final SettingsManager mSettingsManager;
|
||||
private final UserPreferences mUserPreferences;
|
||||
private AudioChannelsPanel mAudioChannelsPanel;
|
||||
private JButton mMuteButton;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param iconModel for icon lookup
|
||||
* @param userPreferences for preference lookup
|
||||
* @param settingsManager to monitor for changes
|
||||
* @param audioPlaybackManager for accessing the audio output
|
||||
* @param aliasModel for alias lookup
|
||||
*/
|
||||
public AudioPanel(IconModel iconModel, UserPreferences userPreferences, SettingsManager settingsManager,
|
||||
AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel)
|
||||
{
|
||||
mIconModel = iconModel;
|
||||
mSettingsManager = settingsManager;
|
||||
mAudioPlaybackManager = audioPlaybackManager;
|
||||
mAliasModel = aliasModel;
|
||||
mUserPreferences = userPreferences;
|
||||
mAudioPlaybackManager.addAudioEventListener(this);
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the display
|
||||
*/
|
||||
private void init()
|
||||
{
|
||||
setLayout(new MigLayout("insets 0 0 0 0", "[]0[grow,fill]", "[fill]0[]"));
|
||||
setBackground(Color.BLACK);
|
||||
mMuteButton = new MuteButton();
|
||||
mMuteButton.setBackground(getBackground());
|
||||
add(mMuteButton);
|
||||
mAudioChannelsPanel = new AudioChannelsPanel(mIconModel, mUserPreferences, mSettingsManager, mAudioPlaybackManager, mAliasModel);
|
||||
add(mAudioChannelsPanel);
|
||||
addMouseListener(new MouseSelectionListener());
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive audio event notifications from the audio playback controller
|
||||
*/
|
||||
@Override
|
||||
public void receive(AudioEvent event)
|
||||
{
|
||||
switch(event.getType())
|
||||
{
|
||||
case AUDIO_CONFIGURATION_CHANGE_STARTED:
|
||||
break;
|
||||
case AUDIO_CONFIGURATION_CHANGE_COMPLETE:
|
||||
EventQueue.invokeLater(() -> {
|
||||
remove(mAudioChannelsPanel);
|
||||
mAudioChannelsPanel.dispose();
|
||||
mAudioChannelsPanel = new AudioChannelsPanel(mIconModel, mUserPreferences, mSettingsManager, mAudioPlaybackManager, mAliasModel);
|
||||
add(mAudioChannelsPanel);
|
||||
mAudioChannelsPanel.repaint();
|
||||
revalidate();
|
||||
repaint();
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Audio output mute control menu item.
|
||||
*/
|
||||
public static class AudioOutputMuteItem extends JMenuItem
|
||||
{
|
||||
private final AudioOutput mAudioOutput;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param audioOutput to mute/unmute
|
||||
*/
|
||||
public AudioOutputMuteItem(AudioOutput audioOutput)
|
||||
{
|
||||
super(audioOutput.isMuted() ? "Unmute" : "Mute");
|
||||
mAudioOutput = audioOutput;
|
||||
addActionListener(e -> mAudioOutput.setMuted(!mAudioOutput.isMuted()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mouse listener
|
||||
*/
|
||||
public class MouseSelectionListener implements MouseListener
|
||||
{
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent event)
|
||||
{
|
||||
if(SwingUtilities.isRightMouseButton(event))
|
||||
{
|
||||
JPopupMenu popup = new JPopupMenu();
|
||||
JMenuItem outputMenu = new JMenuItem("Audio Playback Device ...");
|
||||
Icon icon = new ThemedFontIcon(FontAwesome.COG, 14);
|
||||
outputMenu.setIcon(icon);
|
||||
outputMenu.addActionListener(e -> MyEventBus.getGlobalEventBus()
|
||||
.post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.AUDIO_OUTPUT)));
|
||||
popup.add(outputMenu);
|
||||
|
||||
//Add optional gain controller for th eaudio output
|
||||
if(mAudioPlaybackManager.getAudioOutput() != null && mAudioPlaybackManager.getAudioOutput().hasGainControl())
|
||||
{
|
||||
popup.add(new JPopupMenu.Separator());
|
||||
JMenuItem volume = new JMenuItem("Audio Volume");
|
||||
volume.setEnabled(false);
|
||||
Icon volumeIcon = new ThemedFontIcon(FontAwesome.VOLUME_UP, 14);
|
||||
volume.setIcon(volumeIcon);
|
||||
popup.add(volume);
|
||||
popup.add(new VolumeSlider(mAudioPlaybackManager.getAudioOutput().getGainControl()));
|
||||
}
|
||||
|
||||
popup.show(event.getComponent(), event.getX(), event.getY());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mousePressed(MouseEvent e)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseReleased(MouseEvent e)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseEntered(MouseEvent e)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseExited(MouseEvent e)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Audio volume (gain) adjustment slider control
|
||||
*/
|
||||
public static class VolumeSlider extends JSlider
|
||||
{
|
||||
private final FloatControl mFloatControl;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param control to be controlled
|
||||
*/
|
||||
public VolumeSlider(FloatControl control)
|
||||
{
|
||||
super(0, 100, 0);
|
||||
|
||||
setMajorTickSpacing(25);
|
||||
setMinorTickSpacing(5);
|
||||
setPaintTicks(true);
|
||||
setPaintLabels(true);
|
||||
mFloatControl = control;
|
||||
setValue(getIntegerValue(mFloatControl.getValue()));
|
||||
addChangeListener(event -> mFloatControl.shift(mFloatControl.getValue(),
|
||||
getFloatValue(VolumeSlider.this.getValue()),
|
||||
1000));
|
||||
|
||||
addMouseListener(new MouseListener()
|
||||
{
|
||||
@Override
|
||||
public void mouseClicked(MouseEvent event)
|
||||
{
|
||||
if(event.getClickCount() == 2)
|
||||
{
|
||||
VolumeSlider.this.setValue(50);
|
||||
}
|
||||
}
|
||||
public void mouseReleased(MouseEvent arg0) {}
|
||||
public void mousePressed(MouseEvent arg0) {}
|
||||
public void mouseExited(MouseEvent arg0) {}
|
||||
public void mouseEntered(MouseEvent arg0) {}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the integer value to a floating point value to use in the
|
||||
* float control. Assumes an integer value of 50 is the 0.0 dB mid
|
||||
* point (ie no gain ) value.
|
||||
*/
|
||||
private int getIntegerValue(float value)
|
||||
{
|
||||
if(value == 0.0f)
|
||||
{
|
||||
return 50;
|
||||
}
|
||||
else if(value < 0.0f)
|
||||
{
|
||||
float ratio = value / mFloatControl.getMinimum();
|
||||
|
||||
return 50 - (int) (ratio * 50.0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
float ratio = value / mFloatControl.getMaximum();
|
||||
|
||||
return 50 + (int) (ratio * 50.0f);
|
||||
}
|
||||
}
|
||||
|
||||
private float getFloatValue(int value)
|
||||
{
|
||||
if(value == 50)
|
||||
{
|
||||
return 0.0f;
|
||||
}
|
||||
else if(value < 50)
|
||||
{
|
||||
return (float) (50 - value) / 50.0f * mFloatControl.getMinimum();
|
||||
}
|
||||
else
|
||||
{
|
||||
return (float) (value - 50) / 50.0f * mFloatControl.getMaximum();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mute button to mute all audio output channels exposed by the audio
|
||||
* controller
|
||||
*/
|
||||
public class MuteButton extends JButton
|
||||
{
|
||||
private boolean mMuted = false;
|
||||
|
||||
public MuteButton()
|
||||
{
|
||||
setIcon(UNMUTED_ICON);
|
||||
setBorderPainted(false);
|
||||
getAccessibleContext().setAccessibleName("Mute");
|
||||
addActionListener(e -> {
|
||||
mMuted = !mMuted;
|
||||
mAudioPlaybackManager.getAudioOutput().setMuted(mMuted);
|
||||
EventQueue.invokeLater(() -> {
|
||||
setIcon(mMuted ? MUTED_ICON : UNMUTED_ICON);
|
||||
getAccessibleContext().setAccessibleName(mMuted ? "Unmute" : "Mute");
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
private static final Logger mLog = LoggerFactory.getLogger(AudioPlaybackManager.class);
|
||||
private final AudioSegmentPrioritySorter mAudioSegmentPrioritySorter = new AudioSegmentPrioritySorter();
|
||||
private final Broadcaster<AudioEvent> mControllerBroadcaster = new Broadcaster<>();
|
||||
private final Broadcaster<ChannelPlayback> mPlaybackBroadcaster = new Broadcaster<>();
|
||||
private final List<AudioSegment> mAudioSegments = new ArrayList<>();
|
||||
private final List<AudioSegment> mPendingAudioSegments = new ArrayList<>();
|
||||
private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>();
|
||||
@@ -62,8 +61,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
private AudioPlaybackDeviceDescriptor mAudioPlaybackDevice;
|
||||
private AudioOutput mAudioOutput;
|
||||
private ScheduledFuture<?> mProcessingTask;
|
||||
private final TalkgroupHold[] mHolds = new TalkgroupHold[2];
|
||||
private final long[] mHoldActivity = new long[2];
|
||||
|
||||
/**
|
||||
* Constructs an instance.
|
||||
@@ -117,8 +114,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
*/
|
||||
private void processAudioSegments()
|
||||
{
|
||||
updateHoldActivity();
|
||||
|
||||
//Process new audio segments queue. If segment has audio, queue it for replay, otherwise place in pending queue
|
||||
AudioSegment newSegment = mNewAudioSegmentQueue.poll();
|
||||
|
||||
@@ -187,8 +182,7 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
{
|
||||
audioSegment = it.next();
|
||||
|
||||
if((audioSegment.isDoNotMonitor() && getHoldingChannelIndex(audioSegment) < 0) ||
|
||||
(audioSegment.isDuplicate() &&
|
||||
if(audioSegment.isDoNotMonitor() || (audioSegment.isDuplicate() &&
|
||||
mUserPreferences.getCallManagementPreference().isDuplicatePlaybackSuppressionEnabled()))
|
||||
{
|
||||
it.remove();
|
||||
@@ -239,7 +233,20 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
|
||||
try
|
||||
{
|
||||
assignAudioSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels());
|
||||
//Assign empty audio outputs first
|
||||
for(AudioChannel audioChannel: mAudioOutput.getAudioProvider().getAudioChannels())
|
||||
{
|
||||
if(audioChannel.isEmpty())
|
||||
{
|
||||
audioChannel.play(mAudioSegments.removeFirst());
|
||||
if(mAudioSegments.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
replaceLowerPriorityQueuedSegments(mAudioSegments, mAudioOutput.getAudioProvider().getAudioChannels());
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -263,352 +270,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns waiting audio segments, in priority order, to empty audio channels. Calls to a hold talkgroup only go to
|
||||
* the channel that holds the talkgroup, and other calls only go to channels without a hold talkgroup.
|
||||
*
|
||||
* @param waiting audio segments, sorted by playback priority. Assigned segments are removed.
|
||||
* @param audioChannels to assign to.
|
||||
*/
|
||||
static void assignAudioSegments(List<AudioSegment> waiting, List<AudioChannel> audioChannels)
|
||||
{
|
||||
Iterator<AudioSegment> it = waiting.iterator();
|
||||
|
||||
while(it.hasNext())
|
||||
{
|
||||
AudioSegment audioSegment = it.next();
|
||||
AudioChannel holding = getHoldingChannel(audioSegment, audioChannels);
|
||||
AudioChannel target = null;
|
||||
|
||||
if(holding != null)
|
||||
{
|
||||
if(holding.isEmpty())
|
||||
{
|
||||
target = holding;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for(AudioChannel audioChannel: audioChannels)
|
||||
{
|
||||
if(audioChannel.getHold() == null && audioChannel.isEmpty() && !audioChannel.isReplaying())
|
||||
{
|
||||
target = audioChannel;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(target != null)
|
||||
{
|
||||
it.remove();
|
||||
target.play(audioSegment);
|
||||
}
|
||||
}
|
||||
|
||||
//Priority replacement of queued segments only applies to channels and calls without a hold talkgroup
|
||||
List<AudioChannel> unheld = new ArrayList<>();
|
||||
|
||||
for(AudioChannel audioChannel: audioChannels)
|
||||
{
|
||||
if(audioChannel.getHold() == null && !audioChannel.isReplaying())
|
||||
{
|
||||
unheld.add(audioChannel);
|
||||
}
|
||||
}
|
||||
|
||||
if(!unheld.isEmpty() && !waiting.isEmpty())
|
||||
{
|
||||
List<AudioSegment> unmatched = new ArrayList<>();
|
||||
it = waiting.iterator();
|
||||
|
||||
while(it.hasNext())
|
||||
{
|
||||
AudioSegment audioSegment = it.next();
|
||||
|
||||
if(getHoldingChannel(audioSegment, audioChannels) == null)
|
||||
{
|
||||
unmatched.add(audioSegment);
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
replaceLowerPriorityQueuedSegments(unmatched, unheld);
|
||||
waiting.addAll(unmatched);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Channel that holds the talkgroup of the audio segment, or null.
|
||||
*/
|
||||
static AudioChannel getHoldingChannel(AudioSegment audioSegment, List<AudioChannel> audioChannels)
|
||||
{
|
||||
for(AudioChannel audioChannel: audioChannels)
|
||||
{
|
||||
TalkgroupHold hold = audioChannel.getHold();
|
||||
|
||||
if(hold != null && hold.matches(audioSegment))
|
||||
{
|
||||
return audioChannel;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index of the channel that holds the talkgroup of the audio segment, or -1.
|
||||
*/
|
||||
private int getHoldingChannelIndex(AudioSegment audioSegment)
|
||||
{
|
||||
for(int x = 0; x < mHolds.length; x++)
|
||||
{
|
||||
TalkgroupHold hold = mHolds[x];
|
||||
|
||||
if(hold != null && hold.matches(audioSegment))
|
||||
{
|
||||
return x;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets (or clears, with null) the hold talkgroup for the audio channel. Setting a talkgroup that another channel
|
||||
* holds moves the hold to this channel. Queued calls that don't match the hold talkgroup are returned for
|
||||
* assignment to another channel, and a call that is playing and doesn't match stops.
|
||||
*
|
||||
* @param channelIndex of the audio channel (0 = left/mono, 1 = right)
|
||||
* @param hold talkgroup or null to release the hold
|
||||
*/
|
||||
public void setHold(int channelIndex, TalkgroupHold hold)
|
||||
{
|
||||
if(channelIndex < 0 || channelIndex >= mHolds.length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
mAudioChannelsLock.lock();
|
||||
|
||||
try
|
||||
{
|
||||
if(hold != null)
|
||||
{
|
||||
for(int x = 0; x < mHolds.length; x++)
|
||||
{
|
||||
if(x != channelIndex && hold.isSameTalkgroup(mHolds[x]))
|
||||
{
|
||||
applyHold(x, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
applyHold(channelIndex, hold);
|
||||
}
|
||||
finally
|
||||
{
|
||||
mAudioChannelsLock.unlock();
|
||||
}
|
||||
|
||||
mLog.info("Audio channel " + channelIndex + (hold != null ? " hold talkgroup [" + hold + "]" :
|
||||
" hold talkgroup released"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the hold to the channel. Audio channels lock must be held.
|
||||
*/
|
||||
private void applyHold(int channelIndex, TalkgroupHold hold)
|
||||
{
|
||||
mHolds[channelIndex] = hold;
|
||||
mHoldActivity[channelIndex] = System.currentTimeMillis();
|
||||
|
||||
if(mAudioOutput != null)
|
||||
{
|
||||
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
|
||||
|
||||
if(channelIndex < channels.size())
|
||||
{
|
||||
AudioChannel channel = channels.get(channelIndex);
|
||||
channel.setHold(hold);
|
||||
|
||||
if(hold != null)
|
||||
{
|
||||
//Return queued calls that can no longer play on this channel
|
||||
List<AudioSegment> keep = new ArrayList<>();
|
||||
AudioSegment queued = channel.pollQueuedAudioSegment();
|
||||
|
||||
while(queued != null)
|
||||
{
|
||||
if(hold.matches(queued))
|
||||
{
|
||||
keep.add(queued);
|
||||
}
|
||||
else
|
||||
{
|
||||
mNewAudioSegmentQueue.add(queued);
|
||||
}
|
||||
|
||||
queued = channel.pollQueuedAudioSegment();
|
||||
}
|
||||
|
||||
for(AudioSegment segment: keep)
|
||||
{
|
||||
channel.play(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the listener to be notified when an audio channel starts or stops playing a call. Notified on the
|
||||
* audio playback thread.
|
||||
*/
|
||||
public void addPlaybackListener(Listener<ChannelPlayback> listener)
|
||||
{
|
||||
mPlaybackBroadcaster.addListener(listener);
|
||||
}
|
||||
|
||||
public void removePlaybackListener(Listener<ChannelPlayback> listener)
|
||||
{
|
||||
mPlaybackBroadcaster.removeListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Current playback state of each audio channel, for a listener that registers after playback started.
|
||||
*/
|
||||
public List<ChannelPlayback> getChannelPlayback()
|
||||
{
|
||||
List<ChannelPlayback> playback = new ArrayList<>();
|
||||
List<AudioChannel> channels = getAudioChannels();
|
||||
|
||||
for(int x = 0; x < channels.size(); x++)
|
||||
{
|
||||
playback.add(getChannelPlayback(channels.get(x), x, channels.size()));
|
||||
}
|
||||
|
||||
return playback;
|
||||
}
|
||||
|
||||
private static ChannelPlayback getChannelPlayback(AudioChannel channel, int channelIndex, int channelCount)
|
||||
{
|
||||
AudioSegment current = channel.getCurrentAudioSegment();
|
||||
ReplaySource replay = channel.getReplay();
|
||||
return new ChannelPlayback(channelIndex, channel.getChannelName(), channelCount,
|
||||
current != null ? current.getId() : 0, replay != null && !replay.isFinished() ? replay.getCallId() : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays a recorded call through the audio channels. A channel that is already replaying is reused, otherwise
|
||||
* an idle channel (left first), otherwise the left (or mono) channel, which drops the call that it is playing.
|
||||
* Live calls aren't assigned to the channel while it replays.
|
||||
*
|
||||
* @param replay to play
|
||||
* @return index of the channel that replays the call, or -1 if there is no audio output
|
||||
*/
|
||||
public int replay(ReplaySource replay)
|
||||
{
|
||||
mAudioChannelsLock.lock();
|
||||
|
||||
try
|
||||
{
|
||||
List<AudioChannel> channels = getAudioChannels();
|
||||
|
||||
if(channels.isEmpty())
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
int selected = -1;
|
||||
|
||||
for(int x = 0; x < channels.size() && selected < 0; x++)
|
||||
{
|
||||
if(channels.get(x).isReplaying())
|
||||
{
|
||||
selected = x;
|
||||
}
|
||||
}
|
||||
|
||||
for(int x = 0; x < channels.size() && selected < 0; x++)
|
||||
{
|
||||
AudioChannel channel = channels.get(x);
|
||||
|
||||
if(!channel.hasAudioSegment() && channel.isEmpty())
|
||||
{
|
||||
selected = x;
|
||||
}
|
||||
}
|
||||
|
||||
if(selected < 0)
|
||||
{
|
||||
selected = 0;
|
||||
}
|
||||
|
||||
channels.get(selected).startReplay(replay);
|
||||
return selected;
|
||||
}
|
||||
finally
|
||||
{
|
||||
mAudioChannelsLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hold talkgroup for the audio channel, or null.
|
||||
*/
|
||||
public TalkgroupHold getHold(int channelIndex)
|
||||
{
|
||||
return channelIndex >= 0 && channelIndex < mHolds.length ? mHolds[channelIndex] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the last activity time of each hold talkgroup and releases holds that have been idle longer than the
|
||||
* automatic release time.
|
||||
*/
|
||||
private void updateHoldActivity()
|
||||
{
|
||||
int minutes = mUserPreferences.getPlaybackPreference().getHoldAutoReleaseMinutes();
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
for(int x = 0; x < mHolds.length; x++)
|
||||
{
|
||||
TalkgroupHold hold = mHolds[x];
|
||||
|
||||
if(hold == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean active = false;
|
||||
|
||||
for(AudioSegment audioSegment: mAudioSegments)
|
||||
{
|
||||
if(hold.matches(audioSegment))
|
||||
{
|
||||
active = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(!active && mAudioOutput != null)
|
||||
{
|
||||
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
|
||||
active = x < channels.size() && channels.get(x).isPlayingHeldTalkgroup();
|
||||
}
|
||||
|
||||
if(active)
|
||||
{
|
||||
mHoldActivity[x] = now;
|
||||
}
|
||||
else if(minutes > 0 && (now - mHoldActivity[x]) > TimeUnit.MINUTES.toMillis(minutes))
|
||||
{
|
||||
mLog.info("Releasing idle hold talkgroup [" + hold + "] after " + minutes + " minutes");
|
||||
setHold(x, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps audio segments queued on the audio channels for waiting audio segments that have a higher playback priority,
|
||||
* so that a segment queued behind the current playback can't hold a higher priority segment out of the channel.
|
||||
@@ -736,30 +397,6 @@ public class AudioPlaybackManager implements Listener<AudioSegment>, IAudioContr
|
||||
//Note: audio output can use an alternate device if the requested device can't be used, so we assign
|
||||
//the descriptor that was actually used by the audio output
|
||||
mAudioPlaybackDevice = mAudioOutput.getAudioPlaybackDeviceDescriptor();
|
||||
|
||||
//Re-apply hold talkgroups to the new channels (and drop a right channel hold for a mono device)
|
||||
List<AudioChannel> channels = mAudioOutput.getAudioProvider().getAudioChannels();
|
||||
|
||||
for(int x = 0; x < channels.size(); x++)
|
||||
{
|
||||
final int channelIndex = x;
|
||||
final AudioChannel channel = channels.get(x);
|
||||
final int outputChannels = channels.size();
|
||||
channel.setPlaybackListener(() -> mPlaybackBroadcaster.broadcast(
|
||||
getChannelPlayback(channel, channelIndex, outputChannels)));
|
||||
}
|
||||
|
||||
for(int x = 0; x < mHolds.length; x++)
|
||||
{
|
||||
if(x < channels.size())
|
||||
{
|
||||
channels.get(x).setHold(mHolds[x]);
|
||||
}
|
||||
else
|
||||
{
|
||||
mHolds[x] = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.playback;
|
||||
|
||||
/**
|
||||
* Notification that an audio channel started playing a call, or stopped playing.
|
||||
*
|
||||
* @param channelIndex of the audio channel in the audio output (0 = left/mono, 1 = right)
|
||||
* @param channelName of the audio channel (LEFT, RIGHT or MONO)
|
||||
* @param channelCount number of channels in the audio output
|
||||
* @param audioSegmentId of the live call audio segment that is playing, or 0. This is the call key of the call in
|
||||
* the call manager.
|
||||
* @param replayCallId database id of the recorded call that is replaying, or 0.
|
||||
*/
|
||||
public record ChannelPlayback(int channelIndex, String channelName, int channelCount, long audioSegmentId,
|
||||
long replayCallId)
|
||||
{
|
||||
/**
|
||||
* Indicates if the channel is playing a live call or replaying a recorded call
|
||||
*/
|
||||
public boolean isPlaying()
|
||||
{
|
||||
return audioSegmentId != 0 || replayCallId != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the channel is replaying a recorded call
|
||||
*/
|
||||
public boolean isReplay()
|
||||
{
|
||||
return replayCallId != 0;
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.playback;
|
||||
|
||||
/**
|
||||
* Audio of a recorded call that is replayed through an audio channel. The audio channel pulls the audio in 20 ms
|
||||
* intervals on the audio playback thread, and the user interface pauses, seeks and stops it from the FX thread.
|
||||
*/
|
||||
public class ReplaySource
|
||||
{
|
||||
private final float[] mSamples;
|
||||
private final long mCallId;
|
||||
private final String mDescription;
|
||||
private volatile int mPosition;
|
||||
private volatile boolean mPaused;
|
||||
private volatile boolean mStopped;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param samples of 8 kHz audio
|
||||
* @param callId database id of the call that is replayed
|
||||
* @param description of the call for display (e.g. TO and FROM)
|
||||
*/
|
||||
public ReplaySource(float[] samples, long callId, String description)
|
||||
{
|
||||
mSamples = samples;
|
||||
mCallId = callId;
|
||||
mDescription = description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Database id of the replayed call
|
||||
*/
|
||||
public long getCallId()
|
||||
{
|
||||
return mCallId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Description of the replayed call for display
|
||||
*/
|
||||
public String getDescription()
|
||||
{
|
||||
return mDescription;
|
||||
}
|
||||
|
||||
/**
|
||||
* Next 20 ms of audio, silence while paused, or null when the replay is finished or stopped. Audio thread.
|
||||
*/
|
||||
float[] next()
|
||||
{
|
||||
if(isFinished())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
float[] audio = new float[AudioChannel.SAMPLES_PER_INTERVAL];
|
||||
|
||||
if(mPaused)
|
||||
{
|
||||
return audio;
|
||||
}
|
||||
|
||||
int position = mPosition;
|
||||
int length = Math.min(audio.length, mSamples.length - position);
|
||||
System.arraycopy(mSamples, position, audio, 0, length);
|
||||
mPosition = position + length;
|
||||
return audio;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the replay played to the end or was stopped
|
||||
*/
|
||||
public boolean isFinished()
|
||||
{
|
||||
return mStopped || mPosition >= mSamples.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the replay played to the end, as opposed to being stopped or replaced
|
||||
*/
|
||||
public boolean isCompleted()
|
||||
{
|
||||
return !mStopped && mPosition >= mSamples.length;
|
||||
}
|
||||
|
||||
public boolean isPaused()
|
||||
{
|
||||
return mPaused;
|
||||
}
|
||||
|
||||
public void setPaused(boolean paused)
|
||||
{
|
||||
mPaused = paused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the replay. The audio channel releases it at the next audio interval.
|
||||
*/
|
||||
public void stop()
|
||||
{
|
||||
mStopped = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the replay position
|
||||
* @param fraction of the recording, 0.0 to 1.0
|
||||
*/
|
||||
public void seek(double fraction)
|
||||
{
|
||||
double clamped = Math.max(0.0, Math.min(1.0, fraction));
|
||||
mPosition = (int)Math.min(mSamples.length, Math.round(mSamples.length * clamped));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay position in milliseconds
|
||||
*/
|
||||
public long getPositionMillis()
|
||||
{
|
||||
return mPosition * 1000L / 8000L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recording duration in milliseconds
|
||||
*/
|
||||
public long getDurationMillis()
|
||||
{
|
||||
return mSamples.length * 1000L / 8000L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay position as a fraction of the recording, 0.0 to 1.0
|
||||
*/
|
||||
public double getFraction()
|
||||
{
|
||||
return mSamples.length > 0 ? (double)mPosition / mSamples.length : 1.0;
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.audio.playback;
|
||||
|
||||
import io.github.dsheirer.audio.AudioSegment;
|
||||
import io.github.dsheirer.database.call.CallRecord;
|
||||
import io.github.dsheirer.identifier.Identifier;
|
||||
import io.github.dsheirer.identifier.IdentifierCollection;
|
||||
import io.github.dsheirer.identifier.Role;
|
||||
import io.github.dsheirer.identifier.patch.PatchGroup;
|
||||
import io.github.dsheirer.identifier.patch.PatchGroupIdentifier;
|
||||
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
|
||||
import io.github.dsheirer.protocol.Protocol;
|
||||
|
||||
/**
|
||||
* Hold talkgroup for an audio channel. While a channel holds a talkgroup, only calls to that talkgroup play on the
|
||||
* channel and calls to the talkgroup are steered to the channel.
|
||||
*
|
||||
* A call matches when its TO talkgroup has the same protocol and value, or when its TO patch group is (or includes)
|
||||
* the talkgroup. APCO-25 phase 1 and phase 2 are treated as the same protocol since a P25 system's talkgroups are
|
||||
* used on both phase 1 and phase 2 traffic channels.
|
||||
*
|
||||
* @param protocol of the talkgroup
|
||||
* @param talkgroup value
|
||||
* @param label for display (formatted talkgroup and alias)
|
||||
*/
|
||||
public record TalkgroupHold(Protocol protocol, int talkgroup, String label)
|
||||
{
|
||||
/**
|
||||
* Normalizes the protocol for comparison
|
||||
*/
|
||||
private static Protocol normalize(Protocol protocol)
|
||||
{
|
||||
return protocol == Protocol.APCO25_PHASE2 ? Protocol.APCO25 : protocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the talkgroup identifier is this hold talkgroup
|
||||
*/
|
||||
public boolean matches(TalkgroupIdentifier identifier)
|
||||
{
|
||||
return identifier != null && identifier.getValue() != null && identifier.getValue() == talkgroup &&
|
||||
normalize(identifier.getProtocol()) == normalize(protocol);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the call identifiers have this hold talkgroup (or a patch group with it) as the TO identifier.
|
||||
*/
|
||||
public boolean matches(IdentifierCollection identifierCollection)
|
||||
{
|
||||
if(identifierCollection == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for(Identifier identifier: identifierCollection.getIdentifiers(Role.TO))
|
||||
{
|
||||
if(identifier instanceof TalkgroupIdentifier tg && matches(tg))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if(identifier instanceof PatchGroupIdentifier pgi && pgi.getValue() != null)
|
||||
{
|
||||
PatchGroup patchGroup = pgi.getValue();
|
||||
|
||||
if(matches(patchGroup.getPatchGroup()))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
for(TalkgroupIdentifier patched: patchGroup.getPatchedTalkgroupIdentifiers())
|
||||
{
|
||||
if(matches(patched))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the audio segment is a call to this hold talkgroup.
|
||||
*/
|
||||
public boolean matches(AudioSegment audioSegment)
|
||||
{
|
||||
return audioSegment != null && matches(audioSegment.getIdentifierCollection());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a hold for the TO talkgroup (or patch group) of the call identifiers.
|
||||
* @param identifierCollection of a call
|
||||
* @param label for display
|
||||
* @return hold or null if the call doesn't have a TO talkgroup
|
||||
*/
|
||||
public static TalkgroupHold from(IdentifierCollection identifierCollection, String label)
|
||||
{
|
||||
if(identifierCollection == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Identifier to = identifierCollection.getToIdentifier();
|
||||
|
||||
if(to instanceof PatchGroupIdentifier pgi && pgi.getValue() != null && pgi.getValue().getPatchGroup() != null)
|
||||
{
|
||||
to = pgi.getValue().getPatchGroup();
|
||||
}
|
||||
|
||||
if(to instanceof TalkgroupIdentifier tg && tg.getValue() != null && tg.getValue() > 0)
|
||||
{
|
||||
return new TalkgroupHold(tg.getProtocol(), tg.getValue(), label != null ? label : tg.toString());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a hold for the TO talkgroup of a stored call.
|
||||
* @param call with a TO talkgroup
|
||||
* @param toAlias current alias name of the TO talkgroup for the label, or null
|
||||
* @return hold or null if the call doesn't have a TO talkgroup
|
||||
*/
|
||||
public static TalkgroupHold from(CallRecord call, String toAlias)
|
||||
{
|
||||
if(call == null || !call.hasTalkgroup() || call.getToValue() > Integer.MAX_VALUE)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
String label = call.getToId() + (toAlias != null ? " " + toAlias : "");
|
||||
return new TalkgroupHold(call.getProtocolValue(), call.getToValue().intValue(), label);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the other hold is for the same talkgroup (ignoring the label).
|
||||
*/
|
||||
public boolean isSameTalkgroup(TalkgroupHold other)
|
||||
{
|
||||
return other != null && other.talkgroup == talkgroup && normalize(other.protocol) == normalize(protocol);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return label;
|
||||
}
|
||||
}
|
||||
@@ -57,11 +57,10 @@ 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 in bytes (2 bytes per I/Q sample). Typically, this
|
||||
//will be 64k or 128k
|
||||
if(samples.length % (FRAGMENT_SIZE * 2) != 0)
|
||||
//Ensure we're an even multiple of the fragment size. Typically, this will be 64k or 128k
|
||||
if(samples.length % FRAGMENT_SIZE != 0)
|
||||
{
|
||||
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + (FRAGMENT_SIZE * 2));
|
||||
throw new IllegalArgumentException("Samples byte[] length [" + samples.length + "] must be an even multiple of " + FRAGMENT_SIZE);
|
||||
}
|
||||
|
||||
mSamples = samples;
|
||||
|
||||
@@ -1,412 +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.call;
|
||||
|
||||
import io.github.dsheirer.alias.AliasList;
|
||||
import io.github.dsheirer.audio.AudioSegment;
|
||||
import io.github.dsheirer.controller.NamingThreadFactory;
|
||||
import io.github.dsheirer.database.DatabaseManager;
|
||||
import io.github.dsheirer.database.call.CallRecord;
|
||||
import io.github.dsheirer.database.call.CallState;
|
||||
import io.github.dsheirer.database.call.PatchedTalkgroup;
|
||||
import io.github.dsheirer.identifier.Form;
|
||||
import io.github.dsheirer.identifier.Identifier;
|
||||
import io.github.dsheirer.identifier.IdentifierClass;
|
||||
import io.github.dsheirer.identifier.IdentifierCollection;
|
||||
import io.github.dsheirer.identifier.Role;
|
||||
import io.github.dsheirer.identifier.configuration.DecoderTypeConfigurationIdentifier;
|
||||
import io.github.dsheirer.identifier.configuration.FrequencyConfigurationIdentifier;
|
||||
import io.github.dsheirer.identifier.integer.IntegerIdentifier;
|
||||
import io.github.dsheirer.identifier.patch.PatchGroupIdentifier;
|
||||
import io.github.dsheirer.identifier.radio.FullyQualifiedRadioIdentifier;
|
||||
import io.github.dsheirer.identifier.talkgroup.FullyQualifiedTalkgroupIdentifier;
|
||||
import io.github.dsheirer.identifier.talkgroup.TalkgroupIdentifier;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.protocol.Protocol;
|
||||
import io.github.dsheirer.record.CallRecorder;
|
||||
import io.github.dsheirer.sample.Broadcaster;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.LinkedTransferQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Manages the life-cycle of every call: the single audio segment listener for calls.
|
||||
*
|
||||
* Each audio segment is a call. The call manager creates the call record as soon as the call has audio (or is
|
||||
* identified as encrypted), updates it as the call identifiers change and completes it when the call ends. Each
|
||||
* change is saved to the call database and broadcast to the call listeners (Calls tab, and later external
|
||||
* subscribers), so they see the same call activity. The {@link CallRecorder} records the call audio and fills in
|
||||
* the recording details of the call record.
|
||||
*
|
||||
* Calls are processed on a single call manager thread every 200 milliseconds.
|
||||
*/
|
||||
public class CallManager implements Listener<AudioSegment>
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(CallManager.class);
|
||||
private static final long PROCESSING_INTERVAL_MS = 200;
|
||||
private final LinkedTransferQueue<AudioSegment> mNewAudioSegmentQueue = new LinkedTransferQueue<>();
|
||||
private final List<TrackedCall> mTrackedCalls = new ArrayList<>();
|
||||
private final Broadcaster<CallRecord> mCallBroadcaster = new Broadcaster<>();
|
||||
private final ScheduledExecutorService mExecutor =
|
||||
Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("sdrtrunk call manager"));
|
||||
private final UserPreferences mUserPreferences;
|
||||
private final DatabaseManager mDatabaseManager;
|
||||
private final CallRecorder mCallRecorder;
|
||||
private ScheduledFuture<?> mProcessorHandle;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param userPreferences for call recording and identifier formatting
|
||||
* @param databaseManager to store the calls, or null to track and record calls without storing them
|
||||
*/
|
||||
public CallManager(UserPreferences userPreferences, DatabaseManager databaseManager)
|
||||
{
|
||||
mUserPreferences = userPreferences;
|
||||
mDatabaseManager = databaseManager;
|
||||
mCallRecorder = new CallRecorder(userPreferences);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the manager and begins call tracking and audio recording.
|
||||
*/
|
||||
public void start()
|
||||
{
|
||||
if(mProcessorHandle == null)
|
||||
{
|
||||
mProcessorHandle = mExecutor.scheduleWithFixedDelay(this::processSafely, 0, PROCESSING_INTERVAL_MS,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the manager, completing any calls and recordings that are still in progress.
|
||||
*/
|
||||
public void stop()
|
||||
{
|
||||
if(mProcessorHandle != null)
|
||||
{
|
||||
mProcessorHandle.cancel(false);
|
||||
mProcessorHandle = null;
|
||||
|
||||
try
|
||||
{
|
||||
mExecutor.submit(() -> {
|
||||
process();
|
||||
|
||||
for(TrackedCall trackedCall: mTrackedCalls)
|
||||
{
|
||||
trackedCall.complete();
|
||||
}
|
||||
|
||||
mTrackedCalls.clear();
|
||||
}).get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.error("Error completing calls in progress during shutdown", e);
|
||||
}
|
||||
|
||||
mExecutor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the listener to receive a snapshot of each call when it starts, changes and completes. Snapshots
|
||||
* of the same call share the same {@link CallRecord#getCallKey()}, which is the {@link AudioSegment#getId()} of
|
||||
* the call's audio segment. Notified on the call recorder thread.
|
||||
*/
|
||||
public void addCallListener(Listener<CallRecord> listener)
|
||||
{
|
||||
mCallBroadcaster.addListener(listener);
|
||||
}
|
||||
|
||||
public void removeCallListener(Listener<CallRecord> listener)
|
||||
{
|
||||
mCallBroadcaster.removeListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary receive method for incoming audio segments. The consumer count of the segment is already incremented
|
||||
* for this manager.
|
||||
*/
|
||||
@Override
|
||||
public void receive(AudioSegment audioSegment)
|
||||
{
|
||||
mNewAudioSegmentQueue.add(audioSegment);
|
||||
}
|
||||
|
||||
private void processSafely()
|
||||
{
|
||||
try
|
||||
{
|
||||
process();
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
mLog.error("Error while processing calls", t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes new and tracked audio segments. Call recorder thread only.
|
||||
*/
|
||||
private void process()
|
||||
{
|
||||
AudioSegment audioSegment = mNewAudioSegmentQueue.poll();
|
||||
|
||||
while(audioSegment != null)
|
||||
{
|
||||
mTrackedCalls.add(new TrackedCall(audioSegment, audioSegment.getId()));
|
||||
audioSegment = mNewAudioSegmentQueue.poll();
|
||||
}
|
||||
|
||||
Iterator<TrackedCall> it = mTrackedCalls.iterator();
|
||||
|
||||
while(it.hasNext())
|
||||
{
|
||||
TrackedCall trackedCall = it.next();
|
||||
|
||||
if(trackedCall.process())
|
||||
{
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the call record fields from the audio segment.
|
||||
*/
|
||||
void update(CallRecord call, AudioSegment audioSegment)
|
||||
{
|
||||
IdentifierCollection collection = audioSegment.getIdentifierCollection();
|
||||
AliasList aliasList = audioSegment.getAliasList();
|
||||
Identifier to = collection.getToIdentifier();
|
||||
Identifier from = collection.getFromIdentifier();
|
||||
|
||||
Protocol protocol = to != null ? to.getProtocol() : (from != null ? from.getProtocol() : null);
|
||||
|
||||
if(protocol == null || protocol == Protocol.UNKNOWN)
|
||||
{
|
||||
Identifier decoder = collection.getIdentifier(IdentifierClass.CONFIGURATION, Form.DECODER_TYPE, Role.ANY);
|
||||
|
||||
if(decoder instanceof DecoderTypeConfigurationIdentifier dtci && dtci.getValue() != null)
|
||||
{
|
||||
protocol = dtci.getValue().getProtocol();
|
||||
}
|
||||
}
|
||||
|
||||
call.setProtocol(protocol != null ? protocol.name() : null);
|
||||
call.setSystem(getString(collection, Form.SYSTEM));
|
||||
call.setSite(getString(collection, Form.SITE));
|
||||
call.setChannel(getString(collection, Form.CHANNEL));
|
||||
|
||||
Identifier frequency = collection.getIdentifier(IdentifierClass.CONFIGURATION, Form.CHANNEL_FREQUENCY, Role.ANY);
|
||||
|
||||
if(frequency instanceof FrequencyConfigurationIdentifier fci && fci.getValue() != null)
|
||||
{
|
||||
call.setFrequency(fci.getValue());
|
||||
}
|
||||
|
||||
call.setTimeslot(audioSegment.getTimeslot());
|
||||
|
||||
var format = mUserPreferences.getTalkgroupFormatPreference();
|
||||
call.setToId(to != null ? format.format(to) : null);
|
||||
call.setToValue(getValue(to));
|
||||
call.setToForm(to != null ? to.getForm().name() : null);
|
||||
call.setToFullyQualified(to instanceof FullyQualifiedTalkgroupIdentifier fqt ?
|
||||
fqt.getFullyQualifiedTalkgroupAddress() : null);
|
||||
call.setFromId(from != null ? format.format(from) : null);
|
||||
call.setFromValue(getValue(from));
|
||||
call.setFromForm(from != null ? from.getForm().name() : null);
|
||||
call.setFromFullyQualified(from instanceof FullyQualifiedRadioIdentifier fqr ?
|
||||
fqr.getFullyQualifiedRadioAddress() : null);
|
||||
call.setAliasList(aliasList != null ? aliasList.getName() : null);
|
||||
call.setPatchedTalkgroups(getPatchedTalkgroups(to));
|
||||
|
||||
List<Identifier> talkerAliases = collection.getIdentifiers(Form.TALKER_ALIAS);
|
||||
call.setTalkerAlias(talkerAliases.isEmpty() ? null : talkerAliases.getFirst().toString());
|
||||
call.setEncrypted(audioSegment.isEncrypted());
|
||||
call.setDuplicate(audioSegment.isDuplicate());
|
||||
call.setPriority(audioSegment.monitorPriorityProperty().get());
|
||||
call.setAliasRecord(audioSegment.recordAudioProperty().get());
|
||||
call.setStartTime(audioSegment.getStartTimestamp());
|
||||
}
|
||||
|
||||
/**
|
||||
* Talkgroups patched into the patch group TO identifier, or an empty list.
|
||||
*/
|
||||
static List<PatchedTalkgroup> getPatchedTalkgroups(Identifier to)
|
||||
{
|
||||
if(!(to instanceof PatchGroupIdentifier pgi) || pgi.getValue() == null)
|
||||
{
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<PatchedTalkgroup> patched = new ArrayList<>();
|
||||
|
||||
for(TalkgroupIdentifier talkgroup: pgi.getValue().getPatchedTalkgroupIdentifiers())
|
||||
{
|
||||
if(talkgroup != null && talkgroup.getValue() != null)
|
||||
{
|
||||
patched.add(new PatchedTalkgroup(talkgroup.getValue(),
|
||||
talkgroup instanceof FullyQualifiedTalkgroupIdentifier fqt ?
|
||||
fqt.getFullyQualifiedTalkgroupAddress() : null));
|
||||
}
|
||||
}
|
||||
|
||||
return patched;
|
||||
}
|
||||
|
||||
private static String getString(IdentifierCollection collection, Form form)
|
||||
{
|
||||
Identifier identifier = collection.getIdentifier(IdentifierClass.CONFIGURATION, form, Role.ANY);
|
||||
return identifier != null && identifier.getValue() != null ? identifier.getValue().toString() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric value of a talkgroup, patch group (the patch group talkgroup) or radio identifier, or null.
|
||||
*/
|
||||
static Long getValue(Identifier identifier)
|
||||
{
|
||||
if(identifier instanceof PatchGroupIdentifier pgi && pgi.getValue() != null &&
|
||||
pgi.getValue().getPatchGroup() != null)
|
||||
{
|
||||
return pgi.getValue().getPatchGroup().getValue().longValue();
|
||||
}
|
||||
|
||||
if(identifier instanceof IntegerIdentifier ii && ii.getValue() != null)
|
||||
{
|
||||
return ii.getValue().longValue();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Content of a call snapshot that is compared to detect a change that needs to be saved and broadcast.
|
||||
*/
|
||||
private static String getSignature(CallRecord call)
|
||||
{
|
||||
return call.getStartTime() + "|" + call.getCallState() + "|" + call.getProtocol() + "|" + call.getSystem() +
|
||||
"|" + call.getSite() + "|" + call.getChannel() + "|" + call.getFrequency() + "|" + call.getToId() + "|" +
|
||||
call.getToForm() + "|" + call.getFromId() + "|" + call.getFromForm() + "|" + call.getAliasList() + "|" + call.getPatchedTalkgroups() + "|" +
|
||||
call.getTalkerAlias() + "|" +
|
||||
call.isEncrypted() + "|" + call.isDuplicate() + "|" + call.getPriority() + "|" + call.isAliasRecord() + "|" +
|
||||
call.getRecordingState() + "|" + call.getFilePath() + "|" + call.getEndTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* A call that is being tracked and possibly recorded. Call recorder thread only.
|
||||
*/
|
||||
private class TrackedCall
|
||||
{
|
||||
private final AudioSegment mAudioSegment;
|
||||
private final CallRecord mCall = new CallRecord();
|
||||
private final DatabaseManager.CallHandle mHandle;
|
||||
private final CallRecorder.Recording mRecording;
|
||||
private String mLastSignature;
|
||||
private boolean mPublished;
|
||||
|
||||
TrackedCall(AudioSegment audioSegment, long callKey)
|
||||
{
|
||||
mAudioSegment = audioSegment;
|
||||
mRecording = mCallRecorder.createRecording(audioSegment);
|
||||
mCall.setCallKey(callKey);
|
||||
mHandle = mDatabaseManager != null ? mDatabaseManager.createHandle() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the call.
|
||||
* @return true when the call is complete and should no longer be tracked
|
||||
*/
|
||||
boolean process()
|
||||
{
|
||||
boolean complete = mAudioSegment.isComplete();
|
||||
boolean hasAudio = mAudioSegment.hasAudio();
|
||||
|
||||
if(complete)
|
||||
{
|
||||
if(hasAudio || mPublished || mAudioSegment.isEncrypted())
|
||||
{
|
||||
complete();
|
||||
}
|
||||
|
||||
mAudioSegment.decrementConsumerCount();
|
||||
return true;
|
||||
}
|
||||
|
||||
//Wait for audio (or an encrypted call) before creating the call, so that segments that never have audio
|
||||
//don't create empty calls
|
||||
if(!hasAudio && !mAudioSegment.isEncrypted())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
update(mCall, mAudioSegment);
|
||||
mRecording.update(mCall);
|
||||
publish();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes the call and its recording.
|
||||
*/
|
||||
void complete()
|
||||
{
|
||||
update(mCall, mAudioSegment);
|
||||
mRecording.complete(mCall);
|
||||
mCall.setEndTime(mAudioSegment.hasAudio() ? mAudioSegment.getEndTimestamp() : System.currentTimeMillis());
|
||||
mCall.setCallState(CallState.COMPLETE);
|
||||
publish();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves and broadcasts a snapshot of the call when it changed.
|
||||
*/
|
||||
private void publish()
|
||||
{
|
||||
String signature = getSignature(mCall);
|
||||
|
||||
if(!Objects.equals(signature, mLastSignature))
|
||||
{
|
||||
mLastSignature = signature;
|
||||
CallRecord snapshot = mCall.copy();
|
||||
mPublished = true;
|
||||
|
||||
if(mDatabaseManager != null)
|
||||
{
|
||||
//The database writer sets the row id on its own copy
|
||||
mDatabaseManager.save(mHandle, snapshot.copy());
|
||||
}
|
||||
|
||||
mCallBroadcaster.broadcast(snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*******************************************************************************
|
||||
* 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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadata.class);
|
||||
|
||||
private AliasListConfigurationIdentifier mAliasListConfigurationIdentifier;
|
||||
private SystemConfigurationIdentifier mSystemConfigurationIdentifier;
|
||||
private SiteConfigurationIdentifier mSiteConfigurationIdentifier;
|
||||
private ChannelNameConfigurationIdentifier mChannelNameConfigurationIdentifier;
|
||||
@@ -129,19 +128,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias list configuration identifier
|
||||
*/
|
||||
public AliasListConfigurationIdentifier getAliasListConfigurationIdentifier()
|
||||
{
|
||||
return mAliasListConfigurationIdentifier;
|
||||
}
|
||||
|
||||
public boolean hasAliasListConfigurationIdentifier()
|
||||
{
|
||||
return mAliasListConfigurationIdentifier != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* System configuration identifier
|
||||
*/
|
||||
@@ -337,15 +323,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
|
||||
switch(identifier.getForm())
|
||||
{
|
||||
case ALIAS_LIST:
|
||||
if(identifier instanceof AliasListConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))
|
||||
{
|
||||
mAliasListConfigurationIdentifier = (AliasListConfigurationIdentifier)identifier;
|
||||
}
|
||||
else
|
||||
{
|
||||
mAliasListConfigurationIdentifier = null;
|
||||
}
|
||||
|
||||
if(update.isAdd())
|
||||
{
|
||||
mAliasList = mAliasModel.getAliasList((AliasListConfigurationIdentifier)identifier);
|
||||
@@ -362,7 +339,6 @@ public class ChannelMetadata implements Listener<IdentifierUpdateNotification>,
|
||||
}
|
||||
}
|
||||
}
|
||||
broadcastUpdate(ChannelMetadataField.CONFIGURATION_ALIAS_LIST);
|
||||
break;
|
||||
case CHANNEL:
|
||||
if(identifier instanceof ChannelNameConfigurationIdentifier && (update.isAdd() || update.isSilentAdd()))
|
||||
|
||||
@@ -22,7 +22,6 @@ package io.github.dsheirer.channel.metadata;
|
||||
|
||||
public enum ChannelMetadataField
|
||||
{
|
||||
CONFIGURATION_ALIAS_LIST,
|
||||
CONFIGURATION_CHANNEL,
|
||||
CONFIGURATION_FREQUENCY,
|
||||
CONFIGURATION_SITE,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
* Copyright (C) 2014-2024 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@@ -18,73 +18,67 @@
|
||||
*/
|
||||
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 java.util.concurrent.CopyOnWriteArrayList;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 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
|
||||
import javax.swing.table.AbstractTableModel;
|
||||
|
||||
public class ChannelMetadataModel extends AbstractTableModel implements IChannelMetadataUpdateListener
|
||||
{
|
||||
private final List<ChannelMetadata> mChannelMetadata = new ArrayList<>();
|
||||
private final Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap<>();
|
||||
private final List<Listener> mListeners = new CopyOnWriteArrayList<>();
|
||||
private final static Logger mLog = LoggerFactory.getLogger(ChannelMetadataModel.class);
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
/**
|
||||
* Channel metadata(s) for a channel were added to the model.
|
||||
*/
|
||||
void added(ChannelAndMetadata channelAndMetadata);
|
||||
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;
|
||||
|
||||
/**
|
||||
* Channel metadata was removed from the model.
|
||||
*/
|
||||
void removed(ChannelMetadata channelMetadata);
|
||||
private static final String[] COLUMNS = {"Status", "Decoder", "From", "Alias", "To", "Alias", "Channel", "Frequency", "Channel Name"};
|
||||
|
||||
/**
|
||||
* A field of a channel metadata in the model was updated.
|
||||
*/
|
||||
void updated(ChannelMetadata channelMetadata, ChannelMetadataField channelMetadataField);
|
||||
}
|
||||
private List<ChannelMetadata> mChannelMetadata = new ArrayList();
|
||||
private Map<ChannelMetadata,Channel> mMetadataChannelMap = new HashMap();
|
||||
private Listener<ChannelAndMetadata> mChannelAddListener;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
*/
|
||||
public ChannelMetadataModel()
|
||||
{
|
||||
MyEventBus.getGlobalEventBus().register(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Receives preference update notifications via the event bus
|
||||
* @param preferenceType that was updated
|
||||
*/
|
||||
public synchronized List<ChannelMetadata> addListener(Listener listener)
|
||||
@Subscribe
|
||||
public void preferenceUpdated(PreferenceType preferenceType)
|
||||
{
|
||||
mListeners.add(listener);
|
||||
return new ArrayList<>(mChannelMetadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the listener from receiving model change notifications.
|
||||
*/
|
||||
public void removeListener(Listener listener)
|
||||
{
|
||||
mListeners.remove(listener);
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,16 +87,10 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
|
||||
*/
|
||||
public String getDiagnosticInformation()
|
||||
{
|
||||
Map<ChannelMetadata,Channel> mapCopy;
|
||||
List<ChannelMetadata> metadataCopy;
|
||||
|
||||
synchronized(this)
|
||||
{
|
||||
mapCopy = new HashMap<>(mMetadataChannelMap);
|
||||
metadataCopy = new ArrayList<>(mChannelMetadata);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Map<ChannelMetadata,Channel> mapCopy = new HashMap<>(mMetadataChannelMap);
|
||||
List<ChannelMetadata> metadataCopy = new ArrayList<>(mChannelMetadata);
|
||||
|
||||
sb.append("Channel Metadata Model Diagnostics\n");
|
||||
|
||||
for(ChannelMetadata channelMetadata: metadataCopy)
|
||||
@@ -134,34 +122,51 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the model for disposal.
|
||||
*/
|
||||
public void dispose()
|
||||
{
|
||||
mListeners.clear();
|
||||
MyEventBus.getGlobalEventBus().unregister(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the channel metadata(s) for a channel to the model.
|
||||
* Lookup model row for the specified channel metadata
|
||||
*/
|
||||
public synchronized void add(ChannelAndMetadata channelAndMetadata)
|
||||
public int getRow(ChannelMetadata channelMetadata)
|
||||
{
|
||||
for(ChannelMetadata channelMetadata: channelAndMetadata.getChannelMetadata())
|
||||
if(mChannelMetadata.contains(channelMetadata))
|
||||
{
|
||||
if(!mChannelMetadata.contains(channelMetadata))
|
||||
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())
|
||||
{
|
||||
mChannelMetadata.add(channelMetadata);
|
||||
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
|
||||
int index = mChannelMetadata.indexOf(channelMetadata);
|
||||
fireTableRowsInserted(index, index);
|
||||
channelMetadata.setUpdateEventListener(ChannelMetadataModel.this);
|
||||
}
|
||||
|
||||
mMetadataChannelMap.put(channelMetadata, channelAndMetadata.getChannel());
|
||||
channelMetadata.setUpdateEventListener(this);
|
||||
}
|
||||
|
||||
for(Listener listener: mListeners)
|
||||
{
|
||||
listener.added(channelAndMetadata);
|
||||
}
|
||||
if(mChannelAddListener != null)
|
||||
{
|
||||
mChannelAddListener.receive(channelAndMetadata);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,7 +174,7 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
|
||||
* @param channelMetadatas
|
||||
* @param channel
|
||||
*/
|
||||
public synchronized void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
|
||||
public void updateChannelMetadataToChannelMap(Collection<ChannelMetadata> channelMetadatas, Channel channel)
|
||||
{
|
||||
for(ChannelMetadata channelMetadata: channelMetadatas)
|
||||
{
|
||||
@@ -177,46 +182,178 @@ public class ChannelMetadataModel implements IChannelMetadataUpdateListener
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the channel metadata from the model.
|
||||
*/
|
||||
public synchronized void remove(ChannelMetadata channelMetadata)
|
||||
public void remove(ChannelMetadata channelMetadata)
|
||||
{
|
||||
channelMetadata.removeUpdateEventListener();
|
||||
mMetadataChannelMap.remove(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);
|
||||
|
||||
if(mChannelMetadata.remove(channelMetadata))
|
||||
{
|
||||
for(Listener listener: mListeners)
|
||||
if(index >= 0)
|
||||
{
|
||||
listener.removed(channelMetadata);
|
||||
fireTableRowsDeleted(index, index);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Current channel metadata in the model.
|
||||
* @return copy of the channel metadata list.
|
||||
* Get the channel metadata at the specified model row index
|
||||
*/
|
||||
public synchronized List<ChannelMetadata> getChannelMetadata()
|
||||
public ChannelMetadata getChannelMetadata(int row)
|
||||
{
|
||||
return new ArrayList<>(mChannelMetadata);
|
||||
if(row < mChannelMetadata.size())
|
||||
{
|
||||
return mChannelMetadata.get(row);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the channel that matches the metadata or null
|
||||
*/
|
||||
public synchronized Channel getChannelFromMetadata(ChannelMetadata channelMetadata)
|
||||
public 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)
|
||||
{
|
||||
for(Listener listener: mListeners)
|
||||
final int rowIndex = mChannelMetadata.indexOf(channelMetadata);
|
||||
|
||||
if(rowIndex >= 0)
|
||||
{
|
||||
listener.updated(channelMetadata, channelMetadataField);
|
||||
//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;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
117
src/main/java/io/github/dsheirer/controller/ControllerPanel.java
Normal file
117
src/main/java/io/github/dsheirer/controller/ControllerPanel.java
Normal file
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2023 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.controller;
|
||||
|
||||
import com.jidesoft.swing.JideTabbedPane;
|
||||
import io.github.dsheirer.audio.playback.AudioPanel;
|
||||
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
|
||||
import io.github.dsheirer.channel.metadata.NowPlayingPanel;
|
||||
import io.github.dsheirer.eventbus.MyEventBus;
|
||||
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.map.MapPanel;
|
||||
import io.github.dsheirer.map.MapService;
|
||||
import io.github.dsheirer.playlist.PlaylistManager;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.settings.SettingsManager;
|
||||
import io.github.dsheirer.source.tuner.manager.TunerManager;
|
||||
import io.github.dsheirer.source.tuner.ui.TunerViewPanel;
|
||||
import java.awt.Dimension;
|
||||
import jiconfont.icons.font_awesome.FontAwesome;
|
||||
import io.github.dsheirer.gui.theme.ThemedFontIcon;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.swing.Icon;
|
||||
import javax.swing.JLabel;
|
||||
import javax.swing.JPanel;
|
||||
|
||||
public class ControllerPanel extends JPanel
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(ControllerPanel.class);
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int mSettingsTabIndex = -1;
|
||||
|
||||
private AudioPanel mAudioPanel;
|
||||
private NowPlayingPanel mNowPlayingPanel;
|
||||
private MapPanel mMapPanel;
|
||||
private TunerViewPanel mTunerManagerPanel;
|
||||
|
||||
private JideTabbedPane mTabbedPane;
|
||||
|
||||
public ControllerPanel(PlaylistManager playlistManager, AudioPlaybackManager audioPlaybackManager,
|
||||
IconModel iconModel, MapService mapService, SettingsManager settingsManager,
|
||||
TunerManager tunerManager, UserPreferences userPreferences, boolean detailTabsVisible)
|
||||
{
|
||||
mAudioPanel = new AudioPanel(iconModel, userPreferences, settingsManager, audioPlaybackManager,
|
||||
playlistManager.getAliasModel());
|
||||
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, settingsManager, detailTabsVisible);
|
||||
mMapPanel = new MapPanel(mapService, playlistManager.getAliasModel(), iconModel, settingsManager);
|
||||
mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences);
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Now playing panel.
|
||||
*/
|
||||
public NowPlayingPanel getNowPlayingPanel()
|
||||
{
|
||||
return mNowPlayingPanel;
|
||||
}
|
||||
|
||||
private void init()
|
||||
{
|
||||
//Disable visual padding. MigLayout otherwise assumes the tabbed pane has native Aqua margins on macOS and
|
||||
//expands it past the bounds of this panel, clipping the tab content on the left, right and bottom edges.
|
||||
setLayout(new MigLayout("insets 0 0 0 0, novisualpadding", "[grow,fill]", "[]0[grow,fill]0[]"));
|
||||
|
||||
add(mAudioPanel, "wrap");
|
||||
|
||||
mTabbedPane = new JideTabbedPane()
|
||||
{
|
||||
@Override
|
||||
public void setSelectedIndex(int index)
|
||||
{
|
||||
if(index == mSettingsTabIndex)
|
||||
{
|
||||
MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest());
|
||||
}
|
||||
else
|
||||
{
|
||||
super.setSelectedIndex(index);
|
||||
}
|
||||
}
|
||||
};
|
||||
mTabbedPane.setFont(this.getFont());
|
||||
mTabbedPane.addTab("Now Playing", mNowPlayingPanel);
|
||||
mTabbedPane.addTab("Map", mMapPanel);
|
||||
mTabbedPane.addTab("Tuners", mTunerManagerPanel);
|
||||
|
||||
Icon playIcon = new ThemedFontIcon(FontAwesome.PLAY_CIRCLE_O, 20);
|
||||
mTabbedPane.addTab("Playlist Editor", playIcon, new JLabel("Show Playlist Manager"));
|
||||
mSettingsTabIndex = mTabbedPane.getTabCount() - 1;
|
||||
|
||||
//Set preferred size to influence the split between these panels
|
||||
mTabbedPane.setPreferredSize(new Dimension(880, 500));
|
||||
|
||||
add(mTabbedPane, "wrap");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*******************************************************************************
|
||||
* sdr-trunk
|
||||
* Copyright (C) 2014-2018 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
|
||||
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
|
||||
* later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with this program.
|
||||
* If not, see <http://www.gnu.org/licenses/>
|
||||
*
|
||||
******************************************************************************/
|
||||
package io.github.dsheirer.controller.channel;
|
||||
|
||||
import javax.swing.table.AbstractTableModel;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Auto-Start Channel Model
|
||||
*/
|
||||
public class AutoStartChannelModel extends AbstractTableModel
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final int COLUMN_ORDER = 0;
|
||||
public static final int COLUMN_SYSTEM = 1;
|
||||
public static final int COLUMN_SITE = 2;
|
||||
public static final int COLUMN_NAME = 3;
|
||||
public static final int COLUMN_DECODER = 4;
|
||||
|
||||
private static final String[] COLUMN_NAMES = new String[] {"Order", "System", "Site", "Name", "Decoder"};
|
||||
|
||||
private List<Channel> mChannels;
|
||||
|
||||
public AutoStartChannelModel(List<Channel> autoStartChannels)
|
||||
{
|
||||
mChannels = autoStartChannels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRowCount()
|
||||
{
|
||||
return mChannels.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColumnCount()
|
||||
{
|
||||
return COLUMN_NAMES.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getColumnName(int columnIndex)
|
||||
{
|
||||
if(columnIndex < COLUMN_NAMES.length)
|
||||
{
|
||||
return COLUMN_NAMES[columnIndex];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getColumnClass(int columnIndex)
|
||||
{
|
||||
return String.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCellEditable(int rowIndex, int columnIndex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValueAt(int rowIndex, int columnIndex)
|
||||
{
|
||||
Channel channel = mChannels.get(rowIndex);
|
||||
|
||||
switch(columnIndex)
|
||||
{
|
||||
case COLUMN_ORDER:
|
||||
return channel.getAutoStartOrder();
|
||||
case COLUMN_SYSTEM:
|
||||
return channel.getSystem();
|
||||
case COLUMN_SITE:
|
||||
return channel.getSite();
|
||||
case COLUMN_NAME:
|
||||
return channel.getName();
|
||||
case COLUMN_DECODER:
|
||||
return channel.getDecodeConfiguration().getDecoderType().getShortDisplayString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
|
||||
{
|
||||
throw new IllegalArgumentException("Not yet implemented");
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
*/
|
||||
package io.github.dsheirer.controller.channel;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
|
||||
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
|
||||
@@ -84,8 +83,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
|
||||
|
||||
private BooleanProperty mProcessing = new SimpleBooleanProperty();
|
||||
private BooleanProperty mAutoStart = new SimpleBooleanProperty();
|
||||
//Enabled for new channels. Channels loaded from a playlist without the setting keep it disabled, see fromXml().
|
||||
private BooleanProperty mAutoAddTalkerAliases = new SimpleBooleanProperty(true);
|
||||
private IntegerProperty mAutoStartOrder = new SimpleIntegerProperty();
|
||||
private boolean mSelected;
|
||||
private List<TunerChannel> mTunerChannels = null;
|
||||
@@ -126,19 +123,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
|
||||
mChannelID = UNIQUE_ID++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a channel for deserialization from a playlist. Settings added after a channel was saved take their
|
||||
* legacy (disabled) value when the playlist doesn't specify them, instead of the default for new channels, so that
|
||||
* existing channels don't change behavior.
|
||||
*/
|
||||
@JsonCreator
|
||||
private static Channel fromXml()
|
||||
{
|
||||
Channel channel = new Channel();
|
||||
channel.setAutoAddTalkerAliases(false);
|
||||
return channel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a (new) deep copy of this channel
|
||||
*/
|
||||
@@ -150,7 +134,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
|
||||
channel.setAliasListName(mAliasListName.get());
|
||||
channel.setAutoStart(mAutoStart.get());
|
||||
channel.setAutoStartOrder(mAutoStartOrder.get());
|
||||
channel.setAutoAddTalkerAliases(mAutoAddTalkerAliases.get());
|
||||
|
||||
AuxDecodeConfiguration auxCopy = new AuxDecodeConfiguration();
|
||||
|
||||
@@ -526,36 +509,6 @@ public class Channel extends Configuration implements Listener<SourceEvent>
|
||||
mAutoStart.set(autoStart);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-add talker aliases property
|
||||
*/
|
||||
public BooleanProperty autoAddTalkerAliasesProperty()
|
||||
{
|
||||
return mAutoAddTalkerAliases;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if decoded talker aliases are automatically added to the channel's alias list as radio aliases, using
|
||||
* the talker alias as the alias name.
|
||||
*
|
||||
* @return true if talker aliases are automatically added to the alias list
|
||||
*/
|
||||
@JacksonXmlProperty(isAttribute = true, localName = "auto_add_talker_aliases")
|
||||
public boolean isAutoAddTalkerAliases()
|
||||
{
|
||||
return mAutoAddTalkerAliases.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets automatically adding decoded talker aliases to the channel's alias list.
|
||||
*
|
||||
* @param autoAdd true to automatically add talker aliases to the alias list
|
||||
*/
|
||||
public void setAutoAddTalkerAliases(boolean autoAdd)
|
||||
{
|
||||
mAutoAddTalkerAliases.set(autoAdd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-start order. Specifies an optional ordering for channels so that when the application starts up,
|
||||
* the channels can be started in a user-specified order.
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2023 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.controller.channel;
|
||||
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import io.github.dsheirer.util.ThreadPool;
|
||||
import java.awt.Dimension;
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.swing.JButton;
|
||||
import javax.swing.JFrame;
|
||||
import javax.swing.JLabel;
|
||||
import javax.swing.JPanel;
|
||||
import javax.swing.JScrollPane;
|
||||
import javax.swing.JTable;
|
||||
|
||||
public class ChannelAutoStartFrame extends JFrame
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(ChannelAutoStartFrame.class);
|
||||
|
||||
private Listener<ChannelEvent> mChannelEventListener;
|
||||
private List<Channel> mChannels;
|
||||
|
||||
private JLabel mCountdownLabel;
|
||||
private JButton mStartButton;
|
||||
private JButton mCancelButton;
|
||||
private JTable mChannelTable;
|
||||
private AtomicBoolean mChannelsStarted = new AtomicBoolean();
|
||||
private int mAutoStartTimeoutSeconds;
|
||||
private ScheduledFuture<?> mTimerFuture;
|
||||
|
||||
/**
|
||||
* Creates and displays a channel auto-start gui for presenting the user with a list of channels that
|
||||
* will be automatically started once the countdown timer reaches zero, or the user chooses to start
|
||||
* now or cancel.
|
||||
*
|
||||
* @param listener to receive channel start/enable request(s)
|
||||
* @param channels to auto-start
|
||||
*/
|
||||
public ChannelAutoStartFrame(Listener<ChannelEvent> listener, List<Channel> channels, UserPreferences userPreferences)
|
||||
{
|
||||
mChannelEventListener = listener;
|
||||
mChannels = channels;
|
||||
mAutoStartTimeoutSeconds = userPreferences.getApplicationPreference().getChannelAutoStartTimeout();
|
||||
|
||||
init();
|
||||
|
||||
EventQueue.invokeLater(() -> {
|
||||
setVisible(true);
|
||||
toFront();
|
||||
startTimer();
|
||||
});
|
||||
}
|
||||
|
||||
private void init()
|
||||
{
|
||||
setTitle("Auto-Start Channels");
|
||||
setSize(new Dimension(400, 300));
|
||||
setLocationRelativeTo(null);
|
||||
addWindowListener(new WindowAdapter()
|
||||
{
|
||||
@Override
|
||||
public void windowClosing(WindowEvent event)
|
||||
{
|
||||
mLog.info("Channel auto-start canceled by user - window closed");
|
||||
stopTimer();
|
||||
super.windowClosing(event);
|
||||
}
|
||||
});
|
||||
|
||||
JPanel panel = new JPanel();
|
||||
panel.setLayout(new MigLayout("", "[grow,fill][grow,fill]",
|
||||
"[][][grow,fill][]"));
|
||||
panel.add(new JLabel("The following channels will be automatically"), "span");
|
||||
|
||||
mCountdownLabel = new JLabel(getCountdownText(mAutoStartTimeoutSeconds));
|
||||
panel.add(mCountdownLabel, "span");
|
||||
|
||||
panel.add(new JScrollPane(getChannelTable()), "span");
|
||||
|
||||
mStartButton = new JButton("Start Now");
|
||||
mStartButton.addActionListener(new ActionListener()
|
||||
{
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e)
|
||||
{
|
||||
mLog.info("Starting [" + mChannels.size() + "] channels now - user invoked");
|
||||
startChannels();
|
||||
stopTimer();
|
||||
}
|
||||
});
|
||||
panel.add(mStartButton);
|
||||
|
||||
mCancelButton = new JButton("Cancel");
|
||||
mCancelButton.addActionListener(new ActionListener()
|
||||
{
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e)
|
||||
{
|
||||
mLog.info("Channel auto-start canceled by user");
|
||||
stopTimer();
|
||||
}
|
||||
});
|
||||
panel.add(mCancelButton);
|
||||
setContentPane(panel);
|
||||
}
|
||||
|
||||
private String getCountdownText(int value)
|
||||
{
|
||||
return "started in: " + value + " seconds.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the countdown text label on the swing event thread
|
||||
*
|
||||
* @param value for the countdown
|
||||
*/
|
||||
private void updateCountdownText(final int value)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
mCountdownLabel.setText(getCountdownText(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates (once) a table of auto-start channels
|
||||
*/
|
||||
private JTable getChannelTable()
|
||||
{
|
||||
if(mChannelTable == null)
|
||||
{
|
||||
AutoStartChannelModel model = new AutoStartChannelModel(mChannels);
|
||||
mChannelTable = new JTable(model);
|
||||
}
|
||||
|
||||
return mChannelTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an enable (ie start) request for each of the auto start channels.
|
||||
*
|
||||
* This method is thread-safe and will only be executed once.
|
||||
*
|
||||
* Although the redundant channel-start request would be ignored, this once-only will prevent the chance
|
||||
* that both the timer and the user would attempt to start the channels at the same time.
|
||||
*/
|
||||
private void startChannels()
|
||||
{
|
||||
if(mChannelsStarted.compareAndSet(false, true))
|
||||
{
|
||||
if(mChannelEventListener != null)
|
||||
{
|
||||
for(Channel channel : mChannels)
|
||||
{
|
||||
mChannelEventListener.receive(new ChannelEvent(channel, ChannelEvent.Event.REQUEST_ENABLE));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the countdown timer to fire once a second.
|
||||
*/
|
||||
private void startTimer()
|
||||
{
|
||||
if(mTimerFuture == null)
|
||||
{
|
||||
mTimerFuture = ThreadPool.SCHEDULED.scheduleAtFixedRate(new CountdownTimer(), 0, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the countdown timer and disposes this frame
|
||||
*/
|
||||
private void stopTimer()
|
||||
{
|
||||
if(mTimerFuture != null)
|
||||
{
|
||||
mTimerFuture.cancel(true);
|
||||
mTimerFuture = null;
|
||||
}
|
||||
|
||||
EventQueue.invokeLater(() -> dispose());
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the countdown text and auto-starts the channels once the timer falls below zero.
|
||||
*/
|
||||
public class CountdownTimer implements Runnable
|
||||
{
|
||||
private int mCount = mAutoStartTimeoutSeconds;
|
||||
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
if(mCount >= 0)
|
||||
{
|
||||
updateCountdownText(mCount);
|
||||
mCount--;
|
||||
}
|
||||
else
|
||||
{
|
||||
mLog.info("Starting [" + mChannels.size() + "] now - timer invoked");
|
||||
startChannels();
|
||||
stopTimer();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.controller.channel;
|
||||
|
||||
import io.github.dsheirer.gui.ApplicationIcons;
|
||||
import io.github.dsheirer.gui.theme.ThemeManager;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import io.github.dsheirer.util.ThreadPool;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Function;
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.beans.property.ReadOnlyStringWrapper;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ProgressBar;
|
||||
import javafx.scene.control.TableColumn;
|
||||
import javafx.scene.control.TableView;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.Region;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.Window;
|
||||
import javafx.util.Duration;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Lists the channels that are set to start automatically and starts them when the countdown ends. The user can
|
||||
* start them now, or cancel by pressing Cancel or closing the window.
|
||||
*/
|
||||
public class ChannelAutoStartWindow
|
||||
{
|
||||
private static final Logger mLog = LoggerFactory.getLogger(ChannelAutoStartWindow.class);
|
||||
|
||||
private final Listener<ChannelEvent> mChannelEventListener;
|
||||
private final List<Channel> mChannels;
|
||||
private final int mTimeoutSeconds;
|
||||
private final AtomicBoolean mFinished = new AtomicBoolean();
|
||||
private final Stage mStage = new Stage();
|
||||
private final Label mCountdownLabel = new Label();
|
||||
private final ProgressBar mProgressBar = new ProgressBar(1.0);
|
||||
private final Timeline mTimeline;
|
||||
private int mRemainingSeconds;
|
||||
|
||||
/**
|
||||
* Constructs an instance. JavaFX thread only.
|
||||
* @param listener to receive the channel start requests
|
||||
* @param channels to start, in auto-start order
|
||||
* @param userPreferences for the countdown length
|
||||
* @param owner window, or null
|
||||
*/
|
||||
public ChannelAutoStartWindow(Listener<ChannelEvent> listener, List<Channel> channels,
|
||||
UserPreferences userPreferences, Window owner)
|
||||
{
|
||||
mChannelEventListener = listener;
|
||||
mChannels = channels;
|
||||
mTimeoutSeconds = Math.max(0, userPreferences.getApplicationPreference().getChannelAutoStartTimeout());
|
||||
mRemainingSeconds = mTimeoutSeconds;
|
||||
|
||||
Label title = new Label("Starting " + channels.size() + (channels.size() == 1 ? " channel" : " channels"));
|
||||
title.setStyle("-fx-font-size: 1.25em; -fx-font-weight: bold;");
|
||||
mProgressBar.setMaxWidth(Double.MAX_VALUE);
|
||||
|
||||
TableView<Channel> table = new TableView<>(FXCollections.observableArrayList(channels));
|
||||
table.getColumns().addAll(List.of(
|
||||
column("Order", 60, channel -> String.valueOf(channel.getAutoStartOrder())),
|
||||
column("System", 140, Channel::getSystem),
|
||||
column("Site", 120, Channel::getSite),
|
||||
column("Name", 180, Channel::getName),
|
||||
column("Decoder", 100, channel -> channel.getDecodeConfiguration().getDecoderType()
|
||||
.getShortDisplayString())));
|
||||
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN);
|
||||
VBox.setVgrow(table, Priority.ALWAYS);
|
||||
|
||||
Button startButton = new Button("Start Now");
|
||||
startButton.setDefaultButton(true);
|
||||
startButton.setOnAction(event -> {
|
||||
mLog.info("Starting [" + mChannels.size() + "] channels now - user invoked");
|
||||
finish(true);
|
||||
});
|
||||
Button cancelButton = new Button("Cancel");
|
||||
cancelButton.setCancelButton(true);
|
||||
cancelButton.setOnAction(event -> {
|
||||
mLog.info("Channel auto-start canceled by user");
|
||||
finish(false);
|
||||
});
|
||||
Region spacer = new Region();
|
||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||
HBox buttons = new HBox(8, spacer, cancelButton, startButton);
|
||||
buttons.setAlignment(Pos.CENTER_RIGHT);
|
||||
|
||||
VBox root = new VBox(8, title, mCountdownLabel, mProgressBar, table, buttons);
|
||||
root.setPadding(new Insets(12));
|
||||
|
||||
Scene scene = new Scene(root, 640, 340);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mStage.setScene(scene);
|
||||
mStage.setTitle("Auto-Start Channels");
|
||||
ApplicationIcons.apply(mStage);
|
||||
|
||||
if(owner != null)
|
||||
{
|
||||
mStage.initOwner(owner);
|
||||
}
|
||||
|
||||
mStage.setOnCloseRequest(event -> {
|
||||
mLog.info("Channel auto-start canceled by user - window closed");
|
||||
finish(false);
|
||||
});
|
||||
|
||||
mTimeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> tick()));
|
||||
mTimeline.setCycleCount(Timeline.INDEFINITE);
|
||||
updateCountdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the window and starts the countdown. JavaFX thread only.
|
||||
*/
|
||||
public void show()
|
||||
{
|
||||
mStage.show();
|
||||
mStage.toFront();
|
||||
|
||||
if(mTimeoutSeconds == 0)
|
||||
{
|
||||
mLog.info("Starting [" + mChannels.size() + "] now - no auto-start delay");
|
||||
finish(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
mTimeline.play();
|
||||
}
|
||||
}
|
||||
|
||||
private void tick()
|
||||
{
|
||||
mRemainingSeconds--;
|
||||
|
||||
if(mRemainingSeconds <= 0)
|
||||
{
|
||||
mLog.info("Starting [" + mChannels.size() + "] now - timer invoked");
|
||||
finish(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
updateCountdown();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateCountdown()
|
||||
{
|
||||
mCountdownLabel.setText("These channels start automatically in " + mRemainingSeconds +
|
||||
(mRemainingSeconds == 1 ? " second." : " seconds."));
|
||||
mProgressBar.setProgress(mTimeoutSeconds > 0 ? (double)mRemainingSeconds / mTimeoutSeconds : 0.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the countdown, closes the window and optionally starts the channels. Only the first call has an
|
||||
* effect, so that the timer and the user can't both start the channels.
|
||||
*/
|
||||
private void finish(boolean start)
|
||||
{
|
||||
if(!mFinished.compareAndSet(false, true))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
mTimeline.stop();
|
||||
mStage.close();
|
||||
|
||||
if(start && mChannelEventListener != null)
|
||||
{
|
||||
//Starting channels can block while tuners start, so start them off the JavaFX thread, in order
|
||||
ThreadPool.CACHED.submit(() -> {
|
||||
for(Channel channel: mChannels)
|
||||
{
|
||||
mChannelEventListener.receive(new ChannelEvent(channel, ChannelEvent.Event.REQUEST_ENABLE));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static TableColumn<Channel,String> column(String title, double width, Function<Channel,String> value)
|
||||
{
|
||||
TableColumn<Channel,String> column = new TableColumn<>(title);
|
||||
column.setPrefWidth(width);
|
||||
column.setCellValueFactory(param -> new ReadOnlyStringWrapper(value.apply(param.getValue())));
|
||||
return column;
|
||||
}
|
||||
}
|
||||
@@ -153,14 +153,6 @@ 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
|
||||
|
||||
@@ -30,11 +30,13 @@ import javafx.collections.ObservableList;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.swing.AbstractListModel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ChannelMapModel
|
||||
public class ChannelMapModel extends AbstractListModel<ChannelMap>
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final static Logger mLog = LoggerFactory.getLogger(ChannelMapModel.class);
|
||||
|
||||
private ObservableList<ChannelMap> mChannelMaps = FXCollections.observableArrayList(ChannelMap.extractor());
|
||||
@@ -106,6 +108,17 @@ public class ChannelMapModel
|
||||
*/
|
||||
public void broadcast(ChannelMapEvent event)
|
||||
{
|
||||
if(event.getEvent() == ChannelMapEvent.Event.CHANGE ||
|
||||
event.getEvent() == ChannelMapEvent.Event.RENAME)
|
||||
{
|
||||
int index = mChannelMaps.indexOf(event.getChannelMap());
|
||||
|
||||
if(index >= 0)
|
||||
{
|
||||
fireContentsChanged(this, index, index);
|
||||
}
|
||||
}
|
||||
|
||||
mEventBroadcaster.broadcast(event);
|
||||
}
|
||||
|
||||
@@ -129,6 +142,10 @@ public class ChannelMapModel
|
||||
{
|
||||
mChannelMaps.add(channelMap);
|
||||
|
||||
int index = mChannelMaps.indexOf(channelMap);
|
||||
|
||||
fireIntervalAdded(this, index, index);
|
||||
|
||||
broadcast(new ChannelMapEvent(channelMap, Event.ADD));
|
||||
}
|
||||
}
|
||||
@@ -140,9 +157,36 @@ public class ChannelMapModel
|
||||
{
|
||||
if(mChannelMaps.contains(channelMap))
|
||||
{
|
||||
int index = mChannelMaps.indexOf(channelMap);
|
||||
|
||||
mChannelMaps.remove(channelMap);
|
||||
|
||||
fireIntervalRemoved(this, index, index);
|
||||
|
||||
broadcast(new ChannelMapEvent(channelMap, Event.DELETE));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Size/Number of channel maps in this model
|
||||
*/
|
||||
@Override
|
||||
public int getSize()
|
||||
{
|
||||
return mChannelMaps.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the channel map at the specified index
|
||||
*/
|
||||
@Override
|
||||
public ChannelMap getElementAt(int index)
|
||||
{
|
||||
if(index <= mChannelMaps.size())
|
||||
{
|
||||
return mChannelMaps.get(index);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
/*
|
||||
*
|
||||
* * ******************************************************************************
|
||||
* * Copyright (C) 2014-2020 Dennis Sheirer
|
||||
* *
|
||||
* * This program is free software: you can redistribute it and/or modify
|
||||
* * it under the terms of the GNU General Public License as published by
|
||||
* * the Free Software Foundation, either version 3 of the License, or
|
||||
* * (at your option) any later version.
|
||||
* *
|
||||
* * This program is distributed in the hope that it will be useful,
|
||||
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* * GNU General Public License for more details.
|
||||
* *
|
||||
* * You should have received a copy of the GNU General Public License
|
||||
* * along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* * *****************************************************************************
|
||||
*
|
||||
*
|
||||
*/
|
||||
package io.github.dsheirer.controller.channel.map;
|
||||
|
||||
import javax.swing.table.AbstractTableModel;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class ChannelRangeModel extends AbstractTableModel
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static final int START = 0;
|
||||
private static final int STOP = 1;
|
||||
private static final int BASE = 2;
|
||||
private static final int SIZE = 3;
|
||||
private static final int ERROR = 4;
|
||||
|
||||
protected int[] mColumnWidths = { 110, 110, 110, -1, 80 };
|
||||
|
||||
protected String[] mHeaders = new String[] { "Begin",
|
||||
"End",
|
||||
"Base",
|
||||
"Size",
|
||||
"Error" };
|
||||
|
||||
private List<ChannelRange> mRanges = new CopyOnWriteArrayList<>();
|
||||
private ChannelRangeEventListener mListener;
|
||||
|
||||
public ChannelRangeModel()
|
||||
{
|
||||
}
|
||||
|
||||
public void setListener( ChannelRangeEventListener listener )
|
||||
{
|
||||
mListener = listener;
|
||||
}
|
||||
|
||||
private void broadcastChange()
|
||||
{
|
||||
if( mListener != null )
|
||||
{
|
||||
mListener.channelRangesChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public void clear()
|
||||
{
|
||||
for( ChannelRange range: mRanges )
|
||||
{
|
||||
removeRange( range );
|
||||
}
|
||||
|
||||
broadcastChange();
|
||||
}
|
||||
|
||||
public List<ChannelRange> getChannelRanges()
|
||||
{
|
||||
return mRanges;
|
||||
}
|
||||
|
||||
public void addRanges( List<ChannelRange> ranges )
|
||||
{
|
||||
for( ChannelRange range: ranges )
|
||||
{
|
||||
addRange( range );
|
||||
}
|
||||
|
||||
broadcastChange();
|
||||
}
|
||||
|
||||
public void addRange( ChannelRange range )
|
||||
{
|
||||
if( range != null && !mRanges.contains( range ) )
|
||||
{
|
||||
mRanges.add( range );
|
||||
|
||||
int index = mRanges.indexOf( range );
|
||||
|
||||
fireTableRowsInserted( index, index );
|
||||
}
|
||||
|
||||
validate();
|
||||
|
||||
broadcastChange();
|
||||
}
|
||||
|
||||
public void removeRange( ChannelRange range )
|
||||
{
|
||||
if( range != null && mRanges.contains( range ) )
|
||||
{
|
||||
int index = mRanges.indexOf( range );
|
||||
|
||||
mRanges.remove( range );
|
||||
|
||||
fireTableRowsDeleted( index, index );
|
||||
}
|
||||
|
||||
validate();
|
||||
|
||||
broadcastChange();
|
||||
}
|
||||
|
||||
public int[] getColumnWidths()
|
||||
{
|
||||
return mColumnWidths;
|
||||
}
|
||||
|
||||
public void setColumnWidths( int[] widths )
|
||||
{
|
||||
if( widths.length != mHeaders.length )
|
||||
{
|
||||
throw new IllegalArgumentException( "ChannelMapRangeModel - "
|
||||
+ "column widths array should have " +
|
||||
mHeaders.length + " elements" );
|
||||
}
|
||||
else
|
||||
{
|
||||
mColumnWidths = widths;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRowCount()
|
||||
{
|
||||
return mRanges.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColumnCount()
|
||||
{
|
||||
return mHeaders.length;
|
||||
}
|
||||
|
||||
public String getColumnName( int column )
|
||||
{
|
||||
return mHeaders[ column ];
|
||||
}
|
||||
|
||||
public ChannelRange getChannelRange( int index )
|
||||
{
|
||||
if( index < mRanges.size() )
|
||||
{
|
||||
return mRanges.get( index );
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getValueAt( int rowIndex, int columnIndex )
|
||||
{
|
||||
ChannelRange range = getChannelRange( rowIndex );
|
||||
|
||||
if( range != null )
|
||||
{
|
||||
switch( columnIndex )
|
||||
{
|
||||
case START:
|
||||
return range.getFirstChannelNumber();
|
||||
case STOP:
|
||||
return range.getLastChannelNumber();
|
||||
case BASE:
|
||||
return range.getBaseFrequency();
|
||||
case SIZE:
|
||||
return range.getStepSize();
|
||||
case ERROR:
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
if( !range.isValid() )
|
||||
{
|
||||
sb.append( "Sequence" );
|
||||
}
|
||||
|
||||
if( range.isOverlapping() )
|
||||
{
|
||||
if( sb.length() > 0 )
|
||||
{
|
||||
sb.append( "," );
|
||||
}
|
||||
|
||||
sb.append( "Overlap" );
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates each of the channel ranges for overlap
|
||||
*/
|
||||
private void validate()
|
||||
{
|
||||
for( int x = 0; x < mRanges.size(); x++ )
|
||||
{
|
||||
mRanges.get( x ).setOverlapping( false );
|
||||
fireTableCellUpdated( x, ERROR );
|
||||
}
|
||||
|
||||
for( int x = 0; x < mRanges.size(); x++ )
|
||||
{
|
||||
for( int y = x + 1; y < mRanges.size(); y++ )
|
||||
{
|
||||
if( mRanges.get( x ).overlaps( mRanges.get( y ) ) )
|
||||
{
|
||||
mRanges.get( x ).setOverlapping( true );
|
||||
fireTableCellUpdated( x, ERROR );
|
||||
|
||||
mRanges.get( y ).setOverlapping( true );
|
||||
fireTableCellUpdated( y, ERROR );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isCellEditable( int row, int column )
|
||||
{
|
||||
return row < mRanges.size() && column != ERROR;
|
||||
}
|
||||
|
||||
public void setValueAt( Object value, int row, int column )
|
||||
{
|
||||
int parsedValue = -1;
|
||||
|
||||
try
|
||||
{
|
||||
parsedValue = Integer.parseInt( (String)value );
|
||||
}
|
||||
catch( Exception e )
|
||||
{
|
||||
//Do nothing ... we'll use 0
|
||||
}
|
||||
|
||||
if( parsedValue >= 0 )
|
||||
{
|
||||
ChannelRange range = getChannelRange( row );
|
||||
|
||||
if( range != null )
|
||||
{
|
||||
switch( column )
|
||||
{
|
||||
case START:
|
||||
range.setFirstChannelNumber( parsedValue );
|
||||
break;
|
||||
case STOP:
|
||||
range.setLastChannelNumber( parsedValue );
|
||||
break;
|
||||
case BASE:
|
||||
range.setBaseFrequency( parsedValue );
|
||||
break;
|
||||
case SIZE:
|
||||
range.setStepSize( parsedValue );
|
||||
break;
|
||||
}
|
||||
|
||||
validate();
|
||||
|
||||
broadcastChange();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IllegalArgumentException( "Invalid channel range row index" );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface ChannelRangeEventListener
|
||||
{
|
||||
public void channelRangesChanged();
|
||||
}
|
||||
}
|
||||
@@ -1,347 +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.database;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import io.github.dsheirer.database.call.CallRepository;
|
||||
import io.github.dsheirer.database.call.ICallRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* An open connection pool to one database and schema, with the sdrtrunk schema installation logic.
|
||||
*/
|
||||
public class CallDatabase implements AutoCloseable
|
||||
{
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(CallDatabase.class);
|
||||
|
||||
/**
|
||||
* Version of the sdrtrunk tables that this release creates. Increment and add an upgrade step to
|
||||
* {@link #getUpgradeStatements(int)} when the tables change.
|
||||
*/
|
||||
public static final int SCHEMA_VERSION = 2;
|
||||
public static final String SCHEMA_INFO_TABLE = "schema_info";
|
||||
|
||||
private final DatabaseConfiguration mConfiguration;
|
||||
private final HikariDataSource mDataSource;
|
||||
private final ICallRepository mCallRepository;
|
||||
|
||||
/**
|
||||
* Opens a connection pool for the configuration. The schema isn't created or checked.
|
||||
* @param configuration for the database
|
||||
* @param databaseDirectory for the built-in database files
|
||||
* @throws SQLException if the database can't be reached
|
||||
*/
|
||||
public CallDatabase(DatabaseConfiguration configuration, Path databaseDirectory) throws SQLException
|
||||
{
|
||||
mConfiguration = configuration;
|
||||
mCallRepository = new CallRepository(configuration.schema());
|
||||
|
||||
if(configuration.type() == DatabaseType.H2)
|
||||
{
|
||||
try
|
||||
{
|
||||
Files.createDirectories(databaseDirectory);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw new SQLException("Unable to create the database directory [" + databaseDirectory + "]", e);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Class.forName(configuration.type().getDialect().getDriverClass());
|
||||
}
|
||||
catch(ClassNotFoundException cnfe)
|
||||
{
|
||||
throw new SQLException("Database driver isn't available: " + configuration.type().getDialect().getDriverClass(), cnfe);
|
||||
}
|
||||
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setPoolName("sdrtrunk-db-" + configuration.type().name().toLowerCase(Locale.ROOT));
|
||||
config.setJdbcUrl(configuration.getJdbcUrl(databaseDirectory));
|
||||
config.setDriverClassName(configuration.type().getDialect().getDriverClass());
|
||||
|
||||
if(configuration.type().isNetwork())
|
||||
{
|
||||
config.setUsername(configuration.user());
|
||||
config.setPassword(configuration.password());
|
||||
}
|
||||
else
|
||||
{
|
||||
config.setUsername("sa");
|
||||
config.setPassword("");
|
||||
}
|
||||
|
||||
config.setMaximumPoolSize(4);
|
||||
config.setMinimumIdle(1);
|
||||
config.setConnectionTimeout(10_000);
|
||||
config.setValidationTimeout(5_000);
|
||||
//Fail immediately when the database can't be reached, so the user gets an answer
|
||||
config.setInitializationFailTimeout(1);
|
||||
|
||||
try
|
||||
{
|
||||
mDataSource = new HikariDataSource(config);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Throwable cause = e.getCause() != null ? e.getCause() : e;
|
||||
throw new SQLException("Unable to connect to " + configuration.getDescription() + ": " +
|
||||
cause.getMessage(), cause);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for this database
|
||||
*/
|
||||
public DatabaseConfiguration getConfiguration()
|
||||
{
|
||||
return mConfiguration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Repository for the calls table in this schema
|
||||
*/
|
||||
public ICallRepository getCallRepository()
|
||||
{
|
||||
return mCallRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pooled connection. Close it to return it to the pool.
|
||||
*/
|
||||
public Connection getConnection() throws SQLException
|
||||
{
|
||||
return mDataSource.getConnection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the configured schema exists and whether it holds sdrtrunk tables.
|
||||
*/
|
||||
public SchemaStatus getSchemaStatus() throws SQLException
|
||||
{
|
||||
try(Connection connection = getConnection())
|
||||
{
|
||||
return getSchemaStatus(connection, mConfiguration.schema());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the status of the named schema.
|
||||
*/
|
||||
public static SchemaStatus getSchemaStatus(Connection connection, String schema) throws SQLException
|
||||
{
|
||||
boolean schemaExists;
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " +
|
||||
"information_schema.schemata WHERE LOWER(schema_name) = ?"))
|
||||
{
|
||||
statement.setString(1, schema.toLowerCase(Locale.ROOT));
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
schemaExists = rs.next() && rs.getLong(1) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
if(!schemaExists)
|
||||
{
|
||||
return SchemaStatus.MISSING;
|
||||
}
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " +
|
||||
"information_schema.tables WHERE LOWER(table_schema) = ? AND LOWER(table_name) = ?"))
|
||||
{
|
||||
statement.setString(1, schema.toLowerCase(Locale.ROOT));
|
||||
statement.setString(2, SCHEMA_INFO_TABLE);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
return rs.next() && rs.getLong(1) > 0 ? SchemaStatus.SDRTRUNK : SchemaStatus.EMPTY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of calls stored in the schema, or 0 if the schema doesn't have sdrtrunk tables.
|
||||
*/
|
||||
public long getCallCount() throws SQLException
|
||||
{
|
||||
if(getSchemaStatus() != SchemaStatus.SDRTRUNK)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
try(Connection connection = getConnection())
|
||||
{
|
||||
return mCallRepository.count(connection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the schema and tables when they don't exist and upgrades the tables of an older version.
|
||||
* @throws SQLException on error, or if the schema was created by a newer version of sdrtrunk
|
||||
*/
|
||||
public void install() throws SQLException
|
||||
{
|
||||
DatabaseType type = mConfiguration.type();
|
||||
String schema = mConfiguration.schema();
|
||||
|
||||
try(Connection connection = getConnection(); Statement statement = connection.createStatement())
|
||||
{
|
||||
statement.execute(type.getDialect().getCreateSchemaStatement(schema));
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS " + schema + "." + SCHEMA_INFO_TABLE +
|
||||
" (version INT NOT NULL)");
|
||||
|
||||
int version = getVersion(connection);
|
||||
|
||||
if(version > SCHEMA_VERSION)
|
||||
{
|
||||
throw new SQLException("Schema [" + schema + "] was created by a newer version of sdrtrunk (schema " +
|
||||
"version " + version + "). This version supports schema version " + SCHEMA_VERSION + ".");
|
||||
}
|
||||
|
||||
if(version < SCHEMA_VERSION)
|
||||
{
|
||||
for(String sql: getUpgradeStatements(version))
|
||||
{
|
||||
statement.execute(sql);
|
||||
}
|
||||
|
||||
if(version == 0)
|
||||
{
|
||||
statement.executeUpdate("INSERT INTO " + schema + "." + SCHEMA_INFO_TABLE +
|
||||
" (version) VALUES (" + SCHEMA_VERSION + ")");
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.executeUpdate("UPDATE " + schema + "." + SCHEMA_INFO_TABLE + " SET version = " +
|
||||
SCHEMA_VERSION);
|
||||
}
|
||||
|
||||
LOGGER.info("Installed sdrtrunk schema version " + SCHEMA_VERSION + " in " +
|
||||
mConfiguration.getDescription() + (version > 0 ? " (upgraded from version " + version + ")" : ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Statements that bring the tables from the version argument up to the current version.
|
||||
*/
|
||||
private List<String> getUpgradeStatements(int fromVersion)
|
||||
{
|
||||
List<String> statements = new ArrayList<>();
|
||||
|
||||
if(fromVersion < 1)
|
||||
{
|
||||
statements.addAll(CallRepository.getCreateStatements(mConfiguration.type().getDialect(), mConfiguration.schema()));
|
||||
}
|
||||
|
||||
//Version 2: talkgroups patched into patch group calls
|
||||
if(fromVersion < 2)
|
||||
{
|
||||
statements.addAll(CallRepository.getPatchedTalkgroupCreateStatements(mConfiguration.schema()));
|
||||
}
|
||||
|
||||
return statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installed schema version, or 0 when nothing is installed.
|
||||
*/
|
||||
private int getVersion(Connection connection) throws SQLException
|
||||
{
|
||||
try(Statement statement = connection.createStatement();
|
||||
ResultSet rs = statement.executeQuery("SELECT MAX(version) FROM " + mConfiguration.schema() + "." +
|
||||
SCHEMA_INFO_TABLE))
|
||||
{
|
||||
return rs.next() ? rs.getInt(1) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the schema with all of its tables and then installs an empty sdrtrunk schema.
|
||||
*/
|
||||
public void clear() throws SQLException
|
||||
{
|
||||
try(Connection connection = getConnection(); Statement statement = connection.createStatement())
|
||||
{
|
||||
statement.execute(mConfiguration.type().getDialect().getDropSchemaStatement(mConfiguration.schema()));
|
||||
}
|
||||
|
||||
install();
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggests an unused schema name derived from the configured schema name (e.g. sdrtrunk_2).
|
||||
*/
|
||||
public String suggestSchemaName() throws SQLException
|
||||
{
|
||||
try(Connection connection = getConnection())
|
||||
{
|
||||
String base = mConfiguration.schema();
|
||||
|
||||
for(int x = 2; x < 1000; x++)
|
||||
{
|
||||
String candidate = base + "_" + x;
|
||||
|
||||
if(candidate.length() <= 63 && getSchemaStatus(connection, candidate) == SchemaStatus.MISSING)
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return mConfiguration.schema() + "_new";
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the named schema exists in this database.
|
||||
*/
|
||||
public boolean schemaExists(String schema) throws SQLException
|
||||
{
|
||||
try(Connection connection = getConnection())
|
||||
{
|
||||
return getSchemaStatus(connection, schema) != SchemaStatus.MISSING;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close()
|
||||
{
|
||||
if(!mDataSource.isClosed())
|
||||
{
|
||||
mDataSource.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,158 +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.database;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Connection settings for a call database.
|
||||
*
|
||||
* @param type of database engine
|
||||
* @param host name or address of a network database server (ignored for H2)
|
||||
* @param port of the network database server (ignored for H2)
|
||||
* @param database name to connect to (PostgreSQL only)
|
||||
* @param schema name that holds the sdrtrunk tables
|
||||
* @param user name for a network database server
|
||||
* @param password for a network database server
|
||||
*/
|
||||
public record DatabaseConfiguration(DatabaseType type, String host, int port, String database, String schema,
|
||||
String user, String password)
|
||||
{
|
||||
public static final String DEFAULT_SCHEMA = "sdrtrunk";
|
||||
|
||||
/**
|
||||
* Schema names are restricted to unquoted SQL identifiers so that they can be used in statements without quoting
|
||||
* and so that they mean the same thing across all engines (H2 upper-cases unquoted names, the others don't).
|
||||
*/
|
||||
private static final Pattern SCHEMA_PATTERN = Pattern.compile("[a-z][a-z0-9_]{0,62}");
|
||||
|
||||
public DatabaseConfiguration
|
||||
{
|
||||
Objects.requireNonNull(type, "type");
|
||||
host = host == null ? "" : host.trim();
|
||||
database = database == null ? "" : database.trim();
|
||||
schema = schema == null || schema.isBlank() ? DEFAULT_SCHEMA : schema.trim().toLowerCase();
|
||||
user = user == null ? "" : user;
|
||||
password = password == null ? "" : password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default configuration: the built-in H2 database with the default schema.
|
||||
*/
|
||||
public static DatabaseConfiguration getDefault()
|
||||
{
|
||||
return new DatabaseConfiguration(DatabaseType.H2, "", 0, "", DEFAULT_SCHEMA, "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy of this configuration with a different schema name.
|
||||
*/
|
||||
public DatabaseConfiguration withSchema(String schemaName)
|
||||
{
|
||||
return new DatabaseConfiguration(type, host, port, database, schemaName, user, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the schema name is a valid, unquoted identifier.
|
||||
*/
|
||||
public static boolean isValidSchemaName(String schema)
|
||||
{
|
||||
return schema != null && SCHEMA_PATTERN.matcher(schema).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates this configuration.
|
||||
* @return null if valid, or a description of the problem.
|
||||
*/
|
||||
public String validate()
|
||||
{
|
||||
if(!isValidSchemaName(schema))
|
||||
{
|
||||
return "Schema name must start with a letter and contain only lower case letters, digits and underscores " +
|
||||
"(max 63 characters)";
|
||||
}
|
||||
|
||||
if(type.isNetwork())
|
||||
{
|
||||
if(host.isEmpty())
|
||||
{
|
||||
return "Host is required";
|
||||
}
|
||||
|
||||
if(port <= 0 || port > 65535)
|
||||
{
|
||||
return "Port must be in the range 1 - 65535";
|
||||
}
|
||||
|
||||
if(user.isEmpty())
|
||||
{
|
||||
return "User name is required";
|
||||
}
|
||||
}
|
||||
|
||||
if(type.requiresDatabaseName() && database.isEmpty())
|
||||
{
|
||||
return "Database name is required";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* JDBC URL for this configuration.
|
||||
* @param databaseDirectory for the built-in H2 database files
|
||||
*/
|
||||
public String getJdbcUrl(Path databaseDirectory)
|
||||
{
|
||||
return type.getDialect().getJdbcUrl(this, databaseDirectory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Short description for the user, without the password.
|
||||
*/
|
||||
public String getDescription()
|
||||
{
|
||||
return switch(type)
|
||||
{
|
||||
case H2 -> type + " - schema [" + schema + "]";
|
||||
case MARIADB -> type + " " + user + "@" + host + ":" + port + " - schema [" + schema + "]";
|
||||
case POSTGRESQL -> type + " " + user + "@" + host + ":" + port + "/" + database + " - schema [" +
|
||||
schema + "]";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this configuration refers to the same database and schema as the other configuration (ignoring
|
||||
* credentials).
|
||||
*/
|
||||
public boolean isSameLocation(DatabaseConfiguration other)
|
||||
{
|
||||
return other != null && type == other.type && schema.equals(other.schema) &&
|
||||
(!type.isNetwork() || (host.equalsIgnoreCase(other.host) && port == other.port &&
|
||||
database.equals(other.database)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return getDescription();
|
||||
}
|
||||
}
|
||||
@@ -1,45 +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.database;
|
||||
|
||||
/**
|
||||
* Call database status change notification
|
||||
*
|
||||
* @param type of event
|
||||
* @param configuration of the current database
|
||||
* @param errorMessage for an ERROR event, otherwise null
|
||||
*/
|
||||
public record DatabaseEvent(Type type, DatabaseConfiguration configuration, String errorMessage)
|
||||
{
|
||||
public enum Type
|
||||
{
|
||||
/**
|
||||
* Database opened, or a different database was selected
|
||||
*/
|
||||
CONNECTED,
|
||||
/**
|
||||
* Database couldn't be opened or the connection was lost
|
||||
*/
|
||||
ERROR,
|
||||
/**
|
||||
* Stored calls changed outside of the live call updates, for example by an age-off rule
|
||||
*/
|
||||
CALLS_CHANGED
|
||||
}
|
||||
}
|
||||
@@ -1,718 +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.database;
|
||||
|
||||
import io.github.dsheirer.database.ageoff.AgeOffManager;
|
||||
import io.github.dsheirer.database.call.CallRecord;
|
||||
import io.github.dsheirer.database.call.ICallRepository;
|
||||
import io.github.dsheirer.database.call.CallSearchCriteria;
|
||||
import io.github.dsheirer.database.call.CallState;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.sample.Broadcaster;
|
||||
import io.github.dsheirer.sample.Listener;
|
||||
import io.github.dsheirer.controller.NamingThreadFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Manages the call database: opens the selected database at startup, writes call records in the background, runs the
|
||||
* age-off rules and switches between databases (with optional transfer of the existing calls).
|
||||
*
|
||||
* All writes, the age-off rules and database switches run on a single database thread, so they never overlap.
|
||||
* Searches run on a separate thread so that a long write doesn't block the user interface.
|
||||
*
|
||||
* Call recording doesn't depend on the database: when the database is unavailable, call updates are held in memory
|
||||
* (newest update per call) and written when the database becomes available again.
|
||||
*/
|
||||
public class DatabaseManager
|
||||
{
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseManager.class);
|
||||
private static final long FLUSH_INTERVAL_MS = 250;
|
||||
private static final long RETRY_INTERVAL_MS = 30_000;
|
||||
private static final int MAX_PENDING_CALLS = 20_000;
|
||||
private static final int TRANSFER_PAGE_SIZE = 1000;
|
||||
|
||||
private final UserPreferences mUserPreferences;
|
||||
private final ScheduledExecutorService mDatabaseExecutor =
|
||||
Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("sdrtrunk call database"));
|
||||
private final ExecutorService mQueryExecutor =
|
||||
Executors.newSingleThreadExecutor(new NamingThreadFactory("sdrtrunk call database query"));
|
||||
private final Broadcaster<DatabaseEvent> mEventBroadcaster = new Broadcaster<>();
|
||||
private final Broadcaster<CallRecord> mSavedCallBroadcaster = new Broadcaster<>();
|
||||
private final Map<CallHandle,CallRecord> mPendingCalls = new LinkedHashMap<>();
|
||||
private final AgeOffManager mAgeOffManager;
|
||||
private volatile CallDatabase mDatabase;
|
||||
private volatile String mErrorMessage;
|
||||
private volatile int mGeneration = 1;
|
||||
private long mNextRetry;
|
||||
private ScheduledFuture<?> mFlushFuture;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param userPreferences for the database selection and age-off rules
|
||||
*/
|
||||
public DatabaseManager(UserPreferences userPreferences)
|
||||
{
|
||||
mUserPreferences = userPreferences;
|
||||
mAgeOffManager = new AgeOffManager(this, userPreferences);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the selected database, installs or upgrades the sdrtrunk schema and starts the background writer.
|
||||
* Blocks until the database is open (or failed to open) so that calls from the first channels are stored.
|
||||
*/
|
||||
public void start()
|
||||
{
|
||||
try
|
||||
{
|
||||
mDatabaseExecutor.submit(this::openConfiguredDatabase).get(30, TimeUnit.SECONDS);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOGGER.error("Timeout or error while opening the call database", e);
|
||||
}
|
||||
|
||||
mFlushFuture = mDatabaseExecutor.scheduleWithFixedDelay(this::flush, FLUSH_INTERVAL_MS, FLUSH_INTERVAL_MS,
|
||||
TimeUnit.MILLISECONDS);
|
||||
mAgeOffManager.start(mDatabaseExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes any remaining call updates and closes the database.
|
||||
*/
|
||||
public void stop()
|
||||
{
|
||||
mAgeOffManager.stop();
|
||||
|
||||
if(mFlushFuture != null)
|
||||
{
|
||||
mFlushFuture.cancel(false);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
mDatabaseExecutor.submit(() -> {
|
||||
flush();
|
||||
closeDatabase();
|
||||
}).get(15, TimeUnit.SECONDS);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOGGER.error("Error while closing the call database", e);
|
||||
}
|
||||
|
||||
mDatabaseExecutor.shutdownNow();
|
||||
mQueryExecutor.shutdownNow();
|
||||
}
|
||||
|
||||
/**
|
||||
* Directory for the built-in database files
|
||||
*/
|
||||
public Path getDatabaseDirectory()
|
||||
{
|
||||
return mUserPreferences.getDirectoryPreference().getDirectoryDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the database from the user preferences. Database thread only.
|
||||
*/
|
||||
private void openConfiguredDatabase()
|
||||
{
|
||||
DatabaseConfiguration configuration = mUserPreferences.getDatabasePreference().getDatabaseConfiguration();
|
||||
|
||||
try
|
||||
{
|
||||
CallDatabase database = new CallDatabase(configuration, getDatabaseDirectory());
|
||||
|
||||
try
|
||||
{
|
||||
database.install();
|
||||
|
||||
try(Connection connection = database.getConnection())
|
||||
{
|
||||
int interrupted = database.getCallRepository().markInterrupted(connection);
|
||||
|
||||
if(interrupted > 0)
|
||||
{
|
||||
LOGGER.info("Marked " + interrupted + " calls from the previous session as interrupted");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
database.close();
|
||||
throw se;
|
||||
}
|
||||
|
||||
mDatabase = database;
|
||||
mErrorMessage = null;
|
||||
LOGGER.info("Call database opened: " + configuration.getDescription());
|
||||
broadcast(DatabaseEvent.Type.CONNECTED);
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
mErrorMessage = se.getMessage();
|
||||
mNextRetry = System.currentTimeMillis() + RETRY_INTERVAL_MS;
|
||||
LOGGER.error("Unable to open the call database [" + configuration.getDescription() + "] - " +
|
||||
se.getMessage());
|
||||
broadcast(DatabaseEvent.Type.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
private void closeDatabase()
|
||||
{
|
||||
CallDatabase database = mDatabase;
|
||||
mDatabase = null;
|
||||
|
||||
if(database != null)
|
||||
{
|
||||
database.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Currently open database, or null if the database isn't available.
|
||||
*/
|
||||
public CallDatabase getDatabase()
|
||||
{
|
||||
return mDatabase;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current database configuration (from the preferences).
|
||||
*/
|
||||
public DatabaseConfiguration getConfiguration()
|
||||
{
|
||||
CallDatabase database = mDatabase;
|
||||
return database != null ? database.getConfiguration() :
|
||||
mUserPreferences.getDatabasePreference().getDatabaseConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the database is open
|
||||
*/
|
||||
public boolean isConnected()
|
||||
{
|
||||
return mDatabase != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Description of the last error opening the database, or null.
|
||||
*/
|
||||
public String getErrorMessage()
|
||||
{
|
||||
return mErrorMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a handle that tracks the database row of one call across updates.
|
||||
*/
|
||||
public CallHandle createHandle()
|
||||
{
|
||||
return new CallHandle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues a snapshot of the call for insertion (first time) or update. Only the newest snapshot for each call is
|
||||
* written, so this can be invoked as often as the call changes.
|
||||
* @param handle for the call
|
||||
* @param snapshot of the call that is not modified after this call
|
||||
*/
|
||||
public void save(CallHandle handle, CallRecord snapshot)
|
||||
{
|
||||
synchronized(mPendingCalls)
|
||||
{
|
||||
mPendingCalls.put(handle, snapshot);
|
||||
|
||||
//Bound memory use if the database is unavailable for a long time. Drop the oldest completed calls first.
|
||||
if(mPendingCalls.size() > MAX_PENDING_CALLS)
|
||||
{
|
||||
Iterator<Map.Entry<CallHandle,CallRecord>> it = mPendingCalls.entrySet().iterator();
|
||||
|
||||
while(it.hasNext() && mPendingCalls.size() > MAX_PENDING_CALLS)
|
||||
{
|
||||
if(!it.next().getValue().isActive())
|
||||
{
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
LOGGER.warn("Call database is unavailable - discarding the oldest pending call updates");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the pending call updates. Database thread only.
|
||||
*/
|
||||
private void flush()
|
||||
{
|
||||
CallDatabase database = mDatabase;
|
||||
|
||||
if(database == null)
|
||||
{
|
||||
//Retry opening the database periodically
|
||||
if(mErrorMessage != null && System.currentTimeMillis() > mNextRetry)
|
||||
{
|
||||
openConfiguredDatabase();
|
||||
database = mDatabase;
|
||||
}
|
||||
|
||||
if(database == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
List<Map.Entry<CallHandle,CallRecord>> batch;
|
||||
|
||||
synchronized(mPendingCalls)
|
||||
{
|
||||
if(mPendingCalls.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
batch = new ArrayList<>(mPendingCalls.entrySet());
|
||||
mPendingCalls.clear();
|
||||
}
|
||||
|
||||
ICallRepository repository = database.getCallRepository();
|
||||
int written = 0;
|
||||
|
||||
try(Connection connection = database.getConnection())
|
||||
{
|
||||
for(Map.Entry<CallHandle,CallRecord> entry: batch)
|
||||
{
|
||||
CallHandle handle = entry.getKey();
|
||||
CallRecord call = entry.getValue();
|
||||
|
||||
if(handle.mGeneration == mGeneration && handle.mId > 0)
|
||||
{
|
||||
call.setId(handle.mId);
|
||||
|
||||
if(repository.update(connection, call))
|
||||
{
|
||||
written++;
|
||||
mSavedCallBroadcaster.broadcast(call);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
//New call, a call that started before a database switch, or a row removed by an age-off rule.
|
||||
call.setId(0);
|
||||
handle.mId = repository.insert(connection, call);
|
||||
handle.mGeneration = mGeneration;
|
||||
written++;
|
||||
mSavedCallBroadcaster.broadcast(call);
|
||||
}
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
LOGGER.error("Error writing call updates to the database - " + se.getMessage());
|
||||
|
||||
//Put back the updates that weren't written, unless a newer update arrived in the meantime
|
||||
synchronized(mPendingCalls)
|
||||
{
|
||||
Map<CallHandle,CallRecord> newer = new LinkedHashMap<>(mPendingCalls);
|
||||
mPendingCalls.clear();
|
||||
|
||||
for(int x = written; x < batch.size(); x++)
|
||||
{
|
||||
mPendingCalls.put(batch.get(x).getKey(), batch.get(x).getValue());
|
||||
}
|
||||
|
||||
mPendingCalls.putAll(newer);
|
||||
}
|
||||
|
||||
if(!isReachable(database))
|
||||
{
|
||||
LOGGER.error("Call database connection lost - will retry");
|
||||
closeDatabase();
|
||||
mErrorMessage = se.getMessage();
|
||||
mNextRetry = System.currentTimeMillis() + RETRY_INTERVAL_MS;
|
||||
broadcast(DatabaseEvent.Type.ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isReachable(CallDatabase database)
|
||||
{
|
||||
try(Connection connection = database.getConnection())
|
||||
{
|
||||
return connection.isValid(5);
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the calls table on the query thread.
|
||||
*/
|
||||
public CompletableFuture<SearchResult> search(CallSearchCriteria criteria, int offset, int limit)
|
||||
{
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
CallDatabase database = mDatabase;
|
||||
|
||||
if(database == null)
|
||||
{
|
||||
throw new IllegalStateException("Call database is not available" +
|
||||
(mErrorMessage != null ? ": " + mErrorMessage : ""));
|
||||
}
|
||||
|
||||
try(Connection connection = database.getConnection())
|
||||
{
|
||||
List<CallRecord> calls = database.getCallRepository().search(connection, criteria, offset, limit);
|
||||
long total = database.getCallRepository().count(connection, criteria);
|
||||
return new SearchResult(calls, total);
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
throw new IllegalStateException(se.getMessage(), se);
|
||||
}
|
||||
}, mQueryExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search results
|
||||
* @param calls in the requested page
|
||||
* @param total count of matching calls
|
||||
*/
|
||||
public record SearchResult(List<CallRecord> calls, long total) {}
|
||||
|
||||
/**
|
||||
* Connects to the database configuration and reports the state of its schema. Runs on the query thread.
|
||||
*/
|
||||
public CompletableFuture<ProbeResult> probe(DatabaseConfiguration configuration)
|
||||
{
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try(CallDatabase database = new CallDatabase(configuration, getDatabaseDirectory()))
|
||||
{
|
||||
SchemaStatus status = database.getSchemaStatus();
|
||||
long count = status == SchemaStatus.SDRTRUNK ? database.getCallCount() : 0;
|
||||
String suggestion = status == SchemaStatus.MISSING ? configuration.schema() :
|
||||
database.suggestSchemaName();
|
||||
return new ProbeResult(status, count, suggestion);
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
throw new IllegalStateException(se.getMessage(), se);
|
||||
}
|
||||
}, mQueryExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of probing a database configuration
|
||||
* @param status of the configured schema
|
||||
* @param callCount in the configured schema
|
||||
* @param suggestedSchema an unused schema name, for the create separate schema option
|
||||
*/
|
||||
public record ProbeResult(SchemaStatus status, long callCount, String suggestedSchema) {}
|
||||
|
||||
/**
|
||||
* Checks whether a schema exists in the database of the configuration. Runs on the query thread.
|
||||
*/
|
||||
public CompletableFuture<Boolean> schemaExists(DatabaseConfiguration configuration, String schema)
|
||||
{
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try(CallDatabase database = new CallDatabase(configuration, getDatabaseDirectory()))
|
||||
{
|
||||
return database.schemaExists(schema);
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
throw new IllegalStateException(se.getMessage(), se);
|
||||
}
|
||||
}, mQueryExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* How to treat an existing sdrtrunk schema in the database being switched to
|
||||
*/
|
||||
public enum ExistingSchemaOption
|
||||
{
|
||||
/**
|
||||
* Keep the existing calls and add to them
|
||||
*/
|
||||
APPEND,
|
||||
/**
|
||||
* Remove the existing calls and start empty
|
||||
*/
|
||||
CLEAR
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches to a different database.
|
||||
*
|
||||
* @param target configuration, including the schema name to use (a new name for the create separate schema option)
|
||||
* @param schemaOption for an existing sdrtrunk schema in the target
|
||||
* @param transfer true to copy the calls from the current database to the target
|
||||
* @param progress receives status text while the switch runs (on the database thread)
|
||||
* @return future that completes when the switch is complete, or completes exceptionally on error, in which case
|
||||
* the current database remains selected
|
||||
*/
|
||||
public CompletableFuture<SwitchResult> switchDatabase(DatabaseConfiguration target,
|
||||
ExistingSchemaOption schemaOption, boolean transfer,
|
||||
Consumer<String> progress)
|
||||
{
|
||||
CompletableFuture<SwitchResult> future = new CompletableFuture<>();
|
||||
|
||||
mDatabaseExecutor.execute(() -> {
|
||||
CallDatabase targetDatabase = null;
|
||||
|
||||
try
|
||||
{
|
||||
progress.accept("Connecting to " + target.getDescription());
|
||||
targetDatabase = new CallDatabase(target, getDatabaseDirectory());
|
||||
SchemaStatus status = targetDatabase.getSchemaStatus();
|
||||
|
||||
if(status == SchemaStatus.SDRTRUNK && schemaOption == ExistingSchemaOption.CLEAR)
|
||||
{
|
||||
progress.accept("Clearing schema [" + target.schema() + "]");
|
||||
targetDatabase.clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
progress.accept("Installing schema [" + target.schema() + "]");
|
||||
targetDatabase.install();
|
||||
}
|
||||
|
||||
long transferred = 0;
|
||||
long skipped = 0;
|
||||
CallDatabase current = mDatabase;
|
||||
|
||||
if(transfer && current != null && !current.getConfiguration().isSameLocation(target))
|
||||
{
|
||||
//Write pending updates first so that they are included in the transfer
|
||||
flush();
|
||||
long[] counts = transfer(current, targetDatabase, progress);
|
||||
transferred = counts[0];
|
||||
skipped = counts[1];
|
||||
}
|
||||
|
||||
try(Connection connection = targetDatabase.getConnection())
|
||||
{
|
||||
targetDatabase.getCallRepository().markInterrupted(connection);
|
||||
}
|
||||
|
||||
//Write remaining pending updates to the current database before switching, so that active calls
|
||||
//continue in the new database
|
||||
flush();
|
||||
CallDatabase previous = mDatabase;
|
||||
mDatabase = targetDatabase;
|
||||
mGeneration++;
|
||||
mErrorMessage = null;
|
||||
mUserPreferences.getDatabasePreference().setDatabaseConfiguration(target);
|
||||
|
||||
if(previous != null)
|
||||
{
|
||||
//Calls in progress continue in the new database, so remove them from the previous database
|
||||
try(Connection connection = previous.getConnection())
|
||||
{
|
||||
previous.getCallRepository().deleteActive(connection);
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
LOGGER.warn("Unable to remove calls in progress from the previous database - " +
|
||||
se.getMessage());
|
||||
}
|
||||
|
||||
previous.close();
|
||||
}
|
||||
|
||||
LOGGER.info("Switched call database to " + target.getDescription() + " - transferred " +
|
||||
transferred + " calls" + (skipped > 0 ? ", skipped " + skipped + " existing calls" : ""));
|
||||
broadcast(DatabaseEvent.Type.CONNECTED);
|
||||
future.complete(new SwitchResult(transferred, skipped));
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOGGER.error("Error switching the call database to " + target.getDescription(), e);
|
||||
|
||||
if(targetDatabase != null && targetDatabase != mDatabase)
|
||||
{
|
||||
targetDatabase.close();
|
||||
}
|
||||
|
||||
future.completeExceptionally(e);
|
||||
}
|
||||
});
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a database switch
|
||||
* @param transferred count of calls copied to the new database
|
||||
* @param skipped count of calls that already existed in the new database
|
||||
*/
|
||||
public record SwitchResult(long transferred, long skipped) {}
|
||||
|
||||
/**
|
||||
* Copies the calls from the source to the target database, skipping calls in progress (they are written to the
|
||||
* target after the switch) and calls that already exist in the target.
|
||||
* @return transferred and skipped counts
|
||||
*/
|
||||
private long[] transfer(CallDatabase source, CallDatabase target, Consumer<String> progress) throws SQLException
|
||||
{
|
||||
ICallRepository sourceRepository = source.getCallRepository();
|
||||
ICallRepository targetRepository = target.getCallRepository();
|
||||
long transferred = 0;
|
||||
long skipped = 0;
|
||||
|
||||
try(Connection sourceConnection = source.getConnection(); Connection targetConnection = target.getConnection())
|
||||
{
|
||||
long total = sourceRepository.count(sourceConnection);
|
||||
Set<String> existing = targetRepository.count(targetConnection) > 0 ?
|
||||
targetRepository.getTransferKeys(targetConnection) : Collections.emptySet();
|
||||
boolean autoCommit = targetConnection.getAutoCommit();
|
||||
targetConnection.setAutoCommit(false);
|
||||
|
||||
try
|
||||
{
|
||||
long afterId = 0;
|
||||
List<CallRecord> page = sourceRepository.readPage(sourceConnection, afterId, TRANSFER_PAGE_SIZE);
|
||||
|
||||
while(!page.isEmpty())
|
||||
{
|
||||
List<CallRecord> toInsert = new ArrayList<>();
|
||||
|
||||
for(CallRecord call: page)
|
||||
{
|
||||
if(call.getCallState() == CallState.ACTIVE || existing.contains(call.getTransferKey()))
|
||||
{
|
||||
skipped++;
|
||||
}
|
||||
else
|
||||
{
|
||||
toInsert.add(call);
|
||||
}
|
||||
}
|
||||
|
||||
if(!toInsert.isEmpty())
|
||||
{
|
||||
targetRepository.insertBatch(targetConnection, toInsert);
|
||||
targetConnection.commit();
|
||||
transferred += toInsert.size();
|
||||
}
|
||||
|
||||
afterId = page.getLast().getId();
|
||||
progress.accept("Transferring calls: " + (transferred + skipped) + " of " + total);
|
||||
page = sourceRepository.readPage(sourceConnection, afterId, TRANSFER_PAGE_SIZE);
|
||||
}
|
||||
}
|
||||
catch(SQLException se)
|
||||
{
|
||||
targetConnection.rollback();
|
||||
throw se;
|
||||
}
|
||||
finally
|
||||
{
|
||||
targetConnection.setAutoCommit(autoCommit);
|
||||
}
|
||||
}
|
||||
|
||||
return new long[]{transferred, skipped};
|
||||
}
|
||||
|
||||
/**
|
||||
* Age-off rule manager
|
||||
*/
|
||||
public AgeOffManager getAgeOffManager()
|
||||
{
|
||||
return mAgeOffManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the task on the database thread.
|
||||
*/
|
||||
public CompletableFuture<Void> runOnDatabaseThread(Runnable runnable)
|
||||
{
|
||||
return CompletableFuture.runAsync(runnable, mDatabaseExecutor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies listeners that the stored calls changed outside of the normal call updates (age-off, switch, delete).
|
||||
*/
|
||||
public void notifyCallsChanged()
|
||||
{
|
||||
broadcast(DatabaseEvent.Type.CALLS_CHANGED);
|
||||
}
|
||||
|
||||
private void broadcast(DatabaseEvent.Type type)
|
||||
{
|
||||
mEventBroadcaster.broadcast(new DatabaseEvent(type, getConfiguration(), mErrorMessage));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the listener to receive database events (on the database thread)
|
||||
*/
|
||||
public void addListener(Listener<DatabaseEvent> listener)
|
||||
{
|
||||
mEventBroadcaster.addListener(listener);
|
||||
}
|
||||
|
||||
public void removeListener(Listener<DatabaseEvent> listener)
|
||||
{
|
||||
mEventBroadcaster.removeListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the listener to receive each call after it is written to the database, with its row id assigned.
|
||||
* Notified on the database thread.
|
||||
*/
|
||||
public void addCallSavedListener(Listener<CallRecord> listener)
|
||||
{
|
||||
mSavedCallBroadcaster.addListener(listener);
|
||||
}
|
||||
|
||||
public void removeCallSavedListener(Listener<CallRecord> listener)
|
||||
{
|
||||
mSavedCallBroadcaster.removeListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks the database row of a call. Accessed only on the database thread.
|
||||
*/
|
||||
public static class CallHandle
|
||||
{
|
||||
private long mId;
|
||||
private int mGeneration;
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
package io.github.dsheirer.database;
|
||||
|
||||
import io.github.dsheirer.database.dialect.H2Dialect;
|
||||
import io.github.dsheirer.database.dialect.IDatabaseDialect;
|
||||
import io.github.dsheirer.database.dialect.MariaDBDialect;
|
||||
import io.github.dsheirer.database.dialect.PostgreSQLDialect;
|
||||
|
||||
/**
|
||||
* Supported call database engines. The engine differences are implemented by each type's {@link IDatabaseDialect}.
|
||||
*/
|
||||
public enum DatabaseType
|
||||
{
|
||||
H2("Built-in (H2)", new H2Dialect()),
|
||||
MARIADB("MariaDB", new MariaDBDialect()),
|
||||
POSTGRESQL("PostgreSQL", new PostgreSQLDialect());
|
||||
|
||||
private final String mLabel;
|
||||
private final IDatabaseDialect mDialect;
|
||||
|
||||
DatabaseType(String label, IDatabaseDialect dialect)
|
||||
{
|
||||
mLabel = label;
|
||||
mDialect = dialect;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL dialect and connection settings for this engine
|
||||
*/
|
||||
public IDatabaseDialect getDialect()
|
||||
{
|
||||
return mDialect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this is a network database server that needs a host, port and credentials.
|
||||
*/
|
||||
public boolean isNetwork()
|
||||
{
|
||||
return mDialect.isNetwork();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this engine needs a database name in addition to the schema name.
|
||||
*/
|
||||
public boolean requiresDatabaseName()
|
||||
{
|
||||
return mDialect.requiresDatabaseName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Default TCP port for a network database, or 0 for the embedded database.
|
||||
*/
|
||||
public int getDefaultPort()
|
||||
{
|
||||
return mDialect.getDefaultPort();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return mLabel;
|
||||
}
|
||||
}
|
||||
@@ -1,329 +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.database.ageoff;
|
||||
|
||||
import io.github.dsheirer.database.CallDatabase;
|
||||
import io.github.dsheirer.database.DatabaseManager;
|
||||
import io.github.dsheirer.database.call.CallRecord;
|
||||
import io.github.dsheirer.database.call.ICallRepository;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.preference.database.DatabasePreference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Applies the call audio age-off rules:
|
||||
* <ul>
|
||||
* <li>Retention rule: deletes duplicate calls, and Do Not Monitor calls that no alias marked for recording, with
|
||||
* their recordings, after the retention period (default 1 hour).</li>
|
||||
* <li>Age rule: removes calls older than a number of days.</li>
|
||||
* <li>Size rule: removes the oldest recordings when the total size of the recordings exceeds a limit.</li>
|
||||
* </ul>
|
||||
* The age and size rules either delete the call row and its recording file, or delete only the recording file and
|
||||
* keep the call row.
|
||||
*
|
||||
* The rules run a minute after startup, then every 5 minutes, and when the user requests it. Calls in progress are
|
||||
* never removed. Only recordings tracked in the call database are considered.
|
||||
*/
|
||||
public class AgeOffManager
|
||||
{
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(AgeOffManager.class);
|
||||
private static final long INITIAL_DELAY_SECONDS = 60;
|
||||
private static final long INTERVAL_SECONDS = 300;
|
||||
private static final int PAGE_SIZE = 500;
|
||||
public static final long BYTES_PER_MB = 1024L * 1024L;
|
||||
|
||||
private final DatabaseManager mDatabaseManager;
|
||||
private final DatabasePreference mPreference;
|
||||
private ScheduledFuture<?> mScheduledFuture;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
*/
|
||||
public AgeOffManager(DatabaseManager databaseManager, UserPreferences userPreferences)
|
||||
{
|
||||
mDatabaseManager = databaseManager;
|
||||
mPreference = userPreferences.getDatabasePreference();
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules the periodic age-off on the database thread.
|
||||
*/
|
||||
public void start(ScheduledExecutorService databaseExecutor)
|
||||
{
|
||||
if(mScheduledFuture == null)
|
||||
{
|
||||
mScheduledFuture = databaseExecutor.scheduleWithFixedDelay(this::runSafely, INITIAL_DELAY_SECONDS,
|
||||
INTERVAL_SECONDS, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop()
|
||||
{
|
||||
if(mScheduledFuture != null)
|
||||
{
|
||||
mScheduledFuture.cancel(false);
|
||||
mScheduledFuture = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the enabled rules now.
|
||||
* @return future with the results
|
||||
*/
|
||||
public CompletableFuture<AgeOffResult> runNow()
|
||||
{
|
||||
CompletableFuture<AgeOffResult> future = new CompletableFuture<>();
|
||||
mDatabaseManager.runOnDatabaseThread(() -> {
|
||||
try
|
||||
{
|
||||
future.complete(run());
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
future.completeExceptionally(e);
|
||||
}
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
private void runSafely()
|
||||
{
|
||||
try
|
||||
{
|
||||
run();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
LOGGER.error("Error applying the call age-off rules", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the enabled rules. Database thread only.
|
||||
*/
|
||||
private AgeOffResult run() throws SQLException
|
||||
{
|
||||
CallDatabase database = mDatabaseManager.getDatabase();
|
||||
|
||||
RetentionPeriod retention = mPreference.getDuplicateDoNotMonitorRetention();
|
||||
|
||||
if(database == null || (!retention.isEnabled() && !mPreference.isAgeRuleEnabled() &&
|
||||
!mPreference.isSizeRuleEnabled()))
|
||||
{
|
||||
return new AgeOffResult(0, 0, 0);
|
||||
}
|
||||
|
||||
AgeOffResult result = new AgeOffResult(0, 0, 0);
|
||||
|
||||
try(Connection connection = database.getConnection())
|
||||
{
|
||||
ICallRepository repository = database.getCallRepository();
|
||||
|
||||
if(retention.isEnabled())
|
||||
{
|
||||
long cutoff = System.currentTimeMillis() - retention.getMilliseconds();
|
||||
result = result.add(applyRetentionRule(connection, repository, cutoff));
|
||||
}
|
||||
|
||||
if(mPreference.isAgeRuleEnabled())
|
||||
{
|
||||
long cutoff = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(mPreference.getAgeRuleDays());
|
||||
result = result.add(applyAgeRule(connection, repository, cutoff, mPreference.getAgeRuleAction()));
|
||||
}
|
||||
|
||||
if(mPreference.isSizeRuleEnabled())
|
||||
{
|
||||
long limit = mPreference.getSizeRuleLimitMB() * BYTES_PER_MB;
|
||||
result = result.add(applySizeRule(connection, repository, limit, mPreference.getSizeRuleAction()));
|
||||
}
|
||||
}
|
||||
|
||||
if(result.calls() > 0 || result.recordings() > 0)
|
||||
{
|
||||
LOGGER.info("Call age-off removed " + result.calls() + " calls and " + result.recordings() +
|
||||
" recordings (" + (result.bytes() / BYTES_PER_MB) + " MB)");
|
||||
mDatabaseManager.notifyCallsChanged();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes duplicate calls and Do Not Monitor calls (without an alias record option) that started before the
|
||||
* cutoff time, with their recordings.
|
||||
*/
|
||||
static AgeOffResult applyRetentionRule(Connection connection, ICallRepository repository, long cutoff)
|
||||
throws SQLException
|
||||
{
|
||||
AgeOffResult result = new AgeOffResult(0, 0, 0);
|
||||
List<CallRecord> page = repository.getDuplicateAndDoNotMonitorCalls(connection, cutoff, PAGE_SIZE);
|
||||
|
||||
while(!page.isEmpty())
|
||||
{
|
||||
result = result.add(remove(connection, repository, page, AgeOffAction.DELETE_CALL_AND_RECORDING));
|
||||
page = repository.getDuplicateAndDoNotMonitorCalls(connection, cutoff, PAGE_SIZE);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the calls (or recordings) of calls that started before the cutoff time.
|
||||
*/
|
||||
static AgeOffResult applyAgeRule(Connection connection, ICallRepository repository, long cutoff,
|
||||
AgeOffAction action) throws SQLException
|
||||
{
|
||||
AgeOffResult result = new AgeOffResult(0, 0, 0);
|
||||
List<CallRecord> page = action == AgeOffAction.DELETE_CALL_AND_RECORDING ?
|
||||
repository.getCallsStartedBefore(connection, cutoff, PAGE_SIZE) :
|
||||
repository.getRecordedCalls(connection, cutoff, PAGE_SIZE);
|
||||
|
||||
while(!page.isEmpty())
|
||||
{
|
||||
result = result.add(remove(connection, repository, page, action));
|
||||
|
||||
page = action == AgeOffAction.DELETE_CALL_AND_RECORDING ?
|
||||
repository.getCallsStartedBefore(connection, cutoff, PAGE_SIZE) :
|
||||
repository.getRecordedCalls(connection, cutoff, PAGE_SIZE);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the oldest recordings until the total size of the recordings is at or below the limit.
|
||||
*/
|
||||
static AgeOffResult applySizeRule(Connection connection, ICallRepository repository, long limitBytes,
|
||||
AgeOffAction action) throws SQLException
|
||||
{
|
||||
AgeOffResult result = new AgeOffResult(0, 0, 0);
|
||||
long total = repository.getRecordedFileSize(connection);
|
||||
|
||||
while(total > limitBytes)
|
||||
{
|
||||
List<CallRecord> page = repository.getRecordedCalls(connection, 0, PAGE_SIZE);
|
||||
|
||||
if(page.isEmpty())
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
List<CallRecord> toRemove = new ArrayList<>();
|
||||
|
||||
for(CallRecord call: page)
|
||||
{
|
||||
if(total <= limitBytes)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
toRemove.add(call);
|
||||
total -= call.getFileSize();
|
||||
}
|
||||
|
||||
result = result.add(remove(connection, repository, toRemove, action));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the recording files of the calls and then deletes the call rows or marks their recordings deleted.
|
||||
*/
|
||||
private static AgeOffResult remove(Connection connection, ICallRepository repository, List<CallRecord> calls,
|
||||
AgeOffAction action) throws SQLException
|
||||
{
|
||||
long bytes = 0;
|
||||
int recordings = 0;
|
||||
List<Long> ids = new ArrayList<>();
|
||||
|
||||
for(CallRecord call: calls)
|
||||
{
|
||||
ids.add(call.getId());
|
||||
|
||||
if(call.getFilePath() != null && deleteRecording(call.getFilePath()))
|
||||
{
|
||||
recordings++;
|
||||
bytes += call.getFileSize();
|
||||
}
|
||||
}
|
||||
|
||||
if(action == AgeOffAction.DELETE_CALL_AND_RECORDING)
|
||||
{
|
||||
repository.delete(connection, ids);
|
||||
return new AgeOffResult(ids.size(), recordings, bytes);
|
||||
}
|
||||
|
||||
repository.markRecordingsDeleted(connection, ids);
|
||||
return new AgeOffResult(0, recordings, bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the audio recording file. Only audio files (.mp3, .wav) are deleted.
|
||||
* @return true if the file was deleted
|
||||
*/
|
||||
static boolean deleteRecording(String filePath)
|
||||
{
|
||||
String lower = filePath.toLowerCase(Locale.ROOT);
|
||||
|
||||
if(!lower.endsWith(".mp3") && !lower.endsWith(".wav"))
|
||||
{
|
||||
LOGGER.warn("Age-off skipped deleting non-audio file [" + filePath + "]");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Files.deleteIfExists(Path.of(filePath));
|
||||
}
|
||||
catch(IOException | RuntimeException e)
|
||||
{
|
||||
LOGGER.warn("Age-off unable to delete recording [" + filePath + "] - " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Age-off results
|
||||
* @param calls deleted
|
||||
* @param recordings deleted
|
||||
* @param bytes of recordings deleted
|
||||
*/
|
||||
public record AgeOffResult(long calls, long recordings, long bytes)
|
||||
{
|
||||
public AgeOffResult add(AgeOffResult other)
|
||||
{
|
||||
return new AgeOffResult(calls + other.calls, recordings + other.recordings, bytes + other.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +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.database.ageoff;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* How long duplicate and Do Not Monitor calls (and their recordings) are kept before they are deleted
|
||||
*/
|
||||
public enum RetentionPeriod
|
||||
{
|
||||
MINUTES_30("30 minutes", TimeUnit.MINUTES.toMillis(30)),
|
||||
HOUR_1("1 hour", TimeUnit.HOURS.toMillis(1)),
|
||||
HOURS_2("2 hours", TimeUnit.HOURS.toMillis(2)),
|
||||
HOURS_4("4 hours", TimeUnit.HOURS.toMillis(4)),
|
||||
HOURS_8("8 hours", TimeUnit.HOURS.toMillis(8)),
|
||||
HOURS_12("12 hours", TimeUnit.HOURS.toMillis(12)),
|
||||
DAY_1("1 day", TimeUnit.DAYS.toMillis(1)),
|
||||
DAYS_2("2 days", TimeUnit.DAYS.toMillis(2)),
|
||||
DAYS_7("7 days", TimeUnit.DAYS.toMillis(7)),
|
||||
NEVER("Never delete", 0);
|
||||
|
||||
public static final RetentionPeriod DEFAULT = HOUR_1;
|
||||
|
||||
private final String mLabel;
|
||||
private final long mMilliseconds;
|
||||
|
||||
RetentionPeriod(String label, long milliseconds)
|
||||
{
|
||||
mLabel = label;
|
||||
mMilliseconds = milliseconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retention time in milliseconds, or 0 for never
|
||||
*/
|
||||
public long getMilliseconds()
|
||||
{
|
||||
return mMilliseconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if calls are deleted after this period
|
||||
*/
|
||||
public boolean isEnabled()
|
||||
{
|
||||
return this != NEVER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return mLabel;
|
||||
}
|
||||
}
|
||||
@@ -1,568 +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.database.call;
|
||||
|
||||
import io.github.dsheirer.protocol.Protocol;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A call audio event as stored in the calls table.
|
||||
*
|
||||
* Instances are mutable while they are being built, but a record that has been handed to the database writer or to
|
||||
* the user interface is a snapshot that is never changed afterwards. Use {@link #copy()} to create a new snapshot.
|
||||
*/
|
||||
public class CallRecord
|
||||
{
|
||||
public static final String FORM_TALKGROUP = "TALKGROUP";
|
||||
public static final String FORM_PATCH_GROUP = "PATCH_GROUP";
|
||||
public static final String FORM_RADIO = "RADIO";
|
||||
|
||||
private long mId;
|
||||
private long mCallKey;
|
||||
private long mStartTime;
|
||||
private long mEndTime;
|
||||
private CallState mCallState = CallState.ACTIVE;
|
||||
private String mProtocol;
|
||||
private String mSystem;
|
||||
private String mSite;
|
||||
private String mChannel;
|
||||
private long mFrequency;
|
||||
private int mTimeslot;
|
||||
private String mToId;
|
||||
private Long mToValue;
|
||||
private String mToForm;
|
||||
private String mToFullyQualified;
|
||||
private String mFromId;
|
||||
private Long mFromValue;
|
||||
private String mFromForm;
|
||||
private String mFromFullyQualified;
|
||||
private String mAliasList;
|
||||
private List<PatchedTalkgroup> mPatchedTalkgroups = List.of();
|
||||
private String mTalkerAlias;
|
||||
private boolean mEncrypted;
|
||||
private boolean mDuplicate;
|
||||
private int mPriority;
|
||||
private boolean mAliasRecord;
|
||||
private String mRecordFormat;
|
||||
private String mFilePath;
|
||||
private long mFileSize;
|
||||
private RecordingState mRecordingState = RecordingState.NONE;
|
||||
|
||||
/**
|
||||
* Creates a copy (snapshot) of this record.
|
||||
*/
|
||||
public CallRecord copy()
|
||||
{
|
||||
CallRecord copy = new CallRecord();
|
||||
copy.mId = mId;
|
||||
copy.mCallKey = mCallKey;
|
||||
copy.mStartTime = mStartTime;
|
||||
copy.mEndTime = mEndTime;
|
||||
copy.mCallState = mCallState;
|
||||
copy.mProtocol = mProtocol;
|
||||
copy.mSystem = mSystem;
|
||||
copy.mSite = mSite;
|
||||
copy.mChannel = mChannel;
|
||||
copy.mFrequency = mFrequency;
|
||||
copy.mTimeslot = mTimeslot;
|
||||
copy.mToId = mToId;
|
||||
copy.mToValue = mToValue;
|
||||
copy.mToForm = mToForm;
|
||||
copy.mToFullyQualified = mToFullyQualified;
|
||||
copy.mFromId = mFromId;
|
||||
copy.mFromValue = mFromValue;
|
||||
copy.mFromForm = mFromForm;
|
||||
copy.mFromFullyQualified = mFromFullyQualified;
|
||||
copy.mAliasList = mAliasList;
|
||||
copy.mPatchedTalkgroups = mPatchedTalkgroups;
|
||||
copy.mTalkerAlias = mTalkerAlias;
|
||||
copy.mEncrypted = mEncrypted;
|
||||
copy.mDuplicate = mDuplicate;
|
||||
copy.mPriority = mPriority;
|
||||
copy.mAliasRecord = mAliasRecord;
|
||||
copy.mRecordFormat = mRecordFormat;
|
||||
copy.mFilePath = mFilePath;
|
||||
copy.mFileSize = mFileSize;
|
||||
copy.mRecordingState = mRecordingState;
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Database row identifier, or 0 if this call hasn't been inserted yet.
|
||||
*/
|
||||
public long getId()
|
||||
{
|
||||
return mId;
|
||||
}
|
||||
|
||||
public void setId(long id)
|
||||
{
|
||||
mId = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory key that identifies a live call across snapshots, or 0 for records loaded from the database.
|
||||
*/
|
||||
public long getCallKey()
|
||||
{
|
||||
return mCallKey;
|
||||
}
|
||||
|
||||
public void setCallKey(long callKey)
|
||||
{
|
||||
mCallKey = callKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call start time, milliseconds since epoch
|
||||
*/
|
||||
public long getStartTime()
|
||||
{
|
||||
return mStartTime;
|
||||
}
|
||||
|
||||
public void setStartTime(long startTime)
|
||||
{
|
||||
mStartTime = startTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call end time, milliseconds since epoch, or 0 while the call is active.
|
||||
*/
|
||||
public long getEndTime()
|
||||
{
|
||||
return mEndTime;
|
||||
}
|
||||
|
||||
public void setEndTime(long endTime)
|
||||
{
|
||||
mEndTime = endTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call duration in milliseconds. For an active call this is the elapsed time up to now.
|
||||
*/
|
||||
public long getDuration()
|
||||
{
|
||||
if(mEndTime > 0)
|
||||
{
|
||||
return Math.max(0, mEndTime - mStartTime);
|
||||
}
|
||||
|
||||
return isActive() ? Math.max(0, System.currentTimeMillis() - mStartTime) : 0;
|
||||
}
|
||||
|
||||
public CallState getCallState()
|
||||
{
|
||||
return mCallState;
|
||||
}
|
||||
|
||||
public void setCallState(CallState callState)
|
||||
{
|
||||
mCallState = callState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the call is in progress.
|
||||
*/
|
||||
public boolean isActive()
|
||||
{
|
||||
return mCallState == CallState.ACTIVE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Protocol enumeration entry name (e.g. APCO25)
|
||||
*/
|
||||
public String getProtocol()
|
||||
{
|
||||
return mProtocol;
|
||||
}
|
||||
|
||||
public void setProtocol(String protocol)
|
||||
{
|
||||
mProtocol = protocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Protocol, or UNKNOWN if the stored value isn't recognized.
|
||||
*/
|
||||
public Protocol getProtocolValue()
|
||||
{
|
||||
if(mProtocol != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Protocol.valueOf(mProtocol);
|
||||
}
|
||||
catch(IllegalArgumentException iae)
|
||||
{
|
||||
//Fall through
|
||||
}
|
||||
}
|
||||
|
||||
return Protocol.UNKNOWN;
|
||||
}
|
||||
|
||||
public String getSystem()
|
||||
{
|
||||
return mSystem;
|
||||
}
|
||||
|
||||
public void setSystem(String system)
|
||||
{
|
||||
mSystem = system;
|
||||
}
|
||||
|
||||
public String getSite()
|
||||
{
|
||||
return mSite;
|
||||
}
|
||||
|
||||
public void setSite(String site)
|
||||
{
|
||||
mSite = site;
|
||||
}
|
||||
|
||||
public String getChannel()
|
||||
{
|
||||
return mChannel;
|
||||
}
|
||||
|
||||
public void setChannel(String channel)
|
||||
{
|
||||
mChannel = channel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Channel frequency in Hertz, or 0 if unknown.
|
||||
*/
|
||||
public long getFrequency()
|
||||
{
|
||||
return mFrequency;
|
||||
}
|
||||
|
||||
public void setFrequency(long frequency)
|
||||
{
|
||||
mFrequency = frequency;
|
||||
}
|
||||
|
||||
public int getTimeslot()
|
||||
{
|
||||
return mTimeslot;
|
||||
}
|
||||
|
||||
public void setTimeslot(int timeslot)
|
||||
{
|
||||
mTimeslot = timeslot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formatted TO identifier (talkgroup, patch group or radio)
|
||||
*/
|
||||
public String getToId()
|
||||
{
|
||||
return mToId;
|
||||
}
|
||||
|
||||
public void setToId(String toId)
|
||||
{
|
||||
mToId = toId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric TO identifier value, or null. For a patch group, this is the patch group talkgroup.
|
||||
*/
|
||||
public Long getToValue()
|
||||
{
|
||||
return mToValue;
|
||||
}
|
||||
|
||||
public void setToValue(Long toValue)
|
||||
{
|
||||
mToValue = toValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the TO identifier of this call is a talkgroup or patch group that can be used as a hold talkgroup.
|
||||
*/
|
||||
public boolean hasTalkgroup()
|
||||
{
|
||||
return mToValue != null && mToValue > 0 && isToTalkgroup();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the TO identifier is a talkgroup or patch group (as opposed to a radio, for a private call).
|
||||
*/
|
||||
public boolean isToTalkgroup()
|
||||
{
|
||||
return FORM_TALKGROUP.equals(mToForm) || FORM_PATCH_GROUP.equals(mToForm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call type (group, patch, private or telephone), derived from the TO and FROM identifier forms.
|
||||
*/
|
||||
public CallType getCallType()
|
||||
{
|
||||
return CallType.from(mToForm, mFromForm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifier form (Form enumeration name, e.g. TALKGROUP, PATCH_GROUP or RADIO) of the TO identifier, or null.
|
||||
*/
|
||||
public String getToForm()
|
||||
{
|
||||
return mToForm;
|
||||
}
|
||||
|
||||
public void setToForm(String toForm)
|
||||
{
|
||||
mToForm = toForm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully qualified address (wacn.system.id) of a fully qualified (roaming) TO talkgroup, or null.
|
||||
*/
|
||||
public String getToFullyQualified()
|
||||
{
|
||||
return mToFullyQualified;
|
||||
}
|
||||
|
||||
public void setToFullyQualified(String toFullyQualified)
|
||||
{
|
||||
mToFullyQualified = toFullyQualified;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifier form (Form enumeration name, e.g. RADIO) of the FROM identifier, or null.
|
||||
*/
|
||||
public String getFromForm()
|
||||
{
|
||||
return mFromForm;
|
||||
}
|
||||
|
||||
public void setFromForm(String fromForm)
|
||||
{
|
||||
mFromForm = fromForm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the FROM identifier is a radio
|
||||
*/
|
||||
public boolean isFromRadio()
|
||||
{
|
||||
return FORM_RADIO.equals(mFromForm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully qualified address (wacn.system.id) of a fully qualified (roaming) FROM radio, or null.
|
||||
*/
|
||||
public String getFromFullyQualified()
|
||||
{
|
||||
return mFromFullyQualified;
|
||||
}
|
||||
|
||||
public void setFromFullyQualified(String fromFullyQualified)
|
||||
{
|
||||
mFromFullyQualified = fromFullyQualified;
|
||||
}
|
||||
|
||||
/**
|
||||
* Talkgroups that are patched into the TO patch group of the call, or an empty list. Searching for a talkgroup
|
||||
* finds the calls that it participated in through a patch.
|
||||
*/
|
||||
public List<PatchedTalkgroup> getPatchedTalkgroups()
|
||||
{
|
||||
return mPatchedTalkgroups;
|
||||
}
|
||||
|
||||
public void setPatchedTalkgroups(List<PatchedTalkgroup> patchedTalkgroups)
|
||||
{
|
||||
mPatchedTalkgroups = patchedTalkgroups == null ? List.of() : List.copyOf(patchedTalkgroups);
|
||||
}
|
||||
|
||||
/**
|
||||
* Name of the alias list that was assigned to the channel for this call, or null. Aliases for the TO and FROM
|
||||
* identifiers are looked up in the current version of this alias list when the call is displayed.
|
||||
*/
|
||||
public String getAliasList()
|
||||
{
|
||||
return mAliasList;
|
||||
}
|
||||
|
||||
public void setAliasList(String aliasList)
|
||||
{
|
||||
mAliasList = aliasList;
|
||||
}
|
||||
|
||||
public String getFromId()
|
||||
{
|
||||
return mFromId;
|
||||
}
|
||||
|
||||
public void setFromId(String fromId)
|
||||
{
|
||||
mFromId = fromId;
|
||||
}
|
||||
|
||||
public Long getFromValue()
|
||||
{
|
||||
return mFromValue;
|
||||
}
|
||||
|
||||
public void setFromValue(Long fromValue)
|
||||
{
|
||||
mFromValue = fromValue;
|
||||
}
|
||||
|
||||
public String getTalkerAlias()
|
||||
{
|
||||
return mTalkerAlias;
|
||||
}
|
||||
|
||||
public void setTalkerAlias(String talkerAlias)
|
||||
{
|
||||
mTalkerAlias = talkerAlias;
|
||||
}
|
||||
|
||||
public boolean isEncrypted()
|
||||
{
|
||||
return mEncrypted;
|
||||
}
|
||||
|
||||
public void setEncrypted(boolean encrypted)
|
||||
{
|
||||
mEncrypted = encrypted;
|
||||
}
|
||||
|
||||
public boolean isDuplicate()
|
||||
{
|
||||
return mDuplicate;
|
||||
}
|
||||
|
||||
public void setDuplicate(boolean duplicate)
|
||||
{
|
||||
mDuplicate = duplicate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias playback priority
|
||||
*/
|
||||
public int getPriority()
|
||||
{
|
||||
return mPriority;
|
||||
}
|
||||
|
||||
public void setPriority(int priority)
|
||||
{
|
||||
mPriority = priority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if an alias of the call has the record option, as opposed to the call being recorded only because
|
||||
* all calls are recorded. Do Not Monitor calls with an alias record option are kept by the retention rule.
|
||||
*/
|
||||
public boolean isAliasRecord()
|
||||
{
|
||||
return mAliasRecord;
|
||||
}
|
||||
|
||||
public void setAliasRecord(boolean aliasRecord)
|
||||
{
|
||||
mAliasRecord = aliasRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recording format (MP3 or WAVE), or null when the call isn't recorded.
|
||||
*/
|
||||
public String getRecordFormat()
|
||||
{
|
||||
return mRecordFormat;
|
||||
}
|
||||
|
||||
public void setRecordFormat(String recordFormat)
|
||||
{
|
||||
mRecordFormat = recordFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Absolute path of the audio recording file, or null.
|
||||
*/
|
||||
public String getFilePath()
|
||||
{
|
||||
return mFilePath;
|
||||
}
|
||||
|
||||
public void setFilePath(String filePath)
|
||||
{
|
||||
mFilePath = filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recording file size in bytes
|
||||
*/
|
||||
public long getFileSize()
|
||||
{
|
||||
return mFileSize;
|
||||
}
|
||||
|
||||
public void setFileSize(long fileSize)
|
||||
{
|
||||
mFileSize = fileSize;
|
||||
}
|
||||
|
||||
public RecordingState getRecordingState()
|
||||
{
|
||||
return mRecordingState;
|
||||
}
|
||||
|
||||
public void setRecordingState(RecordingState recordingState)
|
||||
{
|
||||
mRecordingState = recordingState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this call has a completed audio recording that can be played.
|
||||
*/
|
||||
public boolean isPlayable()
|
||||
{
|
||||
return mRecordingState == RecordingState.RECORDED && mFilePath != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Key used to detect a call that already exists in a target database during an append transfer. The recording
|
||||
* file path identifies a call uniquely. Calls without a recording use their start time, channel and TO.
|
||||
*/
|
||||
public String getTransferKey()
|
||||
{
|
||||
if(mFilePath != null && !mFilePath.isEmpty())
|
||||
{
|
||||
return "F:" + mFilePath;
|
||||
}
|
||||
|
||||
return "C:" + mStartTime + "|" + mChannel + "|" + mTimeslot + "|" + mToId + "|" + mFromId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "Call " + mId + " " + mProtocol + " TO:" + mToId + " FROM:" + mFromId + " " + mCallState + " " +
|
||||
mRecordingState + (mFilePath != null ? " " + mFilePath : "");
|
||||
}
|
||||
}
|
||||
@@ -1,909 +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.database.call;
|
||||
|
||||
import io.github.dsheirer.alias.id.priority.Priority;
|
||||
import io.github.dsheirer.database.dialect.IDatabaseDialect;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* JDBC implementation of the calls table, using SQL that is portable across all supported database engines. All
|
||||
* methods take a connection from the caller and qualify the table name with the schema, so this class has no state
|
||||
* other than the schema name.
|
||||
*/
|
||||
public class CallRepository implements ICallRepository
|
||||
{
|
||||
public static final String TABLE = "calls";
|
||||
public static final String PATCHED_TABLE = "patched_talkgroups";
|
||||
|
||||
/**
|
||||
* Columns in insert/select order, excluding the generated id.
|
||||
*/
|
||||
private static final String COLUMNS = "start_time, end_time, duration_ms, call_state, protocol, system_name, " +
|
||||
"site_name, channel_name, frequency, timeslot, to_id, to_value, to_form, to_fq, from_id, from_value, " +
|
||||
"from_form, from_fq, alias_list, talker_alias, encrypted, duplicate_call, priority, alias_record, " +
|
||||
"record_format, file_path, file_size, recording_state";
|
||||
private static final int COLUMN_COUNT = 28;
|
||||
|
||||
/**
|
||||
* Maximum stored lengths of the text columns, so that a long alias or channel name can't fail an insert.
|
||||
*/
|
||||
private static final int LENGTH_SHORT = 32;
|
||||
private static final int LENGTH_ID = 64;
|
||||
private static final int LENGTH_NAME = 255;
|
||||
private static final int LENGTH_PATH = 1024;
|
||||
|
||||
private final String mSchema;
|
||||
private final String mTable;
|
||||
private final String mPatchedTable;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param schema that holds the calls table
|
||||
*/
|
||||
public CallRepository(String schema)
|
||||
{
|
||||
mSchema = schema;
|
||||
mTable = schema + "." + TABLE;
|
||||
mPatchedTable = schema + "." + PATCHED_TABLE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Statements that create the calls table and its indexes.
|
||||
*/
|
||||
public static List<String> getCreateStatements(IDatabaseDialect dialect, String schema)
|
||||
{
|
||||
String table = schema + "." + TABLE;
|
||||
List<String> statements = new ArrayList<>();
|
||||
statements.add("CREATE TABLE IF NOT EXISTS " + table + " (" +
|
||||
"id " + dialect.getIdentityColumn() + ", " +
|
||||
"start_time BIGINT NOT NULL, " +
|
||||
"end_time BIGINT NOT NULL, " +
|
||||
"duration_ms BIGINT NOT NULL, " +
|
||||
"call_state VARCHAR(" + LENGTH_SHORT + ") NOT NULL, " +
|
||||
"protocol VARCHAR(" + LENGTH_SHORT + "), " +
|
||||
"system_name VARCHAR(" + LENGTH_NAME + "), " +
|
||||
"site_name VARCHAR(" + LENGTH_NAME + "), " +
|
||||
"channel_name VARCHAR(" + LENGTH_NAME + "), " +
|
||||
"frequency BIGINT NOT NULL, " +
|
||||
"timeslot INT NOT NULL, " +
|
||||
"to_id VARCHAR(" + LENGTH_ID + "), " +
|
||||
"to_value BIGINT, " +
|
||||
"to_form VARCHAR(" + LENGTH_SHORT + "), " +
|
||||
"to_fq VARCHAR(" + LENGTH_ID + "), " +
|
||||
"from_id VARCHAR(" + LENGTH_ID + "), " +
|
||||
"from_value BIGINT, " +
|
||||
"from_form VARCHAR(" + LENGTH_SHORT + "), " +
|
||||
"from_fq VARCHAR(" + LENGTH_ID + "), " +
|
||||
"alias_list VARCHAR(" + LENGTH_NAME + "), " +
|
||||
"talker_alias VARCHAR(" + LENGTH_NAME + "), " +
|
||||
"encrypted BOOLEAN NOT NULL, " +
|
||||
"duplicate_call BOOLEAN NOT NULL, " +
|
||||
"priority INT NOT NULL, " +
|
||||
"alias_record BOOLEAN NOT NULL, " +
|
||||
"record_format VARCHAR(" + LENGTH_SHORT + "), " +
|
||||
"file_path VARCHAR(" + LENGTH_PATH + "), " +
|
||||
"file_size BIGINT NOT NULL, " +
|
||||
"recording_state VARCHAR(" + LENGTH_SHORT + ") NOT NULL)");
|
||||
|
||||
//Index names are scoped to the schema (H2, PostgreSQL) or the table (MariaDB), so prefix them with the table
|
||||
statements.add("CREATE INDEX IF NOT EXISTS calls_start_time_idx ON " + table + " (start_time)");
|
||||
statements.add("CREATE INDEX IF NOT EXISTS calls_to_value_idx ON " + table + " (to_value)");
|
||||
statements.add("CREATE INDEX IF NOT EXISTS calls_from_value_idx ON " + table + " (from_value)");
|
||||
statements.add("CREATE INDEX IF NOT EXISTS calls_recording_state_idx ON " + table +
|
||||
" (recording_state, start_time)");
|
||||
return statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Statements that create the patched talkgroups table (schema version 2). Rows are deleted with their call.
|
||||
*/
|
||||
public static List<String> getPatchedTalkgroupCreateStatements(String schema)
|
||||
{
|
||||
String table = schema + "." + PATCHED_TABLE;
|
||||
List<String> statements = new ArrayList<>();
|
||||
statements.add("CREATE TABLE IF NOT EXISTS " + table + " (" +
|
||||
"call_id BIGINT NOT NULL REFERENCES " + schema + "." + TABLE + "(id) ON DELETE CASCADE, " +
|
||||
"talkgroup BIGINT NOT NULL, " +
|
||||
"fq VARCHAR(" + LENGTH_ID + "))");
|
||||
statements.add("CREATE INDEX IF NOT EXISTS patched_talkgroups_call_idx ON " + table + " (call_id)");
|
||||
statements.add("CREATE INDEX IF NOT EXISTS patched_talkgroups_talkgroup_idx ON " + table + " (talkgroup)");
|
||||
return statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the call and assigns the generated row id to the call.
|
||||
* @return generated row id
|
||||
*/
|
||||
@Override
|
||||
public long insert(Connection connection, CallRecord call) throws SQLException
|
||||
{
|
||||
String sql = "INSERT INTO " + mTable + " (" + COLUMNS + ") VALUES (" + "?, ".repeat(COLUMN_COUNT - 1) + "?)";
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql, new String[]{"id"}))
|
||||
{
|
||||
bind(statement, call);
|
||||
statement.executeUpdate();
|
||||
|
||||
try(ResultSet keys = statement.getGeneratedKeys())
|
||||
{
|
||||
if(keys.next())
|
||||
{
|
||||
long id = keys.getLong(1);
|
||||
call.setId(id);
|
||||
insertPatchedTalkgroups(connection, id, call.getPatchedTalkgroups());
|
||||
return id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new SQLException("Database didn't return a generated id for the inserted call");
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the calls in a single batch without retrieving the generated ids.
|
||||
*/
|
||||
@Override
|
||||
public void insertBatch(Connection connection, List<CallRecord> calls) throws SQLException
|
||||
{
|
||||
String sql = "INSERT INTO " + mTable + " (" + COLUMNS + ") VALUES (" + "?, ".repeat(COLUMN_COUNT - 1) + "?)";
|
||||
|
||||
List<CallRecord> patched = new ArrayList<>();
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
for(CallRecord call: calls)
|
||||
{
|
||||
//Calls with patched talkgroups need their generated id for the patched talkgroup rows
|
||||
if(!call.getPatchedTalkgroups().isEmpty())
|
||||
{
|
||||
patched.add(call);
|
||||
continue;
|
||||
}
|
||||
|
||||
bind(statement, call);
|
||||
statement.addBatch();
|
||||
}
|
||||
|
||||
statement.executeBatch();
|
||||
}
|
||||
|
||||
for(CallRecord call: patched)
|
||||
{
|
||||
insert(connection, call);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the patched talkgroup rows of a call
|
||||
*/
|
||||
private void insertPatchedTalkgroups(Connection connection, long callId, List<PatchedTalkgroup> talkgroups)
|
||||
throws SQLException
|
||||
{
|
||||
if(talkgroups.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement("INSERT INTO " + mPatchedTable +
|
||||
" (call_id, talkgroup, fq) VALUES (?, ?, ?)"))
|
||||
{
|
||||
for(PatchedTalkgroup talkgroup: talkgroups)
|
||||
{
|
||||
statement.setLong(1, callId);
|
||||
statement.setLong(2, talkgroup.value());
|
||||
setString(statement, 3, talkgroup.fullyQualified(), LENGTH_ID);
|
||||
statement.addBatch();
|
||||
}
|
||||
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the patched talkgroup rows of a call
|
||||
*/
|
||||
private void replacePatchedTalkgroups(Connection connection, long callId, List<PatchedTalkgroup> talkgroups)
|
||||
throws SQLException
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mPatchedTable +
|
||||
" WHERE call_id = ?"))
|
||||
{
|
||||
statement.setLong(1, callId);
|
||||
statement.executeUpdate();
|
||||
}
|
||||
|
||||
insertPatchedTalkgroups(connection, callId, talkgroups);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the patched talkgroups of the patch group calls in the list.
|
||||
*/
|
||||
private void loadPatchedTalkgroups(Connection connection, List<CallRecord> calls) throws SQLException
|
||||
{
|
||||
Map<Long,CallRecord> patchCalls = new HashMap<>();
|
||||
|
||||
for(CallRecord call: calls)
|
||||
{
|
||||
if(CallRecord.FORM_PATCH_GROUP.equals(call.getToForm()))
|
||||
{
|
||||
patchCalls.put(call.getId(), call);
|
||||
}
|
||||
}
|
||||
|
||||
if(patchCalls.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Map<Long,List<PatchedTalkgroup>> talkgroups = new HashMap<>();
|
||||
String placeholders = String.join(", ", Collections.nCopies(patchCalls.size(), "?"));
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement("SELECT call_id, talkgroup, fq FROM " +
|
||||
mPatchedTable + " WHERE call_id IN (" + placeholders + ") ORDER BY call_id, talkgroup"))
|
||||
{
|
||||
int index = 1;
|
||||
|
||||
for(Long id: patchCalls.keySet())
|
||||
{
|
||||
statement.setLong(index++, id);
|
||||
}
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
while(rs.next())
|
||||
{
|
||||
talkgroups.computeIfAbsent(rs.getLong(1), id -> new ArrayList<>())
|
||||
.add(new PatchedTalkgroup(rs.getLong(2), rs.getString(3)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(Map.Entry<Long,List<PatchedTalkgroup>> entry: talkgroups.entrySet())
|
||||
{
|
||||
patchCalls.get(entry.getKey()).setPatchedTalkgroups(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates all columns of the existing call row.
|
||||
* @return true if the row exists and was updated
|
||||
*/
|
||||
@Override
|
||||
public boolean update(Connection connection, CallRecord call) throws SQLException
|
||||
{
|
||||
String assignments = String.join(" = ?, ", COLUMNS.split(", ")) + " = ?";
|
||||
String sql = "UPDATE " + mTable + " SET " + assignments + " WHERE id = ?";
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
bind(statement, call);
|
||||
statement.setLong(COLUMN_COUNT + 1, call.getId());
|
||||
|
||||
if(statement.executeUpdate() == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if(CallRecord.FORM_PATCH_GROUP.equals(call.getToForm()) || !call.getPatchedTalkgroups().isEmpty())
|
||||
{
|
||||
replacePatchedTalkgroups(connection, call.getId(), call.getPatchedTalkgroups());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the call column values to statement parameters 1 - COLUMN_COUNT.
|
||||
*/
|
||||
private static void bind(PreparedStatement statement, CallRecord call) throws SQLException
|
||||
{
|
||||
int index = 1;
|
||||
statement.setLong(index++, call.getStartTime());
|
||||
statement.setLong(index++, call.getEndTime());
|
||||
statement.setLong(index++, call.getEndTime() > 0 ? call.getDuration() : 0);
|
||||
statement.setString(index++, call.getCallState().name());
|
||||
setString(statement, index++, call.getProtocol(), LENGTH_SHORT);
|
||||
setString(statement, index++, call.getSystem(), LENGTH_NAME);
|
||||
setString(statement, index++, call.getSite(), LENGTH_NAME);
|
||||
setString(statement, index++, call.getChannel(), LENGTH_NAME);
|
||||
statement.setLong(index++, call.getFrequency());
|
||||
statement.setInt(index++, call.getTimeslot());
|
||||
setString(statement, index++, call.getToId(), LENGTH_ID);
|
||||
setLong(statement, index++, call.getToValue());
|
||||
setString(statement, index++, call.getToForm(), LENGTH_SHORT);
|
||||
setString(statement, index++, call.getToFullyQualified(), LENGTH_ID);
|
||||
setString(statement, index++, call.getFromId(), LENGTH_ID);
|
||||
setLong(statement, index++, call.getFromValue());
|
||||
setString(statement, index++, call.getFromForm(), LENGTH_SHORT);
|
||||
setString(statement, index++, call.getFromFullyQualified(), LENGTH_ID);
|
||||
setString(statement, index++, call.getAliasList(), LENGTH_NAME);
|
||||
setString(statement, index++, call.getTalkerAlias(), LENGTH_NAME);
|
||||
statement.setBoolean(index++, call.isEncrypted());
|
||||
statement.setBoolean(index++, call.isDuplicate());
|
||||
statement.setInt(index++, call.getPriority());
|
||||
statement.setBoolean(index++, call.isAliasRecord());
|
||||
setString(statement, index++, call.getRecordFormat(), LENGTH_SHORT);
|
||||
setString(statement, index++, call.getFilePath(), LENGTH_PATH);
|
||||
statement.setLong(index++, call.getFileSize());
|
||||
statement.setString(index, call.getRecordingState().name());
|
||||
}
|
||||
|
||||
private static void setString(PreparedStatement statement, int index, String value, int maxLength)
|
||||
throws SQLException
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
statement.setNull(index, Types.VARCHAR);
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.setString(index, value.length() > maxLength ? value.substring(0, maxLength) : value);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setLong(PreparedStatement statement, int index, Long value) throws SQLException
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
statement.setNull(index, Types.BIGINT);
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.setLong(index, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a call record from the current result set row.
|
||||
*/
|
||||
private static CallRecord read(ResultSet rs) throws SQLException
|
||||
{
|
||||
CallRecord call = new CallRecord();
|
||||
call.setId(rs.getLong("id"));
|
||||
call.setStartTime(rs.getLong("start_time"));
|
||||
call.setEndTime(rs.getLong("end_time"));
|
||||
call.setCallState(CallState.fromValue(rs.getString("call_state")));
|
||||
call.setProtocol(rs.getString("protocol"));
|
||||
call.setSystem(rs.getString("system_name"));
|
||||
call.setSite(rs.getString("site_name"));
|
||||
call.setChannel(rs.getString("channel_name"));
|
||||
call.setFrequency(rs.getLong("frequency"));
|
||||
call.setTimeslot(rs.getInt("timeslot"));
|
||||
call.setToId(rs.getString("to_id"));
|
||||
call.setToValue(getLong(rs, "to_value"));
|
||||
call.setToForm(rs.getString("to_form"));
|
||||
call.setToFullyQualified(rs.getString("to_fq"));
|
||||
call.setFromId(rs.getString("from_id"));
|
||||
call.setFromValue(getLong(rs, "from_value"));
|
||||
call.setFromForm(rs.getString("from_form"));
|
||||
call.setFromFullyQualified(rs.getString("from_fq"));
|
||||
call.setAliasList(rs.getString("alias_list"));
|
||||
call.setTalkerAlias(rs.getString("talker_alias"));
|
||||
call.setEncrypted(rs.getBoolean("encrypted"));
|
||||
call.setDuplicate(rs.getBoolean("duplicate_call"));
|
||||
call.setPriority(rs.getInt("priority"));
|
||||
call.setAliasRecord(rs.getBoolean("alias_record"));
|
||||
call.setRecordFormat(rs.getString("record_format"));
|
||||
call.setFilePath(rs.getString("file_path"));
|
||||
call.setFileSize(rs.getLong("file_size"));
|
||||
call.setRecordingState(RecordingState.fromValue(rs.getString("recording_state")));
|
||||
return call;
|
||||
}
|
||||
|
||||
private static Long getLong(ResultSet rs, String column) throws SQLException
|
||||
{
|
||||
long value = rs.getLong(column);
|
||||
return rs.wasNull() ? null : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks any calls left in the active state, by a previous session that didn't shut down cleanly, as interrupted.
|
||||
* Recordings that were being written are left as recorded if the file has data.
|
||||
* @return count of calls updated
|
||||
*/
|
||||
@Override
|
||||
public int markInterrupted(Connection connection) throws SQLException
|
||||
{
|
||||
try(Statement statement = connection.createStatement())
|
||||
{
|
||||
int count = statement.executeUpdate("UPDATE " + mTable + " SET call_state = '" +
|
||||
CallState.INTERRUPTED.name() + "' WHERE call_state = '" + CallState.ACTIVE.name() + "'");
|
||||
statement.executeUpdate("UPDATE " + mTable + " SET recording_state = '" + RecordingState.RECORDED.name() +
|
||||
"' WHERE recording_state = '" + RecordingState.RECORDING.name() + "' AND file_path IS NOT NULL");
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteActive(Connection connection) throws SQLException
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mTable +
|
||||
" WHERE call_state = ?"))
|
||||
{
|
||||
statement.setString(1, CallState.ACTIVE.name());
|
||||
return statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for calls matching the criteria, newest first.
|
||||
* @param criteria to filter by
|
||||
* @param offset of the first row to return
|
||||
* @param limit maximum rows to return
|
||||
*/
|
||||
@Override
|
||||
public List<CallRecord> search(Connection connection, CallSearchCriteria criteria, int offset, int limit)
|
||||
throws SQLException
|
||||
{
|
||||
List<Object> parameters = new ArrayList<>();
|
||||
String where = getWhereClause(criteria, parameters);
|
||||
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " c" + where +
|
||||
" ORDER BY start_time DESC, id DESC LIMIT ? OFFSET ?";
|
||||
parameters.add(limit);
|
||||
parameters.add(offset);
|
||||
|
||||
List<CallRecord> calls = new ArrayList<>();
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
bindParameters(statement, parameters);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
while(rs.next())
|
||||
{
|
||||
calls.add(read(rs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadPatchedTalkgroups(connection, calls);
|
||||
return calls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count of calls matching the criteria
|
||||
*/
|
||||
@Override
|
||||
public long count(Connection connection, CallSearchCriteria criteria) throws SQLException
|
||||
{
|
||||
List<Object> parameters = new ArrayList<>();
|
||||
String sql = "SELECT COUNT(*) FROM " + mTable + " c" + getWhereClause(criteria, parameters);
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
bindParameters(statement, parameters);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
return rs.next() ? rs.getLong(1) : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the WHERE clause (with a leading space) for the criteria and adds the parameter values to the list.
|
||||
*/
|
||||
private String getWhereClause(CallSearchCriteria criteria, List<Object> parameters)
|
||||
{
|
||||
List<String> clauses = new ArrayList<>();
|
||||
|
||||
if(!criteria.to().isEmpty())
|
||||
{
|
||||
clauses.add(getIdentifierClause("to", criteria.to(), "to_form IN ('" + CallRecord.FORM_TALKGROUP + "', '" +
|
||||
CallRecord.FORM_PATCH_GROUP + "')", mPatchedTable, parameters));
|
||||
}
|
||||
|
||||
if(!criteria.from().isEmpty())
|
||||
{
|
||||
clauses.add(getIdentifierClause("from", criteria.from(), "from_form = '" + CallRecord.FORM_RADIO + "'",
|
||||
null, parameters));
|
||||
}
|
||||
|
||||
if(!criteria.talkerAlias().isEmpty())
|
||||
{
|
||||
clauses.add("LOWER(talker_alias) LIKE ? ESCAPE '!'");
|
||||
parameters.add(getLikePattern(criteria.talkerAlias()));
|
||||
}
|
||||
|
||||
if(criteria.protocol() != null)
|
||||
{
|
||||
clauses.add("protocol = ?");
|
||||
parameters.add(criteria.protocol().name());
|
||||
}
|
||||
|
||||
if(criteria.callType() != null)
|
||||
{
|
||||
clauses.add(criteria.callType().getWhereClause());
|
||||
}
|
||||
|
||||
if(!criteria.system().isEmpty())
|
||||
{
|
||||
clauses.add("LOWER(system_name) LIKE ? ESCAPE '!'");
|
||||
parameters.add(getLikePattern(criteria.system()));
|
||||
}
|
||||
|
||||
if(criteria.startTime() > 0)
|
||||
{
|
||||
clauses.add("start_time >= ?");
|
||||
parameters.add(criteria.startTime());
|
||||
}
|
||||
|
||||
if(criteria.endTime() > 0)
|
||||
{
|
||||
clauses.add("start_time <= ?");
|
||||
parameters.add(criteria.endTime());
|
||||
}
|
||||
|
||||
return clauses.isEmpty() ? "" : " WHERE " + String.join(" AND ", clauses);
|
||||
}
|
||||
|
||||
/**
|
||||
* WHERE clause for a TO or FROM identifier filter.
|
||||
* @param prefix of the identifier columns (to or from)
|
||||
* @param filter to apply
|
||||
* @param formClause that restricts an alias filter to the identifier forms that the alias identifiers apply to
|
||||
* @param patchedTable to also match the talkgroups patched into a patch group call (TO filter), or null
|
||||
* @param parameters to add the parameter values to
|
||||
*/
|
||||
private static String getIdentifierClause(String prefix, IdentifierFilter filter, String formClause,
|
||||
String patchedTable, List<Object> parameters)
|
||||
{
|
||||
String valueColumn = prefix + "_value";
|
||||
String fqColumn = prefix + "_fq";
|
||||
String patched = patchedTable != null ? "EXISTS (SELECT 1 FROM " + patchedTable + " p WHERE p.call_id = c.id AND " :
|
||||
null;
|
||||
|
||||
if(filter.isAlias())
|
||||
{
|
||||
List<String> matches = new ArrayList<>();
|
||||
List<Object> matchParameters = new ArrayList<>();
|
||||
|
||||
for(IdentifierFilter.ValueRange range: filter.ranges())
|
||||
{
|
||||
matches.add("(" + fqColumn + " IS NULL AND protocol = ? AND " + valueColumn + " BETWEEN ? AND ?)");
|
||||
matchParameters.add(range.protocol().name());
|
||||
matchParameters.add((long)range.min());
|
||||
matchParameters.add((long)range.max());
|
||||
|
||||
if(patched != null)
|
||||
{
|
||||
matches.add("(protocol = ? AND " + patched + "p.fq IS NULL AND p.talkgroup BETWEEN ? AND ?))");
|
||||
matchParameters.add(range.protocol().name());
|
||||
matchParameters.add((long)range.min());
|
||||
matchParameters.add((long)range.max());
|
||||
}
|
||||
}
|
||||
|
||||
for(IdentifierFilter.FullyQualifiedAddress address: filter.fullyQualified())
|
||||
{
|
||||
matches.add("(protocol = ? AND " + fqColumn + " = ?)");
|
||||
matchParameters.add(address.protocol().name());
|
||||
matchParameters.add(address.address());
|
||||
|
||||
if(patched != null)
|
||||
{
|
||||
matches.add("(protocol = ? AND " + patched + "p.fq = ?))");
|
||||
matchParameters.add(address.protocol().name());
|
||||
matchParameters.add(address.address());
|
||||
}
|
||||
}
|
||||
|
||||
if(matches.isEmpty())
|
||||
{
|
||||
return "1 = 0";
|
||||
}
|
||||
|
||||
parameters.add(filter.aliasList() != null ? filter.aliasList().toLowerCase(Locale.ROOT) : "");
|
||||
parameters.addAll(matchParameters);
|
||||
return "(LOWER(alias_list) = ? AND " + formClause + " AND (" + String.join(" OR ", matches) + "))";
|
||||
}
|
||||
|
||||
Long value = CallSearchCriteria.parseValue(filter.text());
|
||||
parameters.add(getLikePattern(filter.text()));
|
||||
|
||||
if(value != null)
|
||||
{
|
||||
parameters.add(value);
|
||||
|
||||
if(patched != null)
|
||||
{
|
||||
parameters.add(value);
|
||||
return "(LOWER(" + prefix + "_id) LIKE ? ESCAPE '!' OR " + valueColumn + " = ? OR " + patched +
|
||||
"p.talkgroup = ?))";
|
||||
}
|
||||
|
||||
return "(LOWER(" + prefix + "_id) LIKE ? ESCAPE '!' OR " + valueColumn + " = ?)";
|
||||
}
|
||||
|
||||
return "LOWER(" + prefix + "_id) LIKE ? ESCAPE '!'";
|
||||
}
|
||||
|
||||
/**
|
||||
* Case-insensitive 'contains' LIKE pattern with the LIKE wildcard characters escaped.
|
||||
*/
|
||||
static String getLikePattern(String text)
|
||||
{
|
||||
String escaped = text.toLowerCase(Locale.ROOT).replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||
return "%" + escaped + "%";
|
||||
}
|
||||
|
||||
private static void bindParameters(PreparedStatement statement, List<Object> parameters) throws SQLException
|
||||
{
|
||||
for(int x = 0; x < parameters.size(); x++)
|
||||
{
|
||||
Object parameter = parameters.get(x);
|
||||
|
||||
if(parameter instanceof String s)
|
||||
{
|
||||
statement.setString(x + 1, s);
|
||||
}
|
||||
else if(parameter instanceof Integer i)
|
||||
{
|
||||
statement.setInt(x + 1, i);
|
||||
}
|
||||
else if(parameter instanceof Long l)
|
||||
{
|
||||
statement.setLong(x + 1, l);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IllegalArgumentException("Unsupported parameter type: " + parameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a page of calls in id order, for transferring calls between databases.
|
||||
* @param afterId only return calls with an id greater than this value
|
||||
* @param limit maximum number of calls
|
||||
*/
|
||||
@Override
|
||||
public List<CallRecord> readPage(Connection connection, long afterId, int limit) throws SQLException
|
||||
{
|
||||
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE id > ? ORDER BY id LIMIT ?";
|
||||
List<CallRecord> calls = new ArrayList<>();
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
statement.setLong(1, afterId);
|
||||
statement.setInt(2, limit);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
while(rs.next())
|
||||
{
|
||||
calls.add(read(rs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadPatchedTalkgroups(connection, calls);
|
||||
return calls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Total number of call rows
|
||||
*/
|
||||
@Override
|
||||
public long count(Connection connection) throws SQLException
|
||||
{
|
||||
return count(connection, CallSearchCriteria.all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer keys (see {@link CallRecord#getTransferKey()}) of all calls in the table, for skipping calls that
|
||||
* already exist when appending.
|
||||
*/
|
||||
@Override
|
||||
public Set<String> getTransferKeys(Connection connection) throws SQLException
|
||||
{
|
||||
Set<String> keys = new HashSet<>();
|
||||
long afterId = 0;
|
||||
List<CallRecord> page = readPage(connection, afterId, 5000);
|
||||
|
||||
while(!page.isEmpty())
|
||||
{
|
||||
for(CallRecord call: page)
|
||||
{
|
||||
keys.add(call.getTransferKey());
|
||||
}
|
||||
|
||||
afterId = page.getLast().getId();
|
||||
page = readPage(connection, afterId, 5000);
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls with a recording, oldest first, for age-off processing.
|
||||
* @param startedBefore only include calls that started before this time, or 0 for any time
|
||||
* @param limit maximum number of calls
|
||||
*/
|
||||
@Override
|
||||
public List<CallRecord> getRecordedCalls(Connection connection, long startedBefore, int limit) throws SQLException
|
||||
{
|
||||
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE recording_state = ?" +
|
||||
(startedBefore > 0 ? " AND start_time < ?" : "") + " ORDER BY start_time, id LIMIT ?";
|
||||
List<CallRecord> calls = new ArrayList<>();
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
int index = 1;
|
||||
statement.setString(index++, RecordingState.RECORDED.name());
|
||||
|
||||
if(startedBefore > 0)
|
||||
{
|
||||
statement.setLong(index++, startedBefore);
|
||||
}
|
||||
|
||||
statement.setInt(index, limit);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
while(rs.next())
|
||||
{
|
||||
calls.add(read(rs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completed calls that started before the time, oldest first, for age-off processing.
|
||||
*/
|
||||
@Override
|
||||
public List<CallRecord> getCallsStartedBefore(Connection connection, long startedBefore, int limit)
|
||||
throws SQLException
|
||||
{
|
||||
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE start_time < ? AND call_state <> ? " +
|
||||
"ORDER BY start_time, id LIMIT ?";
|
||||
List<CallRecord> calls = new ArrayList<>();
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
statement.setLong(1, startedBefore);
|
||||
statement.setString(2, CallState.ACTIVE.name());
|
||||
statement.setInt(3, limit);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
while(rs.next())
|
||||
{
|
||||
calls.add(read(rs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CallRecord> getDuplicateAndDoNotMonitorCalls(Connection connection, long startedBefore, int limit)
|
||||
throws SQLException
|
||||
{
|
||||
String sql = "SELECT id, " + COLUMNS + " FROM " + mTable + " WHERE start_time < ? AND call_state <> ? AND " +
|
||||
"(duplicate_call = ? OR (priority <= ? AND alias_record = ?)) ORDER BY start_time, id LIMIT ?";
|
||||
List<CallRecord> calls = new ArrayList<>();
|
||||
|
||||
try(PreparedStatement statement = connection.prepareStatement(sql))
|
||||
{
|
||||
statement.setLong(1, startedBefore);
|
||||
statement.setString(2, CallState.ACTIVE.name());
|
||||
statement.setBoolean(3, true);
|
||||
statement.setInt(4, Priority.DO_NOT_MONITOR);
|
||||
statement.setBoolean(5, false);
|
||||
statement.setInt(6, limit);
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
while(rs.next())
|
||||
{
|
||||
calls.add(read(rs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Total size of all recordings that are still available.
|
||||
*/
|
||||
@Override
|
||||
public long getRecordedFileSize(Connection connection) throws SQLException
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement("SELECT SUM(file_size) FROM " + mTable +
|
||||
" WHERE recording_state = ?"))
|
||||
{
|
||||
statement.setString(1, RecordingState.RECORDED.name());
|
||||
|
||||
try(ResultSet rs = statement.executeQuery())
|
||||
{
|
||||
return rs.next() ? rs.getLong(1) : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the call rows
|
||||
*/
|
||||
@Override
|
||||
public void delete(Connection connection, List<Long> ids) throws SQLException
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement("DELETE FROM " + mTable + " WHERE id = ?"))
|
||||
{
|
||||
for(Long id: ids)
|
||||
{
|
||||
statement.setLong(1, id);
|
||||
statement.addBatch();
|
||||
}
|
||||
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the recording file of the calls and marks the recordings as deleted, keeping the call rows.
|
||||
*/
|
||||
@Override
|
||||
public void markRecordingsDeleted(Connection connection, List<Long> ids) throws SQLException
|
||||
{
|
||||
try(PreparedStatement statement = connection.prepareStatement("UPDATE " + mTable + " SET recording_state = ?, " +
|
||||
"file_path = NULL, file_size = 0 WHERE id = ?"))
|
||||
{
|
||||
for(Long id: ids)
|
||||
{
|
||||
statement.setString(1, RecordingState.DELETED.name());
|
||||
statement.setLong(2, id);
|
||||
statement.addBatch();
|
||||
}
|
||||
|
||||
statement.executeBatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schema name
|
||||
*/
|
||||
@Override
|
||||
public String getSchema()
|
||||
{
|
||||
return mSchema;
|
||||
}
|
||||
}
|
||||
@@ -1,151 +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.database.call;
|
||||
|
||||
import io.github.dsheirer.protocol.Protocol;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Search filter for the calls table. Empty text fields, empty identifier filters and null values don't filter.
|
||||
*
|
||||
* @param to filter for the TO identifier (talkgroup, patch group or radio): typed text or a selected talkgroup alias
|
||||
* @param from filter for the FROM identifier (radio): typed text or a selected radio alias
|
||||
* @param talkerAlias text matched against the decoded talker alias
|
||||
* @param protocol to match or null
|
||||
* @param callType to match or null
|
||||
* @param system text matched against the system name
|
||||
* @param startTime earliest call start time (ms since epoch) or 0
|
||||
* @param endTime latest call start time (ms since epoch) or 0
|
||||
*/
|
||||
public record CallSearchCriteria(IdentifierFilter to, IdentifierFilter from, String talkerAlias, Protocol protocol,
|
||||
CallType callType, String system, long startTime, long endTime)
|
||||
{
|
||||
/**
|
||||
* Criteria without a call type filter
|
||||
*/
|
||||
public CallSearchCriteria(IdentifierFilter to, IdentifierFilter from, String talkerAlias, Protocol protocol,
|
||||
String system, long startTime, long endTime)
|
||||
{
|
||||
this(to, from, talkerAlias, protocol, null, system, startTime, endTime);
|
||||
}
|
||||
|
||||
public CallSearchCriteria
|
||||
{
|
||||
to = to == null ? IdentifierFilter.none() : to;
|
||||
from = from == null ? IdentifierFilter.none() : from;
|
||||
talkerAlias = clean(talkerAlias);
|
||||
system = clean(system);
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria that match every call
|
||||
*/
|
||||
public static CallSearchCriteria all()
|
||||
{
|
||||
return new CallSearchCriteria(null, null, null, null, null, 0, 0);
|
||||
}
|
||||
|
||||
private static String clean(String value)
|
||||
{
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if these criteria match every call.
|
||||
*/
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return to.isEmpty() && from.isEmpty() && talkerAlias.isEmpty() && system.isEmpty() && protocol == null &&
|
||||
callType == null && startTime == 0 && endTime == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the text as a decimal identifier value, or null if it isn't a number.
|
||||
*/
|
||||
static Long parseValue(String text)
|
||||
{
|
||||
if(text == null || text.isEmpty() || text.length() > 18)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
for(int x = 0; x < text.length(); x++)
|
||||
{
|
||||
if(!Character.isDigit(text.charAt(x)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return Long.parseLong(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the criteria against a call in memory, using the same rules as the database query. This is used to
|
||||
* decide whether a live call belongs in the currently displayed search results.
|
||||
*/
|
||||
public boolean matches(CallRecord call)
|
||||
{
|
||||
if(!to.isEmpty() && !to.matches(call, call.getToId(), call.getToValue(), call.getToFullyQualified(),
|
||||
call.isToTalkgroup(), call.getPatchedTalkgroups()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!from.isEmpty() && !from.matches(call, call.getFromId(), call.getFromValue(),
|
||||
call.getFromFullyQualified(), call.isFromRadio(), List.of()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!talkerAlias.isEmpty() && !contains(call.getTalkerAlias(), talkerAlias))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(protocol != null && !protocol.name().equals(call.getProtocol()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(callType != null && call.getCallType() != callType)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!system.isEmpty() && !contains(call.getSystem(), system))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(startTime > 0 && call.getStartTime() < startTime)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return endTime <= 0 || call.getStartTime() <= endTime;
|
||||
}
|
||||
|
||||
private static boolean contains(String value, String text)
|
||||
{
|
||||
return value != null && value.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
@@ -1,71 +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.database.call;
|
||||
|
||||
/**
|
||||
* Call life-cycle state
|
||||
*/
|
||||
public enum CallState
|
||||
{
|
||||
/**
|
||||
* Call is in progress
|
||||
*/
|
||||
ACTIVE("Active"),
|
||||
/**
|
||||
* Call completed normally
|
||||
*/
|
||||
COMPLETE("Complete"),
|
||||
/**
|
||||
* Call was in progress when sdrtrunk stopped (e.g. a crash) and never completed
|
||||
*/
|
||||
INTERRUPTED("Interrupted");
|
||||
|
||||
private final String mLabel;
|
||||
|
||||
CallState(String label)
|
||||
{
|
||||
mLabel = label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return mLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the stored value, defaulting to COMPLETE for unrecognized values.
|
||||
*/
|
||||
public static CallState fromValue(String value)
|
||||
{
|
||||
if(value != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CallState.valueOf(value);
|
||||
}
|
||||
catch(IllegalArgumentException iae)
|
||||
{
|
||||
//Fall through
|
||||
}
|
||||
}
|
||||
|
||||
return COMPLETE;
|
||||
}
|
||||
}
|
||||
@@ -1,120 +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.database.call;
|
||||
|
||||
/**
|
||||
* Type of call, derived from the stored TO and FROM identifier forms.
|
||||
*/
|
||||
public enum CallType
|
||||
{
|
||||
/**
|
||||
* Call to a talkgroup
|
||||
*/
|
||||
GROUP("Group"),
|
||||
/**
|
||||
* Call to a patch group (talkgroups patched together)
|
||||
*/
|
||||
PATCH("Patch"),
|
||||
/**
|
||||
* Private (individual) call from one radio to another radio
|
||||
*/
|
||||
PRIVATE("Private"),
|
||||
/**
|
||||
* Telephone interconnect call between a radio and a telephone
|
||||
*/
|
||||
TELEPHONE("Telephone"),
|
||||
/**
|
||||
* Call without a TO identifier that identifies the call type (e.g. conventional analog)
|
||||
*/
|
||||
UNKNOWN("");
|
||||
|
||||
private static final String FORM_TELEPHONE_NUMBER = "TELEPHONE_NUMBER";
|
||||
private final String mLabel;
|
||||
|
||||
CallType(String label)
|
||||
{
|
||||
mLabel = label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call type for the TO and FROM identifier forms (Form enumeration names).
|
||||
*/
|
||||
public static CallType from(String toForm, String fromForm)
|
||||
{
|
||||
if(CallRecord.FORM_PATCH_GROUP.equals(toForm))
|
||||
{
|
||||
return PATCH;
|
||||
}
|
||||
|
||||
if(CallRecord.FORM_TALKGROUP.equals(toForm))
|
||||
{
|
||||
return GROUP;
|
||||
}
|
||||
|
||||
if(FORM_TELEPHONE_NUMBER.equals(toForm) || FORM_TELEPHONE_NUMBER.equals(fromForm))
|
||||
{
|
||||
return TELEPHONE;
|
||||
}
|
||||
|
||||
if(CallRecord.FORM_RADIO.equals(toForm))
|
||||
{
|
||||
return PRIVATE;
|
||||
}
|
||||
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL condition on the to_form and from_form columns that selects the calls of this type, using the same rules as
|
||||
* {@link #from(String, String)}. The values are constants, so the condition has no parameters.
|
||||
*/
|
||||
public String getWhereClause()
|
||||
{
|
||||
String patch = "'" + CallRecord.FORM_PATCH_GROUP + "'";
|
||||
String group = "'" + CallRecord.FORM_TALKGROUP + "'";
|
||||
String radio = "'" + CallRecord.FORM_RADIO + "'";
|
||||
String telephone = "'" + FORM_TELEPHONE_NUMBER + "'";
|
||||
String fromNotTelephone = "(from_form IS NULL OR from_form <> " + telephone + ")";
|
||||
|
||||
return switch(this)
|
||||
{
|
||||
case PATCH -> "to_form = " + patch;
|
||||
case GROUP -> "to_form = " + group;
|
||||
case TELEPHONE -> "(to_form = " + telephone + " OR (from_form = " + telephone + " AND (to_form IS NULL " +
|
||||
"OR to_form NOT IN (" + patch + ", " + group + "))))";
|
||||
case PRIVATE -> "(to_form = " + radio + " AND " + fromNotTelephone + ")";
|
||||
case UNKNOWN -> "((to_form IS NULL OR to_form NOT IN (" + patch + ", " + group + ", " + radio + ", " +
|
||||
telephone + ")) AND " + fromNotTelephone + ")";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for selecting the type in a search filter (the unknown type is labeled Other)
|
||||
*/
|
||||
public String getFilterLabel()
|
||||
{
|
||||
return this == UNKNOWN ? "Other" : mLabel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return mLabel;
|
||||
}
|
||||
}
|
||||
@@ -1,125 +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.database.call;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Storage operations for call audio events in one database schema. Each method uses the connection from the caller
|
||||
* so that the caller controls pooling and transactions.
|
||||
*/
|
||||
public interface ICallRepository
|
||||
{
|
||||
/**
|
||||
* Inserts the call and assigns the generated row id to the call.
|
||||
* @return generated row id
|
||||
*/
|
||||
long insert(Connection connection, CallRecord call) throws SQLException;
|
||||
|
||||
/**
|
||||
* Inserts the calls in a single batch without retrieving the generated ids.
|
||||
*/
|
||||
void insertBatch(Connection connection, List<CallRecord> calls) throws SQLException;
|
||||
|
||||
/**
|
||||
* Updates the existing call row identified by the call's id.
|
||||
* @return true if the row exists and was updated
|
||||
*/
|
||||
boolean update(Connection connection, CallRecord call) throws SQLException;
|
||||
|
||||
/**
|
||||
* Marks calls left in the active state by a previous session as interrupted.
|
||||
* @return count of calls updated
|
||||
*/
|
||||
int markInterrupted(Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* Deletes the calls that are in progress. Used when switching databases: calls in progress continue in the new
|
||||
* database, so their rows are removed from the old database.
|
||||
* @return count of calls deleted
|
||||
*/
|
||||
int deleteActive(Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* Calls matching the criteria, newest first.
|
||||
*/
|
||||
List<CallRecord> search(Connection connection, CallSearchCriteria criteria, int offset, int limit)
|
||||
throws SQLException;
|
||||
|
||||
/**
|
||||
* Count of calls matching the criteria
|
||||
*/
|
||||
long count(Connection connection, CallSearchCriteria criteria) throws SQLException;
|
||||
|
||||
/**
|
||||
* Total number of calls
|
||||
*/
|
||||
long count(Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* Page of calls in id order with an id greater than the argument, for transfers between databases.
|
||||
*/
|
||||
List<CallRecord> readPage(Connection connection, long afterId, int limit) throws SQLException;
|
||||
|
||||
/**
|
||||
* Transfer keys of all calls (see {@link CallRecord#getTransferKey()})
|
||||
*/
|
||||
Set<String> getTransferKeys(Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* Calls with an available recording, oldest first.
|
||||
* @param startedBefore only calls that started before this time, or 0 for any time
|
||||
*/
|
||||
List<CallRecord> getRecordedCalls(Connection connection, long startedBefore, int limit) throws SQLException;
|
||||
|
||||
/**
|
||||
* Calls that are not in progress and started before the time, oldest first.
|
||||
*/
|
||||
List<CallRecord> getCallsStartedBefore(Connection connection, long startedBefore, int limit) throws SQLException;
|
||||
|
||||
/**
|
||||
* Completed calls that started before the time and are duplicates, or Do Not Monitor calls without an alias record
|
||||
* option, oldest first.
|
||||
*/
|
||||
List<CallRecord> getDuplicateAndDoNotMonitorCalls(Connection connection, long startedBefore, int limit)
|
||||
throws SQLException;
|
||||
|
||||
/**
|
||||
* Total size in bytes of all available recordings
|
||||
*/
|
||||
long getRecordedFileSize(Connection connection) throws SQLException;
|
||||
|
||||
/**
|
||||
* Deletes the call rows
|
||||
*/
|
||||
void delete(Connection connection, List<Long> ids) throws SQLException;
|
||||
|
||||
/**
|
||||
* Clears the recording file of the calls and marks their recordings deleted, keeping the call rows.
|
||||
*/
|
||||
void markRecordingsDeleted(Connection connection, List<Long> ids) throws SQLException;
|
||||
|
||||
/**
|
||||
* Schema that holds the calls table
|
||||
*/
|
||||
String getSchema();
|
||||
}
|
||||
@@ -1,285 +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.database.call;
|
||||
|
||||
import io.github.dsheirer.alias.Alias;
|
||||
import io.github.dsheirer.alias.id.AliasID;
|
||||
import io.github.dsheirer.alias.id.radio.P25FullyQualifiedRadio;
|
||||
import io.github.dsheirer.alias.id.radio.Radio;
|
||||
import io.github.dsheirer.alias.id.radio.RadioRange;
|
||||
import io.github.dsheirer.alias.id.talkgroup.P25FullyQualifiedTalkgroup;
|
||||
import io.github.dsheirer.alias.id.talkgroup.Talkgroup;
|
||||
import io.github.dsheirer.alias.id.talkgroup.TalkgroupRange;
|
||||
import io.github.dsheirer.protocol.Protocol;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Search filter for the TO or FROM identifier of a call. The filter either matches typed text against the formatted
|
||||
* identifier (or the exact identifier value when the text is a number), or matches the identifiers of a selected
|
||||
* alias: calls of the alias's alias list whose identifier value is one of the alias's values or ranges, or whose fully
|
||||
* qualified (roaming) address is one of the alias's fully qualified identifiers. This uses the same matching as the
|
||||
* alias list, so a search for an alias finds the calls that the alias list currently aliases with that alias.
|
||||
*
|
||||
* @param text typed text, or empty for no text filter (ignored when an alias is selected)
|
||||
* @param aliasName of the selected alias, or null
|
||||
* @param aliasList name of the selected alias, or null
|
||||
* @param ranges of identifier values for the selected alias
|
||||
* @param fullyQualified addresses for the selected alias
|
||||
*/
|
||||
public record IdentifierFilter(String text, String aliasName, String aliasList, List<ValueRange> ranges,
|
||||
List<FullyQualifiedAddress> fullyQualified)
|
||||
{
|
||||
/**
|
||||
* Range of identifier values (inclusive) for a protocol
|
||||
*/
|
||||
public record ValueRange(Protocol protocol, int min, int max)
|
||||
{
|
||||
public boolean contains(Protocol callProtocol, long value)
|
||||
{
|
||||
return protocol == callProtocol && min <= value && value <= max;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully qualified identifier address (wacn.system.id) for a protocol
|
||||
*/
|
||||
public record FullyQualifiedAddress(Protocol protocol, String address) {}
|
||||
|
||||
public IdentifierFilter
|
||||
{
|
||||
text = text == null ? "" : text.trim();
|
||||
ranges = ranges == null ? List.of() : List.copyOf(ranges);
|
||||
fullyQualified = fullyQualified == null ? List.of() : List.copyOf(fullyQualified);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter that matches every call
|
||||
*/
|
||||
public static IdentifierFilter none()
|
||||
{
|
||||
return new IdentifierFilter("", null, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter for typed text
|
||||
*/
|
||||
public static IdentifierFilter text(String text)
|
||||
{
|
||||
return new IdentifierFilter(text, null, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter for the talkgroup identifiers (talkgroups, ranges, fully qualified talkgroups) of the alias
|
||||
*/
|
||||
public static IdentifierFilter talkgroupAlias(Alias alias)
|
||||
{
|
||||
List<ValueRange> ranges = new ArrayList<>();
|
||||
List<FullyQualifiedAddress> fullyQualified = new ArrayList<>();
|
||||
|
||||
for(AliasID id: alias.getAliasIdentifiers())
|
||||
{
|
||||
if(!id.isValid())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if(id instanceof P25FullyQualifiedTalkgroup fqt)
|
||||
{
|
||||
fullyQualified.add(new FullyQualifiedAddress(fqt.getProtocol(), fqt.getHashKey()));
|
||||
}
|
||||
else if(id instanceof Talkgroup talkgroup)
|
||||
{
|
||||
ranges.add(new ValueRange(talkgroup.getProtocol(), talkgroup.getValue(), talkgroup.getValue()));
|
||||
}
|
||||
else if(id instanceof TalkgroupRange range)
|
||||
{
|
||||
ranges.add(new ValueRange(range.getProtocol(), range.getMinTalkgroup(), range.getMaxTalkgroup()));
|
||||
}
|
||||
}
|
||||
|
||||
return new IdentifierFilter("", alias.getName(), alias.getAliasListName(), ranges, fullyQualified);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter for the radio identifiers (radios, ranges, fully qualified radios) of the alias
|
||||
*/
|
||||
public static IdentifierFilter radioAlias(Alias alias)
|
||||
{
|
||||
List<ValueRange> ranges = new ArrayList<>();
|
||||
List<FullyQualifiedAddress> fullyQualified = new ArrayList<>();
|
||||
|
||||
for(AliasID id: alias.getAliasIdentifiers())
|
||||
{
|
||||
if(!id.isValid())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if(id instanceof P25FullyQualifiedRadio fqr)
|
||||
{
|
||||
fullyQualified.add(new FullyQualifiedAddress(fqr.getProtocol(), fqr.getHashKey()));
|
||||
}
|
||||
else if(id instanceof Radio radio)
|
||||
{
|
||||
ranges.add(new ValueRange(radio.getProtocol(), radio.getValue(), radio.getValue()));
|
||||
}
|
||||
else if(id instanceof RadioRange range)
|
||||
{
|
||||
ranges.add(new ValueRange(range.getProtocol(), range.getMinRadio(), range.getMaxRadio()));
|
||||
}
|
||||
}
|
||||
|
||||
return new IdentifierFilter("", alias.getName(), alias.getAliasListName(), ranges, fullyQualified);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the alias has talkgroup identifiers that a talkgroup alias filter can search for
|
||||
*/
|
||||
public static boolean hasTalkgroups(Alias alias)
|
||||
{
|
||||
IdentifierFilter filter = talkgroupAlias(alias);
|
||||
return !filter.ranges().isEmpty() || !filter.fullyQualified().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the alias has radio identifiers that a radio alias filter can search for
|
||||
*/
|
||||
public static boolean hasRadios(Alias alias)
|
||||
{
|
||||
IdentifierFilter filter = radioAlias(alias);
|
||||
return !filter.ranges().isEmpty() || !filter.fullyQualified().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this filter is for a selected alias
|
||||
*/
|
||||
public boolean isAlias()
|
||||
{
|
||||
return aliasName != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if this filter doesn't filter anything. An alias filter always filters: an alias without matching
|
||||
* identifiers matches no calls.
|
||||
*/
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return !isAlias() && text.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the filter against a call identifier in memory, using the same rules as the database query.
|
||||
* @param call to evaluate
|
||||
* @param formatted identifier text
|
||||
* @param value of the identifier, or null
|
||||
* @param fullyQualifiedAddress of the identifier, or null
|
||||
* @param formMatches true if the identifier form is the form that the alias identifiers apply to
|
||||
* @param patched talkgroups patched into the TO patch group, which also match, or an empty list
|
||||
*/
|
||||
boolean matches(CallRecord call, String formatted, Long value, String fullyQualifiedAddress, boolean formMatches,
|
||||
List<PatchedTalkgroup> patched)
|
||||
{
|
||||
if(isAlias())
|
||||
{
|
||||
if(!formMatches || call.getAliasList() == null || aliasList == null ||
|
||||
!call.getAliasList().equalsIgnoreCase(aliasList))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Protocol protocol = call.getProtocolValue();
|
||||
|
||||
for(PatchedTalkgroup talkgroup: patched)
|
||||
{
|
||||
if(matchesAlias(protocol, talkgroup.value(), talkgroup.fullyQualified()))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return matchesAlias(protocol, value, fullyQualifiedAddress);
|
||||
}
|
||||
|
||||
if(text.isEmpty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
Long parsed = CallSearchCriteria.parseValue(text);
|
||||
|
||||
if(parsed != null)
|
||||
{
|
||||
if(parsed.equals(value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
for(PatchedTalkgroup talkgroup: patched)
|
||||
{
|
||||
if(talkgroup.value() == parsed)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return formatted != null && formatted.toLowerCase(Locale.ROOT).contains(text.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the identifier value or fully qualified address matches the alias identifiers
|
||||
*/
|
||||
private boolean matchesAlias(Protocol protocol, Long value, String fullyQualifiedAddress)
|
||||
{
|
||||
if(fullyQualifiedAddress != null)
|
||||
{
|
||||
for(FullyQualifiedAddress address: fullyQualified)
|
||||
{
|
||||
if(address.protocol() == protocol && address.address().equals(fullyQualifiedAddress))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if(value != null)
|
||||
{
|
||||
for(ValueRange range: ranges)
|
||||
{
|
||||
if(range.contains(protocol, value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return isAlias() ? aliasName + " (" + aliasList + ")" : text;
|
||||
}
|
||||
}
|
||||
@@ -1,79 +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.database.call;
|
||||
|
||||
/**
|
||||
* State of the audio recording file for a call
|
||||
*/
|
||||
public enum RecordingState
|
||||
{
|
||||
/**
|
||||
* Call is not recorded
|
||||
*/
|
||||
NONE("Not Recorded"),
|
||||
/**
|
||||
* Recording is being written
|
||||
*/
|
||||
RECORDING("Recording"),
|
||||
/**
|
||||
* Recording is complete and the file is available
|
||||
*/
|
||||
RECORDED("Recorded"),
|
||||
/**
|
||||
* Recording file was deleted by an age-off rule or by the user
|
||||
*/
|
||||
DELETED("Deleted"),
|
||||
/**
|
||||
* Recording failed with an error
|
||||
*/
|
||||
FAILED("Failed");
|
||||
|
||||
private final String mLabel;
|
||||
|
||||
RecordingState(String label)
|
||||
{
|
||||
mLabel = label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return mLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the stored value, defaulting to NONE for unrecognized values.
|
||||
*/
|
||||
public static RecordingState fromValue(String value)
|
||||
{
|
||||
if(value != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return RecordingState.valueOf(value);
|
||||
}
|
||||
catch(IllegalArgumentException iae)
|
||||
{
|
||||
//Fall through
|
||||
}
|
||||
}
|
||||
|
||||
return NONE;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +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.database.dialect;
|
||||
|
||||
import io.github.dsheirer.database.DatabaseConfiguration;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Built-in H2 embedded database, stored in the application 'db' directory.
|
||||
*/
|
||||
public class H2Dialect implements IDatabaseDialect
|
||||
{
|
||||
public static final String DATABASE_FILE_NAME = "sdrtrunk";
|
||||
|
||||
@Override
|
||||
public String getDriverClass()
|
||||
{
|
||||
return "org.h2.Driver";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDefaultPort()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNetwork()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean requiresDatabaseName()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
|
||||
{
|
||||
//DB_CLOSE_ON_EXIT=FALSE: the application closes the pool during shutdown, after the last call update.
|
||||
return "jdbc:h2:file:" + databaseDirectory.resolve(DATABASE_FILE_NAME).toAbsolutePath() +
|
||||
";DB_CLOSE_ON_EXIT=FALSE";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdentityColumn()
|
||||
{
|
||||
return "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDropSchemaStatement(String schema)
|
||||
{
|
||||
return "DROP SCHEMA IF EXISTS " + schema + " CASCADE";
|
||||
}
|
||||
}
|
||||
@@ -1,77 +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.database.dialect;
|
||||
|
||||
import io.github.dsheirer.database.DatabaseConfiguration;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Per-engine connection settings and SQL differences for a call database. Everything else that sdrtrunk sends to
|
||||
* the database is portable SQL shared by all engines.
|
||||
*
|
||||
* All supported engines support schemas, so sdrtrunk always qualifies its tables with the configured schema name.
|
||||
*/
|
||||
public interface IDatabaseDialect
|
||||
{
|
||||
/**
|
||||
* JDBC driver class name
|
||||
*/
|
||||
String getDriverClass();
|
||||
|
||||
/**
|
||||
* Default TCP port for a network database server, or 0 for an embedded database.
|
||||
*/
|
||||
int getDefaultPort();
|
||||
|
||||
/**
|
||||
* Indicates if this is a network database server that needs a host, port and credentials.
|
||||
*/
|
||||
boolean isNetwork();
|
||||
|
||||
/**
|
||||
* Indicates if the engine needs a database name in addition to the schema name.
|
||||
*/
|
||||
boolean requiresDatabaseName();
|
||||
|
||||
/**
|
||||
* JDBC URL for the configuration
|
||||
* @param configuration with the host, port and database name
|
||||
* @param databaseDirectory for embedded database files
|
||||
*/
|
||||
String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory);
|
||||
|
||||
/**
|
||||
* Column definition for an auto-generated 64-bit primary key.
|
||||
*/
|
||||
String getIdentityColumn();
|
||||
|
||||
/**
|
||||
* Statement that creates the schema when it doesn't exist.
|
||||
*/
|
||||
default String getCreateSchemaStatement(String schema)
|
||||
{
|
||||
return "CREATE SCHEMA IF NOT EXISTS " + schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Statement that removes the schema and all of its tables.
|
||||
*/
|
||||
String getDropSchemaStatement(String schema);
|
||||
}
|
||||
@@ -1,72 +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.database.dialect;
|
||||
|
||||
import io.github.dsheirer.database.DatabaseConfiguration;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* MariaDB network database server. In MariaDB a schema is a database.
|
||||
*/
|
||||
public class MariaDBDialect implements IDatabaseDialect
|
||||
{
|
||||
@Override
|
||||
public String getDriverClass()
|
||||
{
|
||||
return "org.mariadb.jdbc.Driver";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDefaultPort()
|
||||
{
|
||||
return 3306;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNetwork()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean requiresDatabaseName()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
|
||||
{
|
||||
return "jdbc:mariadb://" + configuration.host() + ":" + configuration.port() + "/";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdentityColumn()
|
||||
{
|
||||
return "BIGINT AUTO_INCREMENT PRIMARY KEY";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDropSchemaStatement(String schema)
|
||||
{
|
||||
//Dropping a MariaDB schema (database) drops all of its tables
|
||||
return "DROP SCHEMA IF EXISTS " + schema;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +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.database.dialect;
|
||||
|
||||
import io.github.dsheirer.database.DatabaseConfiguration;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* PostgreSQL network database server. The schema lives inside the database named in the configuration.
|
||||
*/
|
||||
public class PostgreSQLDialect implements IDatabaseDialect
|
||||
{
|
||||
@Override
|
||||
public String getDriverClass()
|
||||
{
|
||||
return "org.postgresql.Driver";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDefaultPort()
|
||||
{
|
||||
return 5432;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNetwork()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean requiresDatabaseName()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getJdbcUrl(DatabaseConfiguration configuration, Path databaseDirectory)
|
||||
{
|
||||
return "jdbc:postgresql://" + configuration.host() + ":" + configuration.port() + "/" +
|
||||
configuration.database();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdentityColumn()
|
||||
{
|
||||
return "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDropSchemaStatement(String schema)
|
||||
{
|
||||
return "DROP SCHEMA IF EXISTS " + schema + " CASCADE";
|
||||
}
|
||||
}
|
||||
@@ -271,26 +271,6 @@ public abstract class C4FMSymbolProcessor
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of symbols without a sync detection after which syncInactivityTimeout() is invoked. Default is zero,
|
||||
* which disables the timeout.
|
||||
* @return timeout as a count of symbols, or zero to disable.
|
||||
*/
|
||||
protected int getSyncInactivityTimeoutSymbolCount()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notification that no sync was detected for the sync inactivity timeout period (see
|
||||
* getSyncInactivityTimeoutSymbolCount()). Invoked once per period of inactivity. Subclasses can override this to
|
||||
* reset protocol specific state that was learned from the signal. Default implementation is a no-op.
|
||||
*/
|
||||
protected void syncInactivityTimeout()
|
||||
{
|
||||
//No-op default implementation
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of consecutive sync periods (capped at 3) where a sync was detected within the max message length.
|
||||
*/
|
||||
@@ -426,11 +406,6 @@ public abstract class C4FMSymbolProcessor
|
||||
|
||||
symbolsSinceLastSync++;
|
||||
|
||||
if(symbolsSinceLastSync == getSyncInactivityTimeoutSymbolCount())
|
||||
{
|
||||
syncInactivityTimeout();
|
||||
}
|
||||
|
||||
//Clear synchronized state when we miss a sync period.
|
||||
if(mSynchronized && symbolsSinceLastSync > getMaxMessageDibitLength())
|
||||
{
|
||||
|
||||
@@ -42,7 +42,6 @@ public class ChannelDFTFactory
|
||||
case VECTOR_SIMD_PREFERRED:
|
||||
return new VectorChannelDFT(channelCount);
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarChannelDFT(channelCount);
|
||||
}
|
||||
|
||||
@@ -79,11 +79,9 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
|
||||
private static final int MAXIMUM_QUEUED_BATCHES = 50;
|
||||
|
||||
/**
|
||||
* Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batch being filled and the batch
|
||||
* being transformed. Channel output processors copy their channels from a batch instead of retaining it, so no
|
||||
* other batches are held.
|
||||
* Maximum batch sample arrays held for reuse: the queued IFFT batches plus the batches queued for channel output.
|
||||
*/
|
||||
private static final int MAXIMUM_POOLED_BATCHES = MAXIMUM_QUEUED_BATCHES + 2;
|
||||
private static final int MAXIMUM_POOLED_BATCHES = 2 * MAXIMUM_QUEUED_BATCHES;
|
||||
|
||||
//Sized to process 40 times per second
|
||||
private IFFTProcessorDispatcher mIFFTProcessorDispatcher = new IFFTProcessorDispatcher(25);
|
||||
|
||||
@@ -68,12 +68,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
|
||||
private final static Logger mLog = LoggerFactory.getLogger(PolyphaseChannelManager.class);
|
||||
private static final double CHANNEL_OVERSAMPLING = 2.0;
|
||||
private static final int POLYPHASE_CHANNELIZER_TAPS_PER_CHANNEL = 9;
|
||||
/**
|
||||
* Maximum duration of queued native buffers awaiting the channelizer. The queue is bounded by sample count instead
|
||||
* of buffer count because tuner buffer sizes vary widely, for example about 1,000 samples per RSP buffer and 32,768
|
||||
* samples per RTL-SDR buffer, so that each tuner can absorb a processing delay of the same duration.
|
||||
*/
|
||||
private static final double MAXIMUM_QUEUED_SECONDS = 1.0;
|
||||
private static final int MAXIMUM_QUEUED_NATIVE_BUFFERS = 500;
|
||||
|
||||
private Broadcaster<SourceEvent> mSourceEventBroadcaster = new Broadcaster<>();
|
||||
private TunerController mTunerController;
|
||||
@@ -83,7 +78,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
|
||||
private ComplexPolyphaseChannelizerM2 mPolyphaseChannelizer;
|
||||
private ChannelSourceEventListener mChannelSourceEventListener = new ChannelSourceEventListener();
|
||||
private NativeBufferReceiver mNativeBufferReceiver = new NativeBufferReceiver();
|
||||
private Dispatcher<INativeBuffer> mBufferDispatcher;
|
||||
private Dispatcher mBufferDispatcher;
|
||||
private boolean mRunning = true;
|
||||
|
||||
/**
|
||||
@@ -104,21 +99,10 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
|
||||
|
||||
mChannelCalculator = new ChannelCalculator(tunerController.getSampleRate(), channelCount,
|
||||
tunerController.getFrequency(), CHANNEL_OVERSAMPLING);
|
||||
mBufferDispatcher = new Dispatcher<>("sdrtrunk polyphase buffer processor", 10, INativeBuffer::sampleCount,
|
||||
getMaximumQueuedSamples(tunerController.getSampleRate()));
|
||||
mBufferDispatcher = new Dispatcher("sdrtrunk polyphase buffer processor", 10, MAXIMUM_QUEUED_NATIVE_BUFFERS);
|
||||
mBufferDispatcher.setListener(mNativeBufferReceiver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the maximum number of queued samples for the buffer dispatcher.
|
||||
* @param sampleRate of the tuner
|
||||
* @return maximum queued samples, at least one
|
||||
*/
|
||||
private static long getMaximumQueuedSamples(double sampleRate)
|
||||
{
|
||||
return Math.max(1, (long)(sampleRate * MAXIMUM_QUEUED_SECONDS));
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides a description of the state of this manager.
|
||||
*/
|
||||
@@ -294,7 +278,6 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
|
||||
double sampleRate = sourceEvent.getValue().doubleValue();
|
||||
int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate);
|
||||
mChannelCalculator.setRates(sampleRate, channelCount);
|
||||
mBufferDispatcher.setMaximumQueuedWeight(getMaximumQueuedSamples(sampleRate));
|
||||
break;
|
||||
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_LOCKED:
|
||||
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_UNLOCKED:
|
||||
|
||||
@@ -180,8 +180,7 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
|
||||
/**
|
||||
* Performs the output processor update. This method must be invoked on the channel results calling thread so that
|
||||
* replacing the output processor doesn't overlap with delivery of channel results to it. The output processor
|
||||
* applies channel index changes as it copies the next batch, and applies mixer and filter changes on its own
|
||||
* dispatcher thread at that same batch.
|
||||
* applies the configuration changes on its own dispatcher thread.
|
||||
* @param channelCalculator for updates
|
||||
* @param filterManager for updates
|
||||
* @throws IllegalArgumentException if there's an issue.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
* Copyright (C) 2014-2024 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@@ -24,7 +24,6 @@ import io.github.dsheirer.sample.complex.ComplexSamples;
|
||||
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
|
||||
import io.github.dsheirer.util.Dispatcher;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.slf4j.Logger;
|
||||
@@ -35,20 +34,12 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
|
||||
private final static Logger mLog = LoggerFactory.getLogger(ChannelOutputProcessor.class);
|
||||
|
||||
/**
|
||||
* Maximum queued channel sample batches, about one second of samples. A full batch is dropped when this channel
|
||||
* Maximum queued channel results batches, about one second of samples. A full batch is dropped when this channel
|
||||
* falls behind, which preserves the even-sized batch block parity that two-channel synthesis relies on.
|
||||
*/
|
||||
private static final int MAXIMUM_QUEUED_BATCHES = 50;
|
||||
|
||||
/**
|
||||
* Maximum channel sample arrays held for reuse: the queued batches plus the batch being processed and the batch
|
||||
* being copied.
|
||||
*/
|
||||
private static final int MAXIMUM_POOLED_ARRAYS = MAXIMUM_QUEUED_BATCHES + 2;
|
||||
|
||||
private Dispatcher<QueuedChannelSamples> mChannelSamplesDispatcher;
|
||||
private final Queue<float[]> mSamplePool = new ArrayBlockingQueue<>(MAXIMUM_POOLED_ARRAYS);
|
||||
private volatile int[] mChannelOffsets = new int[0];
|
||||
private Dispatcher<QueuedChannelResults> mChannelResultsDispatcher;
|
||||
private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>();
|
||||
private final AtomicLong mBatchSequence = new AtomicLong();
|
||||
private HeartbeatManager mHeartbeatManager;
|
||||
@@ -69,45 +60,25 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
|
||||
mInputChannelCount = inputChannelCount;
|
||||
//Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate)
|
||||
mHeartbeatManager = heartbeatManager;
|
||||
mChannelSamplesDispatcher = new Dispatcher<>(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
|
||||
mChannelSamplesDispatcher.setListener(queued -> {
|
||||
mChannelResultsDispatcher = new Dispatcher(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
|
||||
mChannelResultsDispatcher.setListener(queued -> {
|
||||
try
|
||||
{
|
||||
applyPendingUpdates(queued.sequence());
|
||||
mCurrentSampleTimestamp = queued.timestamp();
|
||||
process(queued.samples(), queued.blockCount());
|
||||
mCurrentSampleTimestamp = queued.channelResults().getTimestamp();
|
||||
process(queued.channelResults());
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
mLog.error("Error processing channel samples", t);
|
||||
mLog.error("Error processing channel results", t);
|
||||
}
|
||||
finally
|
||||
{
|
||||
mSamplePool.offer(queued.samples());
|
||||
queued.channelResults().release();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the I/Q offsets within each channel results block for the polyphase channel(s) that this processor copies.
|
||||
* The offsets take effect at the first channel results batch received after this method is invoked, the same as a
|
||||
* change queued with enqueueUpdate(), so a change of offsets and of the mixer frequency apply to the same batch.
|
||||
* This should only be invoked on the thread that delivers channel results, or before results are delivered.
|
||||
* @param offsets for each polyphase channel, which is twice the channel index.
|
||||
*/
|
||||
protected void setChannelOffsets(int... offsets)
|
||||
{
|
||||
mChannelOffsets = offsets.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Current I/Q offsets within each channel results block for the polyphase channel(s) that this processor copies.
|
||||
*/
|
||||
protected int[] getChannelOffsets()
|
||||
{
|
||||
return mChannelOffsets.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues a configuration change to apply on the dispatcher thread, so that configuration changes don't overlap with
|
||||
* sample processing. The change takes effect at the first channel results batch received after this method is
|
||||
@@ -148,13 +119,13 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
|
||||
@Override
|
||||
public void start()
|
||||
{
|
||||
mChannelSamplesDispatcher.start();
|
||||
mChannelResultsDispatcher.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop()
|
||||
{
|
||||
mChannelSamplesDispatcher.stop();
|
||||
mChannelResultsDispatcher.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -176,66 +147,22 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies this processor's polyphase channel(s) from the channel results batch and queues the copy for processing on
|
||||
* the dispatcher thread. The copy is small (about 8 kB per polyphase channel for a 1024 block batch), so the batch
|
||||
* isn't retained beyond this method and its large shared sample array returns to the channelizer's pool as soon as
|
||||
* the channelizer has dispatched it to every channel. A slow channel then queues only its own samples.
|
||||
*
|
||||
* @param channelResults batch to copy from
|
||||
*/
|
||||
@Override
|
||||
public void receiveChannelResults(ChannelResultsBatch channelResults)
|
||||
{
|
||||
long sequence = mBatchSequence.incrementAndGet();
|
||||
channelResults.retain();
|
||||
|
||||
if(!mChannelSamplesDispatcher.isRunning())
|
||||
if(!mChannelResultsDispatcher.offer(new QueuedChannelResults(channelResults, mBatchSequence.incrementAndGet())))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int[] offsets = mChannelOffsets;
|
||||
float[] source = channelResults.getSamples();
|
||||
int blockLength = channelResults.getBlockLength();
|
||||
int blockCount = channelResults.getBlockCount();
|
||||
float[] samples = getPooledArray(blockCount * offsets.length * 2);
|
||||
int pointer = 0;
|
||||
|
||||
for(int block = 0; block < blockCount; block++)
|
||||
{
|
||||
int blockOffset = block * blockLength;
|
||||
|
||||
for(int offset : offsets)
|
||||
{
|
||||
samples[pointer++] = source[blockOffset + offset];
|
||||
samples[pointer++] = source[blockOffset + offset + 1];
|
||||
}
|
||||
}
|
||||
|
||||
if(!mChannelSamplesDispatcher.offer(new QueuedChannelSamples(samples, blockCount, channelResults.getTimestamp(),
|
||||
sequence)))
|
||||
{
|
||||
mSamplePool.offer(samples);
|
||||
channelResults.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides a reused sample array of the requested length when one is available, or a new array.
|
||||
* Sub-class implementation to process one polyphase channelizer results batch.
|
||||
* @param channelResults to process
|
||||
*/
|
||||
private float[] getPooledArray(int length)
|
||||
{
|
||||
float[] samples = mSamplePool.poll();
|
||||
return samples != null && samples.length == length ? samples : new float[length];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sub-class implementation to process one batch of copied channel samples.
|
||||
* @param samples for each block in order, with the I/Q pair of each polyphase channel in the order of the channel
|
||||
* offsets, for example I1,Q1,I2,Q2 per block for two channels.
|
||||
* @param blockCount number of blocks. Batches start on an even block index, so the index of a block within this
|
||||
* batch has the same parity as its absolute block index.
|
||||
*/
|
||||
public abstract void process(float[] samples, int blockCount);
|
||||
public abstract void process(ChannelResultsBatch channelResults);
|
||||
|
||||
@Override
|
||||
public int getInputChannelCount()
|
||||
@@ -244,10 +171,9 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
|
||||
}
|
||||
|
||||
/**
|
||||
* Copied channel samples with the timestamp of the batch they were copied from and the batch's position in the
|
||||
* sequence of received batches.
|
||||
* Channel results batch and its position in the sequence of received batches.
|
||||
*/
|
||||
private record QueuedChannelSamples(float[] samples, int blockCount, long timestamp, long sequence) {}
|
||||
private record QueuedChannelResults(ChannelResultsBatch channelResults, long sequence) {}
|
||||
|
||||
/**
|
||||
* Configuration change and the sequence number of the last batch received before the change was requested.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
* Copyright (C) 2014-2024 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@@ -18,9 +18,9 @@
|
||||
*/
|
||||
package io.github.dsheirer.dsp.filter.channelizer.output;
|
||||
|
||||
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
|
||||
import io.github.dsheirer.sample.complex.ComplexSamples;
|
||||
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -29,6 +29,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class);
|
||||
private final OneChannelMixerAssembler mMixerAssembler;
|
||||
private int mChannelOffset;
|
||||
|
||||
/**
|
||||
* Processor to extract a single channel from a polyphase channelizer and produce an output I/Q complex sample
|
||||
@@ -54,7 +55,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("One Channel Output Processor");
|
||||
sb.append("\n\tIndex (doubled) ").append(Arrays.toString(getChannelOffsets()));
|
||||
sb.append("\n\tIndex (doubled) [").append(mChannelOffset).append("]");
|
||||
sb.append("\n\tMixer Assembler: none");
|
||||
return sb.toString();
|
||||
}
|
||||
@@ -80,7 +81,8 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
|
||||
|
||||
//Set the channelized output results offset to twice the channel index to account for each channel having
|
||||
//an I/Q pair
|
||||
setChannelOffsets(indexes.get(0) * 2);
|
||||
int channelOffset = indexes.get(0) * 2;
|
||||
enqueueUpdate(() -> mChannelOffset = channelOffset);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -90,18 +92,19 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
|
||||
}
|
||||
|
||||
/**
|
||||
* Passes the copied channel samples to the assembler. The assembler will apply frequency translation and gain and
|
||||
* indicate when a buffer is fully assembled.
|
||||
* Extract the channel from the channel results array and pass to the assembler. The assembler will
|
||||
* apply frequency translation and gain and indicate when a buffer is fully assembled.
|
||||
*
|
||||
* @param samples containing an I/Q pair for each block (I0,Q0,I1,Q1...In,Qn)
|
||||
* @param blockCount number of blocks
|
||||
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
|
||||
*/
|
||||
@Override
|
||||
public void process(float[] samples, int blockCount)
|
||||
public void process(ChannelResultsBatch channelResults)
|
||||
{
|
||||
int length = blockCount * 2;
|
||||
float[] samples = channelResults.getSamples();
|
||||
int blockLength = channelResults.getBlockLength();
|
||||
int channelOffset = mChannelOffset;
|
||||
|
||||
for(int index = 0; index < length; index += 2)
|
||||
for(int index = channelOffset; index < samples.length; index += blockLength)
|
||||
{
|
||||
mMixerAssembler.receive(samples[index], samples[index + 1]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
* Copyright (C) 2014-2024 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@@ -18,9 +18,9 @@
|
||||
*/
|
||||
package io.github.dsheirer.dsp.filter.channelizer.output;
|
||||
|
||||
import io.github.dsheirer.dsp.filter.channelizer.ChannelResultsBatch;
|
||||
import io.github.dsheirer.sample.complex.ComplexSamples;
|
||||
import io.github.dsheirer.source.heartbeat.HeartbeatManager;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -29,6 +29,8 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class);
|
||||
private TwoChannelMixerAssembler mMixerAssembler;
|
||||
private int mChannelOffset1;
|
||||
private int mChannelOffset2;
|
||||
|
||||
/**
|
||||
* Processor to extract two channels from a polyphase channelizer, synthesize/recombine the channels, apply
|
||||
@@ -58,7 +60,7 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Two Channel Output Processor");
|
||||
sb.append("\n\tIndices (doubled) ").append(Arrays.toString(getChannelOffsets()));
|
||||
sb.append("\n\tIndices (doubled) 1 [").append(mChannelOffset1).append("] 2 [").append(mChannelOffset2).append("]");
|
||||
sb.append("\n\tMixer Assembler: ").append(mMixerAssembler.getStateDescription());
|
||||
return sb.toString();
|
||||
}
|
||||
@@ -96,32 +98,45 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
|
||||
|
||||
//Set the channelized output results offsets to twice the channel index to account for each channel having
|
||||
//an I/Q pair
|
||||
setChannelOffsets(indexes.get(0) * 2, indexes.get(1) * 2);
|
||||
int channelOffset1 = indexes.get(0) * 2;
|
||||
int channelOffset2 = indexes.get(1) * 2;
|
||||
|
||||
enqueueUpdate(() -> {
|
||||
mChannelOffset1 = channelOffset1;
|
||||
mChannelOffset2 = channelOffset2;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesizes the two copied channels, applies frequency translation, and delivers the frequency-corrected channel
|
||||
* I/Q sample set to the complex sample listener.
|
||||
* Extract the channel from the channel results array, apply frequency translation, and deliver the
|
||||
* extracted frequency-corrected channel I/Q sample set to the complex sample listener.
|
||||
*
|
||||
* @param samples containing an I/Q pair for each of the two channels per block (I1,Q1,I2,Q2 ...)
|
||||
* @param blockCount number of blocks
|
||||
* @param channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
|
||||
*/
|
||||
@Override
|
||||
public void process(float[] samples, int blockCount)
|
||||
public void process(ChannelResultsBatch channelResults)
|
||||
{
|
||||
float[] samples = channelResults.getSamples();
|
||||
int blockLength = channelResults.getBlockLength();
|
||||
int blockCount = channelResults.getBlockCount();
|
||||
int channelOffset1 = mChannelOffset1;
|
||||
int channelOffset2 = mChannelOffset2;
|
||||
|
||||
//Translate channel 2 up by FS/2 (multiply by (-1)^n) so that it sits adjacent to channel 1 for synthesis. The
|
||||
//channelizer dispatches even-sized batches, so the index within the batch carries the absolute block parity.
|
||||
for(int x = 0; x < blockCount; x++)
|
||||
{
|
||||
int block = x * 4;
|
||||
int block = x * blockLength;
|
||||
|
||||
if((x & 1) == 0)
|
||||
{
|
||||
mMixerAssembler.receive(samples[block], samples[block + 1], samples[block + 2], samples[block + 3]);
|
||||
mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
|
||||
samples[block + channelOffset2], samples[block + channelOffset2 + 1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
mMixerAssembler.receive(samples[block], samples[block + 1], -samples[block + 2], -samples[block + 3]);
|
||||
mMixerAssembler.receive(samples[block + channelOffset1], samples[block + channelOffset1 + 1],
|
||||
-samples[block + channelOffset2], -samples[block + channelOffset2 + 1]);
|
||||
}
|
||||
|
||||
if(mMixerAssembler.hasBuffer())
|
||||
|
||||
@@ -42,7 +42,6 @@ public class DcRemovalFilterFactory
|
||||
case VECTOR_SIMD_PREFERRED:
|
||||
return new VectorDcRemovalFilter(gain);
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarDcRemovalFilter(gain);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
package io.github.dsheirer.dsp.filter.design;
|
||||
|
||||
import io.github.dsheirer.gui.FxToolkit;
|
||||
import javafx.application.Platform;
|
||||
import javafx.embed.swing.JFXPanel;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class FilterViewerLauncher
|
||||
{
|
||||
private JFXPanel mJFXPanel;
|
||||
|
||||
public FilterViewerLauncher()
|
||||
{
|
||||
FxToolkit.ensureStarted();
|
||||
mJFXPanel = new JFXPanel();
|
||||
|
||||
Platform.runLater(() ->
|
||||
{
|
||||
|
||||
@@ -52,7 +52,6 @@ public class FmDemodulatorFactory
|
||||
case VECTOR_SIMD_512:
|
||||
return new VectorFMDemodulator512();
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarFMDemodulator();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,6 @@ public class ComplexGainFactory
|
||||
return new VectorComplexGainControl();
|
||||
}
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ComplexGainControl();
|
||||
}
|
||||
@@ -65,7 +64,6 @@ public class ComplexGainFactory
|
||||
return new VectorComplexGain(gain);
|
||||
}
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarComplexGain(gain);
|
||||
}
|
||||
|
||||
@@ -52,7 +52,6 @@ public class MagnitudeFactory
|
||||
case VECTOR_SIMD_512:
|
||||
return new VectorMagnitudeCalculator512();
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarMagnitudeCalculator();
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ public class ComplexMixerFactory
|
||||
return new VectorComplexMixer(frequency, sampleRate);
|
||||
}
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
{
|
||||
return new ScalarComplexMixer(frequency, sampleRate);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ public class OscillatorFactory
|
||||
case VECTOR_SIMD_PREFERRED:
|
||||
return new VectorRealOscillator(frequency, sampleRate);
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarRealOscillator(frequency, sampleRate);
|
||||
}
|
||||
@@ -70,7 +69,6 @@ public class OscillatorFactory
|
||||
case VECTOR_SIMD_PREFERRED:
|
||||
return new VectorComplexOscillator(frequency, sampleRate);
|
||||
case SCALAR:
|
||||
case UNCALIBRATED:
|
||||
default:
|
||||
return new ScalarComplexOscillator(frequency, sampleRate);
|
||||
}
|
||||
|
||||
@@ -45,8 +45,7 @@ public class DifferentialDemodulatorFactory
|
||||
case VECTOR_SIMD_128 -> new DifferentialDemodulatorFloatVector128(sampleRate, symbolRate);
|
||||
case VECTOR_SIMD_256 -> new DifferentialDemodulatorFloatVector256(sampleRate, symbolRate);
|
||||
case VECTOR_SIMD_512 -> new DifferentialDemodulatorFloatVector512(sampleRate, symbolRate);
|
||||
case SCALAR, UNCALIBRATED -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
|
||||
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
|
||||
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate); //Includes SCALAR case
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,29 +68,6 @@ 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);
|
||||
|
||||
@@ -37,8 +37,7 @@ 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, -1 if no errors are detected, or 1000 if more than one bit error is
|
||||
* detected.
|
||||
* @return message index for an error bit or -1 if no errors are detected.
|
||||
*/
|
||||
public static int getErrorIndex(BinaryMessage message, int offset)
|
||||
{
|
||||
@@ -46,8 +45,7 @@ public class Hamming13
|
||||
|
||||
if(syndrome > 0)
|
||||
{
|
||||
int errorIndex = ERROR_INDEX[syndrome];
|
||||
return errorIndex >= 0 ? offset + errorIndex : IHamming.MULTIPLE_ERRORS;
|
||||
return offset + ERROR_INDEX[syndrome];
|
||||
}
|
||||
|
||||
return IHamming.NO_ERRORS;
|
||||
|
||||
@@ -47,6 +47,13 @@ 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])
|
||||
|
||||
@@ -46,6 +46,13 @@ 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])
|
||||
|
||||
@@ -1,421 +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.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;
|
||||
}
|
||||
}
|
||||
@@ -19,191 +19,54 @@
|
||||
|
||||
package io.github.dsheirer.filter;
|
||||
|
||||
import io.github.dsheirer.gui.ApplicationIcons;
|
||||
import io.github.dsheirer.gui.theme.ThemeManager;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.CheckBoxTreeItem;
|
||||
import javafx.scene.control.TreeItem;
|
||||
import javafx.scene.control.TreeView;
|
||||
import javafx.scene.control.cell.CheckBoxTreeCell;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.Region;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.Window;
|
||||
import javafx.util.StringConverter;
|
||||
import java.awt.Component;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
|
||||
import javax.swing.JButton;
|
||||
import javax.swing.JFrame;
|
||||
import javax.swing.JScrollPane;
|
||||
|
||||
/**
|
||||
* Window for turning filters and filter elements on and off. Each filter shows how many of its elements are
|
||||
* enabled. Checking a filter turns all of its elements on or off. Changes apply immediately.
|
||||
*
|
||||
* @param <T> type of item that is filtered
|
||||
* Filter editor
|
||||
* @param <T> item type for editing
|
||||
*/
|
||||
public class FilterEditor<T>
|
||||
public class FilterEditor<T> extends JFrame
|
||||
{
|
||||
private final Stage mStage = new Stage();
|
||||
private final TreeView<Object> mTreeView = new TreeView<>();
|
||||
private FilterEditorPanel<T> mEditorPanel;
|
||||
|
||||
/**
|
||||
* Constructs an instance. JavaFX thread only.
|
||||
* @param title for the window
|
||||
* @param owner window, or null
|
||||
* @param filterSet to edit
|
||||
* Constructor
|
||||
* @param title for the editor window frame
|
||||
* @param owner to register the popup location
|
||||
* @param filterSet to use initially
|
||||
*/
|
||||
public FilterEditor(String title, Window owner, FilterSet<T> filterSet)
|
||||
public FilterEditor(String title, Component owner, FilterSet<T> filterSet)
|
||||
{
|
||||
if(filterSet == null)
|
||||
{
|
||||
throw new IllegalArgumentException("Unable to construct FilterEditor - FilterSet cannot be null");
|
||||
}
|
||||
|
||||
mTreeView.setShowRoot(true);
|
||||
mTreeView.setCellFactory(CheckBoxTreeCell.forTreeView(item -> ((CheckBoxTreeItem<Object>)item)
|
||||
.selectedProperty(), new LabelConverter()));
|
||||
VBox.setVgrow(mTreeView, Priority.ALWAYS);
|
||||
|
||||
Button expand = new Button("Expand All");
|
||||
expand.setOnAction(event -> setExpanded(mTreeView.getRoot(), true));
|
||||
Button collapse = new Button("Collapse All");
|
||||
collapse.setOnAction(event -> {
|
||||
setExpanded(mTreeView.getRoot(), false);
|
||||
mTreeView.getRoot().setExpanded(true);
|
||||
});
|
||||
Button close = new Button("Close");
|
||||
close.setCancelButton(true);
|
||||
close.setDefaultButton(true);
|
||||
close.setOnAction(event -> mStage.close());
|
||||
Region spacer = new Region();
|
||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||
HBox buttons = new HBox(8, expand, collapse, spacer, close);
|
||||
buttons.setAlignment(Pos.CENTER_LEFT);
|
||||
|
||||
VBox root = new VBox(8, mTreeView, buttons);
|
||||
root.setPadding(new Insets(10));
|
||||
|
||||
Scene scene = new Scene(root, 600, 500);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mStage.setScene(scene);
|
||||
mStage.setTitle(title);
|
||||
ApplicationIcons.apply(mStage);
|
||||
|
||||
if(owner != null)
|
||||
{
|
||||
mStage.initOwner(owner);
|
||||
}
|
||||
|
||||
updateFilterSet(filterSet);
|
||||
setTitle(title);
|
||||
setSize(600, 400);
|
||||
setLocationRelativeTo(owner);
|
||||
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
|
||||
setLayout(new MigLayout("", "[grow,fill]", "[grow,fill][]"));
|
||||
mEditorPanel = new FilterEditorPanel<>(filterSet);
|
||||
JScrollPane scroller = new JScrollPane(mEditorPanel);
|
||||
scroller.getVerticalScrollBar().setUnitIncrement(16);
|
||||
scroller.setViewportView(mEditorPanel);
|
||||
add(scroller, "wrap");
|
||||
JButton close = new JButton("Close");
|
||||
close.addActionListener(e -> dispose());
|
||||
add(close);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the window and brings it to the front. JavaFX thread only.
|
||||
*/
|
||||
public void show()
|
||||
{
|
||||
mStage.show();
|
||||
mStage.toFront();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates this editor with the filter set. JavaFX thread only.
|
||||
* @param filterSet to edit
|
||||
* Updates this editor with the filterset.
|
||||
* @param filterSet to use in this editor.
|
||||
*/
|
||||
public void updateFilterSet(FilterSet<T> filterSet)
|
||||
{
|
||||
CheckBoxTreeItem<Object> root = new CheckBoxTreeItem<>(filterSet);
|
||||
root.setExpanded(true);
|
||||
addFilterSet(filterSet, root);
|
||||
mTreeView.setRoot(root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tree view, for testing.
|
||||
*/
|
||||
TreeView<Object> getTreeView()
|
||||
{
|
||||
return mTreeView;
|
||||
}
|
||||
|
||||
private void addFilterSet(FilterSet<?> filterSet, CheckBoxTreeItem<Object> parent)
|
||||
{
|
||||
for(IFilter<?> filter: filterSet.getFilters())
|
||||
{
|
||||
CheckBoxTreeItem<Object> item = new CheckBoxTreeItem<>(filter);
|
||||
parent.getChildren().add(item);
|
||||
|
||||
if(filter instanceof FilterSet<?> childFilterSet)
|
||||
{
|
||||
addFilterSet(childFilterSet, item);
|
||||
}
|
||||
else if(filter instanceof Filter<?,?> childFilter)
|
||||
{
|
||||
addFilter(childFilter, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addFilter(Filter<?,?> filter, CheckBoxTreeItem<Object> parent)
|
||||
{
|
||||
List<FilterElement<?>> elements = new ArrayList<>(filter.getFilterElements());
|
||||
elements.sort(Comparator.comparing(FilterElement::getName));
|
||||
|
||||
for(FilterElement<?> element: elements)
|
||||
{
|
||||
CheckBoxTreeItem<Object> item = new CheckBoxTreeItem<>(element);
|
||||
parent.getChildren().add(item);
|
||||
|
||||
//Set the state after adding the item, so that the parent check boxes follow their elements
|
||||
item.setSelected(element.isEnabled());
|
||||
item.selectedProperty().addListener((observable, wasSelected, selected) -> {
|
||||
element.setEnabled(selected);
|
||||
//Update the enabled counts shown on the filters
|
||||
mTreeView.refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static void setExpanded(TreeItem<Object> item, boolean expanded)
|
||||
{
|
||||
if(item != null)
|
||||
{
|
||||
item.setExpanded(expanded);
|
||||
item.getChildren().forEach(child -> setExpanded(child, expanded));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for each tree item: a filter's name and enabled count, or a filter element's name.
|
||||
*/
|
||||
private static class LabelConverter extends StringConverter<TreeItem<Object>>
|
||||
{
|
||||
@Override
|
||||
public String toString(TreeItem<Object> item)
|
||||
{
|
||||
Object value = item != null ? item.getValue() : null;
|
||||
|
||||
if(value instanceof IFilter<?> filter)
|
||||
{
|
||||
return filter.getName() + " (" + filter.getEnabledCount() + "/" + filter.getElementCount() + ")";
|
||||
}
|
||||
else if(value instanceof FilterElement<?> element)
|
||||
{
|
||||
return element.getName();
|
||||
}
|
||||
|
||||
return value != null ? value.toString() : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public TreeItem<Object> fromString(String string)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
mEditorPanel.updateFilterSet(filterSet);
|
||||
}
|
||||
}
|
||||
|
||||
444
src/main/java/io/github/dsheirer/filter/FilterEditorPanel.java
Normal file
444
src/main/java/io/github/dsheirer/filter/FilterEditorPanel.java
Normal file
@@ -0,0 +1,444 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2023 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.filter;
|
||||
|
||||
import java.awt.Component;
|
||||
import java.util.Comparator;
|
||||
import java.util.Enumeration;
|
||||
import java.util.EventObject;
|
||||
import java.util.List;
|
||||
import net.miginfocom.swing.MigLayout;
|
||||
|
||||
import javax.swing.JCheckBox;
|
||||
import javax.swing.JLabel;
|
||||
import javax.swing.JPanel;
|
||||
import javax.swing.JTree;
|
||||
import javax.swing.event.CellEditorListener;
|
||||
import javax.swing.tree.DefaultMutableTreeNode;
|
||||
import javax.swing.tree.DefaultTreeCellRenderer;
|
||||
import javax.swing.tree.DefaultTreeModel;
|
||||
import javax.swing.tree.TreeCellEditor;
|
||||
import javax.swing.tree.TreeNode;
|
||||
import javax.swing.tree.TreeSelectionModel;
|
||||
|
||||
/**
|
||||
* Editor panel for managing the state of a filter set.
|
||||
*
|
||||
* @param <T> element type for the filter set.
|
||||
*/
|
||||
public class FilterEditorPanel<T> extends JPanel
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private JTree mTree;
|
||||
private DefaultTreeModel mModel;
|
||||
private FilterSet<T> mFilterSet;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
* @param filterSet to manage
|
||||
*/
|
||||
public FilterEditorPanel(FilterSet<T> filterSet)
|
||||
{
|
||||
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
|
||||
mFilterSet = filterSet;
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the panel and the tree model.
|
||||
*/
|
||||
private void init()
|
||||
{
|
||||
DefaultMutableTreeNode root = new DefaultMutableTreeNode(mFilterSet);
|
||||
mModel = new DefaultTreeModel(root);
|
||||
addFilterSet(mFilterSet, root);
|
||||
|
||||
mTree = new JTree(mModel);
|
||||
mTree.setShowsRootHandles(true);
|
||||
mTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
|
||||
mTree.setCellRenderer(new EditorTreeCellRenderer());
|
||||
mTree.setCellEditor(new FilterTreeCellEditor());
|
||||
mTree.setEditable(true);
|
||||
add(mTree);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the filter set for this editor panel
|
||||
* @param filterSet to use
|
||||
*/
|
||||
public void updateFilterSet(FilterSet<T> filterSet)
|
||||
{
|
||||
remove(mTree);
|
||||
mFilterSet = filterSet;
|
||||
init();
|
||||
revalidate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the filter set as a child tree node to the parent.
|
||||
* @param filterSet to add to the tree
|
||||
* @param parent node for the filter set child tree node.
|
||||
*/
|
||||
private void addFilterSet(FilterSet<T> filterSet, DefaultMutableTreeNode parent)
|
||||
{
|
||||
List<IFilter<T>> filters = filterSet.getFilters();
|
||||
|
||||
for(IFilter<T> filter : filters)
|
||||
{
|
||||
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(filter);
|
||||
mModel.insertNodeInto(childNode, parent, parent.getChildCount());
|
||||
|
||||
if(filter instanceof FilterSet childFilterSet)
|
||||
{
|
||||
addFilterSet(childFilterSet, childNode);
|
||||
}
|
||||
else if(filter instanceof Filter childFilter)
|
||||
{
|
||||
addFilter(childFilter, childNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the filter as a child tree node to the parent.
|
||||
*
|
||||
* @param filter to add
|
||||
* @param parent tree node
|
||||
*/
|
||||
private void addFilter(Filter filter, DefaultMutableTreeNode parent)
|
||||
{
|
||||
List<FilterElement<?>> elements = filter.getFilterElements();
|
||||
|
||||
elements.sort(Comparator.comparing(FilterElement::getName));
|
||||
|
||||
for(FilterElement<?> element : elements)
|
||||
{
|
||||
DefaultMutableTreeNode child = new DefaultMutableTreeNode(element);
|
||||
mModel.insertNodeInto(child, parent, parent.getChildCount());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accesses the tree's root tree node.
|
||||
* @return root node.
|
||||
*/
|
||||
private DefaultMutableTreeNode getRoot()
|
||||
{
|
||||
if(mTree.getModel().getRoot() instanceof DefaultMutableTreeNode root)
|
||||
{
|
||||
return root;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively sets the enabled state on all filter node children below the specified parent node.
|
||||
*
|
||||
* @param model - model containing the tree nodes
|
||||
* @param node - parent node
|
||||
* @param enabled - true or false to enable or disable the filters
|
||||
*/
|
||||
private void setFilterEnabled(DefaultTreeModel model, DefaultMutableTreeNode node, boolean enabled)
|
||||
{
|
||||
Object obj = node.getUserObject();
|
||||
|
||||
if(obj instanceof FilterElement filterElement)
|
||||
{
|
||||
filterElement.setEnabled(enabled);
|
||||
}
|
||||
|
||||
/* Recursively set the children of this node */
|
||||
Enumeration<?> children = node.children();
|
||||
|
||||
while(children.hasMoreElements())
|
||||
{
|
||||
Object child = children.nextElement();
|
||||
|
||||
if(child instanceof DefaultMutableTreeNode childNode)
|
||||
{
|
||||
setFilterEnabled(model, childNode, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
model.nodeChanged(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively searches the tree to find the tree node containing the specified filter element.
|
||||
*
|
||||
* @param node to start search
|
||||
* @param element to find
|
||||
*/
|
||||
private DefaultMutableTreeNode findFilterElementNode(DefaultMutableTreeNode node, FilterElement<?> element)
|
||||
{
|
||||
if(node != null)
|
||||
{
|
||||
if(node.getUserObject() instanceof FilterElement<?> selfFilterElement && selfFilterElement.equals(element))
|
||||
{
|
||||
return node;
|
||||
}
|
||||
|
||||
for(int x = 0; x < node.getChildCount(); x++)
|
||||
{
|
||||
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
|
||||
{
|
||||
DefaultMutableTreeNode found = findFilterElementNode(child, element);
|
||||
|
||||
if(found != null)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the display value for the specified node and all parents in the nodes parentage.
|
||||
* @param node to update
|
||||
*/
|
||||
private void updateParentage(DefaultMutableTreeNode node)
|
||||
{
|
||||
mModel.nodeChanged(node);
|
||||
|
||||
TreeNode parent = node.getParent();
|
||||
|
||||
while(parent != null)
|
||||
{
|
||||
mModel.nodeChanged(parent);
|
||||
parent = parent.getParent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively searches the tree to find the tree node containing the specified filter.
|
||||
*
|
||||
* @param node to start search
|
||||
* @param filter to find
|
||||
*/
|
||||
private DefaultMutableTreeNode findFilterNode(DefaultMutableTreeNode node, IFilter<?> filter)
|
||||
{
|
||||
if(node != null)
|
||||
{
|
||||
if(node.getUserObject() instanceof IFilter<?> selfFilter && selfFilter.equals(filter))
|
||||
{
|
||||
return node;
|
||||
}
|
||||
|
||||
for(int x = 0; x < node.getChildCount(); x++)
|
||||
{
|
||||
if(node.getChildAt(x) instanceof DefaultMutableTreeNode child)
|
||||
{
|
||||
DefaultMutableTreeNode found = findFilterNode(child, filter);
|
||||
|
||||
if(found != null)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
System.out.println("Can't evaluate - node is null");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom cell renderer
|
||||
*/
|
||||
public class EditorTreeCellRenderer extends DefaultTreeCellRenderer
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Component getTreeCellRendererComponent(JTree tree, Object treeNode, boolean selected, boolean expanded,
|
||||
boolean leaf, int row, boolean hasFocus)
|
||||
{
|
||||
if(treeNode instanceof DefaultMutableTreeNode)
|
||||
{
|
||||
Object userObject = ((DefaultMutableTreeNode) treeNode).getUserObject();
|
||||
JCheckBox checkBox = null;
|
||||
|
||||
if(userObject instanceof IFilter filter)
|
||||
{
|
||||
checkBox = new FilterCheckBox(filter);
|
||||
checkBox.setSelected(filter.isEnabled());
|
||||
}
|
||||
else if(userObject instanceof FilterElement element)
|
||||
{
|
||||
checkBox = new FilterElementCheckBox(element);
|
||||
checkBox.setSelected(element.isEnabled());
|
||||
}
|
||||
|
||||
if(checkBox != null)
|
||||
{
|
||||
if(selected)
|
||||
{
|
||||
checkBox.setForeground(getTextSelectionColor());
|
||||
checkBox.setBackground(getBackgroundSelectionColor());
|
||||
}
|
||||
else
|
||||
{
|
||||
checkBox.setForeground(getTextNonSelectionColor());
|
||||
checkBox.setBackground(getBackgroundNonSelectionColor());
|
||||
}
|
||||
|
||||
return checkBox;
|
||||
}
|
||||
}
|
||||
|
||||
return super.getTreeCellRendererComponent(tree, treeNode, selected, expanded, leaf, row, hasFocus);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check box used in filter tree nodes
|
||||
*/
|
||||
public class FilterCheckBox extends JCheckBox
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private IFilter<?> mFilter;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
*
|
||||
* @param filter
|
||||
*/
|
||||
public FilterCheckBox(IFilter<?> filter)
|
||||
{
|
||||
mFilter = filter;
|
||||
setSelected(mFilter.isEnabled());
|
||||
addItemListener(e -> {
|
||||
DefaultMutableTreeNode selfNode = findFilterNode(getRoot(), mFilter);
|
||||
|
||||
if(selfNode != null)
|
||||
{
|
||||
setFilterEnabled(mModel, selfNode, FilterCheckBox.this.isSelected());
|
||||
updateLabel();
|
||||
updateParentage(selfNode);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSelected(boolean b)
|
||||
{
|
||||
super.setSelected(b);
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
public void updateLabel()
|
||||
{
|
||||
setText(mFilter.getName() + " (" + mFilter.getEnabledCount() + "/" + mFilter.getElementCount() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check box used in filter element tree nodes
|
||||
*/
|
||||
public class FilterElementCheckBox extends JCheckBox
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private FilterElement<?> mFilter;
|
||||
|
||||
/**
|
||||
* Constructs an instance
|
||||
*
|
||||
* @param filter element
|
||||
*/
|
||||
public FilterElementCheckBox(FilterElement<?> filter)
|
||||
{
|
||||
super(filter.getName());
|
||||
mFilter = filter;
|
||||
setSelected(mFilter.isEnabled());
|
||||
addItemListener(arg0 -> {
|
||||
mFilter.setEnabled(FilterElementCheckBox.this.isSelected());
|
||||
DefaultMutableTreeNode self = findFilterElementNode(getRoot(), mFilter);
|
||||
if(self != null)
|
||||
{
|
||||
updateParentage(self);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Editor for filter tree nodes
|
||||
*/
|
||||
public class FilterTreeCellEditor implements TreeCellEditor
|
||||
{
|
||||
@Override
|
||||
public Component getTreeCellEditorComponent(JTree tree, Object node, boolean isSelected, boolean expanded, boolean leaf, int row)
|
||||
{
|
||||
if(node instanceof DefaultMutableTreeNode mutableTreeNode)
|
||||
{
|
||||
Object userObject = mutableTreeNode.getUserObject();
|
||||
|
||||
if(userObject instanceof IFilter filter)
|
||||
{
|
||||
return new FilterCheckBox(filter);
|
||||
}
|
||||
else if(userObject instanceof FilterElement filterElement)
|
||||
{
|
||||
return new FilterElementCheckBox(filterElement);
|
||||
}
|
||||
}
|
||||
return new JLabel(node.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCellEditorListener(CellEditorListener l) {}
|
||||
|
||||
@Override
|
||||
public void cancelCellEditing() {}
|
||||
|
||||
@Override
|
||||
public Object getCellEditorValue()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCellEditable(EventObject anEvent)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeCellEditorListener(CellEditorListener l) {}
|
||||
|
||||
@Override
|
||||
public boolean shouldSelectCell(EventObject anEvent)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean stopCellEditing()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.gui;
|
||||
|
||||
import java.awt.Image;
|
||||
import java.awt.Taskbar;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import javafx.application.Platform;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.Window;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* sdrtrunk application icon for JavaFX stages and the macOS Dock.
|
||||
*
|
||||
* Call installJavaFx() once the JavaFX toolkit is running, which also sets the macOS Dock icon. After that, each
|
||||
* window that opens without its own icon gets the sdrtrunk icon, so individual windows don't have to set it.
|
||||
*/
|
||||
public final class ApplicationIcons
|
||||
{
|
||||
private static final Logger mLog = LoggerFactory.getLogger(ApplicationIcons.class);
|
||||
private static final String RESOURCE_PATTERN = "/images/sdrtrunk/sdrtrunk-icon-%d.png";
|
||||
private static final int[] SIZES = {16, 24, 32, 48, 64, 128, 256, 512};
|
||||
private static final int TASKBAR_SIZE = 512;
|
||||
|
||||
private static List<Image> sAwtImages;
|
||||
private static List<javafx.scene.image.Image> sFxImages;
|
||||
private static boolean sTaskbarInstalled;
|
||||
private static boolean sJavaFxInstalled;
|
||||
|
||||
private ApplicationIcons()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Application icon in each available size, smallest first, as AWT images for the macOS Dock.
|
||||
* @return images, or an empty list if the icon resources can't be loaded.
|
||||
*/
|
||||
public static synchronized List<Image> getAwtImages()
|
||||
{
|
||||
if(sAwtImages == null)
|
||||
{
|
||||
List<Image> images = new ArrayList<>();
|
||||
|
||||
for(int size: SIZES)
|
||||
{
|
||||
String path = String.format(RESOURCE_PATTERN, size);
|
||||
|
||||
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
|
||||
{
|
||||
if(in != null)
|
||||
{
|
||||
Image image = ImageIO.read(in);
|
||||
|
||||
if(image != null)
|
||||
{
|
||||
images.add(image);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
mLog.warn("Application icon resource not found [" + path + "]");
|
||||
}
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.warn("Unable to load application icon [" + path + "]", ioe);
|
||||
}
|
||||
}
|
||||
|
||||
sAwtImages = Collections.unmodifiableList(images);
|
||||
}
|
||||
|
||||
return sAwtImages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Application icon in each available size, smallest first, for JavaFX stages.
|
||||
* @return images, or an empty list if the icon resources can't be loaded.
|
||||
*/
|
||||
public static synchronized List<javafx.scene.image.Image> getFxImages()
|
||||
{
|
||||
if(sFxImages == null)
|
||||
{
|
||||
List<javafx.scene.image.Image> images = new ArrayList<>();
|
||||
|
||||
for(int size: SIZES)
|
||||
{
|
||||
String path = String.format(RESOURCE_PATTERN, size);
|
||||
|
||||
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
|
||||
{
|
||||
if(in != null)
|
||||
{
|
||||
javafx.scene.image.Image image = new javafx.scene.image.Image(in);
|
||||
|
||||
if(!image.isError())
|
||||
{
|
||||
images.add(image);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.warn("Unable to load application icon [" + path + "]", ioe);
|
||||
}
|
||||
}
|
||||
|
||||
sFxImages = Collections.unmodifiableList(images);
|
||||
}
|
||||
|
||||
return sFxImages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the application icon on the JavaFX stage if it doesn't already have one. Call on the FX thread.
|
||||
*/
|
||||
public static void apply(Stage stage)
|
||||
{
|
||||
if(stage != null && stage.getIcons().isEmpty() && !getFxImages().isEmpty())
|
||||
{
|
||||
stage.getIcons().setAll(getFxImages());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the macOS Dock icon. Windows and Linux take the icon from each window instead. Safe to call more than
|
||||
* once. Does nothing in a headless environment.
|
||||
*/
|
||||
public static synchronized void installTaskbarIcon()
|
||||
{
|
||||
if(sTaskbarInstalled || java.awt.GraphicsEnvironment.isHeadless())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sTaskbarInstalled = true;
|
||||
|
||||
try
|
||||
{
|
||||
if(Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
|
||||
{
|
||||
List<Image> images = getAwtImages();
|
||||
|
||||
for(int x = 0; x < SIZES.length && x < images.size(); x++)
|
||||
{
|
||||
if(SIZES[x] == TASKBAR_SIZE)
|
||||
{
|
||||
Taskbar.getTaskbar().setIconImage(images.get(x));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.debug("Unable to set taskbar icon", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives each JavaFX stage that shows without an icon the application icon, and closes the startup splash screen
|
||||
* if a JavaFX window opens before the main window does. Safe to call more than once. The JavaFX toolkit must
|
||||
* already be running.
|
||||
*/
|
||||
public static synchronized void installJavaFx()
|
||||
{
|
||||
if(sJavaFxInstalled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
sJavaFxInstalled = true;
|
||||
installTaskbarIcon();
|
||||
|
||||
Platform.runLater(() -> {
|
||||
for(Window window: Window.getWindows())
|
||||
{
|
||||
onFxWindowShown(window);
|
||||
}
|
||||
|
||||
Window.getWindows().addListener((ListChangeListener<Window>)change -> {
|
||||
while(change.next())
|
||||
{
|
||||
for(Window window: change.getAddedSubList())
|
||||
{
|
||||
onFxWindowShown(window);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a JavaFX window that is showing.
|
||||
*/
|
||||
private static void onFxWindowShown(Window window)
|
||||
{
|
||||
//Only stages are top-level windows. Popups (menus, tooltips) are other Window types.
|
||||
if(window instanceof Stage stage)
|
||||
{
|
||||
apply(stage);
|
||||
|
||||
//A JavaFX window (e.g. an error dialog) that shows before the main window would sit behind the splash.
|
||||
Splash.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.gui;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.image.Image;
|
||||
import javafx.scene.image.PixelReader;
|
||||
|
||||
/**
|
||||
* Starts the JavaFX toolkit, runs work on the JavaFX application thread and converts images for ImageIO.
|
||||
*/
|
||||
public class FxToolkit
|
||||
{
|
||||
private static boolean sStarted;
|
||||
|
||||
private FxToolkit()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the JavaFX toolkit if it isn't running. Safe to call more than once and from any thread except the
|
||||
* JavaFX application thread before the toolkit starts.
|
||||
*/
|
||||
public static synchronized void ensureStarted()
|
||||
{
|
||||
if(sStarted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Platform.startup(() -> {});
|
||||
}
|
||||
catch(IllegalStateException alreadyStarted)
|
||||
{
|
||||
//The toolkit is already running
|
||||
}
|
||||
|
||||
Platform.setImplicitExit(false);
|
||||
ApplicationIcons.installJavaFx();
|
||||
sStarted = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the toolkit was started.
|
||||
*/
|
||||
public static synchronized boolean isStarted()
|
||||
{
|
||||
return sStarted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the callable on the JavaFX application thread and waits for the result.
|
||||
* @throws Exception thrown by the callable
|
||||
*/
|
||||
public static <T> T callAndWait(Callable<T> callable) throws Exception
|
||||
{
|
||||
if(Platform.isFxApplicationThread())
|
||||
{
|
||||
return callable.call();
|
||||
}
|
||||
|
||||
CompletableFuture<T> future = new CompletableFuture<>();
|
||||
Platform.runLater(() -> {
|
||||
try
|
||||
{
|
||||
future.complete(callable.call());
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
future.completeExceptionally(t);
|
||||
}
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
return future.get();
|
||||
}
|
||||
catch(ExecutionException e)
|
||||
{
|
||||
if(e.getCause() instanceof Exception exception)
|
||||
{
|
||||
throw exception;
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the JavaFX image to an AWT image for writing with ImageIO.
|
||||
*/
|
||||
public static BufferedImage toBufferedImage(Image image)
|
||||
{
|
||||
int width = (int)image.getWidth();
|
||||
int height = (int)image.getHeight();
|
||||
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
|
||||
PixelReader reader = image.getPixelReader();
|
||||
int[] row = new int[width];
|
||||
|
||||
for(int y = 0; y < height; y++)
|
||||
{
|
||||
reader.getPixels(0, y, width, 1, javafx.scene.image.PixelFormat.getIntArgbInstance(), row, 0, width);
|
||||
bufferedImage.setRGB(0, y, width, 1, row, 0, width);
|
||||
}
|
||||
|
||||
return bufferedImage;
|
||||
}
|
||||
}
|
||||
@@ -20,26 +20,36 @@
|
||||
package io.github.dsheirer.gui;
|
||||
|
||||
import com.google.common.eventbus.Subscribe;
|
||||
import io.github.dsheirer.alias.AliasModel;
|
||||
import io.github.dsheirer.controller.channel.map.ChannelMap;
|
||||
import io.github.dsheirer.controller.channel.map.ChannelRange;
|
||||
import io.github.dsheirer.eventbus.MyEventBus;
|
||||
import io.github.dsheirer.gui.icon.IconManager;
|
||||
import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
|
||||
import io.github.dsheirer.gui.playlist.PlaylistEditor;
|
||||
import io.github.dsheirer.gui.playlist.PlaylistEditorRequest;
|
||||
import io.github.dsheirer.database.DatabaseManager;
|
||||
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
|
||||
import io.github.dsheirer.gui.playlist.channelMap.ChannelMapEditor;
|
||||
import io.github.dsheirer.gui.playlist.channelMap.ViewChannelMapEditorRequest;
|
||||
import io.github.dsheirer.gui.preference.PreferenceEditorType;
|
||||
import io.github.dsheirer.gui.preference.UserPreferencesEditor;
|
||||
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
|
||||
import io.github.dsheirer.gui.preference.calibration.CalibrationDialog;
|
||||
import io.github.dsheirer.gui.theme.ThemeManager;
|
||||
import io.github.dsheirer.gui.viewer.MessageRecordingViewer;
|
||||
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.jmbe.JmbeEditor;
|
||||
import io.github.dsheirer.jmbe.JmbeEditorRequest;
|
||||
import io.github.dsheirer.module.log.EventLogManager;
|
||||
import io.github.dsheirer.monitor.ResourceMonitor;
|
||||
import io.github.dsheirer.monitor.StatusBox;
|
||||
import io.github.dsheirer.playlist.PlaylistManager;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.source.tuner.manager.TunerManager;
|
||||
import javafx.application.Application;
|
||||
import javafx.application.Platform;
|
||||
import javafx.embed.swing.JFXPanel;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.stage.Stage;
|
||||
import jiconfont.javafx.IconFontFX;
|
||||
@@ -47,15 +57,17 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Opens the application's tool windows (playlist editor, user preferences, icon manager, channel map editor, JMBE
|
||||
* library editor and message recording viewer) when it receives their request events on the event bus. Each window
|
||||
* is created once, then restored and brought to the front on later requests, and its size and location are kept
|
||||
* across sessions.
|
||||
* Java FX window manager. Handles all secondary Java FX windows that are used within this primarily
|
||||
* Swing application.
|
||||
*/
|
||||
public class WindowManager
|
||||
public class JavaFxWindowManager extends Application
|
||||
{
|
||||
private final static Logger mLog = LoggerFactory.getLogger(WindowManager.class);
|
||||
private final static Logger mLog = LoggerFactory.getLogger(JavaFxWindowManager.class);
|
||||
|
||||
public static final String CHANNEL_MAP_EDITOR = "channelmap";
|
||||
public static final String ICON_MANAGER = "iconmanager";
|
||||
public static final String PLAYLIST_EDITOR = "playlist";
|
||||
public static final String USER_PREFERENCES_EDITOR = "preferences";
|
||||
public static final String STAGE_MONITOR_KEY_CALIBRATION_DIALOG = "calibration.dialog";
|
||||
public static final String STAGE_MONITOR_KEY_CHANNEL_MAP_EDITOR = "channel.map";
|
||||
public static final String STAGE_MONITOR_KEY_RECORDING_VIEWER = "recording.viewer";
|
||||
@@ -64,6 +76,7 @@ public class WindowManager
|
||||
public static final String STAGE_MONITOR_KEY_PLAYLIST_EDITOR = "playlist";
|
||||
public static final String STAGE_MONITOR_KEY_USER_PREFERENCES_EDITOR = "user.preferences";
|
||||
|
||||
private JFXPanel mJFXPanel;
|
||||
private ChannelMapEditor mChannelMapEditor;
|
||||
private IconManager mIconManager;
|
||||
private JmbeEditor mJmbeEditor;
|
||||
@@ -71,7 +84,6 @@ public class WindowManager
|
||||
private PlaylistManager mPlaylistManager;
|
||||
private TunerManager mTunerManager;
|
||||
private UserPreferences mUserPreferences;
|
||||
private final DatabaseManager mDatabaseManager;
|
||||
private UserPreferencesEditor mUserPreferencesEditor;
|
||||
private MessageRecordingViewer mMessageRecordingViewer;
|
||||
|
||||
@@ -81,25 +93,57 @@ public class WindowManager
|
||||
private Stage mPlaylistStage;
|
||||
private Stage mUserPreferencesStage;
|
||||
private Stage mRecordingViewerStage;
|
||||
private JFXPanel mStatusPanel;
|
||||
|
||||
/**
|
||||
* Constructs an instance and registers it to receive window requests on the event bus.
|
||||
* @param userPreferences for the windows and their stored locations
|
||||
* @param tunerManager for the playlist editor
|
||||
* @param playlistManager for the playlist and channel map editors
|
||||
* @param databaseManager for the call database preference editor
|
||||
* Constructs an instance. Note: this constructor is used for Swing applications.
|
||||
*/
|
||||
public WindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager,
|
||||
DatabaseManager databaseManager)
|
||||
public JavaFxWindowManager(UserPreferences userPreferences, TunerManager tunerManager, PlaylistManager playlistManager)
|
||||
{
|
||||
mUserPreferences = userPreferences;
|
||||
mDatabaseManager = databaseManager;
|
||||
mTunerManager = tunerManager;
|
||||
mPlaylistManager = playlistManager;
|
||||
|
||||
setup();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs an instance. Note: this constructor is used for standalone JavaFX application testing
|
||||
*/
|
||||
public JavaFxWindowManager()
|
||||
{
|
||||
mUserPreferences = new UserPreferences();
|
||||
AliasModel aliasModel = new AliasModel();
|
||||
EventLogManager eventLogManager = new EventLogManager(aliasModel, mUserPreferences);
|
||||
mTunerManager = new TunerManager(mUserPreferences);
|
||||
mTunerManager.start();
|
||||
mPlaylistManager = new PlaylistManager(mUserPreferences, mTunerManager, aliasModel, eventLogManager, new IconModel());
|
||||
mPlaylistManager.init();
|
||||
setup();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or accesses the JavaFX status panel, used by the main application GUI.
|
||||
* @param resourceMonitor for statistics
|
||||
* @return JFXPanel accessible on Swing thread that delegates JavaFX scene creation to the FX event thread.
|
||||
*/
|
||||
public JFXPanel getStatusPanel(ResourceMonitor resourceMonitor)
|
||||
{
|
||||
if(mStatusPanel == null)
|
||||
{
|
||||
mStatusPanel = new JFXPanel();
|
||||
|
||||
//JFXPanel has to be populated on the FX event thread
|
||||
Platform.runLater(() -> {
|
||||
Scene scene = new Scene(new StatusBox(resourceMonitor));
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mStatusPanel.setScene(scene);
|
||||
});
|
||||
}
|
||||
|
||||
return mStatusPanel;
|
||||
}
|
||||
|
||||
private void setup()
|
||||
{
|
||||
//Register this class to receive events via each method annotated with @Subscribe
|
||||
@@ -108,7 +152,7 @@ public class WindowManager
|
||||
//Register JavaFX icon fonts
|
||||
IconFontFX.register(jiconfont.icons.font_awesome.FontAwesome.getIconFont());
|
||||
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,7 +160,7 @@ public class WindowManager
|
||||
*/
|
||||
private void execute(Runnable runnable)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
|
||||
if(Platform.isFxApplicationThread())
|
||||
{
|
||||
@@ -129,11 +173,15 @@ public class WindowManager
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the JavaFX toolkit if it is not running
|
||||
* Creates a JavaFX panel for Swing application compatibility
|
||||
*/
|
||||
private void startToolkit()
|
||||
private void createJFXPanel()
|
||||
{
|
||||
FxToolkit.ensureStarted();
|
||||
if(mJFXPanel == null)
|
||||
{
|
||||
mJFXPanel = new JFXPanel();
|
||||
Platform.setImplicitExit(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -148,7 +196,7 @@ public class WindowManager
|
||||
|
||||
public CalibrationDialog getCalibrationDialog(UserPreferences userPreferences)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
return new CalibrationDialog(userPreferences);
|
||||
}
|
||||
|
||||
@@ -159,7 +207,7 @@ public class WindowManager
|
||||
{
|
||||
if(mRecordingViewerStage == null)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
Scene scene = new Scene(getRecordingViewer(), 1100, 800);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mRecordingViewerStage = new Stage();
|
||||
@@ -185,7 +233,7 @@ public class WindowManager
|
||||
{
|
||||
if(mIconManagerStage == null)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
Scene scene = new Scene(getIconManager(), 500, 500);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mIconManagerStage = new Stage();
|
||||
@@ -234,7 +282,7 @@ public class WindowManager
|
||||
{
|
||||
if(mJmbeEditorStage == null)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
Scene scene = new Scene(getJmbeEditor(), 650, 650);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mJmbeEditorStage = new Stage();
|
||||
@@ -276,7 +324,7 @@ public class WindowManager
|
||||
{
|
||||
if(mPlaylistStage == null)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
Scene scene = new Scene(getPlaylistEditor(), 1000, 750);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mPlaylistStage = new Stage();
|
||||
@@ -314,7 +362,7 @@ public class WindowManager
|
||||
{
|
||||
if(mUserPreferencesEditor == null)
|
||||
{
|
||||
mUserPreferencesEditor = new UserPreferencesEditor(mUserPreferences, mDatabaseManager);
|
||||
mUserPreferencesEditor = new UserPreferencesEditor(mUserPreferences);
|
||||
}
|
||||
|
||||
return mUserPreferencesEditor;
|
||||
@@ -327,7 +375,7 @@ public class WindowManager
|
||||
{
|
||||
if(mUserPreferencesStage == null)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
Scene scene = new Scene(getUserPreferencesEditor(), 900, 500);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mUserPreferencesStage = new Stage();
|
||||
@@ -371,7 +419,7 @@ public class WindowManager
|
||||
{
|
||||
if(mChannelMapStage == null)
|
||||
{
|
||||
startToolkit();
|
||||
createJFXPanel();
|
||||
Scene scene = new Scene(getChannelMapEditor(), 500, 500);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
mChannelMapStage = new Stage();
|
||||
@@ -421,4 +469,75 @@ public class WindowManager
|
||||
stage.requestFocus();
|
||||
stage.toFront();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) throws Exception
|
||||
{
|
||||
mLog.debug("Starting ...");
|
||||
Parameters parameters = getParameters();
|
||||
mLog.debug("Parameters: " + (parameters != null));
|
||||
|
||||
boolean valid = false;
|
||||
|
||||
if(parameters != null && parameters.getRaw().size() == 1)
|
||||
{
|
||||
String window = parameters.getRaw().get(0);
|
||||
|
||||
if(window != null)
|
||||
{
|
||||
switch(window)
|
||||
{
|
||||
case CHANNEL_MAP_EDITOR:
|
||||
//Generate some test data for the editor
|
||||
ChannelMap channelMap1 = new ChannelMap("Test Map 1");
|
||||
channelMap1.addRange(new ChannelRange(1,199,150000000, 12500));
|
||||
channelMap1.addRange(new ChannelRange(200,299,160000000, 25000));
|
||||
channelMap1.addRange(new ChannelRange(300,399,170000000, 12500));
|
||||
channelMap1.addRange(new ChannelRange(400,499,180000000, 25000));
|
||||
mPlaylistManager.getChannelMapModel().addChannelMap(channelMap1);
|
||||
|
||||
ChannelMap channelMap2 = new ChannelMap("Test Map 2");
|
||||
channelMap2.addRange(new ChannelRange(1,199,450000000, 12500));
|
||||
channelMap2.addRange(new ChannelRange(200,299,460000000, 25000));
|
||||
channelMap2.addRange(new ChannelRange(300,399,470000000, 12500));
|
||||
channelMap2.addRange(new ChannelRange(400,499,480000000, 25000));
|
||||
mPlaylistManager.getChannelMapModel().addChannelMap(channelMap2);
|
||||
valid = true;
|
||||
process(new ViewChannelMapEditorRequest());
|
||||
break;
|
||||
case ICON_MANAGER:
|
||||
valid = true;
|
||||
process(new ViewIconManagerRequest());
|
||||
break;
|
||||
case PLAYLIST_EDITOR:
|
||||
valid = true;
|
||||
process(new ViewPlaylistRequest());
|
||||
break;
|
||||
case USER_PREFERENCES_EDITOR:
|
||||
valid = true;
|
||||
process(new ViewUserPreferenceEditorRequest(PreferenceEditorType.DEFAULT));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(!valid)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("An argument is required to launch JavaFX windows from this window manager. " +
|
||||
"Valid options are:\n\tchannelmap\tChannel Map Editor\n\ticonmanager\tIcon Manager\n\tplaylist\tPlaylist Editor\n" +
|
||||
"\tpreferences\tUser Preferences Editor\n");
|
||||
sb.append("Supplied Argument(s): ").append(parameters.getRaw());
|
||||
|
||||
mLog.error(sb.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
mLog.info("Application Start - Parameters: " + args);
|
||||
launch(args);
|
||||
}
|
||||
}
|
||||
@@ -1,766 +0,0 @@
|
||||
/*
|
||||
* *****************************************************************************
|
||||
* Copyright (C) 2014-2026 Dennis Sheirer
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>
|
||||
* ****************************************************************************
|
||||
*/
|
||||
|
||||
package io.github.dsheirer.gui;
|
||||
|
||||
import io.github.dsheirer.alias.AliasModel;
|
||||
import io.github.dsheirer.audio.playback.AudioPlaybackManager;
|
||||
import io.github.dsheirer.call.CallManager;
|
||||
import io.github.dsheirer.database.DatabaseManager;
|
||||
import io.github.dsheirer.gui.calls.CallsView;
|
||||
import io.github.dsheirer.eventbus.MyEventBus;
|
||||
import io.github.dsheirer.gui.audio.AudioView;
|
||||
import io.github.dsheirer.gui.broadcast.BroadcastStatusView;
|
||||
import io.github.dsheirer.gui.icon.ViewIconManagerRequest;
|
||||
import io.github.dsheirer.gui.map.MapView;
|
||||
import io.github.dsheirer.gui.nowplaying.NowPlayingView;
|
||||
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
|
||||
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
|
||||
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
|
||||
import io.github.dsheirer.gui.spectrum.MainSpectralDisplay;
|
||||
import io.github.dsheirer.gui.spectrum.TunerSpectralDisplay;
|
||||
import io.github.dsheirer.gui.theme.ThemeManager;
|
||||
import io.github.dsheirer.gui.viewer.ViewRecordingViewerRequest;
|
||||
import io.github.dsheirer.icon.IconModel;
|
||||
import io.github.dsheirer.map.MapService;
|
||||
import io.github.dsheirer.monitor.DiagnosticMonitor;
|
||||
import io.github.dsheirer.monitor.ResourceMonitor;
|
||||
import io.github.dsheirer.monitor.StatusBox;
|
||||
import io.github.dsheirer.playlist.PlaylistManager;
|
||||
import io.github.dsheirer.preference.UserPreferences;
|
||||
import io.github.dsheirer.properties.SystemProperties;
|
||||
import io.github.dsheirer.source.tuner.Tuner;
|
||||
import io.github.dsheirer.source.tuner.TunerEvent;
|
||||
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
|
||||
import io.github.dsheirer.source.tuner.manager.TunerManager;
|
||||
import io.github.dsheirer.util.ThreadPool;
|
||||
import io.github.dsheirer.util.TimeStamp;
|
||||
import java.awt.Desktop;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.prefs.Preferences;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Alert;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.CheckMenuItem;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.Menu;
|
||||
import javafx.scene.control.MenuBar;
|
||||
import javafx.scene.control.MenuItem;
|
||||
import javafx.scene.control.SeparatorMenuItem;
|
||||
import javafx.scene.control.SplitPane;
|
||||
import javafx.scene.control.Tab;
|
||||
import javafx.scene.control.TabPane;
|
||||
import javafx.scene.control.TextArea;
|
||||
import javafx.scene.image.WritableImage;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyCodeCombination;
|
||||
import javafx.scene.input.KeyCombination;
|
||||
import javafx.scene.layout.BorderPane;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.Region;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.stage.Stage;
|
||||
import javax.imageio.ImageIO;
|
||||
import jiconfont.icons.font_awesome.FontAwesome;
|
||||
import jiconfont.javafx.IconFontFX;
|
||||
import jiconfont.javafx.IconNode;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Main application window: menu bar, audio playback display, the spectrum and waterfall, the Now Playing, Map and
|
||||
* Tuners tabs, the optional streaming status and the optional resource status bar.
|
||||
*
|
||||
* The spectrum and waterfall can be hidden from the View menu, the hide button in the display settings panel or a
|
||||
* keyboard shortcut. A hidden spectrum is disposed so that it uses no processing or memory.
|
||||
*/
|
||||
public class MainWindow
|
||||
{
|
||||
private static final Logger mLog = LoggerFactory.getLogger(MainWindow.class);
|
||||
public static final String STAGE_MONITOR_KEY = "main.window";
|
||||
private static final String PREFERENCE_BROADCAST_STATUS_VISIBLE = "sdrtrunk.broadcast.status.visible";
|
||||
private static final String PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE = "sdrtrunk.now.playing.details.visible";
|
||||
private static final String PREFERENCE_RESOURCE_STATUS_VISIBLE = "sdrtrunk.resource.status.visible";
|
||||
private static final String PREFERENCE_SPECTRAL_DISPLAY_VISIBLE = "sdrtrunk.spectral.display.visible";
|
||||
private static final String PREFERENCE_SPECTRAL_DIVIDER = "sdrtrunk.main.window.spectral.fraction";
|
||||
private static final String PREFERENCE_BROADCAST_DIVIDER = "sdrtrunk.main.window.streaming.fraction";
|
||||
private static final double DEFAULT_SPECTRAL_DIVIDER = 0.38;
|
||||
private static final double DEFAULT_BROADCAST_FRACTION = 0.18;
|
||||
static final KeyCombination SPECTRAL_TOGGLE_SHORTCUT = new KeyCodeCombination(KeyCode.S,
|
||||
KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN);
|
||||
|
||||
private final Preferences mPreferences = Preferences.userNodeForPackage(SDRTrunk.class);
|
||||
private final UserPreferences mUserPreferences;
|
||||
private final PlaylistManager mPlaylistManager;
|
||||
private final TunerManager mTunerManager;
|
||||
private final DiagnosticMonitor mDiagnosticMonitor;
|
||||
private final ResourceMonitor mResourceMonitor;
|
||||
private final Runnable mExitHandler;
|
||||
private final String mTitle;
|
||||
|
||||
private final Stage mStage;
|
||||
private final BorderPane mRoot = new BorderPane();
|
||||
private final SplitPane mSplitPane = new SplitPane();
|
||||
private final VBox mCenter = new VBox();
|
||||
private final AudioView mAudioView;
|
||||
private final MainSpectralDisplay mSpectralDisplay;
|
||||
private final HBox mSpectralHiddenBar;
|
||||
private final NowPlayingView mNowPlayingView;
|
||||
private final CallsView mCallsView;
|
||||
private final TabPane mTabPane = new TabPane();
|
||||
private BroadcastStatusView mBroadcastStatusView;
|
||||
private StatusBox mStatusBox;
|
||||
private final CheckMenuItem mSpectralMenuItem = new CheckMenuItem("Show Spectrum & Waterfall");
|
||||
private final CheckMenuItem mBroadcastMenuItem = new CheckMenuItem("Show Streaming Status");
|
||||
private final CheckMenuItem mResourceMenuItem = new CheckMenuItem("Show Resource Status");
|
||||
private final CheckMenuItem mNowPlayingDetailsMenuItem = new CheckMenuItem("Show Now Playing Channel Details");
|
||||
private double mSpectralDivider;
|
||||
private double mBroadcastFraction;
|
||||
private boolean mUpdatingDividers;
|
||||
|
||||
static
|
||||
{
|
||||
IconFontFX.register(FontAwesome.getIconFont());
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the main window. JavaFX thread only.
|
||||
* @param userPreferences for the views
|
||||
* @param playlistManager for the channels, aliases and streams
|
||||
* @param tunerManager for the tuners
|
||||
* @param audioPlaybackManager for the audio display
|
||||
* @param aliasModel for alias lookup
|
||||
* @param iconModel for alias icons
|
||||
* @param mapService for the map
|
||||
* @param resourceMonitor for the status bar
|
||||
* @param diagnosticMonitor for the reports
|
||||
* @param databaseManager for the Calls tab
|
||||
* @param callManager for live call updates in the Calls tab
|
||||
* @param exitHandler that shuts down the application, invoked on a background thread
|
||||
*/
|
||||
public MainWindow(UserPreferences userPreferences, PlaylistManager playlistManager, TunerManager tunerManager,
|
||||
AudioPlaybackManager audioPlaybackManager, AliasModel aliasModel, IconModel iconModel,
|
||||
MapService mapService, ResourceMonitor resourceMonitor, DiagnosticMonitor diagnosticMonitor,
|
||||
DatabaseManager databaseManager, CallManager callManager,
|
||||
Runnable exitHandler)
|
||||
{
|
||||
mUserPreferences = userPreferences;
|
||||
mPlaylistManager = playlistManager;
|
||||
mTunerManager = tunerManager;
|
||||
mResourceMonitor = resourceMonitor;
|
||||
mDiagnosticMonitor = diagnosticMonitor;
|
||||
mExitHandler = exitHandler;
|
||||
mTitle = SystemProperties.getInstance().getApplicationName();
|
||||
mSpectralDivider = clamp(mPreferences.getDouble(PREFERENCE_SPECTRAL_DIVIDER, DEFAULT_SPECTRAL_DIVIDER));
|
||||
mBroadcastFraction = clamp(mPreferences.getDouble(PREFERENCE_BROADCAST_DIVIDER, DEFAULT_BROADCAST_FRACTION));
|
||||
|
||||
mAudioView = new AudioView(audioPlaybackManager, aliasModel, iconModel, userPreferences);
|
||||
|
||||
boolean spectralVisible = mPreferences.getBoolean(PREFERENCE_SPECTRAL_DISPLAY_VISIBLE, true);
|
||||
mSpectralDisplay = new MainSpectralDisplay(playlistManager, tunerManager.getDiscoveredTunerModel(),
|
||||
spectralVisible);
|
||||
mSpectralDisplay.setHideRequestHandler(() -> setSpectralDisplayVisible(false));
|
||||
mSpectralHiddenBar = createSpectralHiddenBar();
|
||||
|
||||
boolean detailsVisible = mPreferences.getBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, true);
|
||||
mNowPlayingView = new NowPlayingView(playlistManager, iconModel, userPreferences, detailsVisible);
|
||||
mCallsView = new CallsView(databaseManager, callManager, audioPlaybackManager, aliasModel);
|
||||
createTabs(mapService, iconModel);
|
||||
|
||||
URL stylesheet = MainWindow.class.getResource("/main_window.css");
|
||||
|
||||
if(stylesheet != null)
|
||||
{
|
||||
mRoot.getStylesheets().add(stylesheet.toExternalForm());
|
||||
}
|
||||
|
||||
mRoot.getStyleClass().add("main-window");
|
||||
mSplitPane.setOrientation(javafx.geometry.Orientation.VERTICAL);
|
||||
mSplitPane.getStyleClass().add("main-split-pane");
|
||||
//The split pane moves its dividers while it lays out, so only store the positions after the user drags one
|
||||
mSplitPane.addEventFilter(javafx.scene.input.MouseEvent.MOUSE_RELEASED, event -> storeDividers());
|
||||
mSpectralDisplay.setMinHeight(80);
|
||||
mTabPane.setMinHeight(150);
|
||||
VBox.setVgrow(mSplitPane, Priority.ALWAYS);
|
||||
mCenter.getChildren().addAll(mSpectralHiddenBar, mSplitPane);
|
||||
mRoot.setTop(new VBox(createMenuBar(), mAudioView));
|
||||
mRoot.setCenter(mCenter);
|
||||
|
||||
mSpectralMenuItem.setSelected(spectralVisible);
|
||||
mNowPlayingDetailsMenuItem.setSelected(detailsVisible);
|
||||
mBroadcastMenuItem.setSelected(mPreferences.getBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, false));
|
||||
mResourceMenuItem.setSelected(mPreferences.getBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, true));
|
||||
updateSplitPaneItems();
|
||||
updateStatusBar();
|
||||
|
||||
mStage = new Stage();
|
||||
mStage.setTitle(mTitle);
|
||||
ApplicationIcons.apply(mStage);
|
||||
Scene scene = new Scene(mRoot, 1280, 800);
|
||||
ThemeManager.getInstance().register(scene);
|
||||
scene.getAccelerators().put(SPECTRAL_TOGGLE_SHORTCUT,
|
||||
() -> setSpectralDisplayVisible(!mSpectralDisplay.displayVisibleProperty().get()));
|
||||
mStage.setScene(scene);
|
||||
mStage.setMinWidth(640);
|
||||
mStage.setMinHeight(480);
|
||||
mStage.setOnCloseRequest(event -> {
|
||||
event.consume();
|
||||
exit();
|
||||
});
|
||||
|
||||
migrateSwingWindowLocation();
|
||||
mUserPreferences.getJavaFxPreferences().monitor(mStage, STAGE_MONITOR_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main window stage.
|
||||
*/
|
||||
public Stage getStage()
|
||||
{
|
||||
return mStage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spectrum and waterfall display.
|
||||
*/
|
||||
public MainSpectralDisplay getSpectralDisplay()
|
||||
{
|
||||
return mSpectralDisplay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the window. JavaFX thread only.
|
||||
*/
|
||||
public void show()
|
||||
{
|
||||
mStage.show();
|
||||
//The split pane only applies divider positions once it has a size
|
||||
Platform.runLater(this::applyDividers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the stage's title with the tuner name, or the application name when the tuner is null. Any thread.
|
||||
*/
|
||||
public void updateTitle(String tunerName)
|
||||
{
|
||||
String title = tunerName != null ? mTitle + " - " + tunerName : mTitle;
|
||||
Platform.runLater(() -> mStage.setTitle(title));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles tuner events for the main spectral display. Any thread.
|
||||
*/
|
||||
public void receive(TunerEvent event)
|
||||
{
|
||||
switch(event.getEvent())
|
||||
{
|
||||
case REQUEST_MAIN_SPECTRAL_DISPLAY:
|
||||
//The user asked to see a tuner, so show the display if it's hidden
|
||||
Platform.runLater(() -> setSpectralDisplayVisible(true));
|
||||
updateTitle(event.getTuner().getPreferredName());
|
||||
break;
|
||||
case REQUEST_CLEAR_MAIN_SPECTRAL_DISPLAY:
|
||||
updateTitle(null);
|
||||
break;
|
||||
case NOTIFICATION_SHUTTING_DOWN:
|
||||
Tuner currentTuner = mSpectralDisplay.getTuner();
|
||||
|
||||
if(currentTuner == null || (event.hasTuner() && event.getTuner().equals(currentTuner)))
|
||||
{
|
||||
updateTitle(null);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the divider positions and stops the views. Called during application shutdown.
|
||||
*/
|
||||
public void dispose()
|
||||
{
|
||||
mAudioView.dispose();
|
||||
mCallsView.dispose();
|
||||
|
||||
if(mBroadcastStatusView != null)
|
||||
{
|
||||
mBroadcastStatusView.dispose();
|
||||
}
|
||||
|
||||
mSpectralDisplay.dispose();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows or hides the spectrum and waterfall. A hidden display is disposed. JavaFX thread only.
|
||||
*/
|
||||
public void setSpectralDisplayVisible(boolean visible)
|
||||
{
|
||||
mSpectralMenuItem.setSelected(visible);
|
||||
|
||||
if(visible != mSpectralDisplay.displayVisibleProperty().get())
|
||||
{
|
||||
mPreferences.putBoolean(PREFERENCE_SPECTRAL_DISPLAY_VISIBLE, visible);
|
||||
mSpectralDisplay.setDisplayVisible(visible);
|
||||
updateSplitPaneItems();
|
||||
applyDividers();
|
||||
}
|
||||
}
|
||||
|
||||
private HBox createSpectralHiddenBar()
|
||||
{
|
||||
IconNode icon = new IconNode(FontAwesome.EYE_SLASH);
|
||||
icon.setIconSize(13);
|
||||
icon.getStyleClass().add("main-hidden-bar-icon");
|
||||
Label label = new Label("Spectrum and waterfall are hidden and turned off, so they use no processing or memory.");
|
||||
label.getStyleClass().add("main-hidden-bar-label");
|
||||
label.setMinWidth(0);
|
||||
Region spacer = new Region();
|
||||
HBox.setHgrow(spacer, Priority.ALWAYS);
|
||||
IconNode showIcon = new IconNode(FontAwesome.EYE);
|
||||
showIcon.setIconSize(12);
|
||||
Button show = new Button("Show Spectrum & Waterfall", showIcon);
|
||||
showIcon.fillProperty().bind(show.textFillProperty());
|
||||
show.setOnAction(event -> setSpectralDisplayVisible(true));
|
||||
HBox bar = new HBox(8, icon, label, spacer, show);
|
||||
bar.getStyleClass().add("main-hidden-bar");
|
||||
bar.setAlignment(Pos.CENTER_LEFT);
|
||||
return bar;
|
||||
}
|
||||
|
||||
private void createTabs(MapService mapService, IconModel iconModel)
|
||||
{
|
||||
MapView mapView = new MapView(mapService, iconModel, mUserPreferences,
|
||||
mPlaylistManager.getRadioReference() != null ?
|
||||
mPlaylistManager.getRadioReference().getFrequencyIndex() : null,
|
||||
new RadioReferencePlaylistActions(mPlaylistManager), true);
|
||||
|
||||
Tab nowPlaying = new Tab("Now Playing", mNowPlayingView);
|
||||
Tab calls = new Tab("Calls", mCallsView);
|
||||
Tab map = new Tab("Map", mapView);
|
||||
Tab tuners = new Tab("Tuners", new io.github.dsheirer.source.tuner.ui.TunerView(mTunerManager,
|
||||
mUserPreferences));
|
||||
|
||||
//The playlist editor tab opens the playlist editor window and stays on the current tab
|
||||
IconNode playIcon = new IconNode(FontAwesome.PLAY_CIRCLE_O);
|
||||
playIcon.setIconSize(15);
|
||||
playIcon.getStyleClass().add("main-playlist-tab-icon");
|
||||
Tab playlist = new Tab("Playlist Editor");
|
||||
playlist.setGraphic(playIcon);
|
||||
playlist.setContent(new Region());
|
||||
|
||||
mTabPane.getTabs().addAll(nowPlaying, calls, map, tuners, playlist);
|
||||
mTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
|
||||
mTabPane.getStyleClass().add("main-tab-pane");
|
||||
mTabPane.getSelectionModel().selectedItemProperty().addListener((observable, oldTab, newTab) -> {
|
||||
if(newTab == playlist)
|
||||
{
|
||||
MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest());
|
||||
Platform.runLater(() -> mTabPane.getSelectionModel().select(oldTab != null ? oldTab : nowPlaying));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the split pane to hold the visible panes: spectrum (optional), tabs and streaming status (optional).
|
||||
*/
|
||||
private void updateSplitPaneItems()
|
||||
{
|
||||
mUpdatingDividers = true;
|
||||
|
||||
List<Node> items = new ArrayList<>();
|
||||
|
||||
boolean spectralVisible = mSpectralDisplay.displayVisibleProperty().get();
|
||||
|
||||
if(spectralVisible)
|
||||
{
|
||||
items.add(mSpectralDisplay);
|
||||
}
|
||||
|
||||
items.add(mTabPane);
|
||||
|
||||
if(mBroadcastMenuItem.isSelected())
|
||||
{
|
||||
if(mBroadcastStatusView == null)
|
||||
{
|
||||
mBroadcastStatusView = new BroadcastStatusView(mPlaylistManager.getBroadcastModel(),
|
||||
mUserPreferences.getSwingPreference());
|
||||
mBroadcastStatusView.setMinHeight(70);
|
||||
}
|
||||
|
||||
items.add(mBroadcastStatusView);
|
||||
}
|
||||
|
||||
mSplitPane.getItems().setAll(items);
|
||||
SplitPane.setResizableWithParent(mTabPane, true);
|
||||
|
||||
if(mBroadcastStatusView != null)
|
||||
{
|
||||
SplitPane.setResizableWithParent(mBroadcastStatusView, false);
|
||||
}
|
||||
|
||||
mSpectralHiddenBar.setVisible(!spectralVisible);
|
||||
mSpectralHiddenBar.setManaged(!spectralVisible);
|
||||
|
||||
mUpdatingDividers = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the stored divider positions to the split pane.
|
||||
*/
|
||||
private void applyDividers()
|
||||
{
|
||||
mUpdatingDividers = true;
|
||||
List<SplitPane.Divider> dividers = mSplitPane.getDividers();
|
||||
int index = 0;
|
||||
|
||||
if(mSpectralDisplay.displayVisibleProperty().get() && index < dividers.size())
|
||||
{
|
||||
dividers.get(index++).setPosition(mSpectralDivider);
|
||||
}
|
||||
|
||||
if(mBroadcastMenuItem.isSelected() && index < dividers.size())
|
||||
{
|
||||
dividers.get(index).setPosition(1.0 - mBroadcastFraction);
|
||||
}
|
||||
|
||||
mUpdatingDividers = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the divider positions after the user moves a divider.
|
||||
*/
|
||||
private void storeDividers()
|
||||
{
|
||||
if(mUpdatingDividers || !mStage.isShowing() || mSplitPane.getDividers().isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
List<SplitPane.Divider> dividers = mSplitPane.getDividers();
|
||||
int index = 0;
|
||||
|
||||
if(mSpectralDisplay.displayVisibleProperty().get() && index < dividers.size())
|
||||
{
|
||||
mSpectralDivider = clamp(dividers.get(index++).getPosition());
|
||||
mPreferences.putDouble(PREFERENCE_SPECTRAL_DIVIDER, mSpectralDivider);
|
||||
}
|
||||
|
||||
if(mBroadcastMenuItem.isSelected() && index < dividers.size())
|
||||
{
|
||||
mBroadcastFraction = clamp(1.0 - dividers.get(index).getPosition());
|
||||
mPreferences.putDouble(PREFERENCE_BROADCAST_DIVIDER, mBroadcastFraction);
|
||||
}
|
||||
}
|
||||
|
||||
private static double clamp(double value)
|
||||
{
|
||||
return Double.isNaN(value) ? 0.3 : Math.max(0.05, Math.min(0.6, value));
|
||||
}
|
||||
|
||||
private void updateStatusBar()
|
||||
{
|
||||
if(mResourceMenuItem.isSelected())
|
||||
{
|
||||
if(mStatusBox == null)
|
||||
{
|
||||
mStatusBox = new StatusBox(mResourceMonitor);
|
||||
}
|
||||
|
||||
mRoot.setBottom(mStatusBox);
|
||||
}
|
||||
else
|
||||
{
|
||||
mRoot.setBottom(null);
|
||||
}
|
||||
}
|
||||
|
||||
private MenuBar createMenuBar()
|
||||
{
|
||||
//File
|
||||
MenuItem processingReport = new MenuItem("Processing Diagnostic Report");
|
||||
processingReport.setOnAction(event -> createReport("Processing Status Report",
|
||||
() -> mDiagnosticMonitor.generateProcessingDiagnosticReport("User initiated diagnostic report")));
|
||||
MenuItem threadDumpReport = new MenuItem("Thread Dump Report");
|
||||
threadDumpReport.setOnAction(event -> createReport("Thread Dump Report",
|
||||
mDiagnosticMonitor::generateThreadDumpReport));
|
||||
Menu reports = new Menu("Reports", null, processingReport, threadDumpReport);
|
||||
|
||||
MenuItem screenCapture = new MenuItem("Screen Capture", icon(FontAwesome.CAMERA));
|
||||
screenCapture.setAccelerator(new KeyCodeCombination(KeyCode.C, KeyCombination.ALT_DOWN));
|
||||
screenCapture.setOnAction(event -> captureScreen());
|
||||
|
||||
MenuItem exit = new MenuItem("Exit");
|
||||
exit.setOnAction(event -> exit());
|
||||
|
||||
Menu file = new Menu("File", null, reports, screenCapture, new SeparatorMenuItem(), exit);
|
||||
|
||||
//View
|
||||
MenuItem playlistEditor = new MenuItem("Playlist Editor", icon(FontAwesome.PLAY_CIRCLE_O));
|
||||
playlistEditor.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewPlaylistRequest()));
|
||||
|
||||
MenuItem logs = folderItem("Application Log Files",
|
||||
() -> mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog());
|
||||
MenuItem recordings = folderItem("Audio Recordings",
|
||||
() -> mUserPreferences.getDirectoryPreference().getDirectoryRecording());
|
||||
MenuItem eventLogs = folderItem("Channel Event Log Files",
|
||||
() -> mUserPreferences.getDirectoryPreference().getDirectoryEventLog());
|
||||
MenuItem screenCaptures = folderItem("Screen Captures",
|
||||
() -> mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture());
|
||||
|
||||
MenuItem iconManager = new MenuItem("Icon Manager", icon(FontAwesome.PICTURE_O));
|
||||
iconManager.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewIconManagerRequest()));
|
||||
MenuItem recordingViewer = new MenuItem("Message Recording Viewer (.bits)", icon(FontAwesome.BRAILLE));
|
||||
recordingViewer.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewRecordingViewerRequest()));
|
||||
MenuItem preferences = new MenuItem("User Preferences", icon(FontAwesome.COG));
|
||||
preferences.setOnAction(event -> MyEventBus.getGlobalEventBus().post(new ViewUserPreferenceEditorRequest()));
|
||||
|
||||
Menu tuners = new Menu("Tuners");
|
||||
tuners.getItems().add(new MenuItem("(none)"));
|
||||
tuners.setOnShowing(event -> updateTunersMenu(tuners));
|
||||
|
||||
mSpectralMenuItem.setAccelerator(SPECTRAL_TOGGLE_SHORTCUT);
|
||||
mSpectralMenuItem.setOnAction(event -> setSpectralDisplayVisible(mSpectralMenuItem.isSelected()));
|
||||
mNowPlayingDetailsMenuItem.setOnAction(event -> {
|
||||
mNowPlayingView.setDetailTabsVisible(mNowPlayingDetailsMenuItem.isSelected());
|
||||
mPreferences.putBoolean(PREFERENCE_NOW_PLAYING_DETAILS_VISIBLE, mNowPlayingDetailsMenuItem.isSelected());
|
||||
});
|
||||
mBroadcastMenuItem.setOnAction(event -> {
|
||||
mPreferences.putBoolean(PREFERENCE_BROADCAST_STATUS_VISIBLE, mBroadcastMenuItem.isSelected());
|
||||
updateSplitPaneItems();
|
||||
applyDividers();
|
||||
});
|
||||
mResourceMenuItem.setOnAction(event -> {
|
||||
mPreferences.putBoolean(PREFERENCE_RESOURCE_STATUS_VISIBLE, mResourceMenuItem.isSelected());
|
||||
updateStatusBar();
|
||||
});
|
||||
|
||||
Menu view = new Menu("View", null, playlistEditor, new SeparatorMenuItem(), logs, recordings, eventLogs,
|
||||
iconManager, recordingViewer, screenCaptures, preferences, new SeparatorMenuItem(), tuners,
|
||||
new SeparatorMenuItem(), mSpectralMenuItem, mNowPlayingDetailsMenuItem, mBroadcastMenuItem,
|
||||
mResourceMenuItem);
|
||||
|
||||
MenuBar menuBar = new MenuBar(file, view);
|
||||
menuBar.setUseSystemMenuBar(true);
|
||||
return menuBar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the available tuners, each of which shows the tuner in the main spectral display.
|
||||
*/
|
||||
private void updateTunersMenu(Menu menu)
|
||||
{
|
||||
menu.getItems().clear();
|
||||
|
||||
for(DiscoveredTuner discoveredTuner: mTunerManager.getAvailableTuners())
|
||||
{
|
||||
Tuner tuner = discoveredTuner.getTuner();
|
||||
|
||||
if(tuner != null)
|
||||
{
|
||||
MenuItem item = new MenuItem("Show: " + tuner.getPreferredName());
|
||||
item.setOnAction(event -> ThreadPool.CACHED.submit(() -> {
|
||||
SystemProperties.getInstance().set(TunerSpectralDisplay.SPECTRAL_DISPLAY_ENABLED, true);
|
||||
mTunerManager.getDiscoveredTunerModel().broadcast(new TunerEvent(tuner,
|
||||
TunerEvent.Event.REQUEST_MAIN_SPECTRAL_DISPLAY));
|
||||
}));
|
||||
menu.getItems().add(item);
|
||||
}
|
||||
}
|
||||
|
||||
if(menu.getItems().isEmpty())
|
||||
{
|
||||
MenuItem none = new MenuItem("No tuners available");
|
||||
none.setDisable(true);
|
||||
menu.getItems().add(none);
|
||||
}
|
||||
}
|
||||
|
||||
private static IconNode icon(FontAwesome code)
|
||||
{
|
||||
IconNode icon = new IconNode(code);
|
||||
icon.setIconSize(12);
|
||||
icon.getStyleClass().add("main-menu-icon");
|
||||
return icon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies a path that can throw an IO exception.
|
||||
*/
|
||||
private interface PathSupplier
|
||||
{
|
||||
Path get() throws IOException;
|
||||
}
|
||||
|
||||
private MenuItem folderItem(String title, PathSupplier folder)
|
||||
{
|
||||
MenuItem item = new MenuItem(title, icon(FontAwesome.FOLDER_OPEN_O));
|
||||
item.setOnAction(event -> ThreadPool.CACHED.submit(() -> {
|
||||
File directory = null;
|
||||
|
||||
try
|
||||
{
|
||||
directory = folder.get().toFile();
|
||||
Desktop.getDesktop().open(directory);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.error("Couldn't open file explorer", e);
|
||||
String location = directory != null ? directory.toString() : "unknown";
|
||||
Platform.runLater(() -> showAlert(Alert.AlertType.ERROR, "Can't launch file explorer",
|
||||
"Can't launch the file explorer. The files are located at:\n\n" + location));
|
||||
}
|
||||
}));
|
||||
return item;
|
||||
}
|
||||
|
||||
private void createReport(String title, PathSupplier report)
|
||||
{
|
||||
ThreadPool.CACHED.submit(() -> {
|
||||
try
|
||||
{
|
||||
Path path = report.get();
|
||||
Platform.runLater(() -> showAlert(Alert.AlertType.INFORMATION, title + " Created",
|
||||
"Report created:\n\n" + path));
|
||||
}
|
||||
catch(IOException ioe)
|
||||
{
|
||||
mLog.error("Error creating " + title, ioe);
|
||||
Platform.runLater(() -> showAlert(Alert.AlertType.ERROR, title + " Failed",
|
||||
"Unable to create the report file. Please see the application log for details."));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a message dialog owned by the main window. JavaFX thread only.
|
||||
*/
|
||||
public void showAlert(Alert.AlertType type, String title, String message)
|
||||
{
|
||||
Alert alert = new Alert(type, message);
|
||||
alert.setTitle(title);
|
||||
alert.setHeaderText(null);
|
||||
alert.initOwner(mStage);
|
||||
alert.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* Warns that the library folder holds more than one version of some libraries. JavaFX thread only.
|
||||
* @param details listing the duplicate libraries
|
||||
* @param folder holding the libraries
|
||||
*/
|
||||
public void showDuplicateLibraries(String details, String folder)
|
||||
{
|
||||
Alert alert = new Alert(Alert.AlertType.WARNING);
|
||||
alert.setTitle("Duplicate Library Versions");
|
||||
alert.setHeaderText("The sdrtrunk library folder has more than one version of some libraries");
|
||||
alert.setContentText("This happens when a new version of sdrtrunk is unzipped over an older one. sdrtrunk " +
|
||||
"can load the older library code, which can cause crashes or errors that the newer version fixed.\n\n" +
|
||||
"Close sdrtrunk, delete the sdrtrunk folder that contains this library folder and unzip the release " +
|
||||
"into a new, empty folder:\n\n" + folder + "\n\nYour playlist and settings are stored in your user " +
|
||||
"folder and won't be affected.");
|
||||
TextArea libraries = new TextArea(details);
|
||||
libraries.setEditable(false);
|
||||
libraries.setPrefRowCount(8);
|
||||
alert.getDialogPane().setExpandableContent(libraries);
|
||||
alert.getDialogPane().setExpanded(true);
|
||||
alert.initOwner(mStage);
|
||||
alert.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves an image of the main window to the screen captures folder.
|
||||
*/
|
||||
private void captureScreen()
|
||||
{
|
||||
WritableImage image = mStage.getScene().snapshot(null);
|
||||
String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png";
|
||||
|
||||
ThreadPool.CACHED.submit(() -> {
|
||||
Path file = null;
|
||||
|
||||
try
|
||||
{
|
||||
file = mUserPreferences.getDirectoryPreference().getDirectoryScreenCapture().resolve(filename);
|
||||
ImageIO.write(FxToolkit.toBufferedImage(image), "png", file.toFile());
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
mLog.error("Couldn't write screen capture to file [" + file + "]", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Hides the window and shuts down the application on a background thread, since stopping the tuners can block.
|
||||
*/
|
||||
private void exit()
|
||||
{
|
||||
mStage.hide();
|
||||
Thread thread = new Thread(() -> {
|
||||
try
|
||||
{
|
||||
mExitHandler.run();
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
mLog.error("Error during shutdown", t);
|
||||
}
|
||||
|
||||
System.exit(0);
|
||||
}, "sdrtrunk shutdown");
|
||||
thread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the main window size and location from the Swing window preferences to the JavaFX stage preferences,
|
||||
* once, so that users keep their window placement.
|
||||
*/
|
||||
private void migrateSwingWindowLocation()
|
||||
{
|
||||
if(mUserPreferences.getJavaFxPreferences().hasStoredLocation(STAGE_MONITOR_KEY))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
String swingKey = "sdrtrunk.main.window.frame";
|
||||
java.awt.Point location = mUserPreferences.getSwingPreference().getLocation(swingKey);
|
||||
java.awt.Dimension size = mUserPreferences.getSwingPreference().getDimension(swingKey);
|
||||
|
||||
if(location != null && size != null)
|
||||
{
|
||||
mUserPreferences.getJavaFxPreferences().storeLocation(STAGE_MONITOR_KEY, location.x, location.y,
|
||||
size.width, size.height, mUserPreferences.getSwingPreference().getMaximized(swingKey, false));
|
||||
}
|
||||
else
|
||||
{
|
||||
mStage.centerOnScreen();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user