Compare commits

..

1 Commits

Author SHA1 Message Date
Denny Sheirer
9f7e37f9ec Update README.md
Adds badget for google groups
2026-11-17 06:48:52 -05:00
134 changed files with 10510 additions and 6135 deletions

View File

@@ -213,13 +213,6 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
return; 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) if(getIdentityCount(existing) > 1)
{ {
//The alias also identifies other radios or talkgroups - leave it alone. //The alias also identifies other radios or talkgroups - leave it alone.

View File

@@ -26,7 +26,7 @@ import io.github.dsheirer.gui.nowplaying.NowPlayingPanel;
import io.github.dsheirer.gui.playlist.ViewPlaylistRequest; import io.github.dsheirer.gui.playlist.ViewPlaylistRequest;
import io.github.dsheirer.icon.IconModel; import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions; import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.map.MapPanel; import io.github.dsheirer.map.MapPanel;
import io.github.dsheirer.map.MapService; import io.github.dsheirer.map.MapService;
import io.github.dsheirer.playlist.PlaylistManager; import io.github.dsheirer.playlist.PlaylistManager;
import io.github.dsheirer.preference.UserPreferences; import io.github.dsheirer.preference.UserPreferences;
@@ -64,7 +64,7 @@ public class ControllerPanel extends JPanel
mAudioPanel = new AudioPanel(iconModel, userPreferences, settingsManager, audioPlaybackManager, mAudioPanel = new AudioPanel(iconModel, userPreferences, settingsManager, audioPlaybackManager,
playlistManager.getAliasModel()); playlistManager.getAliasModel());
mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, detailTabsVisible); mNowPlayingPanel = new NowPlayingPanel(playlistManager, iconModel, userPreferences, detailTabsVisible);
mMapPanel = new MapPanel(mapService, iconModel, userPreferences, mMapPanel = new MapPanel(mapService, playlistManager.getAliasModel(), iconModel, userPreferences,
playlistManager.getRadioReference() != null ? playlistManager.getRadioReference().getFrequencyIndex() : null, playlistManager.getRadioReference() != null ? playlistManager.getRadioReference().getFrequencyIndex() : null,
new RadioReferencePlaylistActions(playlistManager)); new RadioReferencePlaylistActions(playlistManager));
mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences); mTunerManagerPanel = new TunerViewPanel(tunerManager, userPreferences);

View File

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

View File

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

View File

@@ -68,12 +68,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private final static Logger mLog = LoggerFactory.getLogger(PolyphaseChannelManager.class); private final static Logger mLog = LoggerFactory.getLogger(PolyphaseChannelManager.class);
private static final double CHANNEL_OVERSAMPLING = 2.0; private static final double CHANNEL_OVERSAMPLING = 2.0;
private static final int POLYPHASE_CHANNELIZER_TAPS_PER_CHANNEL = 9; private static final int POLYPHASE_CHANNELIZER_TAPS_PER_CHANNEL = 9;
/** private static final int MAXIMUM_QUEUED_NATIVE_BUFFERS = 500;
* 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 Broadcaster<SourceEvent> mSourceEventBroadcaster = new Broadcaster<>(); private Broadcaster<SourceEvent> mSourceEventBroadcaster = new Broadcaster<>();
private TunerController mTunerController; private TunerController mTunerController;
@@ -83,7 +78,7 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
private ComplexPolyphaseChannelizerM2 mPolyphaseChannelizer; private ComplexPolyphaseChannelizerM2 mPolyphaseChannelizer;
private ChannelSourceEventListener mChannelSourceEventListener = new ChannelSourceEventListener(); private ChannelSourceEventListener mChannelSourceEventListener = new ChannelSourceEventListener();
private NativeBufferReceiver mNativeBufferReceiver = new NativeBufferReceiver(); private NativeBufferReceiver mNativeBufferReceiver = new NativeBufferReceiver();
private Dispatcher<INativeBuffer> mBufferDispatcher; private Dispatcher mBufferDispatcher;
private boolean mRunning = true; private boolean mRunning = true;
/** /**
@@ -104,21 +99,10 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
mChannelCalculator = new ChannelCalculator(tunerController.getSampleRate(), channelCount, mChannelCalculator = new ChannelCalculator(tunerController.getSampleRate(), channelCount,
tunerController.getFrequency(), CHANNEL_OVERSAMPLING); tunerController.getFrequency(), CHANNEL_OVERSAMPLING);
mBufferDispatcher = new Dispatcher<>("sdrtrunk polyphase buffer processor", 10, INativeBuffer::sampleCount, mBufferDispatcher = new Dispatcher("sdrtrunk polyphase buffer processor", 10, MAXIMUM_QUEUED_NATIVE_BUFFERS);
getMaximumQueuedSamples(tunerController.getSampleRate()));
mBufferDispatcher.setListener(mNativeBufferReceiver); 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. * Provides a description of the state of this manager.
*/ */
@@ -294,7 +278,6 @@ public class PolyphaseChannelManager implements ISourceEventProcessor
double sampleRate = sourceEvent.getValue().doubleValue(); double sampleRate = sourceEvent.getValue().doubleValue();
int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate); int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate);
mChannelCalculator.setRates(sampleRate, channelCount); mChannelCalculator.setRates(sampleRate, channelCount);
mBufferDispatcher.setMaximumQueuedWeight(getMaximumQueuedSamples(sampleRate));
break; break;
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_LOCKED: case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_LOCKED:
case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_UNLOCKED: case NOTIFICATION_FREQUENCY_AND_SAMPLE_RATE_UNLOCKED:

View File

@@ -180,8 +180,7 @@ public class PolyphaseChannelSource extends TunerChannelSource implements Listen
/** /**
* Performs the output processor update. This method must be invoked on the channel results calling thread so that * 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 * 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 * applies the configuration changes on its own dispatcher thread.
* dispatcher thread at that same batch.
* @param channelCalculator for updates * @param channelCalculator for updates
* @param filterManager for updates * @param filterManager for updates
* @throws IllegalArgumentException if there's an issue. * @throws IllegalArgumentException if there's an issue.

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * 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.source.heartbeat.HeartbeatManager;
import io.github.dsheirer.util.Dispatcher; import io.github.dsheirer.util.Dispatcher;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -35,20 +34,12 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
private final static Logger mLog = LoggerFactory.getLogger(ChannelOutputProcessor.class); 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. * falls behind, which preserves the even-sized batch block parity that two-channel synthesis relies on.
*/ */
private static final int MAXIMUM_QUEUED_BATCHES = 50; private static final int MAXIMUM_QUEUED_BATCHES = 50;
/** private Dispatcher<QueuedChannelResults> mChannelResultsDispatcher;
* 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 final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>(); private final Queue<PendingUpdate> mPendingUpdates = new ConcurrentLinkedQueue<>();
private final AtomicLong mBatchSequence = new AtomicLong(); private final AtomicLong mBatchSequence = new AtomicLong();
private HeartbeatManager mHeartbeatManager; private HeartbeatManager mHeartbeatManager;
@@ -69,45 +60,25 @@ public abstract class ChannelOutputProcessor implements IPolyphaseChannelOutputP
mInputChannelCount = inputChannelCount; mInputChannelCount = inputChannelCount;
//Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate) //Process 1/10th of the sample rate per second at a rate of 20 times a second (200% of anticipated rate)
mHeartbeatManager = heartbeatManager; mHeartbeatManager = heartbeatManager;
mChannelSamplesDispatcher = new Dispatcher<>(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES); mChannelResultsDispatcher = new Dispatcher(threadName,50, mHeartbeatManager, MAXIMUM_QUEUED_BATCHES);
mChannelSamplesDispatcher.setListener(queued -> { mChannelResultsDispatcher.setListener(queued -> {
try try
{ {
applyPendingUpdates(queued.sequence()); applyPendingUpdates(queued.sequence());
mCurrentSampleTimestamp = queued.timestamp(); mCurrentSampleTimestamp = queued.channelResults().getTimestamp();
process(queued.samples(), queued.blockCount()); process(queued.channelResults());
} }
catch(Throwable t) catch(Throwable t)
{ {
mLog.error("Error processing channel samples", t); mLog.error("Error processing channel results", t);
} }
finally 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 * 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 * 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 @Override
public void start() public void start()
{ {
mChannelSamplesDispatcher.start(); mChannelResultsDispatcher.start();
} }
@Override @Override
public void stop() 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 @Override
public void receiveChannelResults(ChannelResultsBatch channelResults) public void receiveChannelResults(ChannelResultsBatch channelResults)
{ {
long sequence = mBatchSequence.incrementAndGet(); channelResults.retain();
if(!mChannelSamplesDispatcher.isRunning()) if(!mChannelResultsDispatcher.offer(new QueuedChannelResults(channelResults, mBatchSequence.incrementAndGet())))
{ {
return; channelResults.release();
}
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);
} }
} }
/** /**
* 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) public abstract void process(ChannelResultsBatch channelResults);
{
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);
@Override @Override
public int getInputChannelCount() 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 * Channel results batch and its position in the sequence of received batches.
* 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. * Configuration change and the sequence number of the last batch received before the change was requested.

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * 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; 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.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager; import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -29,6 +29,7 @@ public class OneChannelOutputProcessor extends ChannelOutputProcessor
{ {
private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class); private final static Logger mLog = LoggerFactory.getLogger(OneChannelOutputProcessor.class);
private final OneChannelMixerAssembler mMixerAssembler; 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 * 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(); StringBuilder sb = new StringBuilder();
sb.append("One Channel Output Processor"); 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"); sb.append("\n\tMixer Assembler: none");
return sb.toString(); 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 //Set the channelized output results offset to twice the channel index to account for each channel having
//an I/Q pair //an I/Q pair
setChannelOffsets(indexes.get(0) * 2); int channelOffset = indexes.get(0) * 2;
enqueueUpdate(() -> mChannelOffset = channelOffset);
} }
@Override @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 * Extract the channel from the channel results array and pass to the assembler. The assembler will
* indicate when a buffer is fully assembled. * 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 channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
* @param blockCount number of blocks
*/ */
@Override @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]); mMixerAssembler.receive(samples[index], samples[index + 1]);

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2024 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * 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; 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.sample.complex.ComplexSamples;
import io.github.dsheirer.source.heartbeat.HeartbeatManager; import io.github.dsheirer.source.heartbeat.HeartbeatManager;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -29,6 +29,8 @@ public class TwoChannelOutputProcessor extends ChannelOutputProcessor
{ {
private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class); private final static Logger mLog = LoggerFactory.getLogger(TwoChannelOutputProcessor.class);
private TwoChannelMixerAssembler mMixerAssembler; private TwoChannelMixerAssembler mMixerAssembler;
private int mChannelOffset1;
private int mChannelOffset2;
/** /**
* Processor to extract two channels from a polyphase channelizer, synthesize/recombine the channels, apply * 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(); StringBuilder sb = new StringBuilder();
sb.append("Two Channel Output Processor"); 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()); sb.append("\n\tMixer Assembler: ").append(mMixerAssembler.getStateDescription());
return sb.toString(); 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 //Set the channelized output results offsets to twice the channel index to account for each channel having
//an I/Q pair //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 * Extract the channel from the channel results array, apply frequency translation, and deliver the
* I/Q sample set to the complex sample listener. * 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 channelResults to process containing blocks of channel I/Q sample pairs (I0,Q0,I1,Q1...In,Qn)
* @param blockCount number of blocks
*/ */
@Override @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 //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. //channelizer dispatches even-sized batches, so the index within the batch carries the absolute block parity.
for(int x = 0; x < blockCount; x++) for(int x = 0; x < blockCount; x++)
{ {
int block = x * 4; int block = x * blockLength;
if((x & 1) == 0) 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 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()) if(mMixerAssembler.hasBuffer())

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -693,10 +693,9 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
{ {
mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases"); mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases");
mAutoAddTalkerAliasesCheckBox.setDisable(true); mAutoAddTalkerAliasesCheckBox.setDisable(true);
mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds decoded talker aliases as radio aliases in " + mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds a radio alias for each talker alias decoded " +
"the Talker Alias group. Only radio aliases in that group are automatically renamed; existing " + "on this system, named with the talker alias, and renames the radio alias when its talker alias " +
"radio aliases outside the group are left unchanged. Move an alias out of the Talker Alias group " + "changes. Applies when the channel is (re)started."));
"to preserve a custom name. Applies when the channel is (re)started."));
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true)); mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
} }

View File

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

View File

@@ -24,7 +24,6 @@ import io.github.dsheirer.gui.spectrum.layer.DecibelLayer;
import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer; import io.github.dsheirer.gui.spectrum.layer.FrequencyLayer;
import io.github.dsheirer.properties.SystemProperties; import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.spectrum.ComplexDftProcessor; import io.github.dsheirer.spectrum.ComplexDftProcessor;
import io.github.dsheirer.spectrum.DFTResultsListener;
import io.github.dsheirer.spectrum.DFTSize; import io.github.dsheirer.spectrum.DFTSize;
import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter; import io.github.dsheirer.spectrum.converter.FullScaleDecibelConverter;
import javafx.application.Platform; import javafx.application.Platform;
@@ -301,14 +300,6 @@ public abstract class DftSpectralDisplay extends StackPane
/** /**
* DFT processor. Register it with the sample source to feed the display. * DFT processor. Register it with the sample source to feed the display.
*/ */
/**
* Adds a listener for the dBFS spectrum frames, lowest frequency first. Frames arrive on the DFT processor thread.
*/
protected void addDecibelListener(DFTResultsListener listener)
{
mDecibelConverter.addListener(listener);
}
protected ComplexDftProcessor getDftProcessor() protected ComplexDftProcessor getDftProcessor()
{ {
return mDftProcessor; return mDftProcessor;

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,219 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.map;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.alias.AliasList;
import io.github.dsheirer.alias.AliasModel;
import io.github.dsheirer.icon.IconModel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.util.Collections;
import java.util.List;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import javax.swing.ImageIcon;
/**
* Paints a single plottable entity to the map.
*/
public class PlottableEntityRenderer
{
private AliasModel mAliasModel;
private IconModel mIconModel;
private int mTrackHistoryLength = 3;
/**
* Constructs an instance
* @param aliasModel for alias lookup for the entity to determine plot color and icon
* @param iconModel to retrieve icon for plotting.
*/
public PlottableEntityRenderer(AliasModel aliasModel, IconModel iconModel)
{
mAliasModel = aliasModel;
mIconModel = iconModel;
}
/**
* Sets the length of the plotted history trails.
* @param length of history trails
*/
public void setTrackHistoryLength(int length)
{
mTrackHistoryLength = length;
}
/**
* Current size of the history trail length.
*/
public int getTrackHistoryLength()
{
return mTrackHistoryLength;
}
/**
* Requests the plottable entity be painted to the map viewer.
* @param g graphics
* @param viewer requesting the painting
* @param entity to be painted
* @param antiAliasing for rendering.
*/
public void paintPlottableEntity(Graphics2D g, JXMapViewer viewer, PlottableEntityHistory entity, boolean antiAliasing)
{
List<TimestampedGeoPosition> locationHistory = entity.getTrackHistoryModel().getTrackHistory();
if(!locationHistory.isEmpty() && locationHistory.getLast().isValid())
{
Graphics2D graphics = (Graphics2D)g.create();
if(antiAliasing)
{
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
List<Alias> aliases = getAliases(entity);
Alias alias = aliases.isEmpty() ? null : aliases.get(0);
/**
* Use the entity's preferred color for lines and labels
*/
Color color = (alias != null ? alias.getDisplayColor() : Color.BLUE);
graphics.setColor(color);
/**
* Paint the route first, so the icon and label overlay it
*/
paintRoute(graphics, viewer, entity, color);
/**
* Convert the lat/long geoposition to an x/y point on the viewer
*/
Point2D point = viewer.getTileFactory().geoToPixel(entity.getLatestPosition(), viewer.getZoom());
/**
* Paint the icon at the current location
*/
ImageIcon icon = getIcon(alias);
paintIcon(graphics, point, icon);
/**
* Paint the label offset to the right of the icon
*/
String label = (alias != null ? alias.getName() : entity.getIdentifier().toString());
paintLabel(graphics, point, label, (int)(icon.getIconWidth() / 2), 0);
/**
* Cleanup
*/
graphics.dispose();
}
}
/**
* Optional alias that matches the identifier for the entity history
*/
private List<Alias> getAliases(PlottableEntityHistory entityHistory)
{
AliasList aliasList = mAliasModel.getAliasList(entityHistory.getIdentifierCollection());
if(aliasList != null)
{
return aliasList.getAliases(entityHistory.getIdentifier());
}
return Collections.EMPTY_LIST;
}
private ImageIcon getIcon(Alias alias)
{
String iconName = (alias != null ? alias.getIconName() : null);
return mIconModel.getIcon(iconName, IconModel.DEFAULT_ICON_SIZE);
}
private void paintIcon(Graphics2D graphics, Point2D point, ImageIcon icon)
{
graphics.drawImage(icon.getImage(), (int)point.getX() - (icon.getIconWidth() / 2),
(int)point.getY() - (icon.getIconHeight() / 2), null);
}
private void paintLabel(Graphics2D graphics, Point2D point, String label, int xOffset, int yOffset)
{
graphics.drawString(label, (int)point.getX() + xOffset, (int)point.getY() + yOffset);
}
/**
* Paints a two-tone route from the entity's list of plottables (locations).
* using black as a wider background route, and the entity's preferred color
* as a narrower foreground route.
*/
private void paintRoute(Graphics2D graphics, JXMapViewer viewer, PlottableEntityHistory entity, Color color)
{
List<TimestampedGeoPosition> locations = entity.getTrackHistoryModel().getTrackHistory();
if(!locations.isEmpty())
{
// Draw the route with a black background line
graphics.setColor(Color.BLACK);
graphics.setStroke(new BasicStroke(3));
drawRoute(locations, graphics, viewer);
// Draw the route again, in the entity's preferred color
graphics.setColor(color);
graphics.setStroke(new BasicStroke(1));
drawRoute(locations, graphics, viewer);
}
}
/**
* Draws a route from a list of plottables
*/
private void drawRoute(List<TimestampedGeoPosition> locations, Graphics2D g, JXMapViewer viewer)
{
Point2D previousPoint = null;
int length = Math.min(locations.size(), mTrackHistoryLength);
for(int x = 0; x < length; x++)
{
GeoPosition location = locations.get(x);
// convert geo-coordinate to world bitmap pixel
Point2D currentPoint = viewer.getTileFactory().geoToPixel(location, viewer.getZoom());
if(previousPoint != null)
{
g.drawLine((int)previousPoint.getX(), (int)previousPoint.getY(), (int)currentPoint.getX(), (int)currentPoint.getY());
}
previousPoint = currentPoint;
}
}
}

View File

@@ -0,0 +1,187 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.map;
import io.github.dsheirer.preference.radioreference.RadioReferencePreference;
import io.github.dsheirer.rrapi.type.Coverage;
import io.github.dsheirer.service.radioreference.DistanceFormat;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* HTML card with the details of radio reference trunked system sites, shown when the mouse is over a site's tower on
* the map: the system and protocol, the site, and the site's channels.
*/
public final class RadioReferenceSiteCard
{
private static final int MAX_SITES = 3;
private static final int CHANNEL_COLUMNS = 3;
private static final int MAX_CHANNELS = 24;
private static final String SEPARATOR = " &middot; ";
private RadioReferenceSiteCard()
{
}
/**
* Card for the sites
* @param sites under the mouse, nearest first
* @param location of the user, for the distances, or null
* @return HTML for a tooltip
*/
public static String html(List<SiteRecord> sites, RadioReferencePreference.Location location)
{
DecimalFormat frequencyFormat = new DecimalFormat("0.00000");
StringBuilder sb = new StringBuilder("<html><body style='padding:3px'>");
int shown = Math.min(sites.size(), MAX_SITES);
for(int index = 0; index < shown; index++)
{
SiteRecord site = sites.get(index);
if(index > 0)
{
sb.append("<hr>");
}
sb.append("<div><b>").append(escape(site.systemName() != null ? site.systemName() : "(unnamed system)"))
.append("</b></div>");
appendLine(sb, site.protocol(), site.voice());
String siteName = "Site " + site.siteNumber();
String distance = location != null ? DistanceFormat.format(Coverage.distanceKilometers(
location.latitude(), location.longitude(), site.latitude(), site.longitude())) : null;
appendLine(sb, siteName, site.description(), site.county(), distance);
appendLine(sb, site.nac() != null ? "NAC " + site.nac() : null,
site.rfss() > 0 ? "RFSS " + site.rfss() : null, site.zone() > 0 ? "Zone " + site.zone() : null);
appendChannels(sb, site.channels(), frequencyFormat);
}
if(sites.size() > shown)
{
sb.append("<hr><div>+ ").append(sites.size() - shown).append(" more site")
.append(sites.size() - shown > 1 ? "s" : "").append(" here</div>");
}
sb.append("</body></html>");
return sb.toString();
}
/**
* Channels in columns, control channels marked C and alternate control channels marked A
*/
private static void appendChannels(StringBuilder sb, List<SiteRecord.SiteChannel> channels,
DecimalFormat frequencyFormat)
{
if(channels == null || channels.isEmpty())
{
return;
}
int shown = Math.min(channels.size(), MAX_CHANNELS);
boolean control = false;
sb.append("<table cellspacing='0' cellpadding='1'>");
for(int index = 0; index < shown; index++)
{
if(index % CHANNEL_COLUMNS == 0)
{
sb.append("<tr>");
}
SiteRecord.SiteChannel channel = channels.get(index);
sb.append("<td style='padding-right:8px'>").append(frequencyFormat.format(channel.frequencyHz() / 1E6));
if("Control".equals(channel.use()))
{
sb.append(" <b>C</b>");
control = true;
}
else if("Alternate control".equals(channel.use()))
{
sb.append(" <b>A</b>");
control = true;
}
sb.append("</td>");
if(index % CHANNEL_COLUMNS == CHANNEL_COLUMNS - 1)
{
sb.append("</tr>");
}
}
if(shown % CHANNEL_COLUMNS != 0)
{
sb.append("</tr>");
}
sb.append("</table>");
List<String> notes = new ArrayList<>();
if(channels.size() > shown)
{
notes.add("+ " + (channels.size() - shown) + " more channels");
}
if(control)
{
notes.add("C control, A alternate control");
}
if(!notes.isEmpty())
{
appendLine(sb, notes.toArray(new String[0]));
}
}
/**
* Appends a line with the non-empty values separated by dots, or nothing when all are empty
*/
private static void appendLine(StringBuilder sb, String... values)
{
StringBuilder line = new StringBuilder();
for(String value: values)
{
if(value != null && !value.isBlank())
{
if(!line.isEmpty())
{
line.append(SEPARATOR);
}
line.append(escape(value));
}
}
if(!line.isEmpty())
{
sb.append("<div>").append(line).append("</div>");
}
}
private static String escape(String text)
{
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
}

View File

@@ -0,0 +1,184 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.map;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.painter.AbstractPainter;
/**
* Paints a radio tower at each radio reference trunked system site, with the base of the tower at the site location.
*/
public class RadioReferenceSitePainter extends AbstractPainter<JXMapViewer>
{
private static final Color TOWER = new Color(240, 128, 32);
private static final Color OUTLINE = new Color(40, 40, 40, 200);
private static final Stroke TOWER_STROKE = new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
private static final Stroke OUTLINE_STROKE = new BasicStroke(3.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
private static final double HEIGHT = 16;
private static final double HALF_BASE = 5;
//Hit area around the tower, in pixels from the site location
private static final Rectangle HIT_AREA = new Rectangle(-10, -24, 20, 28);
private final Supplier<List<SiteRecord>> mSites;
private volatile boolean mShowSites = true;
/**
* Constructs an instance
* @param sites to paint, read each time the map is painted
*/
public RadioReferenceSitePainter(Supplier<List<SiteRecord>> sites)
{
mSites = sites;
setAntialiasing(true);
setCacheable(false);
}
/**
* Shows or hides the sites
*/
public void setShowSites(boolean show)
{
mShowSites = show;
}
public boolean isShowSites()
{
return mShowSites;
}
/**
* Sites whose tower is under the point, nearest first
* @param map viewer
* @param point in the viewer
* @return sites, or an empty list when the sites are hidden or none is under the point
*/
public List<SiteRecord> getSitesAt(JXMapViewer map, Point point)
{
if(!mShowSites)
{
return Collections.emptyList();
}
Rectangle viewport = map.getViewportBounds();
List<SiteRecord> sites = new ArrayList<>();
List<Double> distances = new ArrayList<>();
for(SiteRecord site: mSites.get())
{
Point2D pixel = map.getTileFactory().geoToPixel(new GeoPosition(site.latitude(), site.longitude()),
map.getZoom());
double dx = point.x - (pixel.getX() - viewport.getX());
double dy = point.y - (pixel.getY() - viewport.getY());
if(HIT_AREA.contains(dx, dy))
{
//Nearest to the middle of the tower first
double distance = Math.hypot(dx, dy + (HEIGHT / 2.0));
int index = 0;
while(index < distances.size() && distances.get(index) <= distance)
{
index++;
}
sites.add(index, site);
distances.add(index, distance);
}
}
return sites;
}
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
if(!mShowSites)
{
return;
}
Rectangle viewport = map.getViewportBounds();
for(SiteRecord site: mSites.get())
{
Point2D pixel = map.getTileFactory().geoToPixel(new GeoPosition(site.latitude(), site.longitude()),
map.getZoom());
double x = pixel.getX() - viewport.getX();
double y = pixel.getY() - viewport.getY();
if(x >= -20 && x <= width + 20 && y >= -4 && y <= height + 30)
{
paintTower(g, x, y);
}
}
}
/**
* Paints a tower with its base at the point: an A-frame mast with a cross brace and radio waves at the top
*/
private static void paintTower(Graphics2D g, double x, double y)
{
double top = y - HEIGHT;
Path2D mast = new Path2D.Double();
mast.moveTo(x - HALF_BASE, y);
mast.lineTo(x, top);
mast.lineTo(x + HALF_BASE, y);
mast.moveTo(x - (HALF_BASE * 0.55), y - (HEIGHT * 0.45));
mast.lineTo(x + (HALF_BASE * 0.55), y - (HEIGHT * 0.45));
Arc2D leftInner = new Arc2D.Double(x - 5, top - 4, 10, 8, 135, 90, Arc2D.OPEN);
Arc2D rightInner = new Arc2D.Double(x - 5, top - 4, 10, 8, -45, 90, Arc2D.OPEN);
Arc2D leftOuter = new Arc2D.Double(x - 9, top - 7, 18, 14, 135, 90, Arc2D.OPEN);
Arc2D rightOuter = new Arc2D.Double(x - 9, top - 7, 18, 14, -45, 90, Arc2D.OPEN);
g.setStroke(OUTLINE_STROKE);
g.setColor(OUTLINE);
g.draw(mast);
g.draw(leftInner);
g.draw(rightInner);
g.draw(leftOuter);
g.draw(rightOuter);
g.setStroke(TOWER_STROKE);
g.setColor(TOWER);
g.draw(mast);
g.draw(leftInner);
g.draw(rightInner);
g.draw(leftOuter);
g.draw(rightOuter);
g.fill(new Ellipse2D.Double(x - 2, top - 2, 4, 4));
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,109 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.painter.AbstractPainter;
/**
* Paints a push-pin at the user's location, with the tip of the pin at the location.
*/
public class UserLocationPainter extends AbstractPainter<JXMapViewer>
{
private static final Color NEEDLE = new Color(90, 90, 90);
private static final Color HEAD = new Color(220, 40, 40);
private static final Color HEAD_OUTLINE = new Color(110, 0, 0);
private static final Color HIGHLIGHT = new Color(255, 255, 255, 170);
private static final Color SHADOW = new Color(0, 0, 0, 70);
private static final double NEEDLE_LENGTH = 14.0;
private static final double HEAD_RADIUS = 7.0;
private volatile GeoPosition mPosition;
/**
* Constructs an instance
*/
public UserLocationPainter()
{
setAntialiasing(true);
setCacheable(false);
}
/**
* Sets the location to mark
* @param position of the user, or null to remove the pin
*/
public void setPosition(GeoPosition position)
{
mPosition = position;
}
/**
* Location that is marked
* @return position, or null
*/
public GeoPosition getPosition()
{
return mPosition;
}
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
GeoPosition position = mPosition;
if(position == null)
{
return;
}
Rectangle viewportBounds = map.getViewportBounds();
Point2D point = map.getTileFactory().geoToPixel(position, map.getZoom());
double x = point.getX() - viewportBounds.getX();
double y = point.getY() - viewportBounds.getY();
double headY = y - NEEDLE_LENGTH - HEAD_RADIUS;
//Shadow where the needle enters the map, so the tip reads as the location
g.setColor(SHADOW);
g.fill(new Ellipse2D.Double(x - 4, y - 2, 8, 4));
g.setColor(NEEDLE);
g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.draw(new Line2D.Double(x, y, x, headY));
Ellipse2D head = new Ellipse2D.Double(x - HEAD_RADIUS, headY - HEAD_RADIUS, HEAD_RADIUS * 2, HEAD_RADIUS * 2);
g.setColor(HEAD);
g.fill(head);
g.setColor(HEAD_OUTLINE);
g.setStroke(new BasicStroke(1.0f));
g.draw(head);
g.setColor(HIGHLIGHT);
g.fill(new Ellipse2D.Double(x - HEAD_RADIUS / 2 - 1, headY - HEAD_RADIUS / 2 - 1, 4, 4));
}
}

View File

@@ -108,7 +108,7 @@ import io.github.dsheirer.source.tuner.channel.rotation.AddChannelRotationActive
import io.github.dsheirer.util.PacketUtil; import io.github.dsheirer.util.PacketUtil;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

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

View File

@@ -52,7 +52,6 @@ public class DMRSoftSyncDetectorFactory
case VECTOR_SIMD_512: case VECTOR_SIMD_512:
return new DMRSoftSyncDetectorVector512(); return new DMRSoftSyncDetectorVector512();
case SCALAR: case SCALAR:
case UNCALIBRATED:
default: default:
return new DMRSoftSyncDetectorScalar(); return new DMRSoftSyncDetectorScalar();
} }

View File

@@ -22,7 +22,7 @@ package io.github.dsheirer.module.decode.event;
import io.github.dsheirer.channel.IChannelDescriptor; import io.github.dsheirer.channel.IChannelDescriptor;
import io.github.dsheirer.identifier.IdentifierCollection; import io.github.dsheirer.identifier.IdentifierCollection;
import io.github.dsheirer.protocol.Protocol; import io.github.dsheirer.protocol.Protocol;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
public class PlottableDecodeEvent extends DecodeEvent public class PlottableDecodeEvent extends DecodeEvent
{ {

View File

@@ -22,7 +22,7 @@ package io.github.dsheirer.module.decode.fleetsync2.message;
import io.github.dsheirer.bits.CorrectedBinaryMessage; import io.github.dsheirer.bits.CorrectedBinaryMessage;
import io.github.dsheirer.identifier.Identifier; import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;

View File

@@ -75,9 +75,6 @@ import io.github.dsheirer.module.decode.nxdn.layer3.mobility.RegistrationCommand
import io.github.dsheirer.module.decode.nxdn.layer3.mobility.RegistrationResponse; import io.github.dsheirer.module.decode.nxdn.layer3.mobility.RegistrationResponse;
import io.github.dsheirer.module.decode.nxdn.layer3.mobility.RegistrationResponseTypeD; import io.github.dsheirer.module.decode.nxdn.layer3.mobility.RegistrationResponseTypeD;
import io.github.dsheirer.module.decode.nxdn.layer3.proprietary.TalkerAliasComplete; import io.github.dsheirer.module.decode.nxdn.layer3.proprietary.TalkerAliasComplete;
import io.github.dsheirer.module.decode.nxdn.layer3.scch.Information1;
import io.github.dsheirer.module.decode.nxdn.layer3.scch.InitializationVectorPart1;
import io.github.dsheirer.module.decode.nxdn.layer3.type.CipherType;
import io.github.dsheirer.protocol.Protocol; import io.github.dsheirer.protocol.Protocol;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -291,9 +288,8 @@ public class NXDNDecoderState extends DecoderState
{ {
//Controller responds to a voice call request with either a channel grant, or this message if //Controller responds to a voice call request with either a channel grant, or this message if
//it can't support the call or the called party is not available //it can't support the call or the called party is not available
//Type-D call response doesn't carry a cause.
broadcastEvent(vcr.getIdentifiers(), vcr.getTimestamp(), DecodeEventType.RESPONSE, broadcastEvent(vcr.getIdentifiers(), vcr.getTimestamp(), DecodeEventType.RESPONSE,
vcr.isTypeD() ? "CALL RESPONSE" : "VOICE CALL REQUEST - RESPONSE:" + vcr.getCause()); "VOICE CALL REQUEST - RESPONSE:" + vcr.getCause().toString());
} }
break; break;
case TRAFFIC_OUT_01_CC_VOICE_CALL: case TRAFFIC_OUT_01_CC_VOICE_CALL:
@@ -730,24 +726,6 @@ public class NXDNDecoderState extends DecoderState
break; break;
} }
//Messages that don't otherwise change the state (e.g. Type-D SCCH) but are carried in a frame that also carries
//voice are a continuation of the call. Otherwise, the ACTIVE state toggles the channel out of CALL state on
//every voice frame, squelching the audio module which then discards the call audio.
if(state == State.ACTIVE && event == DecoderStateEvent.Event.DECODE && layer3.getLICH().hasAudio())
{
//Type-D only sends the VOICE CALL at the start of a call. When we join late, or miss it, use the SCCH call
//info or initialization vector to determine the encryption state.
if(!mEncryptedCallStateDetermined && layer3 instanceof Information1 info1)
{
mEncryptedCallStateDetermined = true;
mEncryptedCall = info1 instanceof InitializationVectorPart1 ||
info1.getCipherType() != CipherType.UNENCRYPTED;
}
state = (mEncryptedCallStateDetermined && mEncryptedCall) ? State.ENCRYPTED : State.CALL;
event = DecoderStateEvent.Event.CONTINUATION;
}
broadcast(new DecoderStateEvent(this, event, state)); broadcast(new DecoderStateEvent(this, event, state));
} }

View File

@@ -27,10 +27,8 @@ import io.github.dsheirer.module.decode.nxdn.layer3.call.Audio;
import io.github.dsheirer.module.decode.nxdn.layer3.call.Disconnect; import io.github.dsheirer.module.decode.nxdn.layer3.call.Disconnect;
import io.github.dsheirer.module.decode.nxdn.layer3.call.TransmissionRelease; import io.github.dsheirer.module.decode.nxdn.layer3.call.TransmissionRelease;
import io.github.dsheirer.module.decode.nxdn.layer3.call.VoiceCall; import io.github.dsheirer.module.decode.nxdn.layer3.call.VoiceCall;
import io.github.dsheirer.module.decode.nxdn.layer3.scch.Information1; import io.github.dsheirer.module.decode.nxdn.layer3.call.VoiceCallWithOptionalLocation;
import io.github.dsheirer.module.decode.nxdn.layer3.scch.InitializationVectorPart1;
import io.github.dsheirer.module.decode.nxdn.layer3.type.AudioCodec; import io.github.dsheirer.module.decode.nxdn.layer3.type.AudioCodec;
import io.github.dsheirer.module.decode.nxdn.layer3.type.CipherType;
import io.github.dsheirer.preference.UserPreferences; import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.sample.Listener; import io.github.dsheirer.sample.Listener;
import java.util.ArrayList; import java.util.ArrayList;
@@ -102,18 +100,11 @@ public class NXDNAudioModule extends AmbeAudioModule
mAudioCodec = voiceCall.getCallOption().getCodec(); mAudioCodec = voiceCall.getCallOption().getCodec();
processCachedAudio(); processCachedAudio();
} }
//Note: VoiceCallWithOptionalLocation subclasses (request, response, assignment, etc.) don't carry the else if(message instanceof VoiceCallWithOptionalLocation voiceCall)
//cipher type and key ID, so they can't be used to establish the encryption state.
else if(!mEncryptedCallStateEstablished && message instanceof Information1 info1 &&
info1.getLICH().hasAudio())
{ {
//Type-D only sends the VOICE CALL message at the start of the call. Use the SCCH call info or mEncryptedCall = voiceCall.getEncryptionKeyIdentifier().isEncrypted();
//initialization vector from a voice frame to establish the encryption state when we join a call
//late, or when the VOICE CALL message was missed. Type-D only supports AMBE+ half-rate.
mEncryptedCall = info1 instanceof InitializationVectorPart1 ||
info1.getCipherType() != CipherType.UNENCRYPTED;
mEncryptedCallStateEstablished = true; mEncryptedCallStateEstablished = true;
mAudioCodec = AudioCodec.HALF_RATE; mAudioCodec = voiceCall.getCallOption().getCodec();
processCachedAudio(); processCachedAudio();
} }
else if(message instanceof Disconnect || message instanceof TransmissionRelease) else if(message instanceof Disconnect || message instanceof TransmissionRelease)

View File

@@ -51,7 +51,6 @@ public class NXDNSyncDetectorFactory
case VECTOR_SIMD_512: case VECTOR_SIMD_512:
return new NXDNSoftSyncDetectorVector512(); return new NXDNSoftSyncDetectorVector512();
case SCALAR: case SCALAR:
case UNCALIBRATED:
default: default:
return new NXDNSoftSyncDetectorScalar(); return new NXDNSoftSyncDetectorScalar();
} }

View File

@@ -25,25 +25,15 @@ import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.module.decode.nxdn.layer2.LICH; import io.github.dsheirer.module.decode.nxdn.layer2.LICH;
import io.github.dsheirer.module.decode.nxdn.layer3.NXDNMessageType; import io.github.dsheirer.module.decode.nxdn.layer3.NXDNMessageType;
import io.github.dsheirer.module.decode.nxdn.layer3.type.CauseVD; import io.github.dsheirer.module.decode.nxdn.layer3.type.CauseVD;
import io.github.dsheirer.module.decode.nxdn.layer3.type.SystemID;
import java.util.List; import java.util.List;
/** /**
* Voice call response (VCALL_RESP) or Type-D call response (CALL_RESP). * Voice call response
*
* Note: the Type-D call response (NXDN TS 1-E, Figure 6.4-21) has no cause or cipher fields. Instead, octets 7-9
* optionally carry a System ID Option and System ID when the CC Option indicates a multi trunked system.
*/ */
public class VoiceCallResponse extends VoiceCallWithOptionalLocation public class VoiceCallResponse extends VoiceCallWithOptionalLocation
{ {
private static final IntField CAUSE_VD = IntField.length8(OCTET_7); private static final IntField CAUSE_VD = IntField.length8(OCTET_7);
private static final int LOCATION_ID_OFFSET = OCTET_8; private static final int LOCATION_ID_OFFSET = OCTET_8;
private static final int TYPE_D_MASK_MULTI_TRUNKED_SYSTEM = 0x10; //CC Option T-Type flag
private static final IntField TYPE_D_SYSTEM_ID_RELATED_UNIT = IntField.length2(OCTET_7);
private static final int TYPE_D_SYSTEM_ID_OFFSET = OCTET_7 + 5;
private static final int TYPE_D_RELATED_UNIT_SOURCE = 2;
private static final int TYPE_D_RELATED_UNIT_DESTINATION = 1;
private SystemID mTypeDSystemID;
/** /**
* Constructs an instance * Constructs an instance
@@ -68,11 +58,6 @@ public class VoiceCallResponse extends VoiceCallWithOptionalLocation
@Override @Override
public String toString() public String toString()
{ {
if(isTypeD())
{
return toStringTypeD();
}
StringBuilder sb = getMessageBuilder(); StringBuilder sb = getMessageBuilder();
if(getCallControlOption().isEmergency()) if(getCallControlOption().isEmergency())
@@ -103,124 +88,28 @@ public class VoiceCallResponse extends VoiceCallWithOptionalLocation
sb.append(" FROM:").append(getSource()); sb.append(" FROM:").append(getSource());
sb.append(" TO:").append(getDestination()); sb.append(" TO:").append(getDestination());
sb.append(" ").append(getEncryptionKeyIdentifier()); sb.append(" ").append(getEncryptionKeyIdentifier());
if(isTypeD())
{
sb.append(" FREE REPEATER:").append(getMessage().getInt(CALL_OPTION));
}
sb.append(" ").append(getCallOption()); sb.append(" ").append(getCallOption());
return sb.toString(); return sb.toString();
} }
/**
* Type-D call response formatted as a string.
*/
private String toStringTypeD()
{
StringBuilder sb = getMessageBuilder();
if(getCallControlOption().isEmergency())
{
sb.append("EMERGENCY ");
}
if(getCallControlOption().isPriorityPaging())
{
sb.append("PRIORITY ");
}
sb.append("TYPE-D ").append(getCallType()).append(" CALL RESPONSE");
sb.append(" FROM:").append(getSource());
sb.append(" TO:").append(getDestination());
if(hasTypeDSystemID())
{
sb.append(" MULTI-SYSTEM ").append(getTypeDSystemID());
if(isTypeDSystemIDForSource())
{
sb.append(" (SOURCE)");
}
else if(isTypeDSystemIDForDestination())
{
sb.append(" (DESTINATION)");
}
}
sb.append(" FREE REPEATER:").append(getFreeRepeater());
sb.append(" ").append(getCallOption());
return sb.toString();
}
/**
* Type-D free repeater number.
*/
public int getFreeRepeater()
{
return getMessage().getInt(CALL_OPTION);
}
/**
* Indicates if this Type-D call response carries the optional System ID, which is present for a multi trunked
* system.
*/
public boolean hasTypeDSystemID()
{
return isTypeD() && (getCallControlOption().value() & TYPE_D_MASK_MULTI_TRUNKED_SYSTEM) ==
TYPE_D_MASK_MULTI_TRUNKED_SYSTEM;
}
/**
* Optional Type-D System ID.
* @return system ID or null if the message doesn't carry a system ID.
*/
public SystemID getTypeDSystemID()
{
if(mTypeDSystemID == null && hasTypeDSystemID())
{
mTypeDSystemID = new SystemID(getMessage(), TYPE_D_SYSTEM_ID_OFFSET);
}
return mTypeDSystemID;
}
/**
* Indicates if the Type-D System ID relates to the source unit.
*/
public boolean isTypeDSystemIDForSource()
{
return hasTypeDSystemID() && getMessage().getInt(TYPE_D_SYSTEM_ID_RELATED_UNIT) == TYPE_D_RELATED_UNIT_SOURCE;
}
/**
* Indicates if the Type-D System ID relates to the destination unit.
*/
public boolean isTypeDSystemIDForDestination()
{
return hasTypeDSystemID() &&
getMessage().getInt(TYPE_D_SYSTEM_ID_RELATED_UNIT) == TYPE_D_RELATED_UNIT_DESTINATION;
}
/** /**
* Amplifying cause for the response. * Amplifying cause for the response.
* @return cause, or UNKNOWN for a Type-D call response which doesn't carry a cause.
*/ */
public CauseVD getCause() public CauseVD getCause()
{ {
if(isTypeD())
{
return CauseVD.UNKNOWN;
}
return CauseVD.fromValue(getMessage().getInt(CAUSE_VD)); return CauseVD.fromValue(getMessage().getInt(CAUSE_VD));
} }
@Override @Override
public List<Identifier> getIdentifiers() public List<Identifier> getIdentifiers()
{ {
if(isTypeD())
{
//Type-D call response doesn't carry an encryption key
return List.of(getSource(), getDestination());
}
return List.of(getSource(), getDestination(), getEncryptionKeyIdentifier()); return List.of(getSource(), getDestination(), getEncryptionKeyIdentifier());
} }
} }

View File

@@ -30,7 +30,7 @@ import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
/** /**
* JVC/Kenwood NEXEDGE GPS position report. * JVC/Kenwood NEXEDGE GPS position report.

View File

@@ -175,7 +175,7 @@ import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.util.PacketUtil; import io.github.dsheirer.util.PacketUtil;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@@ -34,7 +34,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
/** /**
* L3Harris Talker GPS Complete. This message is assembled from FLC L3Harris Talker GPS Block 1 and Block 2. * L3Harris Talker GPS Complete. This message is assembled from FLC L3Harris Talker GPS Block 1 and Block 2.

View File

@@ -26,7 +26,7 @@ import io.github.dsheirer.module.decode.dmr.identifier.P25Location;
import io.github.dsheirer.module.decode.p25.phase1.message.lc.LinkControlWord; import io.github.dsheirer.module.decode.p25.phase1.message.lc.LinkControlWord;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
/** /**
* Motorola Unit Self-Reported GPS Location * Motorola Unit Self-Reported GPS Location

View File

@@ -52,7 +52,6 @@ public class P25P1SoftSyncDetectorFactory
case VECTOR_SIMD_512: case VECTOR_SIMD_512:
return new P25P1SoftSyncDetectorVector512(); return new P25P1SoftSyncDetectorVector512();
case SCALAR: case SCALAR:
case UNCALIBRATED:
default: default:
return new P25P1SoftSyncDetectorScalar(); return new P25P1SoftSyncDetectorScalar();
} }

View File

@@ -29,7 +29,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
/** /**
* L3Harris Talker GPS Location. * L3Harris Talker GPS Location.

View File

@@ -32,7 +32,7 @@ import io.github.dsheirer.module.decode.event.PlottableDecodeEvent;
import io.github.dsheirer.module.decode.tait.identifier.TaitIdentifier; import io.github.dsheirer.module.decode.tait.identifier.TaitIdentifier;
import io.github.dsheirer.protocol.Protocol; import io.github.dsheirer.protocol.Protocol;
import java.util.TreeSet; import java.util.TreeSet;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
public class Tait1200DecoderState extends DecoderState public class Tait1200DecoderState extends DecoderState
{ {

View File

@@ -25,7 +25,7 @@ import io.github.dsheirer.identifier.Identifier;
import io.github.dsheirer.message.Message; import io.github.dsheirer.message.Message;
import io.github.dsheirer.module.decode.tait.identifier.TaitIdentifier; import io.github.dsheirer.module.decode.tait.identifier.TaitIdentifier;
import io.github.dsheirer.protocol.Protocol; import io.github.dsheirer.protocol.Protocol;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@@ -40,21 +40,9 @@ public class MapPreference extends Preference
*/ */
public static final int DEFAULT_ZOOM = 7; public static final int DEFAULT_ZOOM = 7;
/**
* Range of OpenStreetMap tile zoom levels the map shows
*/
public static final int MINIMUM_TILE_ZOOM = 2;
public static final int MAXIMUM_TILE_ZOOM = 19;
/**
* Tile zoom level plus the stored zoom level, for the original Swing map viewer's inverted zoom scale
*/
private static final int TILE_ZOOM_OFFSET = 19;
private static final String CENTER = "center"; private static final String CENTER = "center";
private static final String ZOOM = "zoom"; private static final String ZOOM = "zoom";
private static final String SHOW_RADIO_REFERENCE_SITES = "show.radioreference.sites"; private static final String SHOW_RADIO_REFERENCE_SITES = "show.radioreference.sites";
private static final String TILE_SERVER = "tile.server";
private static final String TILE_SERVER_KEY = "tile.server.key.";
private static final String TILE_STYLE = "tile.style";
private final Preferences mPreferences = Preferences.userNodeForPackage(MapPreference.class); private final Preferences mPreferences = Preferences.userNodeForPackage(MapPreference.class);
/** /**
@@ -157,27 +145,6 @@ public class MapPreference extends Preference
} }
} }
/**
* Last zoom level of the map as an OpenStreetMap tile zoom level, where 0 shows the whole world in one tile and
* higher levels are closer. The stored zoom level uses the inverted scale of the original Swing map viewer,
* where the tile zoom level is {@link #TILE_ZOOM_OFFSET} minus the stored level, so existing views carry over.
* Can be called from any thread.
* @return tile zoom level, {@link #MINIMUM_TILE_ZOOM} to {@link #MAXIMUM_TILE_ZOOM}
*/
public int getTileZoom()
{
return Math.clamp(TILE_ZOOM_OFFSET - getZoom(), MINIMUM_TILE_ZOOM, MAXIMUM_TILE_ZOOM);
}
/**
* Stores the zoom level of the map as an OpenStreetMap tile zoom level
* @param tileZoom level, clamped to {@link #MINIMUM_TILE_ZOOM} to {@link #MAXIMUM_TILE_ZOOM}
*/
public void setTileZoom(int tileZoom)
{
setZoom(TILE_ZOOM_OFFSET - Math.clamp(tileZoom, MINIMUM_TILE_ZOOM, MAXIMUM_TILE_ZOOM));
}
/** /**
* Indicates if the map shows the radio reference trunked system sites near the user * Indicates if the map shows the radio reference trunked system sites near the user
*/ */
@@ -198,82 +165,6 @@ public class MapPreference extends Preference
} }
} }
/**
* Identifier of the map tile server
* @return identifier, or null when none was chosen
*/
public String getTileServer()
{
return mPreferences.get(TILE_SERVER, null);
}
/**
* Stores the identifier of the map tile server
*/
public void setTileServer(String id)
{
if(id != null && !id.equals(getTileServer()))
{
mPreferences.put(TILE_SERVER, id);
notifyPreferenceUpdated();
}
}
/**
* Style of the map tiles: following the theme, light or dark
* @return style name, or null when none was chosen
*/
public String getTileStyle()
{
return mPreferences.get(TILE_STYLE, null);
}
/**
* Stores the style of the map tiles
*/
public void setTileStyle(String style)
{
if(style != null && !style.equals(getTileStyle()))
{
mPreferences.put(TILE_STYLE, style);
notifyPreferenceUpdated();
}
}
/**
* Key the user entered for a map tile server that needs one
* @param id of the tile server
* @return key, or null
*/
public String getTileServerKey(String id)
{
return mPreferences.get(TILE_SERVER_KEY + id, null);
}
/**
* Stores the key for a map tile server, or removes it when it's blank
* @param id of the tile server
* @param key for the server, or null
*/
public void setTileServerKey(String id, String key)
{
String value = key != null && !key.isBlank() ? key.strip() : null;
if(!Objects.equals(value, getTileServerKey(id)))
{
if(value != null)
{
mPreferences.put(TILE_SERVER_KEY + id, value);
}
else
{
mPreferences.remove(TILE_SERVER_KEY + id);
}
notifyPreferenceUpdated();
}
}
/** /**
* Moves the map view stored in the settings file by older versions of the application into this preference. * Moves the map view stored in the settings file by older versions of the application into this preference.
* Does nothing once a center point is stored here. * Does nothing once a center point is stored here.

View File

@@ -20,7 +20,7 @@ package io.github.dsheirer.settings;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
/** /**
* Map view stored in the settings file by older versions of the application. Only read so that settings files from * Map view stored in the settings file by older versions of the application. Only read so that settings files from

View File

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

View File

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

View File

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

View File

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

View File

@@ -656,8 +656,6 @@ public class TunerManager implements IDiscoveredTunerStatusListener
if(source != null) if(source != null)
{ {
source.setTunerName(discoveredTuner.getTuner().getPreferredName()); source.setTunerName(discoveredTuner.getTuner().getPreferredName());
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
.getNoiseFloorEstimator());
return source; return source;
} }
} }
@@ -687,8 +685,6 @@ public class TunerManager implements IDiscoveredTunerStatusListener
if(source != null) if(source != null)
{ {
source.setTunerName(discoveredTuner.getTuner().getPreferredName()); source.setTunerName(discoveredTuner.getTuner().getPreferredName());
source.setNoiseFloorEstimator(discoveredTuner.getTuner().getTunerController()
.getNoiseFloorEstimator());
} }
} }
catch(Exception e) catch(Exception e)

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2023 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -70,7 +70,7 @@ public class RspNativeBuffer extends AbstractNativeBuffer
@Override @Override
public int sampleCount() public int sampleCount()
{ {
return mISamples.length; return mISamples.length * 2;
} }
/** /**

View File

@@ -1,187 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.spectrum;
import java.util.function.Consumer;
import java.util.function.DoubleSupplier;
/**
* Measures a channel's power within the channel bandwidth from dBFS spectrum frames and compares it to the tuner noise
* floor to produce the channel's signal level and signal-to-noise ratio.
*
* Uses the spectrum frames that a channel spectral display already calculates, so the measurement costs only a sum
* over the in-band bins of each frame. The frames come from a FullScaleDecibelConverter, lowest frequency first, with
* the channel centered in the frame. Each bin's power is the window's noise bandwidth times the noise power per bin
* width, so the in-band power is the sum of the in-band bin powers divided by the window noise bandwidth (in bins).
* That is also correct for a tone, whose power spreads across the main lobe bins by the same factor.
*
* Frames are averaged and a reading is produced every 500 milliseconds.
*
* Receive frames on one thread. The configuration can change from any thread.
*/
public class ChannelSignalMeter implements DFTResultsListener
{
private static final long READING_INTERVAL_MS = 500;
/**
* Channel measurement configuration.
* @param sampleRate of the channel samples
* @param bandwidth of the channel in Hertz
* @param noiseDensity supplier of the tuner noise density in full-scale units per Hertz, or NaN when unknown
*/
private record Configuration(double sampleRate, int bandwidth, DoubleSupplier noiseDensity) {}
/**
* Channel signal reading.
* @param dbfs channel power (signal plus noise) within the channel bandwidth, relative to full scale
* @param snr signal-to-noise ratio in dB, or NaN when the noise floor is unknown. Negative infinity when the
* channel power doesn't exceed the noise floor.
* @param noiseDbfs noise floor within the channel bandwidth, relative to full scale, or NaN when unknown
*/
public record Reading(double dbfs, double snr, double noiseDbfs)
{
/**
* Indicates if the signal-to-noise ratio is available
*/
public boolean hasSnr()
{
return !Double.isNaN(snr);
}
}
private final Consumer<Reading> mListener;
private final long mReadingInterval;
private volatile Configuration mConfiguration;
private volatile double mWindowNoiseBandwidth = 1.0;
private Configuration mAccumulatorConfiguration;
private double mPowerAccumulator;
private int mFrameCount;
private double mMeasuredBandwidth;
private long mReadingStart;
/**
* Constructs an instance
* @param listener to receive readings on the frame thread
*/
public ChannelSignalMeter(Consumer<Reading> listener)
{
this(listener, READING_INTERVAL_MS);
}
/**
* Constructs an instance with a custom reading interval, for tests.
* @param listener to receive readings on the frame thread
* @param readingInterval in milliseconds, or 0 for a reading from each frame
*/
ChannelSignalMeter(Consumer<Reading> listener, long readingInterval)
{
mListener = listener;
mReadingInterval = readingInterval;
}
/**
* Sets the channel to measure, or clears it.
* @param sampleRate of the channel samples, or 0 to clear the channel
* @param bandwidth of the channel in Hertz, or 0 to clear the channel
* @param noiseDensity supplier of the tuner noise density in full-scale units per Hertz, or null when unavailable
*/
public void setChannel(double sampleRate, int bandwidth, DoubleSupplier noiseDensity)
{
mConfiguration = (sampleRate > 0 && bandwidth > 0) ? new Configuration(sampleRate, bandwidth, noiseDensity) : null;
}
/**
* Sets the noise bandwidth of the DFT window, in bins.
*/
public void setWindowNoiseBandwidth(double noiseBandwidth)
{
mWindowNoiseBandwidth = noiseBandwidth > 0 ? noiseBandwidth : 1.0;
}
/**
* Receives a dBFS spectrum frame for the channel.
*/
@Override
public void receive(float[] frame)
{
Configuration configuration = mConfiguration;
if(configuration == null || frame == null || frame.length == 0)
{
return;
}
long now = System.currentTimeMillis();
//Restart on a channel change
if(configuration != mAccumulatorConfiguration)
{
mAccumulatorConfiguration = configuration;
mPowerAccumulator = 0.0;
mFrameCount = 0;
mReadingStart = now;
}
int bins = frame.length;
double binWidth = configuration.sampleRate() / bins;
int halfWidth = Math.min(bins / 2 - 1, (int)Math.floor(configuration.bandwidth() / 2.0 / binWidth));
int center = bins / 2;
double power = 0.0;
for(int bin = center - halfWidth; bin <= center + halfWidth; bin++)
{
power += Math.pow(10.0, frame[bin] / 10.0);
}
mPowerAccumulator += power / mWindowNoiseBandwidth;
mMeasuredBandwidth = (2 * halfWidth + 1) * binWidth;
mFrameCount++;
if(now - mReadingStart >= mReadingInterval)
{
mListener.accept(getReading(mPowerAccumulator / mFrameCount, mMeasuredBandwidth,
configuration.noiseDensity()));
mPowerAccumulator = 0.0;
mFrameCount = 0;
mReadingStart = now;
}
}
/**
* Creates a reading.
* @param power within the measured bandwidth in full-scale units
* @param measuredBandwidth in Hertz
* @param noiseDensity supplier, or null
*/
static Reading getReading(double power, double measuredBandwidth, DoubleSupplier noiseDensity)
{
double dbfs = 10.0 * Math.log10(power);
double density = noiseDensity != null ? noiseDensity.getAsDouble() : Double.NaN;
if(Double.isFinite(density) && density > 0.0)
{
double noise = density * measuredBandwidth;
double snr = power > noise ? 10.0 * Math.log10((power - noise) / noise) : Double.NEGATIVE_INFINITY;
return new Reading(dbfs, snr, 10.0 * Math.log10(noise));
}
return new Reading(dbfs, Double.NaN, Double.NaN);
}
}

View File

@@ -1,6 +1,6 @@
/* /*
* ***************************************************************************** * *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer * Copyright (C) 2014-2025 Dennis Sheirer
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -31,8 +31,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.ToLongFunction;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -56,9 +54,6 @@ public class Dispatcher<E> implements Listener<E>
private HeartbeatManager mHeartbeatManager; private HeartbeatManager mHeartbeatManager;
private long mDroppedCount = 0; private long mDroppedCount = 0;
private long mLastOverflowLogTimestamp = 0; private long mLastOverflowLogTimestamp = 0;
private final ToLongFunction<E> mWeigher;
private volatile long mMaximumQueuedWeight = Long.MAX_VALUE;
private final AtomicLong mQueuedWeight = new AtomicLong();
/** /**
* Constructs an instance of a Dispatcher with integrated heartbeat support. * Constructs an instance of a Dispatcher with integrated heartbeat support.
@@ -95,7 +90,6 @@ public class Dispatcher<E> implements Listener<E>
mThreadName = threadName; mThreadName = threadName;
mInterval = interval; mInterval = interval;
mQueue = new LinkedTransferQueue<>(); mQueue = new LinkedTransferQueue<>();
mWeigher = null;
} }
/** /**
@@ -109,46 +103,6 @@ public class Dispatcher<E> implements Listener<E>
mThreadName = threadName; mThreadName = threadName;
mInterval = interval; mInterval = interval;
mQueue = new LinkedBlockingQueue<>(maximumQueueSize); mQueue = new LinkedBlockingQueue<>(maximumQueueSize);
mWeigher = null;
}
/**
* Constructs an instance that is bounded by the total weight of the queued elements instead of the element count,
* for when element sizes vary widely, for example sample buffers from different tuners. An element is dropped
* when adding it would exceed the maximum weight, except when nothing is queued, so that an element heavier than
* the maximum is still delivered. Elements count toward the weight until the listener has processed them.
*
* @param threadName to name the dispatcher thread
* @param interval for processing each batch in milliseconds.
* @param weigher to calculate the weight of each element, for example a sample count.
* @param maximumQueuedWeight for the queued elements.
*/
public Dispatcher(String threadName, long interval, ToLongFunction<E> weigher, long maximumQueuedWeight)
{
if(weigher == null)
{
throw new IllegalArgumentException("Weigher cannot be null");
}
mThreadName = threadName;
mInterval = interval;
mQueue = new LinkedTransferQueue<>();
mWeigher = weigher;
setMaximumQueuedWeight(maximumQueuedWeight);
}
/**
* Sets the maximum total weight of the queued elements, for a dispatcher that was constructed with a weigher.
* @param maximumQueuedWeight for the queued elements.
*/
public void setMaximumQueuedWeight(long maximumQueuedWeight)
{
if(maximumQueuedWeight <= 0)
{
throw new IllegalArgumentException("Maximum queued weight must be positive: " + maximumQueuedWeight);
}
mMaximumQueuedWeight = maximumQueuedWeight;
} }
/** /**
@@ -195,27 +149,7 @@ public class Dispatcher<E> implements Listener<E>
return false; return false;
} }
boolean queued; boolean queued = mQueue.offer(e);
if(mWeigher != null)
{
long weight = mWeigher.applyAsLong(e);
long queuedWeight = mQueuedWeight.addAndGet(weight);
if(queuedWeight > mMaximumQueuedWeight && queuedWeight > weight)
{
mQueuedWeight.addAndGet(-weight);
queued = false;
}
else
{
queued = mQueue.offer(e);
}
}
else
{
queued = mQueue.offer(e);
}
if(!queued) if(!queued)
{ {
@@ -255,7 +189,6 @@ public class Dispatcher<E> implements Listener<E>
} }
mQueue.clear(); mQueue.clear();
mQueuedWeight.set(0);
mExecutorService = Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory(mThreadName)); mExecutorService = Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory(mThreadName));
Runnable r = (mHeartbeatManager != null ? new ProcessorWithHeartbeat() : new Processor()); Runnable r = (mHeartbeatManager != null ? new ProcessorWithHeartbeat() : new Processor());
@@ -277,7 +210,6 @@ public class Dispatcher<E> implements Listener<E>
mScheduledFuture.cancel(false); mScheduledFuture.cancel(false);
mScheduledFuture = null; mScheduledFuture = null;
mQueue.clear(); mQueue.clear();
mQueuedWeight.set(0);
} }
if(mExecutorService != null) if(mExecutorService != null)
@@ -327,8 +259,6 @@ public class Dispatcher<E> implements Listener<E>
mListener.getClass() + "]", t); mListener.getClass() + "]", t);
} }
} }
release(element);
} }
} }
} }
@@ -364,19 +294,6 @@ public class Dispatcher<E> implements Listener<E>
mListener.getClass() + "]", t); mListener.getClass() + "]", t);
} }
} }
release(element);
}
}
/**
* Removes the weight of a dequeued element from the queued weight, once the element is processed.
*/
private void release(E element)
{
if(mWeigher != null)
{
mQueuedWeight.addAndGet(-mWeigher.applyAsLong(element));
} }
} }

View File

@@ -25,7 +25,7 @@ import io.github.dsheirer.module.decode.ip.mototrbo.lrrp.LRRPPacket;
import io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token.Point2d; import io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token.Point2d;
import io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token.Token; import io.github.dsheirer.module.decode.ip.mototrbo.lrrp.token.Token;
import io.github.dsheirer.module.decode.ip.udp.UDPPacket; import io.github.dsheirer.module.decode.ip.udp.UDPPacket;
import io.github.dsheirer.map.GeoPosition; import org.jdesktop.swingx.mapviewer.GeoPosition;
/** /**
* Packet utility methods. * Packet utility methods.

View File

@@ -0,0 +1,504 @@
/*
* $Id: AbstractBean.java 4088 2011-11-17 19:53:49Z kschaefe $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.beans;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
/**
* <p>
* A convenience class from which to extend all non-visual AbstractBeans. It
* manages the PropertyChange notification system, making it relatively trivial
* to add support for property change events in getters/setters.
* </p>
*
* <p>
* A non-visual java bean is a Java class that conforms to the AbstractBean
* patterns to allow visual manipulation of the bean's properties and event
* handlers at design-time.
* </p>
*
* <p>
* Here is a simple example bean that contains one property, foo, and the proper
* pattern for implementing property change notification:
*
* <pre><code>
* public class ABean extends AbstractBean {
* private String foo;
*
* public void setFoo(String newFoo) {
* String old = getFoo();
* this.foo = newFoo;
* firePropertyChange(&quot;foo&quot;, old, getFoo());
* }
*
* public String getFoo() {
* return foo;
* }
* }
* </code></pre>
*
* </p>
*
* <p>
* You will notice that "getFoo()" is used in the setFoo method rather than
* accessing "foo" directly for the gets. This is done intentionally so that if
* a subclass overrides getFoo() to return, for instance, a constant value the
* property change notification system will continue to work properly.
* </p>
*
* <p>
* The firePropertyChange method takes into account the old value and the new
* value. Only if the two differ will it fire a property change event. So you
* can be assured from the above code fragment that a property change event will
* only occur if old is indeed different from getFoo()
* </p>
*
* <p>
* <code>AbstractBean</code> also supports vetoable
* {@link PropertyChangeEvent} events. These events are similar to
* <code>PropertyChange</code> events, except a special exception can be used
* to veto changing the property. For example, perhaps the property is changing
* from "fred" to "red", but a listener deems that "red" is unexceptable. In
* this case, the listener can fire a veto exception and the property must
* remain "fred". For example:
*
* <pre><code>
* public class ABean extends AbstractBean {
* private String foo;
*
* public void setFoo(String newFoo) throws PropertyVetoException {
* String old = getFoo();
* this.foo = newFoo;
* fireVetoableChange(&quot;foo&quot;, old, getFoo());
* }
* public String getFoo() {
* return foo;
* }
* }
*
* public class Tester {
* public static void main(String... args) {
* try {
* ABean a = new ABean();
* a.setFoo(&quot;fred&quot;);
* a.addVetoableChangeListener(new VetoableChangeListener() {
* public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
* if (&quot;red&quot;.equals(evt.getNewValue()) {
* throw new PropertyVetoException(&quot;Cannot be red!&quot;, evt);
* }
* }
* }
* a.setFoo(&quot;red&quot;);
* } catch (Exception e) {
* e.printStackTrace(); // this will be executed
* }
* }
* }
* </code></pre>
*
* </p>
* <p>
* {@code AbstractBean} is not {@link java.io.Serializable}. Special care must
* be taken when creating {@code Serializable} subclasses, as the
* {@code Serializable} listeners will not be saved. Subclasses will need to
* manually save the serializable listeners. The {@link AbstractSerializableBean}
* is {@code Serializable} and already handles the listeners correctly. If
* possible, it is recommended that {@code Serializable} beans should extend
* {@code AbstractSerializableBean}. If it is not possible, the
* {@code AbstractSerializableBean} bean implementation provides details on
* how to correctly serialize an {@code AbstractBean} subclass.
* </p>
*
* @see AbstractSerializableBean
* @status REVIEWED
* @author rbair
*/
@SuppressWarnings("nls")
public abstract class AbstractBean {
/**
* Helper class that manages all the property change notification machinery.
* PropertyChangeSupport cannot be extended directly because it requires
* a bean in the constructor, and the "this" argument is not valid until
* after super construction. Hence, delegation instead of extension
*/
private transient PropertyChangeSupport pcs;
/**
* Helper class that manages all the veto property change notification machinery.
*/
private transient VetoableChangeSupport vcs;
/** Creates a new instance of AbstractBean */
protected AbstractBean() {
pcs = new PropertyChangeSupport(this);
vcs = new VetoableChangeSupport(this);
}
/**
* Creates a new instance of AbstractBean, using the supplied PropertyChangeSupport and
* VetoableChangeSupport delegates. Neither of these may be null.
* @param pcs the property change support
* @param vcs the vetoable change support
*/
protected AbstractBean(PropertyChangeSupport pcs, VetoableChangeSupport vcs) {
if (pcs == null) {
throw new NullPointerException("PropertyChangeSupport must not be null");
}
if (vcs == null) {
throw new NullPointerException("VetoableChangeSupport must not be null");
}
this.pcs = pcs;
this.vcs = vcs;
}
/**
* Add a PropertyChangeListener to the listener list.
* The listener is registered for all properties.
* The same listener object may be added more than once, and will be called
* as many times as it is added.
* If <code>listener</code> is null, no exception is thrown and no action
* is taken.
*
* @param listener The PropertyChangeListener to be added
*/
public final void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
/**
* Remove a PropertyChangeListener from the listener list.
* This removes a PropertyChangeListener that was registered
* for all properties.
* If <code>listener</code> was added more than once to the same event
* source, it will be notified one less time after being removed.
* If <code>listener</code> is null, or was never added, no exception is
* thrown and no action is taken.
*
* @param listener The PropertyChangeListener to be removed
*/
public final void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
/**
* Returns an array of all the listeners that were added to the
* PropertyChangeSupport object with addPropertyChangeListener().
* <p>
* If some listeners have been added with a named property, then
* the returned array will be a mixture of PropertyChangeListeners
* and <code>PropertyChangeListenerProxy</code>s. If the calling
* method is interested in distinguishing the listeners then it must
* test each element to see if it's a
* <code>PropertyChangeListenerProxy</code>, perform the cast, and examine
* the parameter.
*
* <pre>
* PropertyChangeListener[] listeners = bean.getPropertyChangeListeners();
* for (int i = 0; i < listeners.length; i++) {
* if (listeners[i] instanceof PropertyChangeListenerProxy) {
* PropertyChangeListenerProxy proxy =
* (PropertyChangeListenerProxy)listeners[i];
* if (proxy.getPropertyName().equals("foo")) {
* // proxy is a PropertyChangeListener which was associated
* // with the property named "foo"
* }
* }
* }
*</pre>
*
* @see java.beans.PropertyChangeListenerProxy
* @return all of the <code>PropertyChangeListeners</code> added or an
* empty array if no listeners have been added
*/
public final PropertyChangeListener[] getPropertyChangeListeners() {
return pcs.getPropertyChangeListeners();
}
/**
* Add a PropertyChangeListener for a specific property. The listener
* will be invoked only when a call on firePropertyChange names that
* specific property.
* The same listener object may be added more than once. For each
* property, the listener will be invoked the number of times it was added
* for that property.
* If <code>propertyName</code> or <code>listener</code> is null, no
* exception is thrown and no action is taken.
*
* @param propertyName The name of the property to listen on.
* @param listener The PropertyChangeListener to be added
*/
public final void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
pcs.addPropertyChangeListener(propertyName, listener);
}
/**
* Remove a PropertyChangeListener for a specific property.
* If <code>listener</code> was added more than once to the same event
* source for the specified property, it will be notified one less time
* after being removed.
* If <code>propertyName</code> is null, no exception is thrown and no
* action is taken.
* If <code>listener</code> is null, or was never added for the specified
* property, no exception is thrown and no action is taken.
*
* @param propertyName The name of the property that was listened on.
* @param listener The PropertyChangeListener to be removed
*/
public final void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
pcs.removePropertyChangeListener(propertyName, listener);
}
/**
* Returns an array of all the listeners which have been associated
* with the named property.
*
* @param propertyName The name of the property being listened to
* @return all of the <code>PropertyChangeListeners</code> associated with
* the named property. If no such listeners have been added,
* or if <code>propertyName</code> is null, an empty array is
* returned.
*/
public final PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
return pcs.getPropertyChangeListeners(propertyName);
}
/**
* Report a bound property update to any registered listeners.
* No event is fired if old and new are equal and non-null.
*
* <p>
* This is merely a convenience wrapper around the more general
* firePropertyChange method that takes {@code
* PropertyChangeEvent} value.
*
* @param propertyName The programmatic name of the property
* that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
*/
protected final void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
pcs.firePropertyChange(propertyName, oldValue, newValue);
}
/**
* Fire an existing PropertyChangeEvent to any registered listeners.
* No event is fired if the given event's old and new values are
* equal and non-null.
* @param evt The PropertyChangeEvent object.
*/
protected final void firePropertyChange(PropertyChangeEvent evt) {
pcs.firePropertyChange(evt);
}
/**
* Report a bound indexed property update to any registered
* listeners.
* <p>
* No event is fired if old and new values are equal
* and non-null.
*
* <p>
* This is merely a convenience wrapper around the more general
* firePropertyChange method that takes {@code PropertyChangeEvent} value.
*
* @param propertyName The programmatic name of the property that
* was changed.
* @param index index of the property element that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
*/
protected final void fireIndexedPropertyChange(String propertyName, int index,
Object oldValue, Object newValue) {
pcs.fireIndexedPropertyChange(propertyName, index, oldValue, newValue);
}
/**
* Check if there are any listeners for a specific property, including
* those registered on all properties. If <code>propertyName</code>
* is null, only check for listeners registered on all properties.
*
* @param propertyName the property name.
* @return true if there are one or more listeners for the given property
*/
protected final boolean hasPropertyChangeListeners(String propertyName) {
return pcs.hasListeners(propertyName);
}
/**
* Check if there are any listeners for a specific property, including
* those registered on all properties. If <code>propertyName</code>
* is null, only check for listeners registered on all properties.
*
* @param propertyName the property name.
* @return true if there are one or more listeners for the given property
*/
protected final boolean hasVetoableChangeListeners(String propertyName) {
return vcs.hasListeners(propertyName);
}
/**
* Add a VetoableListener to the listener list.
* The listener is registered for all properties.
* The same listener object may be added more than once, and will be called
* as many times as it is added.
* If <code>listener</code> is null, no exception is thrown and no action
* is taken.
*
* @param listener The VetoableChangeListener to be added
*/
public final void addVetoableChangeListener(VetoableChangeListener listener) {
vcs.addVetoableChangeListener(listener);
}
/**
* Remove a VetoableChangeListener from the listener list.
* This removes a VetoableChangeListener that was registered
* for all properties.
* If <code>listener</code> was added more than once to the same event
* source, it will be notified one less time after being removed.
* If <code>listener</code> is null, or was never added, no exception is
* thrown and no action is taken.
*
* @param listener The VetoableChangeListener to be removed
*/
public final void removeVetoableChangeListener(VetoableChangeListener listener) {
vcs.removeVetoableChangeListener(listener);
}
/**
* Returns the list of VetoableChangeListeners. If named vetoable change listeners
* were added, then VetoableChangeListenerProxy wrappers will returned
* <p>
* @return List of VetoableChangeListeners and VetoableChangeListenerProxys
* if named property change listeners were added.
*/
public final VetoableChangeListener[] getVetoableChangeListeners(){
return vcs.getVetoableChangeListeners();
}
/**
* Add a VetoableChangeListener for a specific property. The listener
* will be invoked only when a call on fireVetoableChange names that
* specific property.
* The same listener object may be added more than once. For each
* property, the listener will be invoked the number of times it was added
* for that property.
* If <code>propertyName</code> or <code>listener</code> is null, no
* exception is thrown and no action is taken.
*
* @param propertyName The name of the property to listen on.
* @param listener The VetoableChangeListener to be added
*/
public final void addVetoableChangeListener(String propertyName,
VetoableChangeListener listener) {
vcs.addVetoableChangeListener(propertyName, listener);
}
/**
* Remove a VetoableChangeListener for a specific property.
* If <code>listener</code> was added more than once to the same event
* source for the specified property, it will be notified one less time
* after being removed.
* If <code>propertyName</code> is null, no exception is thrown and no
* action is taken.
* If <code>listener</code> is null, or was never added for the specified
* property, no exception is thrown and no action is taken.
*
* @param propertyName The name of the property that was listened on.
* @param listener The VetoableChangeListener to be removed
*/
public final void removeVetoableChangeListener(String propertyName,
VetoableChangeListener listener) {
vcs.removeVetoableChangeListener(propertyName, listener);
}
/**
* Returns an array of all the listeners which have been associated
* with the named property.
*
* @param propertyName The name of the property being listened to
* @return all the <code>VetoableChangeListeners</code> associated with
* the named property. If no such listeners have been added,
* or if <code>propertyName</code> is null, an empty array is
* returned.
*/
public final VetoableChangeListener[] getVetoableChangeListeners(String propertyName) {
return vcs.getVetoableChangeListeners(propertyName);
}
/**
* Report a vetoable property update to any registered listeners. If
* anyone vetos the change, then fire a new event reverting everyone to
* the old value and then rethrow the PropertyVetoException.
* <p>
* No event is fired if old and new are equal and non-null.
*
* @param propertyName The programmatic name of the property
* that is about to change..
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
* @exception PropertyVetoException if the recipient wishes the property
* change to be rolled back.
*/
protected final void fireVetoableChange(String propertyName,
Object oldValue, Object newValue)
throws PropertyVetoException {
vcs.fireVetoableChange(propertyName, oldValue, newValue);
}
/**
* Fire a vetoable property update to any registered listeners. If
* anyone vetos the change, then fire a new event reverting everyone to
* the old value and then rethrow the PropertyVetoException.
* <p>
* No event is fired if old and new are equal and non-null.
*
* @param evt The PropertyChangeEvent to be fired.
* @exception PropertyVetoException if the recipient wishes the property
* change to be rolled back.
*/
protected final void fireVetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
vcs.fireVetoableChange(evt);
}
/**
* {@inheritDoc}
*/
@Override
public Object clone() throws CloneNotSupportedException {
AbstractBean result = (AbstractBean) super.clone();
result.pcs = new PropertyChangeSupport(result);
result.vcs = new VetoableChangeSupport(result);
return result;
}
}

View File

@@ -0,0 +1,104 @@
/*
* $Id: AbstractSerializableBean.java 4088 2011-11-17 19:53:49Z kschaefe $
*
* Copyright 2008 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.beans;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.VetoableChangeListener;
import java.beans.VetoableChangeSupport;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* This subclass enhances {@code AbstractBean} by implementing the
* {@code Serializable} interface. {@code AbstractSerializableBean} correctly
* serializes all {@code Serializable} listeners that it contains. Implementors
* that need to extends {@code AbstractBean} or one of its subclasses and
* require serialization should use this class if possible. If it is not
* possible to extend this class, the implementation can guide implementors on
* how to properly serialize the listeners.
*
* @author Karl George Schaefer
*
* @see Serializable
* @see ObjectInputStream
* @see ObjectOutputStream
*/
@SuppressWarnings("serial")
public abstract class AbstractSerializableBean extends AbstractBean implements
Serializable {
/**
* Creates a new instance of {@code AbstractSerializableBean}.
*/
protected AbstractSerializableBean() {
super();
}
/**
* Creates a new instance of {@code AbstractSerializableBean}, using the
* supplied support delegates. Neither of these may be {@code null}.
*
* @param pcs
* the property change support class to use
* @param vcs
* the vetoable change support class to use
* @throws NullPointerException
* if any parameter is {@code null}
*/
protected AbstractSerializableBean(PropertyChangeSupport pcs,
VetoableChangeSupport vcs) {
super(pcs, vcs);
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
for (PropertyChangeListener l : getPropertyChangeListeners()) {
if (l instanceof Serializable) {
s.writeObject(l);
}
}
for (VetoableChangeListener l : getVetoableChangeListeners()) {
if (l instanceof Serializable) {
s.writeObject(l);
}
}
s.writeObject(null);
}
private void readObject(ObjectInputStream s) throws ClassNotFoundException,
IOException {
s.defaultReadObject();
Object listenerOrNull;
while (null != (listenerOrNull = s.readObject())) {
if (listenerOrNull instanceof PropertyChangeListener) {
addPropertyChangeListener((PropertyChangeListener) listenerOrNull);
} else if (listenerOrNull instanceof VetoableChangeListener) {
addVetoableChangeListener((VetoableChangeListener) listenerOrNull);
}
}
}
}

View File

@@ -0,0 +1,145 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.0" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
<AuxValues>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,0,-11,0,0,1,125"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
<SubComponents>
<Container class="org.jdesktop.swingx.JXMapViewer" name="mainMap">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
<GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="1" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="1.0" weightY="1.0"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
<SubComponents>
<Container class="org.jdesktop.swingx.JXMapViewer" name="miniMap">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.LineBorderInfo">
<LineBorder/>
</Border>
</Property>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[100, 100]"/>
</Property>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[100, 100]"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
<GridBagConstraints gridX="1" gridY="0" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="14" weightX="1.0" weightY="1.0"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
</Container>
<Container class="javax.swing.JPanel" name="jPanel1">
<Properties>
<Property name="opaque" type="boolean" value="false"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
<GridBagConstraints gridX="0" gridY="0" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="4" insetsLeft="4" insetsBottom="4" insetsRight="4" anchor="16" weightX="1.0" weightY="1.0"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
<SubComponents>
<Component class="javax.swing.JButton" name="zoomInButton">
<Properties>
<Property name="action" type="javax.swing.Action" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="getZoomOutAction()" type="code"/>
</Property>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/org/jdesktop/swingx/mapviewer/resources/plus.png"/>
</Property>
<Property name="margin" type="java.awt.Insets" editor="org.netbeans.beaninfo.editors.InsetsEditor">
<Insets value="[2, 2, 2, 2]"/>
</Property>
<Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[20, 20]"/>
</Property>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[20, 20]"/>
</Property>
<Property name="opaque" type="boolean" value="false"/>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[20, 20]"/>
</Property>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="zoomInButtonActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
<GridBagConstraints gridX="1" gridY="1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="12" weightX="1.0" weightY="1.0"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JButton" name="zoomOutButton">
<Properties>
<Property name="action" type="javax.swing.Action" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
<Connection code="getZoomInAction()" type="code"/>
</Property>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/org/jdesktop/swingx/mapviewer/resources/minus.png"/>
</Property>
<Property name="margin" type="java.awt.Insets" editor="org.netbeans.beaninfo.editors.InsetsEditor">
<Insets value="[2, 2, 2, 2]"/>
</Property>
<Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[20, 20]"/>
</Property>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[20, 20]"/>
</Property>
<Property name="opaque" type="boolean" value="false"/>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[20, 20]"/>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
<GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="18" weightX="0.0" weightY="1.0"/>
</Constraint>
</Constraints>
</Component>
<Component class="javax.swing.JSlider" name="zoomSlider">
<Properties>
<Property name="majorTickSpacing" type="int" value="1"/>
<Property name="maximum" type="int" value="15"/>
<Property name="minimum" type="int" value="10"/>
<Property name="minorTickSpacing" type="int" value="1"/>
<Property name="orientation" type="int" value="1"/>
<Property name="paintTicks" type="boolean" value="true"/>
<Property name="snapToTicks" type="boolean" value="true"/>
<Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[35, 100]"/>
</Property>
</Properties>
<Events>
<EventHandler event="stateChanged" listener="javax.swing.event.ChangeListener" parameters="javax.swing.event.ChangeEvent" handler="zoomSliderStateChanged"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
<GridBagConstraints gridX="0" gridY="0" gridWidth="2" gridHeight="1" fill="3" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="11" weightX="0.0" weightY="0.0"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Container>
</SubComponents>
</Form>

View File

@@ -0,0 +1,712 @@
/*
* JXMapKit.java
*
* Created on November 19, 2006, 3:52 AM
*/
package org.jdesktop.swingx;
import org.jdesktop.swingx.mapviewer.DefaultTileFactory;
import org.jdesktop.swingx.mapviewer.DefaultWaypoint;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.mapviewer.TileFactory;
import org.jdesktop.swingx.mapviewer.TileFactoryInfo;
import org.jdesktop.swingx.mapviewer.Waypoint;
import org.jdesktop.swingx.mapviewer.WaypointPainter;
import org.jdesktop.swingx.mapviewer.bmng.CylindricalProjectionTileFactory;
import org.jdesktop.swingx.painter.AbstractPainter;
import org.jdesktop.swingx.painter.CompoundPainter;
import org.jdesktop.swingx.painter.Painter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashSet;
import java.util.Set;
/**
* <p>The JXMapKit is a pair of JXMapViewers preconfigured to be easy to use
* with common features built in. This includes zoom buttons, a zoom slider,
* and a mini-map in the lower right corner showing an overview of the map.
* Each feature can be turned off using an appropriate
* <CODE>is<I>X</I>visible</CODE> property. For example, to turn
* off the minimap call
*
* <PRE><CODE>jxMapKit.setMiniMapVisible(false);</CODE></PRE>
* </p>
*
* <p>
* The JXMapViewer is preconfigured to connect to maps.swinglabs.org which
* serves up global satellite imagery from NASA's
* <a href="http://earthobservatory.nasa.gov/Newsroom/BlueMarble/">Blue
* Marble NG</a> image collection.
* </p>
* @author joshy
*/
public class JXMapKit extends JPanel
{
private static final long serialVersionUID = -8366577998349912380L;
private boolean miniMapVisible = true;
private boolean zoomSliderVisible = true;
private boolean zoomButtonsVisible = true;
private final boolean sliderReversed = false;
@SuppressWarnings("javadoc")
public enum DefaultProviders
{
SwingLabsBlueMarble, OpenStreetMaps, Custom
}
private DefaultProviders defaultProvider = DefaultProviders.SwingLabsBlueMarble;
private boolean addressLocationShown = true;
private boolean dataProviderCreditShown = true;
/**
* Creates a new JXMapKit
*/
public JXMapKit()
{
initComponents();
setDataProviderCreditShown(false);
zoomSlider.setOpaque(false);
try
{
Icon minusIcon = new ImageIcon(getClass().getResource("/org/jdesktop/swingx/mapviewer/resources/minus.png"));
this.zoomOutButton.setIcon(minusIcon);
this.zoomOutButton.setText("");
Icon plusIcon = new ImageIcon(getClass().getResource("/org/jdesktop/swingx/mapviewer/resources/plus.png"));
this.zoomInButton.setIcon(plusIcon);
this.zoomInButton.setText("");
}
catch (Throwable thr)
{
System.out.println("error: " + thr.getMessage());
thr.printStackTrace();
}
setTileFactory(new CylindricalProjectionTileFactory());
mainMap.setCenterPosition(new GeoPosition(0, 0));
miniMap.setCenterPosition(new GeoPosition(0, 0));
mainMap.setRestrictOutsidePanning(true);
miniMap.setRestrictOutsidePanning(true);
rebuildMainMapOverlay();
/*
* // adapter to move the minimap after the main map has moved MouseInputAdapter ma = new MouseInputAdapter() {
* public void mouseReleased(MouseEvent e) { miniMap.setCenterPosition(mapCenterPosition); } };
* mainMap.addMouseMotionListener(ma); mainMap.addMouseListener(ma);
*/
mainMap.addPropertyChangeListener("center", new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
Point2D mapCenter = (Point2D) evt.getNewValue();
TileFactory tf = mainMap.getTileFactory();
GeoPosition mapPos = tf.pixelToGeo(mapCenter, mainMap.getZoom());
miniMap.setCenterPosition(mapPos);
}
});
mainMap.addPropertyChangeListener("centerPosition", new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
mapCenterPosition = (GeoPosition) evt.getNewValue();
miniMap.setCenterPosition(mapCenterPosition);
Point2D pt = miniMap.getTileFactory().geoToPixel(mapCenterPosition, miniMap.getZoom());
miniMap.setCenter(pt);
miniMap.repaint();
}
});
mainMap.addPropertyChangeListener("zoom", new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
zoomSlider.setValue(mainMap.getZoom());
miniMap.setZoom(mainMap.getZoom() + 4);
}
});
// an overlay for the mini-map which shows a rectangle representing the main map
miniMap.setOverlayPainter(new Painter<JXMapViewer>()
{
@Override
public void paint(Graphics2D g, JXMapViewer map, int width, int height)
{
// get the viewport rect of the main map
Rectangle mainMapBounds = mainMap.getViewportBounds();
// convert to Point2Ds
Point2D upperLeft2D = mainMapBounds.getLocation();
Point2D lowerRight2D = new Point2D.Double(upperLeft2D.getX() + mainMapBounds.getWidth(), upperLeft2D
.getY() + mainMapBounds.getHeight());
// convert to GeoPostions
GeoPosition upperLeft = mainMap.getTileFactory().pixelToGeo(upperLeft2D, mainMap.getZoom());
GeoPosition lowerRight = mainMap.getTileFactory().pixelToGeo(lowerRight2D, mainMap.getZoom());
// convert to Point2Ds on the mini-map
upperLeft2D = map.getTileFactory().geoToPixel(upperLeft, map.getZoom());
lowerRight2D = map.getTileFactory().geoToPixel(lowerRight, map.getZoom());
g = (Graphics2D) g.create();
Rectangle rect = map.getViewportBounds();
// p("rect = " + rect);
g.translate(-rect.x, -rect.y);
// Point2D centerpos = map.getTileFactory().geoToPixel(mapCenterPosition, map.getZoom());
// p("center pos = " + centerpos);
g.setPaint(Color.RED);
// g.drawRect((int)centerpos.getX()-30,(int)centerpos.getY()-30,60,60);
g.drawRect((int) upperLeft2D.getX(), (int) upperLeft2D.getY(),
(int) (lowerRight2D.getX() - upperLeft2D.getX()),
(int) (lowerRight2D.getY() - upperLeft2D.getY()));
g.setPaint(new Color(255, 0, 0, 50));
g.fillRect((int) upperLeft2D.getX(), (int) upperLeft2D.getY(),
(int) (lowerRight2D.getX() - upperLeft2D.getX()),
(int) (lowerRight2D.getY() - upperLeft2D.getY()));
// g.drawOval((int)lowerRight2D.getX(),(int)lowerRight2D.getY(),1,1);
g.dispose();
}
});
if (getDefaultProvider() == DefaultProviders.OpenStreetMaps)
{
setZoom(10);
}
else
{
setZoom(3);// joshy: hack, i shouldn't need this here
}
this.setCenterPosition(new GeoPosition(0, 0));
}
// private Point2D mapCenter = new Point2D.Double(0,0);
private GeoPosition mapCenterPosition = new GeoPosition(0, 0);
private boolean zoomChanging = false;
/**
* Set the current zoomlevel for the main map. The minimap will be updated accordingly
* @param zoom the new zoom level
*/
public void setZoom(int zoom)
{
zoomChanging = true;
mainMap.setZoom(zoom);
miniMap.setZoom(mainMap.getZoom() + 4);
if (sliderReversed)
{
zoomSlider.setValue(zoomSlider.getMaximum() - zoom);
}
else
{
zoomSlider.setValue(zoom);
}
zoomChanging = false;
}
/**
* Returns an action which can be attached to buttons or menu items to make the map zoom out
* @return a preconfigured Zoom Out action
*/
public Action getZoomOutAction()
{
Action act = new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 5525706163434375107L;
@Override
public void actionPerformed(ActionEvent e)
{
setZoom(mainMap.getZoom() - 1);
}
};
act.putValue(Action.NAME, "-");
return act;
}
/**
* Returns an action which can be attached to buttons or menu items to make the map zoom in
* @return a preconfigured Zoom In action
*/
public Action getZoomInAction()
{
Action act = new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 5779971489365451352L;
@Override
public void actionPerformed(ActionEvent e)
{
setZoom(mainMap.getZoom() + 1);
}
};
act.putValue(Action.NAME, "+");
return act;
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents()
{
java.awt.GridBagConstraints gridBagConstraints;
mainMap = new org.jdesktop.swingx.JXMapViewer();
miniMap = new org.jdesktop.swingx.JXMapViewer();
jPanel1 = new javax.swing.JPanel();
zoomInButton = new javax.swing.JButton();
zoomOutButton = new javax.swing.JButton();
zoomSlider = new javax.swing.JSlider();
setLayout(new java.awt.GridBagLayout());
mainMap.setLayout(new java.awt.GridBagLayout());
miniMap.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
miniMap.setMinimumSize(new java.awt.Dimension(100, 100));
miniMap.setPreferredSize(new java.awt.Dimension(100, 100));
miniMap.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
mainMap.add(miniMap, gridBagConstraints);
jPanel1.setOpaque(false);
jPanel1.setLayout(new java.awt.GridBagLayout());
zoomInButton.setAction(getZoomOutAction());
zoomInButton.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/org/jdesktop/swingx/mapviewer/resources/plus.png")));
zoomInButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
zoomInButton.setMaximumSize(new java.awt.Dimension(20, 20));
zoomInButton.setMinimumSize(new java.awt.Dimension(20, 20));
zoomInButton.setOpaque(false);
zoomInButton.setPreferredSize(new java.awt.Dimension(20, 20));
zoomInButton.addActionListener(new java.awt.event.ActionListener()
{
@Override
public void actionPerformed(java.awt.event.ActionEvent evt)
{
zoomInButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(zoomInButton, gridBagConstraints);
zoomOutButton.setAction(getZoomInAction());
zoomOutButton.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/org/jdesktop/swingx/mapviewer/resources/minus.png")));
zoomOutButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
zoomOutButton.setMaximumSize(new java.awt.Dimension(20, 20));
zoomOutButton.setMinimumSize(new java.awt.Dimension(20, 20));
zoomOutButton.setOpaque(false);
zoomOutButton.setPreferredSize(new java.awt.Dimension(20, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weighty = 1.0;
jPanel1.add(zoomOutButton, gridBagConstraints);
zoomSlider.setMajorTickSpacing(1);
zoomSlider.setMaximum(15);
zoomSlider.setMinimum(10);
zoomSlider.setMinorTickSpacing(1);
zoomSlider.setOrientation(SwingConstants.VERTICAL);
zoomSlider.setPaintTicks(true);
zoomSlider.setSnapToTicks(true);
zoomSlider.setMinimumSize(new java.awt.Dimension(35, 100));
zoomSlider.setPreferredSize(new java.awt.Dimension(35, 190));
zoomSlider.addChangeListener(new javax.swing.event.ChangeListener()
{
@Override
public void stateChanged(javax.swing.event.ChangeEvent evt)
{
zoomSliderStateChanged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
jPanel1.add(zoomSlider, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
mainMap.add(jPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(mainMap, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
@SuppressWarnings("unused")
private void zoomInButtonActionPerformed(java.awt.event.ActionEvent evt)
{// GEN-FIRST:event_zoomInButtonActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_zoomInButtonActionPerformed
@SuppressWarnings("unused")
private void zoomSliderStateChanged(javax.swing.event.ChangeEvent evt)
{// GEN-FIRST:event_zoomSliderStateChanged
if (!zoomChanging)
{
setZoom(zoomSlider.getValue());
}
// TODO add your handling code here:
}// GEN-LAST:event_zoomSliderStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel jPanel1;
private org.jdesktop.swingx.JXMapViewer mainMap;
private org.jdesktop.swingx.JXMapViewer miniMap;
private javax.swing.JButton zoomInButton;
private javax.swing.JButton zoomOutButton;
private javax.swing.JSlider zoomSlider;
// End of variables declaration//GEN-END:variables
/**
* Indicates if the mini-map is currently visible
* @return the current value of the mini-map property
*/
public boolean isMiniMapVisible()
{
return miniMapVisible;
}
/**
* Sets if the mini-map should be visible
* @param miniMapVisible a new value for the miniMap property
*/
public void setMiniMapVisible(boolean miniMapVisible)
{
boolean old = this.isMiniMapVisible();
this.miniMapVisible = miniMapVisible;
miniMap.setVisible(miniMapVisible);
firePropertyChange("miniMapVisible", old, this.isMiniMapVisible());
}
/**
* Indicates if the zoom slider is currently visible
* @return the current value of the zoomSliderVisible property
*/
public boolean isZoomSliderVisible()
{
return zoomSliderVisible;
}
/**
* Sets if the zoom slider should be visible
* @param zoomSliderVisible the new value of the zoomSliderVisible property
*/
public void setZoomSliderVisible(boolean zoomSliderVisible)
{
boolean old = this.isZoomSliderVisible();
this.zoomSliderVisible = zoomSliderVisible;
zoomSlider.setVisible(zoomSliderVisible);
firePropertyChange("zoomSliderVisible", old, this.isZoomSliderVisible());
}
/**
* Indicates if the zoom buttons are visible. This is a bound property and can be listed for using a
* PropertyChangeListener
* @return current value of the zoomButtonsVisible property
*/
public boolean isZoomButtonsVisible()
{
return zoomButtonsVisible;
}
/**
* Sets if the zoom buttons should be visible. This ia bound property. Changes can be listened for using a
* PropertyChaneListener
* @param zoomButtonsVisible new value of the zoomButtonsVisible property
*/
public void setZoomButtonsVisible(boolean zoomButtonsVisible)
{
boolean old = this.isZoomButtonsVisible();
this.zoomButtonsVisible = zoomButtonsVisible;
zoomInButton.setVisible(zoomButtonsVisible);
zoomOutButton.setVisible(zoomButtonsVisible);
firePropertyChange("zoomButtonsVisible", old, this.isZoomButtonsVisible());
}
/**
* Sets the tile factory for both embedded JXMapViewer components. Calling this method will also reset the center
* and zoom levels of both maps, as well as the bounds of the zoom slider.
* @param fact the new TileFactory
*/
public void setTileFactory(TileFactory fact)
{
mainMap.setTileFactory(fact);
mainMap.setZoom(fact.getInfo().getDefaultZoomLevel());
mainMap.setCenterPosition(new GeoPosition(0, 0));
miniMap.setTileFactory(fact);
miniMap.setZoom(fact.getInfo().getDefaultZoomLevel() + 3);
miniMap.setCenterPosition(new GeoPosition(0, 0));
zoomSlider.setMinimum(fact.getInfo().getMinimumZoomLevel());
zoomSlider.setMaximum(fact.getInfo().getMaximumZoomLevel());
}
/**
* @param pos the new center position
*/
public void setCenterPosition(GeoPosition pos)
{
mainMap.setCenterPosition(pos);
miniMap.setCenterPosition(pos);
}
/**
* @return the center geo position
*/
public GeoPosition getCenterPosition()
{
return mainMap.getCenterPosition();
}
/**
* @return the adress location
*/
public GeoPosition getAddressLocation()
{
return mainMap.getAddressLocation();
}
/**
* @param pos the address location
*/
public void setAddressLocation(GeoPosition pos)
{
mainMap.setAddressLocation(pos);
}
/**
* Returns a reference to the main embedded JXMapViewer component
* @return the main map
*/
public JXMapViewer getMainMap()
{
return this.mainMap;
}
/**
* Returns a reference to the mini embedded JXMapViewer component
* @return the minimap JXMapViewer component
*/
public JXMapViewer getMiniMap()
{
return this.miniMap;
}
/**
* returns a reference to the zoom in button
* @return a jbutton
*/
public JButton getZoomInButton()
{
return this.zoomInButton;
}
/**
* returns a reference to the zoom out button
* @return a jbutton
*/
public JButton getZoomOutButton()
{
return this.zoomOutButton;
}
/**
* returns a reference to the zoom slider
* @return a jslider
*/
public JSlider getZoomSlider()
{
return this.zoomSlider;
}
/**
* @param b the visibility flag
*/
public void setAddressLocationShown(boolean b)
{
boolean old = isAddressLocationShown();
this.addressLocationShown = b;
addressLocationPainter.setVisible(b);
firePropertyChange("addressLocationShown", old, b);
repaint();
}
/**
* @return true if the address location is shown
*/
public boolean isAddressLocationShown()
{
return addressLocationShown;
}
/**
* @param b the visibility flag
*/
public void setDataProviderCreditShown(boolean b)
{
boolean old = isDataProviderCreditShown();
this.dataProviderCreditShown = b;
dataProviderCreditPainter.setVisible(b);
repaint();
firePropertyChange("dataProviderCreditShown", old, b);
}
/**
* @return true if the data provider credit is shown
*/
public boolean isDataProviderCreditShown()
{
return dataProviderCreditShown;
}
@SuppressWarnings("unchecked")
private void rebuildMainMapOverlay()
{
CompoundPainter<JXMapViewer> cp = new CompoundPainter<JXMapViewer>();
cp.setCacheable(false);
/*
* List<Painter> ptrs = new ArrayList<Painter>(); if(isDataProviderCreditShown()) {
* ptrs.add(dataProviderCreditPainter); } if(isAddressLocationShown()) { ptrs.add(addressLocationPainter); }
*/
cp.setPainters(dataProviderCreditPainter, addressLocationPainter);
mainMap.setOverlayPainter(cp);
}
/**
* @param prov the default provider
*/
public void setDefaultProvider(DefaultProviders prov)
{
DefaultProviders old = this.defaultProvider;
this.defaultProvider = prov;
if (prov == DefaultProviders.SwingLabsBlueMarble)
{
setTileFactory(new CylindricalProjectionTileFactory());
setZoom(3);
}
if (prov == DefaultProviders.OpenStreetMaps)
{
TileFactoryInfo info = new OSMTileFactoryInfo();
TileFactory tf = new DefaultTileFactory(info);
setTileFactory(tf);
setZoom(11);
setAddressLocation(new GeoPosition(51.5, 0));
}
firePropertyChange("defaultProvider", old, prov);
repaint();
}
/**
* @return the default provider
*/
public DefaultProviders getDefaultProvider()
{
return this.defaultProvider;
}
private AbstractPainter<JXMapViewer> dataProviderCreditPainter = new AbstractPainter<JXMapViewer>(false)
{
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
g.setPaint(Color.WHITE);
g.drawString("data ", 50, map.getHeight() - 10);
}
};
private WaypointPainter<Waypoint> addressLocationPainter = new WaypointPainter<Waypoint>()
{
@Override
public Set<Waypoint> getWaypoints()
{
Set<Waypoint> set = new HashSet<Waypoint>();
if (getAddressLocation() != null)
{
set.add(new DefaultWaypoint(getAddressLocation()));
}
else
{
set.add(new DefaultWaypoint(0, 0));
}
return set;
}
};
/**
* @param args the program args
*/
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
JXMapKit kit = new JXMapKit();
kit.setDefaultProvider(DefaultProviders.OpenStreetMaps);
TileFactoryInfo info = new OSMTileFactoryInfo();
TileFactory tf = new DefaultTileFactory(info);
kit.setTileFactory(tf);
kit.setZoom(14);
kit.setAddressLocation(new GeoPosition(51.5, 0));
kit.getMainMap().setDrawTileBorders(true);
kit.getMainMap().setRestrictOutsidePanning(true);
kit.getMainMap().setHorizontalWrapped(false);
((DefaultTileFactory) kit.getMainMap().getTileFactory()).setThreadPoolSize(8);
JFrame frame = new JFrame("JXMapKit test");
frame.add(kit);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
}
});
}
}

View File

@@ -0,0 +1,804 @@
/*
* *****************************************************************************
* 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/>
* ****************************************************************************
*/
/*
* MapViewer.java
*
* Created on March 14, 2006, 2:14 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.DesignMode;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Set;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.swing.IconFontSwing;
import org.apache.commons.math3.util.FastMath;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.jdesktop.swingx.mapviewer.Tile;
import org.jdesktop.swingx.mapviewer.TileFactory;
import org.jdesktop.swingx.mapviewer.TileFactoryInfo;
import org.jdesktop.swingx.mapviewer.TileListener;
import org.jdesktop.swingx.mapviewer.empty.EmptyTileFactory;
import org.jdesktop.swingx.painter.AbstractPainter;
import org.jdesktop.swingx.painter.Painter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JPanel;
/**
* A tile oriented map component that can easily be used with tile sources
* on the web like Google and Yahoo maps, satellite data such as NASA imagery,
* and also with file based sources like pre-processed NASA images.
* A known map provider can be used with the SLMapServerInfo,
* which will connect to a 2km resolution version of NASA's Blue Marble Next Generation
* imagery. @see SLMapServerInfo for more information.
*
* Note, the JXMapViewer has three center point properties. The <B>addressLocation</B> property
* represents an abstract center of the map. This would usually be something like the first item
* in a search result. It is a {@link GeoPosition}. The <b>centerPosition</b> property represents
* the current center point of the map. If the user pans the map then the centerPosition point will
* change but the <B>addressLocation</B> will not. Calling <B>recenterToAddressLocation()</B> will move the map
* back to that center address. The <B>center</B> property represents the same point as the centerPosition
* property, but as a Point2D in pixel space instead of a GeoPosition in lat/long space. Note that
* the center property is a Point2D in the entire world bitmap, not in the portion of the map currently
* visible. You can use the <B>getViewportBounds()</B> method to find the portion of the map currently visible
* and adjust your calculations accordingly. Changing the <B>center</B> property will change the <B>centerPosition</B>
* property and vice versa. All three properties are bound.
* @author Joshua.Marinacci@sun.com
* @see org.jdesktop.swingx.mapviewer.bmng.SLMapServerInfo
*/
public class JXMapViewer extends JPanel implements DesignMode
{
private static final long serialVersionUID = -3530746298586937321L;
private final static Logger mLog = LoggerFactory.getLogger(JXMapViewer.class);
private final boolean isNegativeYAllowed = true; // maybe rename to isNorthBounded and isSouthBounded?
/**
* The zoom level. Generally a value between 1 and 15 (TODO Is this true for all the mapping worlds? What does this
* mean if some mapping system doesn't support the zoom level?
*/
private int mZoomLevel = 1;
/**
* The position, in <I>map coordinates</I> of the center point. This is defined as the distance from the top and
* left edges of the map in pixels. Dragging the map component will change the center position. Zooming in/out will
* cause the center to be recalculated so as to remain in the center of the new "map".
*/
private Point2D mCenter = new Point2D.Double(0, 0);
/**
* Indicates whether or not to draw the borders between tiles. Defaults to false. TODO Generally not very nice
* looking, very much a product of testing Consider whether this should really be a property or not.
*/
private boolean mDrawTileBorders = false;
/**
* Factory used by this component to grab the tiles necessary for painting the map.
*/
private TileFactory mTileFactory;
/**
* The position in latitude/longitude of the "address" being mapped. This is a special coordinate that, when moved,
* will cause the map to be moved as well. It is separate from "center" in that "center" tracks the current center
* (in pixels) of the viewport whereas this will not change when panning or zooming. Whenever the addressLocation is
* changed, however, the map will be repositioned.
*/
private GeoPosition mAddressLocation;
/**
* The overlay to delegate to for painting the "foreground" of the map component. This would include painting
* waypoints, day/night, etc. Also receives mouse events.
*/
private Painter<? super JXMapViewer> mOverlay;
private boolean mDesignTime;
private Image mLoadingImage;
private boolean mRestrictOutsidePanning = true;
private boolean mHorizontalWrapped = true;
/**
* Create a new JXMapViewer. By default it will use the EmptyTileFactory
*/
public JXMapViewer()
{
mTileFactory = new EmptyTileFactory();
// setTileFactory(new GoogleTileFactory());
// make a dummy loading image
try
{
Image loading = IconFontSwing.buildImage(FontAwesome.LINK, 16);
this.setLoadingImage(loading);
}
catch (Throwable ex)
{
mLog.error( "JXMapViewer could not load default 'loading.png'" );
BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.black);
g2.fillRect(0, 0, 16, 16);
g2.dispose();
this.setLoadingImage(img);
}
// setAddressLocation(new GeoPosition(37.392137,-121.950431)); // Sun campus
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
doPaintComponent(g);
}
// the method that does the actual painting
private void doPaintComponent(Graphics g)
{/*
* if (isOpaque() || isDesignTime()) { g.setColor(getBackground()); g.fillRect(0,0,getWidth(),getHeight()); }
*/
if (isDesignTime())
{
// do nothing
}
else
{
int z = getZoom();
Rectangle viewportBounds = getViewportBounds();
drawMapTiles(g, z, viewportBounds);
drawOverlays(z, g, viewportBounds);
}
super.paintBorder(g);
}
/**
* Indicate that the component is being used at design time, such as in a visual editor like NetBeans' Matisse
* @param b indicates if the component is being used at design time
*/
@Override
public void setDesignTime(boolean b)
{
this.mDesignTime = b;
}
/**
* Indicates whether the component is being used at design time, such as in a visual editor like NetBeans' Matisse
* @return boolean indicating if the component is being used at design time
*/
@Override
public boolean isDesignTime()
{
return mDesignTime;
}
/**
* Draw the map tiles. This method is for implementation use only.
* @param g Graphics
* @param zoom zoom level to draw at
* @param viewportBounds the bounds to draw within
*/
protected void drawMapTiles(final Graphics g, final int zoom, Rectangle viewportBounds)
{
int size = getTileFactory().getTileSize(zoom);
Dimension mapSize = getTileFactory().getMapSize(zoom);
// calculate the "visible" viewport area in tiles
int numWide = viewportBounds.width / size + 2;
int numHigh = viewportBounds.height / size + 2;
// TilePoint topLeftTile = getTileFactory().getTileCoordinate(
// new Point2D.Double(viewportBounds.x, viewportBounds.y));
TileFactoryInfo info = getTileFactory().getInfo();
int tpx = (int) FastMath.floor(viewportBounds.getX() / info.getTileSize(0));
int tpy = (int) FastMath.floor(viewportBounds.getY() / info.getTileSize(0));
// TilePoint topLeftTile = new TilePoint(tpx, tpy);
// p("top tile = " + topLeftTile);
// fetch the tiles from the factory and store them in the tiles cache
// attach the tileLoadListener
for (int x = 0; x <= numWide; x++)
{
for (int y = 0; y <= numHigh; y++)
{
int itpx = x + tpx;// topLeftTile.getX();
int itpy = y + tpy;// topLeftTile.getY();
// TilePoint point = new TilePoint(x + topLeftTile.getX(), y + topLeftTile.getY());
// only proceed if the specified tile point lies within the area being painted
if (g.getClipBounds().intersects(
new Rectangle(itpx * size - viewportBounds.x, itpy * size - viewportBounds.y, size, size)))
{
Tile tile = getTileFactory().getTile(itpx, itpy, zoom);
int ox = ((itpx * getTileFactory().getTileSize(zoom)) - viewportBounds.x);
int oy = ((itpy * getTileFactory().getTileSize(zoom)) - viewportBounds.y);
// if the tile is off the map to the north/south, then just don't paint anything
if (isTileOnMap(itpx, itpy, mapSize))
{
if (isOpaque())
{
g.setColor(getBackground());
g.fillRect(ox, oy, size, size);
}
}
else if (tile.isLoaded())
{
g.drawImage(tile.getImage(), ox, oy, null);
}
else
{
// Use tile at higher zoom level with 200% magnification
Tile superTile = getTileFactory().getTile(itpx / 2, itpy / 2, zoom + 1);
if (superTile.isLoaded())
{
int offX = (itpx % 2) * size / 2;
int offY = (itpy % 2) * size / 2;
g.drawImage(superTile.getImage(), ox, oy, ox + size, oy + size, offX, offY, offX + size / 2, offY + size / 2, null);
}
else
{
int imageX = (getTileFactory().getTileSize(zoom) - getLoadingImage().getWidth(null)) / 2;
int imageY = (getTileFactory().getTileSize(zoom) - getLoadingImage().getHeight(null)) / 2;
g.setColor(Color.GRAY);
g.fillRect(ox, oy, size, size);
g.drawImage(getLoadingImage(), ox + imageX, oy + imageY, null);
}
}
if (isDrawTileBorders())
{
g.setColor(Color.black);
g.drawRect(ox, oy, size, size);
g.drawRect(ox + size / 2 - 5, oy + size / 2 - 5, 10, 10);
g.setColor(Color.white);
g.drawRect(ox + 1, oy + 1, size, size);
String text = itpx + ", " + itpy + ", " + getZoom();
g.setColor(Color.BLACK);
g.drawString(text, ox + 10, oy + 30);
g.drawString(text, ox + 10 + 2, oy + 30 + 2);
g.setColor(Color.WHITE);
g.drawString(text, ox + 10 + 1, oy + 30 + 1);
}
}
}
}
}
@SuppressWarnings("unused")
private void drawOverlays(final int zoom, final Graphics g, final Rectangle viewportBounds)
{
if (mOverlay != null)
{
mOverlay.paint((Graphics2D) g, this, getWidth(), getHeight());
}
}
@SuppressWarnings("unused")
private boolean isTileOnMap(int x, int y, Dimension mapSize)
{
return !isNegativeYAllowed && y < 0 || y >= mapSize.getHeight();
}
/**
* Sets the map overlay. This is a Painter<JXMapViewer> which will paint on top of the map. It can be used to draw waypoints,
* lines, or static overlays like text messages.
* @param overlay the map overlay to use
*/
public void setOverlayPainter(Painter<? super JXMapViewer> overlay)
{
Painter<? super JXMapViewer> old = getOverlayPainter();
this.mOverlay = overlay;
PropertyChangeListener listener = new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getNewValue().equals(Boolean.TRUE))
{
repaint();
}
}
};
if (old instanceof AbstractPainter)
{
AbstractPainter<?> ap = (AbstractPainter<?>) overlay;
ap.removePropertyChangeListener("dirty", listener);
}
if (overlay instanceof AbstractPainter)
{
AbstractPainter<?> ap = (AbstractPainter<?>) overlay;
ap.addPropertyChangeListener("dirty", listener);
}
firePropertyChange("mapOverlay", old, getOverlayPainter());
repaint();
}
/**
* Gets the current map overlay
* @return the current map overlay
*/
public Painter<? super JXMapViewer> getOverlayPainter()
{
return mOverlay;
}
/**
* Returns the bounds of the viewport in pixels. This can be used to transform points into the world bitmap
* coordinate space.
* @return the bounds in <em>pixels</em> of the "view" of this map
*/
public Rectangle getViewportBounds()
{
return calculateViewportBounds(getCenter());
}
private Rectangle calculateViewportBounds(Point2D centr)
{
Insets insets = getInsets();
// calculate the "visible" viewport area in pixels
int viewportWidth = getWidth() - insets.left - insets.right;
int viewportHeight = getHeight() - insets.top - insets.bottom;
double viewportX = (centr.getX() - viewportWidth / 2);
double viewportY = (centr.getY() - viewportHeight / 2);
return new Rectangle((int) viewportX, (int) viewportY, viewportWidth, viewportHeight);
}
/**
* Set the current zoom level
* @param zoom the new zoom level
*/
public void setZoom(int zoom)
{
if (zoom == this.mZoomLevel)
{
return;
}
TileFactoryInfo info = getTileFactory().getInfo();
// don't repaint if we are out of the valid zoom levels
if (info != null && (zoom < info.getMinimumZoomLevel() || zoom > info.getMaximumZoomLevel()))
{
return;
}
// if(zoom >= 0 && zoom <= 15 && zoom != this.zoom) {
int oldzoom = this.mZoomLevel;
Point2D oldCenter = getCenter();
Dimension oldMapSize = getTileFactory().getMapSize(oldzoom);
this.mZoomLevel = zoom;
this.firePropertyChange("zoom", oldzoom, zoom);
Dimension mapSize = getTileFactory().getMapSize(zoom);
setCenter(new Point2D.Double(oldCenter.getX() * (mapSize.getWidth() / oldMapSize.getWidth()), oldCenter.getY()
* (mapSize.getHeight() / oldMapSize.getHeight())));
repaint();
}
/**
* Gets the current zoom level
* @return the current zoom level
*/
public int getZoom()
{
return this.mZoomLevel;
}
/**
* Gets the current address location of the map. This property does not change when the user pans the map. This
* property is bound.
* @return the current map location (address)
*/
public GeoPosition getAddressLocation()
{
return mAddressLocation;
}
/**
* Gets the current address location of the map
* @param addressLocation the new address location
*/
public void setAddressLocation(GeoPosition addressLocation)
{
GeoPosition old = getAddressLocation();
this.mAddressLocation = addressLocation;
setCenter(getTileFactory().geoToPixel(addressLocation, getZoom()));
firePropertyChange("addressLocation", old, getAddressLocation());
repaint();
}
/**
* Re-centers the map to have the current address location be at the center of the map, accounting for the map's
* width and height.
*/
public void recenterToAddressLocation()
{
setCenter(getTileFactory().geoToPixel(getAddressLocation(), getZoom()));
repaint();
}
/**
* Indicates if the tile borders should be drawn. Mainly used for debugging.
* @return the value of this property
*/
public boolean isDrawTileBorders()
{
return mDrawTileBorders;
}
/**
* Set if the tile borders should be drawn. Mainly used for debugging.
* @param drawTileBorders new value of this drawTileBorders
*/
public void setDrawTileBorders(boolean drawTileBorders)
{
boolean old = isDrawTileBorders();
this.mDrawTileBorders = drawTileBorders;
firePropertyChange("drawTileBorders", old, isDrawTileBorders());
repaint();
}
/**
* A property indicating the center position of the map
* @param geoPosition the new property value
*/
public void setCenterPosition(GeoPosition geoPosition)
{
GeoPosition oldVal = getCenterPosition();
setCenter(getTileFactory().geoToPixel(geoPosition, mZoomLevel));
repaint();
GeoPosition newVal = getCenterPosition();
firePropertyChange("centerPosition", oldVal, newVal);
}
/**
* A property indicating the center position of the map
* @return the current center position
*/
public GeoPosition getCenterPosition()
{
return getTileFactory().pixelToGeo(getCenter(), mZoomLevel);
}
/**
* Get the current factory
* @return the current property value
*/
public TileFactory getTileFactory()
{
return mTileFactory;
}
/**
* Set the current tile factory (must not be <code>null</code>)
* @param factory the new property value
*/
public void setTileFactory(TileFactory factory)
{
if (factory == null)
throw new NullPointerException("factory must not be null");
this.mTileFactory.removeTileListener(tileLoadListener);
this.mTileFactory.dispose();
this.mTileFactory = factory;
this.setZoom(factory.getInfo().getDefaultZoomLevel());
factory.addTileListener(tileLoadListener);
repaint();
}
/**
* A property for an image which will be display when an image is still loading.
* @return the current property value
*/
public Image getLoadingImage()
{
return mLoadingImage;
}
/**
* A property for an image which will be display when an image is still loading.
* @param loadingImage the new property value
*/
public void setLoadingImage(Image loadingImage)
{
this.mLoadingImage = loadingImage;
}
/**
* Gets the current pixel center of the map. This point is in the global bitmap coordinate system, not as lat/longs.
* @return the current center of the map as a pixel value
*/
public Point2D getCenter()
{
return mCenter;
}
/**
* Sets the new center of the map in pixel coordinates.
* @param center the new center of the map in pixel coordinates
*/
public void setCenter(Point2D center)
{
Point2D old = this.getCenter();
double centerX = center.getX();
double centerY = center.getY();
Dimension mapSize = getTileFactory().getMapSize(getZoom());
int mapHeight = (int) mapSize.getHeight() * getTileFactory().getTileSize(getZoom());
int mapWidth = (int) mapSize.getWidth() * getTileFactory().getTileSize(getZoom());
if (isRestrictOutsidePanning())
{
Insets insets = getInsets();
int viewportHeight = getHeight() - insets.top - insets.bottom;
int viewportWidth = getWidth() - insets.left - insets.right;
// don't let the user pan over the top edge
Rectangle newVP = calculateViewportBounds(center);
if (newVP.getY() < 0)
{
centerY = viewportHeight / 2;
}
// don't let the user pan over the left edge
if (!isHorizontalWrapped() && newVP.getX() < 0)
{
centerX = viewportWidth / 2;
}
// don't let the user pan over the bottom edge
if (newVP.getY() + newVP.getHeight() > mapHeight)
{
centerY = mapHeight - viewportHeight / 2;
}
// don't let the user pan over the right edge
if (!isHorizontalWrapped() && (newVP.getX() + newVP.getWidth() > mapWidth))
{
centerX = mapWidth - viewportWidth / 2;
}
// if map is to small then just center it vert
if (mapHeight < newVP.getHeight())
{
centerY = mapHeight / 2;// viewportHeight/2;// - mapHeight/2;
}
// if map is too small then just center it horiz
if (!isHorizontalWrapped() && mapWidth < newVP.getWidth())
{
centerX = mapWidth / 2;
}
}
// If center is outside (0, 0,mapWidth, mapHeight)
// compute modulo to get it back in.
{
centerX = centerX % mapWidth;
centerY = centerY % mapHeight;
if (centerX < 0)
centerX += mapWidth;
if (centerY < 0)
centerY += mapHeight;
}
GeoPosition oldGP = this.getCenterPosition();
this.mCenter = new Point2D.Double(centerX, centerY);
firePropertyChange("center", old, this.mCenter);
firePropertyChange("centerPosition", oldGP, this.getCenterPosition());
repaint();
}
/**
* Calculates a zoom level so that all points in the specified set will be visible on screen. This is useful if you
* have a bunch of points in an area like a city and you want to zoom out so that the entire city and it's points
* are visible without panning.
* @param positions A set of GeoPositions to calculate the new zoom from
*/
public void calculateZoomFrom(Set<GeoPosition> positions)
{
// u.p("calculating a zoom based on: ");
// u.p(positions);
if (positions.size() < 2)
{
return;
}
int zoom = getZoom();
Rectangle2D rect = generateBoundingRect(positions, zoom);
// Rectangle2D viewport = map.getViewportBounds();
int count = 0;
while (!getViewportBounds().contains(rect))
{
// u.p("not contained");
Point2D centr = new Point2D.Double(rect.getX() + rect.getWidth() / 2, rect.getY() + rect.getHeight() / 2);
GeoPosition px = getTileFactory().pixelToGeo(centr, zoom);
// u.p("new geo = " + px);
setCenterPosition(px);
count++;
if (count > 30)
break;
if (getViewportBounds().contains(rect))
{
// u.p("did it finally");
break;
}
zoom = zoom + 1;
if (zoom > 15)
{
break;
}
setZoom(zoom);
rect = generateBoundingRect(positions, zoom);
}
}
private Rectangle2D generateBoundingRect(final Set<GeoPosition> positions, int zoom)
{
Point2D point1 = getTileFactory().geoToPixel(positions.iterator().next(), zoom);
Rectangle2D rect = new Rectangle2D.Double(point1.getX(), point1.getY(), 0, 0);
for (GeoPosition pos : positions)
{
Point2D point = getTileFactory().geoToPixel(pos, zoom);
rect.add(point);
}
return rect;
}
// a property change listener which forces repaints when tiles finish loading
private TileListener tileLoadListener = new TileListener()
{
@Override
public void tileLoaded(Tile tile)
{
if (tile.getZoom() == getZoom())
{
repaint();
/* this optimization doesn't save much and it doesn't work if you
* wrap around the world
Rectangle viewportBounds = getViewportBounds();
TilePoint tilePoint = t.getLocation();
Point point = new Point(tilePoint.getX() * getTileFactory().getTileSize(), tilePoint.getY() * getTileFactory().getTileSize());
Rectangle tileRect = new Rectangle(point, new Dimension(getTileFactory().getTileSize(), getTileFactory().getTileSize()));
if (viewportBounds.intersects(tileRect)) {
//convert tileRect from world space to viewport space
repaint(new Rectangle(
tileRect.x - viewportBounds.x,
tileRect.y - viewportBounds.y,
tileRect.width,
tileRect.height
));
}*/
}
}
};
/**
* @return true if panning is restricted or not
*/
public boolean isRestrictOutsidePanning()
{
return mRestrictOutsidePanning;
}
/**
* @param restrictOutsidePanning set if panning is restricted or not
*/
public void setRestrictOutsidePanning(boolean restrictOutsidePanning)
{
this.mRestrictOutsidePanning = restrictOutsidePanning;
}
/**
* @return true if horizontally wrapped or not
*/
public boolean isHorizontalWrapped()
{
return mHorizontalWrapped;
}
/**
* @param horizontalWrapped true if horizontal wrap is enabled
*/
public void setHorizontalWrapped(boolean horizontalWrapped)
{
this.mHorizontalWrapped = horizontalWrapped;
}
/**
* Converts the specified GeoPosition to a point in the JXMapViewer's local coordinate space. This method is
* especially useful when drawing lat/long positions on the map.
* @param pos a GeoPosition on the map
* @return the point in the local coordinate space of the map
*/
public Point2D convertGeoPositionToPoint(GeoPosition pos)
{
// convert from geo to world bitmap
Point2D pt = getTileFactory().geoToPixel(pos, getZoom());
// convert from world bitmap to local
Rectangle bounds = getViewportBounds();
return new Point2D.Double(pt.getX() - bounds.getX(), pt.getY() - bounds.getY());
}
/**
* Converts the specified Point2D in the JXMapViewer's local coordinate space to a GeoPosition on the map. This
* method is especially useful for determining the GeoPosition under the mouse cursor.
* @param pt a point in the local coordinate space of the map
* @return the point converted to a GeoPosition
*/
public GeoPosition convertPointToGeoPosition(Point2D pt)
{
// convert from local to world bitmap
Rectangle bounds = getViewportBounds();
Point2D pt2 = new Point2D.Double(pt.getX() + bounds.getX(), pt.getY() + bounds.getY());
// convert from world bitmap to geo
GeoPosition pos = getTileFactory().pixelToGeo(pt2, getZoom());
return pos;
}
/**
* @return isNegativeYAllowed
*/
public boolean isNegativeYAllowed()
{
return isNegativeYAllowed;
}
}

View File

@@ -0,0 +1,55 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 Dennis Sheirer
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>
* * *****************************************************************************
*
*
*/
package org.jdesktop.swingx;
import org.jdesktop.swingx.mapviewer.TileFactoryInfo;
/**
* Uses OpenStreetMap
* @author Martin Dummer
*/
public class OSMTileFactoryInfo extends TileFactoryInfo
{
private static final int max = 19;
/**
* Default constructor
*/
public OSMTileFactoryInfo()
{
super("OpenStreetMap",
1, max - 2, max,
256, true, true, // tile size is 256 and x/y orientation is normal
"https://tile.openstreetmap.org",
"x", "y", "z"); // 5/15/10.png
}
@Override
public String getTileUrl(int x, int y, int zoom)
{
zoom = max - zoom;
String url = this.baseURL + "/" + zoom + "/" + x + "/" + y + ".png";
return url;
}
}

View File

@@ -0,0 +1,134 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx;
import org.jdesktop.swingx.mapviewer.TileFactoryInfo;
/*******************************************************************************
* http://www.viavirtualearth.com/vve/Articles/RollYourOwnTileServer.ashx
* @author Fabrizio Giudici
* @version $Id: MicrosoftVirtualEarthProvider.java 115 2007-11-08 22:04:36Z
* fabriziogiudici $
********************************************************************************/
public class VirtualEarthTileFactoryInfo extends TileFactoryInfo
{
/**
* Use road map
*/
public final static MVEMode MAP = new MVEMode("map", "map", "r", ".png");
/**
* Use satellite map
*/
public final static MVEMode SATELLITE = new MVEMode("satellite", "satellite", "a", ".jpeg");
/**
* Use hybrid map
*/
public final static MVEMode HYBRID = new MVEMode("hybrid", "hybrid", "h", ".jpeg");
/**
* The map mode
*/
public static class MVEMode
{
private String type;
private String ext;
private String name;
private String label;
private MVEMode(final String name, final String label, final String type, final String ext)
{
this.type = type;
this.ext = ext;
this.name = name;
this.label = label;
}
}
private final static int TOP_ZOOM_LEVEL = 19;
private final static int MAX_ZOOM_LEVEL = 17;
private final static int MIN_ZOOM_LEVEL = 2;
private final static int TILE_SIZE = 256;
private MVEMode mode;
/**
* @param mode the mode
*/
public VirtualEarthTileFactoryInfo(MVEMode mode)
{
super("Virtual Earth", MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL, TOP_ZOOM_LEVEL, TILE_SIZE, false, false, "", "", "", "");
this.mode = mode;
}
/**
* @return the name of the selected mode
*/
public String getModeName()
{
return mode.name;
}
/**
* @return the label of the selected mode
*/
public String getModeLabel()
{
return mode.label;
}
@Override
public String getTileUrl(final int x, final int y, final int zoom)
{
final String quad = tileToQuadKey(x, y, TOP_ZOOM_LEVEL - 0 - zoom);
return "http://" + mode.type + quad.charAt(quad.length() - 1) +
".ortho.tiles.virtualearth.net/tiles/"
+ mode.type + quad + mode.ext + "?g=1";
}
private String tileToQuadKey(final int tx, final int ty, final int zl)
{
String quad = "";
for (int i = zl; i > 0; i--)
{
int mask = 1 << (i - 1);
int cell = 0;
if ((tx & mask) != 0)
{
cell++;
}
if ((ty & mask) != 0)
{
cell += 2;
}
quad += cell;
}
return quad;
}
}

View File

@@ -0,0 +1,71 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.input;
import org.jdesktop.swingx.JXMapViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
/**
* Centers the map on the mouse cursor
* if left is double-clicked or middle mouse
* button is pressed.
* @author Martin Steiger
* @author joshy
*/
public class CenterMapListener extends MouseAdapter
{
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public CenterMapListener(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent evt)
{
boolean left = SwingUtilities.isLeftMouseButton(evt);
boolean middle = SwingUtilities.isMiddleMouseButton(evt);
boolean doubleClick = (evt.getClickCount() == 2);
if (middle || (left && doubleClick))
{
recenterMap(evt);
}
}
private void recenterMap(MouseEvent evt)
{
Rectangle bounds = viewer.getViewportBounds();
double x = bounds.getX() + evt.getX();
double y = bounds.getY() + evt.getY();
viewer.setCenter(new Point2D.Double(x, y));
viewer.setZoom(viewer.getZoom() - 1);
viewer.repaint();
}
}

View File

@@ -0,0 +1,97 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.input;
import org.jdesktop.swingx.JXMapViewer;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
/**
* used to pan using the arrow keys
* @author joshy
*/
public class PanKeyListener extends KeyAdapter
{
private static final int OFFSET = 10;
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public PanKeyListener(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void keyPressed(KeyEvent e)
{
int delta_x = 0;
int delta_y = 0;
int requestedZoom = 0;
switch ( e.getKeyCode() )
{
case KeyEvent.VK_LEFT:
case KeyEvent.VK_NUMPAD4:
delta_x = -OFFSET;
break;
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_NUMPAD6:
delta_x = OFFSET;
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_NUMPAD8:
delta_y = -OFFSET;
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_NUMPAD2:
delta_y = OFFSET;
break;
case KeyEvent.VK_MINUS:
case KeyEvent.VK_SUBTRACT:
requestedZoom = 1;
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_EQUALS:
requestedZoom = -1;
break;
}
if (delta_x != 0 || delta_y != 0)
{
Rectangle bounds = viewer.getViewportBounds();
double x = bounds.getCenterX() + delta_x;
double y = bounds.getCenterY() + delta_y;
viewer.setCenter(new Point2D.Double(x, y));
viewer.repaint();
}
if( requestedZoom != 0 )
{
int zoomLevel = viewer.getZoom() + requestedZoom;
viewer.setZoom( zoomLevel );
}
}
}

View File

@@ -0,0 +1,104 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.input;
import org.jdesktop.swingx.JXMapViewer;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
/**
* Used to pan using press and drag mouse gestures
* @author joshy
*/
public class PanMouseInputListener extends MouseInputAdapter
{
private Point prev;
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public PanMouseInputListener(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent evt)
{
prev = evt.getPoint();
}
@Override
public void mouseDragged(MouseEvent evt)
{
if (!SwingUtilities.isLeftMouseButton(evt))
return;
Point current = evt.getPoint();
double x = viewer.getCenter().getX() - (current.x - prev.x);
double y = viewer.getCenter().getY() - (current.y - prev.y);
if (!viewer.isNegativeYAllowed())
{
if (y < 0)
{
y = 0;
}
}
int maxHeight = (int) (viewer.getTileFactory().getMapSize(viewer.getZoom()).getHeight() * viewer
.getTileFactory().getTileSize(viewer.getZoom()));
if (y > maxHeight)
{
y = maxHeight;
}
prev = current;
viewer.setCenter(new Point2D.Double(x, y));
viewer.repaint();
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
@Override
public void mouseReleased(MouseEvent evt)
{
if (!SwingUtilities.isLeftMouseButton(evt))
return;
prev = null;
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseEntered(MouseEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
viewer.requestFocusInWindow();
}
});
}
}

View File

@@ -0,0 +1,46 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.input;
import org.jdesktop.swingx.JXMapViewer;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
/**
* zooms using the mouse wheel on the view center
* @author joshy
*/
public class ZoomMouseWheelListenerCenter implements MouseWheelListener
{
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public ZoomMouseWheelListenerCenter(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
viewer.setZoom(viewer.getZoom() + e.getWheelRotation());
}
}

View File

@@ -0,0 +1,72 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.input;
import io.github.dsheirer.map.MapPanel;
import org.jdesktop.swingx.JXMapViewer;
import java.awt.*;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Point2D;
/**
* zooms to the current mouse cursor
* using the mouse wheel
* @author Martin Steiger
*/
public class ZoomMouseWheelListenerCursor implements MouseWheelListener
{
private MapPanel mMapPanel;
private JXMapViewer mViewer;
/**
* @param viewer the jxmapviewer
*/
public ZoomMouseWheelListenerCursor(MapPanel mapPanel)
{
mMapPanel = mapPanel;
mViewer = mMapPanel.getMapViewer();
}
@Override
public void mouseWheelMoved(MouseWheelEvent evt)
{
Point current = evt.getPoint();
Rectangle bound = mViewer.getViewportBounds();
double dx = current.x - bound.width / 2;
double dy = current.y - bound.height / 2;
Dimension oldMapSize = mViewer.getTileFactory().getMapSize(mViewer.getZoom());
mMapPanel.adjustZoom(evt.getWheelRotation());
Dimension mapSize = mViewer.getTileFactory().getMapSize(mViewer.getZoom());
Point2D center = mViewer.getCenter();
double dzw = (mapSize.getWidth() / oldMapSize.getWidth());
double dzh = (mapSize.getHeight() / oldMapSize.getHeight());
double x = center.getX() + dx * (dzw - 1);
double y = center.getY() + dy * (dzh - 1);
mViewer.setCenter(new Point2D.Double(x, y));
}
}

View File

@@ -0,0 +1,497 @@
/*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 Dennis Sheirer
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>
* * *****************************************************************************
*
*
*/
package org.jdesktop.swingx.mapviewer;
import org.apache.commons.math3.util.FastMath;
import org.jdesktop.swingx.mapviewer.util.GeoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.swing.SwingUtilities;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
/**
* The <code>AbstractTileFactory</code> provides
* a basic implementation for the TileFactory.
*/
public abstract class AbstractTileFactory extends TileFactory
{
private final static Logger mLog = LoggerFactory.getLogger( AbstractTileFactory.class );
private boolean mSSLSuitesLogged = false;
/**
* Creates a new instance of DefaultTileFactory using the spcified TileFactoryInfo
* @param info a TileFactoryInfo to configure this TileFactory
*/
public AbstractTileFactory(TileFactoryInfo info)
{
super(info);
}
// private static final boolean doEagerLoading = true;
private int threadPoolSize = 4;
private ExecutorService service;
// TODO the tile map should be static ALWAYS, regardless of the number
// of GoogleTileFactories because each tile is, really, a singleton.
private Map<String, Tile> tileMap = new HashMap<String, Tile>();
private TileCache cache = new TileCache();
/**
* Returns the tile that is located at the given tilePoint
* for this zoom. For example, if getMapSize() returns 10x20
* for this zoom, and the tilePoint is (3,5), then the
* appropriate tile will be located and returned.
*/
@Override
public Tile getTile(int x, int y, int zoom)
{
return getTile(x, y, zoom, true);
}
private Tile getTile(int tpx, int tpy, int zoom, boolean eagerLoad)
{
// wrap the tiles horizontally --> mod the X with the max width
// and use that
int tileX = tpx;// tilePoint.getX();
int numTilesWide = (int) getMapSize(zoom).getWidth();
if (tileX < 0)
{
tileX = numTilesWide - (FastMath.abs(tileX) % numTilesWide);
}
tileX = tileX % numTilesWide;
int tileY = tpy;
// TilePoint tilePoint = new TilePoint(tileX, tpy);
String url = getInfo().getTileUrl(tileX, tileY, zoom);// tilePoint);
// System.out.println("loading: " + url);
Tile.Priority pri = Tile.Priority.High;
if (!eagerLoad)
{
pri = Tile.Priority.Low;
}
Tile tile = null;
// System.out.println("testing for validity: " + tilePoint + " zoom = " + zoom);
if (!tileMap.containsKey(url))
{
if (!GeoUtil.isValidTile(tileX, tileY, zoom, getInfo()))
{
tile = new Tile(tileX, tileY, zoom);
}
else
{
tile = new Tile(tileX, tileY, zoom, url, pri, this);
startLoading(tile);
}
tileMap.put(url, tile);
}
else
{
tile = tileMap.get(url);
// if its in the map but is low and isn't loaded yet
// but we are in high mode
if (tile.getPriority() == Tile.Priority.Low && eagerLoad && !tile.isLoaded())
{
// System.out.println("in high mode and want a low");
// tile.promote();
promote(tile);
}
}
/*
* if (eagerLoad && doEagerLoading) { for (int i = 0; i<1; i++) { for (int j = 0; j<1; j++) { // preload the 4
* tiles under the current one if(zoom > 0) { eagerlyLoad(tilePoint.getX()*2, tilePoint.getY()*2, zoom-1);
* eagerlyLoad(tilePoint.getX()*2+1, tilePoint.getY()*2, zoom-1); eagerlyLoad(tilePoint.getX()*2,
* tilePoint.getY()*2+1, zoom-1); eagerlyLoad(tilePoint.getX()*2+1, tilePoint.getY()*2+1, zoom-1); } } } }
*/
return tile;
}
/*
* private void eagerlyLoad(int x, int y, int zoom) { TilePoint t1 = new TilePoint(x,y); if(!isLoaded(t1,zoom)) {
* getTile(t1,zoom,false); } }
*/
// private boolean isLoaded(int x, int y, int zoom) {
// String url = getInfo().getTileUrl(zoom,x,y);
// return tileMap.containsKey(url);
// }
/**
* @return the tile cache
*/
public TileCache getTileCache()
{
return cache;
}
/**
* @param cache the tile cache
*/
public void setTileCache(TileCache cache)
{
this.cache = cache;
}
/** ==== threaded tile loading stuff === */
/**
* Thread pool for loading the tiles
*/
private static BlockingQueue<Tile> tileQueue = new PriorityBlockingQueue<Tile>(5, new Comparator<Tile>()
{
@Override
public int compare(Tile o1, Tile o2)
{
if (o1.getPriority() == Tile.Priority.Low && o2.getPriority() == Tile.Priority.High)
{
return 1;
}
if (o1.getPriority() == Tile.Priority.High && o2.getPriority() == Tile.Priority.Low)
{
return -1;
}
return 0;
}
});
/**
* Subclasses may override this method to provide their own executor services. This method will be called each time
* a tile needs to be loaded. Implementations should cache the ExecutorService when possible.
* @return ExecutorService to load tiles with
*/
protected synchronized ExecutorService getService()
{
if (service == null)
{
// System.out.println("creating an executor service with a threadpool of size " + threadPoolSize);
service = Executors.newFixedThreadPool(threadPoolSize, new ThreadFactory()
{
private int count = 0;
@Override
public Thread newThread(Runnable r)
{
Thread t = new Thread(r, "map tile fetcher-pool-" + count++);
t.setPriority(Thread.MIN_PRIORITY);
t.setDaemon(true);
return t;
}
});
}
return service;
}
@Override
public void dispose()
{
if (service != null)
{
service.shutdown();
service = null;
}
}
/**
* Set the number of threads to use for loading the tiles. This controls the number of threads used by the
* ExecutorService returned from getService(). Note, this method should be called before loading the first tile.
* Calls after the first tile are loaded will have no effect by default.
* @param size the thread pool size
*/
public void setThreadPoolSize(int size)
{
if (size <= 0)
{
throw new IllegalArgumentException("size invalid: " + size
+ ". The size of the threadpool must be greater than 0.");
}
threadPoolSize = size;
}
@Override
protected synchronized void startLoading(Tile tile)
{
if (tile.isLoading())
{
System.out.println("already loading. bailing");
return;
}
tile.setLoading(true);
try
{
tileQueue.put(tile);
getService().submit(createTileRunner(tile));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* Subclasses can override this if they need custom TileRunners for some reason
* @param tile the tile (unused!)
* @return the tile runner
*/
protected Runnable createTileRunner(Tile tile)
{
return new TileRunner();
}
/**
* Increase the priority of this tile so it will be loaded sooner.
* @param tile the tile
*/
public synchronized void promote(Tile tile)
{
if (tileQueue.contains(tile))
{
try
{
tileQueue.remove(tile);
tile.setPriority(Tile.Priority.High);
tileQueue.put(tile);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
/**
* An inner class which actually loads the tiles. Used by the thread queue. Subclasses can override this if
* necessary.
*/
private class TileRunner implements Runnable
{
/**
* Gets the full URI of a tile.
* @param tile the tile
* @throws URISyntaxException if the URI is invalid
* @return a URI for the tile
*/
protected URI getURI(Tile tile) throws URISyntaxException
{
if (tile.getURL() == null)
{
return null;
}
return new URI(tile.getURL());
}
/**
* implementation of the Runnable interface.
*/
@Override
public void run()
{
/*
* 3 strikes and you're out. Attempt to load the url. If it fails, decrement the number of tries left and
* try again. Log failures. If I run out of try s just get out. This way, if there is some kind of serious
* failure, I can get out and let other tiles try to load.
*/
final Tile tile = tileQueue.remove();
int trys = 3;
while (!tile.isLoaded() && trys > 0)
{
try
{
BufferedImage img = null;
URI uri = getURI(tile);
img = cache.get(uri);
if (img == null)
{
byte[] bimg = cacheInputStream(uri.toURL());
// img = PaintUtils.loadCompatibleImage(new ByteArrayInputStream(bimg));
img = ImageIO.read(new ByteArrayInputStream(bimg));
cache.put(uri, bimg, img);
img = cache.get(uri);
}
if (img == null)
{
trys--;
}
else
{
final BufferedImage i = img;
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run()
{
tile.image = new SoftReference<BufferedImage>(i);
tile.setLoaded(true);
fireTileLoadedEvent(tile);
}
});
}
}
catch (OutOfMemoryError memErr)
{
cache.needMoreMemory();
}
catch(SSLException ssle)
{
if(ssle.getMessage() != null && ssle.getMessage().startsWith("No PSK available"))
{
//JDK 11 bug: https://bugs.openjdk.java.net/browse/JDK-8213202
}
else
{
mLog.error("SSL Exception");
}
}
catch (Throwable e)
{
if (trys == 0)
{
mLog.error("Failed to load a tile at url: " + tile.getURL() + ", stopping", e );
}
else
{
mLog.error("Failed to load a tile at url: " + tile.getURL() + ", retrying", e );
trys--;
}
}
}
tile.setLoading(false);
}
private byte[] cacheInputStream(URL url) throws IOException
{
//Ugly hack. We only use OSM tiles, so detect it here and comply with SOM Terms of Service (ie user agent)
if(url.toString().startsWith("https://tile.openstreetmap.org"))
{
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.addRequestProperty("User-Agent", "sdrtrunk");
try
{
SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
sslContext.init(null, null, new SecureRandom());
conn.setSSLSocketFactory(sslContext.getSocketFactory());
}
catch(KeyManagementException kme)
{
mLog.error("Error initializing SSL context");
}
catch(NoSuchAlgorithmException nsae)
{
mLog.error("Unable to use TLSv1.3 for OpenStreetMap tiles");
}
InputStream is = conn.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true)
{
int n = is.read(buf);
if (n == -1)
break;
bout.write(buf, 0, n);
}
conn.disconnect();
return bout.toByteArray();
}
else
{
InputStream ins = url.openStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true)
{
int n = ins.read(buf);
if (n == -1)
break;
bout.write(buf, 0, n);
}
return bout.toByteArray();
}
}
}
public static void main(String[] args)
{
String a = "https://tile.openstreetmap.org/12/1178/1504.png";
// String a = "https://tile.openstreetmap.org/11/589/751.png";
try
{
URL url = new URL(a);
System.out.println("Fetching URL: " + url.getClass() + " " + url.toString());
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.addRequestProperty("User-Agent", "sdrtrunk");
InputStream is = conn.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true)
{
int n = is.read(buf);
if (n == -1)
break;
bout.write(buf, 0, n);
}
System.out.println("Bytes:" + Arrays.toString(bout.toByteArray()));
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}

View File

@@ -0,0 +1,28 @@
/*
* DefaultTileFactory.java
*
* Created on June 27, 2006, 2:20 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.jdesktop.swingx.mapviewer;
/**
* A tile factory which configures itself using a TileFactoryInfo object and uses a Google Maps like mercator
* projection.
* @author joshy
*/
public class DefaultTileFactory extends AbstractTileFactory
{
/**
* Creates a new instance of DefaultTileFactory using the spcified TileFactoryInfo
* @param info a TileFactoryInfo to configure this TileFactory
*/
public DefaultTileFactory(TileFactoryInfo info)
{
super(info);
}
}

View File

@@ -0,0 +1,63 @@
/*
* Waypoint.java
*
* Created on March 30, 2006, 5:22 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.jdesktop.swingx.mapviewer;
import org.jdesktop.beans.AbstractBean;
/**
* @author joshy
*/
public class DefaultWaypoint extends AbstractBean implements Waypoint
{
private GeoPosition position;
/**
* Creates a new instance of Waypoint
*/
public DefaultWaypoint()
{
this(new GeoPosition(0, 0));
}
/**
* @param latitude the latitude
* @param longitude the longitude
*/
public DefaultWaypoint(double latitude, double longitude)
{
this(new GeoPosition(latitude, longitude));
}
/**
* @param coord the geo coordinate
*/
public DefaultWaypoint(GeoPosition coord)
{
this.position = coord;
}
@Override
public GeoPosition getPosition()
{
return position;
}
/**
* Set a new GeoPosition for this Waypoint
* @param coordinate a new position
*/
public void setPosition(GeoPosition coordinate)
{
GeoPosition old = getPosition();
this.position = coordinate;
firePropertyChange("position", old, getPosition());
}
}

View File

@@ -0,0 +1,60 @@
/*
* WaypointRenderer.java
*
* Created on March 30, 2006, 5:24 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.jdesktop.swingx.mapviewer;
import org.jdesktop.swingx.JXMapViewer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
/**
* This is a standard waypoint renderer.
* @author joshy
*/
public class DefaultWaypointRenderer implements WaypointRenderer<Waypoint>
{
private final static Logger mLog =
LoggerFactory.getLogger( DefaultWaypointRenderer.class );
private BufferedImage img = null;
/**
* Uses a default waypoint image
*/
public DefaultWaypointRenderer()
{
try
{
img = ImageIO.read(getClass().getResource("resources/standard_waypoint.png"));
}
catch (Exception ex)
{
mLog.error("couldn't read standard_waypoint.png", ex );
}
}
@Override
public void paintWaypoint(Graphics2D g, JXMapViewer map, Waypoint w)
{
if (img == null)
return;
Point2D point = map.getTileFactory().geoToPixel(w.getPosition(), map.getZoom());
int x = (int)point.getX() -img.getWidth() / 2;
int y = (int)point.getY() -img.getHeight();
g.drawImage(img, x, y, null);
}
}

View File

@@ -0,0 +1,160 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.mapviewer;
import org.apache.commons.math3.util.FastMath;
import java.awt.geom.Rectangle2D;
import java.util.Set;
/**
* The <code>GeoBounds</code> class provides access the the North East and South West corners of the bounds and provides
* an intersects method.
* @author Dan Andrews
*/
public class GeoBounds
{
/** Internal representation of the bounds */
private Rectangle2D[] rects;
/**
* Constructor.
* @param minLat The minimum latitude.
* @param minLng The minimum longitude.
* @param maxLat The maximum latitude.
* @param maxLng The maximum longitude.
*/
public GeoBounds(double minLat, double minLng, double maxLat, double maxLng)
{
setRect(minLat, minLng, maxLat, maxLng);
}
/**
* Constructor.
* @param geoPositions A non null list of 2 or more different <code>GeoBounds</code> objects.
*/
public GeoBounds(Set<GeoPosition> geoPositions)
{
if (geoPositions == null || geoPositions.size() < 2)
{
throw new IllegalArgumentException("The attribute 'geoPositions' cannot be null and must "
+ "have 2 or more elements.");
}
double minLat = Integer.MAX_VALUE;
double minLng = Integer.MAX_VALUE;
double maxLat = Integer.MIN_VALUE;
double maxLng = Integer.MIN_VALUE;
for (GeoPosition position : geoPositions)
{
minLat = FastMath.min(minLat, position.getLatitude());
minLng = FastMath.min(minLng, position.getLongitude());
maxLat = FastMath.max(maxLat, position.getLatitude());
maxLng = FastMath.max(maxLng, position.getLongitude());
}
setRect(minLat, minLng, maxLat, maxLng);
}
/**
* Sets the internal rectangle representation.
* @param minLat The minimum latitude.
* @param minLng The minimum longitude.
* @param maxLat The maximum latitude.
* @param maxLng The maximum longitude.
*/
private void setRect(double minLat, double minLng, double maxLat, double maxLng)
{
if (!(minLat < maxLat))
{
throw new IllegalArgumentException("GeoBounds is not valid - minLat must be less that maxLat.");
}
if (!(minLng < maxLng))
{
if (minLng > 0 && minLng < 180 && maxLng < 0)
{
rects = new Rectangle2D[] {
// split into two rects e.g. 176.8793 to 180 and -180 to
// -175.0104
new Rectangle2D.Double(minLng, minLat, 180 - minLng, maxLat - minLat),
new Rectangle2D.Double(-180, minLat, maxLng + 180, maxLat - minLat) };
}
else
{
rects = new Rectangle2D[] { new Rectangle2D.Double(minLng, minLat, maxLng - minLng, maxLat - minLat) };
throw new IllegalArgumentException("GeoBounds is not valid - minLng must be less that maxLng or "
+ "minLng must be greater than 0 and maxLng must be less than 0.");
}
}
else
{
rects = new Rectangle2D[] { new Rectangle2D.Double(minLng, minLat, maxLng - minLng, maxLat - minLat) };
}
}
/**
* Determines if this bounds intersects the other bounds.
* @param other The other bounds to test for intersection with.
* @return Returns true if bounds intersect.
*/
public boolean intersects(GeoBounds other)
{
boolean rv = false;
for (Rectangle2D r1 : rects)
{
for (Rectangle2D r2 : other.rects)
{
rv = r1.intersects(r2);
if (rv)
{
break;
}
}
if (rv)
{
break;
}
}
return rv;
}
/**
* Gets the north west position.
* @return Returns the north west position.
*/
public GeoPosition getNorthWest()
{
return new GeoPosition(rects[0].getX(), rects[0].getMaxY());
}
/**
* Gets the south east position.
* @return Returns the south east position.
*/
public GeoPosition getSouthEast()
{
Rectangle2D r = rects[0];
if (rects.length > 1)
{
r = rects[1];
}
return new GeoPosition(r.getMaxX(), r.getY());
}
}

View File

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

View File

@@ -0,0 +1,326 @@
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.mapviewer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ResponseCache;
import java.net.URI;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* @author joshy
*/
public class LocalResponseCache extends ResponseCache
{
private final static Logger mLog =
LoggerFactory.getLogger( LocalResponseCache.class );
private final File cacheDir;
private boolean checkForUpdates;
private String baseURL;
/**
* Private constructor to prevent instantiation.
* @param baseURL the URI that should be cached or <code>null</code> (for all URLs)
* @param cacheDir the cache directory
* @param checkForUpdates true if the URL is queried for newer versions of a file first
*/
private LocalResponseCache(String baseURL, File cacheDir, boolean checkForUpdates)
{
this.baseURL = baseURL;
this.cacheDir = cacheDir;
this.checkForUpdates = checkForUpdates;
if (!cacheDir.exists())
{
cacheDir.mkdirs();
}
}
/**
* Sets this cache as default response cache
* @param baseURL the URL, the caching should be restricted to or <code>null</code> for none
* @param cacheDir the cache directory
* @param checkForUpdates true if the URL is queried for newer versions of a file first
*/
public static void installResponseCache(String baseURL, File cacheDir, boolean checkForUpdates)
{
ResponseCache.setDefault(new LocalResponseCache(baseURL, cacheDir, checkForUpdates));
}
/**
* Returns the local File corresponding to the given remote URI.
* @param remoteUri the remote URI
* @return the corresponding local file
*/
public File getLocalFile(URI remoteUri)
{
if (baseURL != null)
{
String remote = remoteUri.toString();
if (!remote.startsWith(baseURL))
{
return null;
}
}
StringBuilder sb = new StringBuilder();
String host = remoteUri.getHost();
String query = remoteUri.getQuery();
String path = remoteUri.getPath();
String fragment = remoteUri.getFragment();
if (host != null)
{
sb.append(host);
}
if (path != null)
{
sb.append(path);
}
if (query != null)
{
sb.append('?');
sb.append(query);
}
if (fragment != null)
{
sb.append('#');
sb.append(fragment);
}
String name;
final int maxLen = 250;
if (sb.length() < maxLen)
{
name = sb.toString();
}
else
{
name = sb.substring(0, maxLen);
}
name = name.replace('?', '$');
name = name.replace('*', '$');
name = name.replace(':', '$');
name = name.replace('<', '$');
name = name.replace('>', '$');
name = name.replace('"', '$');
File f = new File(cacheDir, name);
return f;
}
/**
* @param remoteUri the remote URI
* @param localFile the corresponding local file
* @return true if the resource at the given remote URI is newer than the resource cached locally.
*/
private static boolean isUpdateAvailable(URI remoteUri, File localFile)
{
URLConnection conn;
try
{
conn = remoteUri.toURL().openConnection();
}
catch (MalformedURLException ex)
{
mLog.error("An exception occurred - ", ex );
return false;
}
catch (IOException ex)
{
mLog.error("An exception occurred - ", ex );
return false;
}
if (!(conn instanceof HttpURLConnection))
{
// don't bother with non-http connections
return false;
}
long localLastMod = localFile.lastModified();
long remoteLastMod = 0L;
HttpURLConnection httpconn = (HttpURLConnection) conn;
// disable caching so we don't get in feedback loop with ResponseCache
httpconn.setUseCaches(false);
try
{
httpconn.connect();
remoteLastMod = httpconn.getLastModified();
}
catch (IOException ex)
{
// log.error("An exception occurred", ex);();
return false;
}
finally
{
httpconn.disconnect();
}
return (remoteLastMod > localLastMod);
}
@Override
public CacheResponse get(URI uri, String rqstMethod, Map<String, List<String>> rqstHeaders) throws IOException
{
File localFile = getLocalFile(uri);
if (localFile == null)
{
// we don't want to cache this URL
return null;
}
if (!localFile.exists())
{
// the file isn't already in our cache, return null
return null;
}
if (checkForUpdates)
{
if (isUpdateAvailable(uri, localFile))
{
// there is an update available, so don't return cached version
return null;
}
}
return new LocalCacheResponse(localFile, rqstHeaders);
}
@Override
public CacheRequest put(URI uri, URLConnection conn) throws IOException
{
// only cache http(s) GET requests
if (!(conn instanceof HttpURLConnection) || !(((HttpURLConnection) conn).getRequestMethod().equals("GET")))
{
return null;
}
File localFile = getLocalFile(uri);
if (localFile == null)
{
// we don't want to cache this URL
return null;
}
new File(localFile.getParent()).mkdirs();
return new LocalCacheRequest(localFile);
}
private class LocalCacheResponse extends CacheResponse
{
private FileInputStream fis;
private final Map<String, List<String>> headers;
private LocalCacheResponse(File localFile, Map<String, List<String>> rqstHeaders)
{
try
{
this.fis = new FileInputStream(localFile);
}
catch (FileNotFoundException ex)
{
// should not happen, since we already checked for existence
mLog.error("An exception occurred - ", ex );
}
this.headers = rqstHeaders;
}
@Override
public Map<String, List<String>> getHeaders() throws IOException
{
return headers;
}
@Override
public InputStream getBody() throws IOException
{
return fis;
}
}
private class LocalCacheRequest extends CacheRequest
{
private final File localFile;
private FileOutputStream fos;
private LocalCacheRequest(File localFile)
{
this.localFile = localFile;
try
{
this.fos = new FileOutputStream(localFile);
}
catch (FileNotFoundException ex)
{
// should not happen if cache dir is valid
mLog.error("An exception occurred", ex );
}
}
@Override
public OutputStream getBody() throws IOException
{
return fos;
}
@Override
public void abort()
{
// abandon the cache attempt by closing the stream and deleting
// the local file
try
{
fos.close();
localFile.delete();
}
catch (IOException e)
{
// ignore
}
}
}
}

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