diff options
Diffstat (limited to 'qmap')
47 files changed, 2081 insertions, 533 deletions
diff --git a/qmap/CMakeLists.txt b/qmap/CMakeLists.txt index bd943589..4a4e43ba 100644 --- a/qmap/CMakeLists.txt +++ b/qmap/CMakeLists.txt @@ -2,14 +2,19 @@ set (qmap_CXXSRCS about.cpp astro.cpp devsetup.cpp + decode_click_coalescer.cpp displaytext.cpp getfile.cpp + livecq_parser.cpp main.cpp mainwindow.cpp meterwidget.cpp plotter.cpp + runtime_paths.cpp signalmeter.cpp soundin.cpp + vertwaterfall.cpp + vplotter.cpp widegraph.cpp ) @@ -22,6 +27,7 @@ set (qmap_UISRCS astro.ui devsetup.ui mainwindow.ui + vertwaterfall.ui widegraph.ui ) @@ -38,22 +44,16 @@ add_subdirectory (libqmap) # UI generation qt5_wrap_ui (qmap_GENUISRCS ${qmap_UISRCS}) -add_executable (qmap ${qmap_CXXSRCS} ${qmap_CSRCS} ${qmap_GENUISRCS} qmap.rc) +# windres doesn't track a .rc file's ICON directive as a dependency, so an icon-only edit needs this to trigger a rebuild. +set_property (SOURCE qmap.rc APPEND PROPERTY OBJECT_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/wsjt.ico) + +# Resource generation (About dialog logo + GPL logo) +qt5_add_resources (qmap_RESOURCES_RCC about.qrc) + +add_executable (qmap ${qmap_CXXSRCS} ${qmap_CSRCS} ${qmap_GENUISRCS} ${qmap_RESOURCES_RCC} qmap.rc) target_include_directories (qmap PRIVATE ${CMAKE_SOURCE_DIR} ${FFTW3_INCLUDE_DIRS}) target_link_libraries (qmap wsjt_qt qmap_impl ${FFTW3_LIBRARIES} Qt5::Widgets Qt5::Network Usb::Usb) if (WSJT_CREATE_WINMAIN) set_target_properties (qmap PROPERTIES WIN32_EXECUTABLE ON) endif (WSJT_CREATE_WINMAIN) - -if (WIN32) - install ( - CODE "get_filename_component (_path \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}/wsjtx_dir.txt\" REALPATH) - if (WIN32) - set (_separator \"\\\\\") - else () - set (_separator \"/\") - endif () - file (WRITE \"\${_path}\" \".\${_separator}\\n\")" - ) -endif () diff --git a/qmap/about.cpp b/qmap/about.cpp index 7ee4adcb..62374325 100644 --- a/qmap/about.cpp +++ b/qmap/about.cpp @@ -7,14 +7,21 @@ CAboutDlg::CAboutDlg(QWidget *parent) : ui(new Ui::CAboutDlg) { ui->setupUi(this); - ui->labelTxt->setText("<html><h2>" + QString {"QMAP v" + ui->labelTxt->setText("<html><h2>" + QString {"QMAP™ v" + QCoreApplication::applicationVersion ()+ " " + revision ()}.simplified () + "</h2>" - "QMAP is a wideband receiver for the Q65 protocol, intended<br/>" + "QMAP™ is a wideband receiver for the Q65 protocol, intended<br/>" "primarily for amateur radio EME communication. It works<br/>" - "in close cooperation with WSJT-X versions 2.7.0 and later.<br/><br/>" - "Copyright 2001-2026 by Joe Taylor, K1JT., and the WSJT <br/>" - "Development Group. <br/>"); + "in close cooperation with WSJT-X™ versions 2.7.0 and later.<br/><br/>" + "Copyright 2001-2026 by Joe Taylor, K1JT., and the WSJT™ <br/>" + "Development Team. <br/><br/>" + "QMAP is licensed under the terms of Version 3 <br />" + "of the GNU General Public License (GPL) <br /><br />" + "<a href=" TO_STRING__ (PROJECT_HOMEPAGE) ">" + "<img src=\":/icon_128x128.png\" /></a>" + "<a href=\"https://www.gnu.org/licenses/gpl-3.0.txt\">" + "<img src=\":/gpl-v3-logo.svg\" height=\"80\" /><br />" + "https://www.gnu.org/licenses/gpl-3.0.txt</a>"); } CAboutDlg::~CAboutDlg() diff --git a/qmap/about.qrc b/qmap/about.qrc new file mode 100644 index 00000000..9520adbc --- /dev/null +++ b/qmap/about.qrc @@ -0,0 +1,6 @@ +<RCC> + <qresource prefix="/"> + <file alias="icon_128x128.png">about_icon.png</file> + <file alias="gpl-v3-logo.svg">../contrib/gpl-v3-logo.svg</file> + </qresource> +</RCC> diff --git a/qmap/about.ui b/qmap/about.ui index dbcd8651..614f25d6 100644 --- a/qmap/about.ui +++ b/qmap/about.ui @@ -5,22 +5,8 @@ <property name="windowModality"> <enum>Qt::NonModal</enum> </property> - <property name="geometry"> - <rect> - <x>0</x> - <y>0</y> - <width>374</width> - <height>164</height> - </rect> - </property> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> <property name="windowTitle"> - <string>About QMAP</string> + <string>About QMAP™</string> </property> <layout class="QHBoxLayout" name="horizontalLayout"> <item> @@ -28,6 +14,12 @@ <property name="text"> <string/> </property> + <property name="alignment"> + <set>Qt::AlignCenter</set> + </property> + <property name="openExternalLinks"> + <bool>true</bool> + </property> </widget> </item> </layout> diff --git a/qmap/about_icon.png b/qmap/about_icon.png Binary files differnew file mode 100644 index 00000000..11026fa2 --- /dev/null +++ b/qmap/about_icon.png diff --git a/qmap/commons.h b/qmap/commons.h index d62a9570..0b8c10d0 100644 --- a/qmap/commons.h +++ b/qmap/commons.h @@ -1,6 +1,8 @@ #ifndef COMMONS_H #define COMMONS_H +#include "qmap_ipc.h" + #define NFFT 32768 extern "C" { @@ -87,19 +89,8 @@ extern struct { //This is "common/datcom/..." in Fortran bool bAlso30; //Process for 30-second submode as well as 60-second } datcom2_; -extern struct { - int ndecodes; //These are flags for inter-process communication - int ncand; //between QMAP and WSJT-X - int nQDecoderDone; //1 for real-time decodes, 2 for data from disk - int nWDecoderBusy; //Set to 1 when WSJT-X decoder is busy - int nWTransmitting; //Set to TRperiod when WSJT-X is transmitting - int kHzRequested; //Integer kHz dial frequency request to WSJT-X - char result[50][72]; //Staging area for QMAP decodes -} decodes_; - -extern struct { - char result2[50][8]; -} decodes2_; +extern qmap_decode_ipc::DecodeRows decodes_; +extern qmap_decode_ipc::LiveCqRows decodes2_; extern struct { char revision[22]; diff --git a/qmap/decode_click_coalescer.cpp b/qmap/decode_click_coalescer.cpp new file mode 100644 index 00000000..b1c2725e --- /dev/null +++ b/qmap/decode_click_coalescer.cpp @@ -0,0 +1,50 @@ +#include "decode_click_coalescer.h" + +#include <utility> + +#include <QApplication> +#include <QObject> + +DecodeClickCoalescer::DecodeClickCoalescer (QObject * context, Dispatch dispatch, int interval) + : dispatch_ {std::move (dispatch)} +{ + timer_.setSingleShot (true); + timer_.setTimerType (Qt::PreciseTimer); + timer_.setInterval (interval >= 0 ? interval : QApplication::doubleClickInterval ()); + QObject::connect (&timer_, &QTimer::timeout, context, [this] { dispatchPending (); }); +} + +void DecodeClickCoalescer::press (QString const& identity, QByteArray const& decodeRow) +{ + // Qt reports the first press before deciding whether the gesture is a double-click. + if (timer_.isActive () && pendingIdentity_ != identity) { + timer_.stop (); + dispatchPending (); + } + dispatch_ (decodeRow, DecodeClickGesture::Press); + pendingIdentity_ = identity; + pending_ = decodeRow; + timer_.start (); +} + +void DecodeClickCoalescer::doubleClick (QString const& identity, QByteArray const& decodeRow) +{ + if (timer_.isActive ()) { + timer_.stop (); + if (pendingIdentity_ != identity) dispatchPending (); + else { + pendingIdentity_.clear (); + pending_.clear (); + } + } + dispatch_ (decodeRow, DecodeClickGesture::DoubleClick); +} + +void DecodeClickCoalescer::dispatchPending () +{ + if (pending_.isEmpty ()) return; + auto const decodeRow = pending_; + pendingIdentity_.clear (); + pending_.clear (); + dispatch_ (decodeRow, DecodeClickGesture::SingleClick); +} diff --git a/qmap/decode_click_coalescer.h b/qmap/decode_click_coalescer.h new file mode 100644 index 00000000..98a59c10 --- /dev/null +++ b/qmap/decode_click_coalescer.h @@ -0,0 +1,38 @@ +#ifndef QMAP_DECODE_CLICK_COALESCER_H +#define QMAP_DECODE_CLICK_COALESCER_H + +#include <functional> + +#include <QByteArray> +#include <QString> +#include <QTimer> + +class QObject; + +enum class DecodeClickGesture +{ + Press, + SingleClick, + DoubleClick, +}; + +class DecodeClickCoalescer +{ +public: + using Dispatch = std::function<void (QByteArray const&, DecodeClickGesture)>; + + DecodeClickCoalescer (QObject * context, Dispatch dispatch, int interval = -1); + + void press (QString const& identity, QByteArray const& decodeRow); + void doubleClick (QString const& identity, QByteArray const& decodeRow); + +private: + void dispatchPending (); + + Dispatch dispatch_; + QTimer timer_; + QString pendingIdentity_; + QByteArray pending_; +}; + +#endif // QMAP_DECODE_CLICK_COALESCER_H diff --git a/qmap/decode_ipc.h b/qmap/decode_ipc.h new file mode 100644 index 00000000..8b554b33 --- /dev/null +++ b/qmap/decode_ipc.h @@ -0,0 +1,53 @@ +#ifndef QMAP_DECODE_IPC_H +#define QMAP_DECODE_IPC_H + +#include <cstddef> +#include <type_traits> + +namespace qmap_decode_ipc +{ + // Keep row dimensions in sync with qmap_decode_ipc.f90. + constexpr std::size_t shared_memory_size {4096}; + constexpr std::size_t max_rows {50}; + constexpr std::size_t row_size {80}; + constexpr std::size_t live_cq_row_size {8}; + + struct DecodeRows + { + int ndecodes; // Number of populated decode rows in the current cycle. + int ncand; // Number of QMAP candidates found in the current cycle. + int nQDecoderDone; // QMAP completion state: 1 for live data, 2 for disk data. + int nWDecoderBusy; // WSJT-X decoder busy flag: 1 while busy, otherwise 0. + int nWTransmitting; // WSJT-X transmit period while transmitting, otherwise 0. + int kHzRequested; // QMAP dial request in integer kHz; 0 means no request. + char result[max_rows][row_size]; // Formatted QMAP decode rows. + }; + + struct LiveCqRows + { + char result2[max_rows][live_cq_row_size]; + }; + + template<std::size_t Size> + std::size_t text_length (char const (&row)[Size]) noexcept + { + std::size_t length {0}; + while (length < Size && row[length]) ++length; + return length; + } + + static_assert (std::is_standard_layout<DecodeRows>::value, + "QMAP decode IPC data must have a stable layout"); + static_assert (std::is_trivially_copyable<DecodeRows>::value, + "QMAP decode IPC data must support shared-memory copies"); + static_assert (sizeof (int) == 4, + "QMAP decode IPC integers must match Fortran INTEGER storage"); + static_assert (sizeof (DecodeRows) == 6 * sizeof (int) + max_rows * row_size, + "QMAP decode IPC data must not contain padding"); + static_assert (sizeof (DecodeRows) <= shared_memory_size, + "QMAP decode IPC data must fit in shared memory"); + static_assert (sizeof (LiveCqRows) == max_rows * live_cq_row_size, + "QMAP LiveCQ data must not contain padding"); +} + +#endif diff --git a/qmap/decode_label.h b/qmap/decode_label.h new file mode 100644 index 00000000..5e9417cb --- /dev/null +++ b/qmap/decode_label.h @@ -0,0 +1,38 @@ +#ifndef QMAP_DECODE_LABEL_H +#define QMAP_DECODE_LABEL_H + +#include <algorithm> + +#include <QList> + +#include "qmap_decode_record.h" + +using QMapDecodeLabel = QMapDecodeRecord; +constexpr int QMapDecodeLabelMaximum = 100; +constexpr int QMapDecodeLabelLifetimeSecs = 3 * 60; + +inline void upsertQMapDecodeLabel (QList<QMapDecodeLabel>& labels, + QMapDecodeRecord const& record) +{ + for (auto& label : labels) { + if (label.callsign == record.callsign) { + label = record; + return; + } + } + if (labels.size () >= QMapDecodeLabelMaximum) labels.removeFirst (); + labels.append (record); +} + +inline void pruneQMapDecodeLabels (QList<QMapDecodeLabel>& labels, int nowSeconds) +{ + labels.erase (std::remove_if (labels.begin (), labels.end (), + [nowSeconds] (QMapDecodeLabel const& label) { + int delta = nowSeconds - label.secondsSinceMidnight; + if (delta < -43200) delta += 86400; + else if (delta > 43200) delta -= 86400; + return delta > QMapDecodeLabelLifetimeSecs; + }), labels.end ()); +} + +#endif // QMAP_DECODE_LABEL_H diff --git a/qmap/getfile.cpp b/qmap/getfile.cpp index 644d4b05..dc29b279 100644 --- a/qmap/getfile.cpp +++ b/qmap/getfile.cpp @@ -1,11 +1,11 @@ #include "getfile.h" -#include <QDir> -#include <stdio.h> +#include <QFile> +#include <algorithm> +#include <array> +#include <vector> #include <stdlib.h> #include <math.h> -extern qint16 id[2*60*96000]; - void getfile(QString fname, int dbDgrd) { // int npts=2*56*96000; @@ -16,34 +16,36 @@ void getfile(QString fname, int dbDgrd) if(dbDgrd<0) dgrd = 23.0*sqrt(pow(10.0,-0.1*(double)dbDgrd) - 1.0); float fac=23.0/sqrt(dgrd*dgrd + 23.0*23.0); - memset(id,0,2*npts); - char name[80]; - strcpy(name,fname.toLocal8Bit()); - FILE* fp=fopen(name,"rb"); + QFile file(fname); - if(fp != NULL) { - auto n = fread(&datcom_.fcenter,sizeof(datcom_.fcenter),1,fp); - n=fread(id,2,npts,fp); - n=fread(&datcom_.ntx30a,4,1,fp); - n=fread(&datcom_.ntx30b,4,1,fp); - if(n==0) { - datcom_.ntx30a=0; - datcom_.ntx30b=0; - } + if(file.open(QIODevice::ReadOnly)) { + file.read(reinterpret_cast<char *>(&datcom_.fcenter), sizeof(datcom_.fcenter)); + std::array<qint16, 16384> samples; int j=0; - - if(dbDgrd<0) { - for(int i=0; i<npts; i+=2) { - datcom_.d4[j++]=fac*((float)id[i] + dgrd*gran()); - datcom_.d4[j++]=fac*((float)id[i+1] + dgrd*gran()); - } - } else { - for(int i=0; i<npts; i+=2) { - datcom_.d4[j++]=(float)id[i]; - datcom_.d4[j++]=(float)id[i+1]; + while(j<npts) { + int want=std::min<int>(samples.size(),npts-j); + qint64 bytes_read=file.read(reinterpret_cast<char *>(samples.data()), + want * static_cast<qint64>(sizeof(qint16))); + size_t n=bytes_read > 0 + ? static_cast<size_t>(bytes_read / static_cast<qint64>(sizeof(qint16))) + : 0; + for(size_t i=0; i<n; ++i) { + datcom_.d4[j++]=dbDgrd<0 + ? fac*((float)samples[i] + dgrd*gran()) + : (float)samples[i]; } + if(n<static_cast<size_t>(want)) break; + } + while(j<npts) datcom_.d4[j++]=0.0; + qint64 ntx30_size=static_cast<qint64>(sizeof(datcom_.ntx30a)); + bool read_ntx30a=file.read(reinterpret_cast<char *>(&datcom_.ntx30a), + ntx30_size) == ntx30_size; + bool read_ntx30b=file.read(reinterpret_cast<char *>(&datcom_.ntx30b), + ntx30_size) == ntx30_size; + if(!read_ntx30a || !read_ntx30b) { + datcom_.ntx30a=0; + datcom_.ntx30b=0; } - fclose(fp); datcom_.ndiskdat=1; // int nfreq=(int)datcom_.fcenter; @@ -59,23 +61,23 @@ void getfile(QString fname, int dbDgrd) void save_iq(QString fname) { int npts=2*60*96000; - qint16* buf=(qint16*)malloc(2*npts); - char name[80]; - strcpy(name,fname.toLocal8Bit()); - FILE* fp=fopen(name,"wb"); + std::vector<qint16> buf(npts); + QFile file(fname); - if(fp != NULL) { - fwrite(&datcom_.fcenter,sizeof(datcom_.fcenter),1,fp); + if(file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + file.write(reinterpret_cast<char const *>(&datcom_.fcenter), + sizeof(datcom_.fcenter)); int j=0; for(int i=0; i<npts; i+=2) { buf[i]=(qint16)qRound(datcom_.d4[j++]); buf[i+1]=(qint16)qRound(datcom_.d4[j++]); } - fwrite(buf,2,npts,fp); - fwrite(&datcom_.ntx30a,4,2,fp); //Write ntx30a and ntx30b to disk - fclose(fp); + file.write(reinterpret_cast<char const *>(buf.data()), + static_cast<qint64>(buf.size() * sizeof(qint16))); + qint64 ntx30_size=static_cast<qint64>(sizeof(datcom_.ntx30a)); + file.write(reinterpret_cast<char const *>(&datcom_.ntx30a), + 2 * ntx30_size); } - free(buf); } /* Generate gaussian random float with mean=0 and std_dev=1 */ diff --git a/qmap/libqmap/CMakeLists.txt b/qmap/libqmap/CMakeLists.txt index 2eb3a0bb..5480486b 100644 --- a/qmap/libqmap/CMakeLists.txt +++ b/qmap/libqmap/CMakeLists.txt @@ -1,5 +1,7 @@ set (libq65_FSRCS # Modules come first: + qmap_decode_ipc.f90 + cacb_mod.f90 # Non-module Fortran routines: astro.f90 @@ -48,10 +50,20 @@ set (libq65_C_and_CXXSRCS set_property (SOURCE ${libq65_C_and_CXXSRCS} APPEND_STRING PROPERTY COMPILE_FLAGS " -include wsjtx_config.h") set_property (SOURCE ${libq65_C_and_CXXSRCS} APPEND PROPERTY OBJECT_DEPENDS ${CMAKE_BINARY_DIR}/wsjtx_config.h) +# These carry dummy arguments that are genuine QMAP-GUI-supplied state +# (see qmap/mainwindow.cpp) which the current Fortran implementation +# doesn't happen to reference; removing them would mean touching the +# GUI call sites too, so we suppress the warning instead. +set_source_files_properties (chkstat.f90 PROPERTIES COMPILE_FLAGS "-Wno-unused-dummy-argument") +set_source_files_properties (symspec.f90 PROPERTIES COMPILE_FLAGS "-Wno-unused-dummy-argument") +set_source_files_properties (q65b.f90 PROPERTIES COMPILE_FLAGS "-Wno-unused-dummy-argument") + # # build our targets # add_library (qmap_impl STATIC ${libq65_FSRCS} ${libq65_CSRCS} ${libq65_CXXSRCS}) -target_link_libraries (qmap_impl wsjt_fort wsjt_cxx Qt5::Core) - +if (NOT APPLE) + target_link_libraries (qmap_impl PUBLIC Qt5::Core) +endif () +wsjt_link_common_fortran (qmap_impl) diff --git a/qmap/libqmap/cacb_mod.f90 b/qmap/libqmap/cacb_mod.f90 new file mode 100644 index 00000000..ed4af75c --- /dev/null +++ b/qmap/libqmap/cacb_mod.f90 @@ -0,0 +1,23 @@ +module cacb_mod + implicit none + + complex, allocatable :: ca(:) ! FFT of raw I/Q data from Linrad + +contains + + subroutine init_cacb(n) + integer, intent(in) :: n + + if (allocated(ca)) then + if (size(ca) >= n) return + deallocate(ca) + endif + + allocate(ca(n)) + end subroutine init_cacb + + subroutine free_cacb() + if (allocated(ca)) deallocate(ca) + end subroutine free_cacb + +end module cacb_mod diff --git a/qmap/libqmap/decode0.f90 b/qmap/libqmap/decode0.f90 index d119fdcb..901da861 100644 --- a/qmap/libqmap/decode0.f90 +++ b/qmap/libqmap/decode0.f90 @@ -1,6 +1,7 @@ subroutine decode0(dd,ss,savg) use timer_module, only: timer + use qmap_decode_ipc, only: nQDecoderDone parameter (NSMAX=60*96000,NFFT=32768) real*4 dd(2,NSMAX),ss(400,NFFT),savg(NFFT) @@ -10,9 +11,6 @@ subroutine decode0(dd,ss,savg) logical*1 bAlso30 character mycall*12,hiscall*12,mygrid*6,hisgrid*6,datetime*20 character mycall0*12,hiscall0*12,hisgrid0*6 - character*72 result - common/decodes/ndecodes,ncand2,nQDecoderDone,nWDecoderBusy, & - nWTransmitting,kHzRequested,result(50) common/npar/fcenter,nutc,fselected,mousedf,mousefqso,nagain, & ndepth,ndiskdat,ntx60,newdat,nfa,nfb,nfcal,nfshift, & ntx30a,ntx30b,ntol,n60,nCFOM,nfsample,ndop58,nmode, & diff --git a/qmap/libqmap/fftbig.f90 b/qmap/libqmap/fftbig.f90 index 085fd39f..5fc2af6e 100644 --- a/qmap/libqmap/fftbig.f90 +++ b/qmap/libqmap/fftbig.f90 @@ -6,13 +6,12 @@ subroutine fftbig(dd,nmax) use FFTW3 use timer_module, only: timer + use cacb_mod, only: ca, init_cacb, free_cacb parameter (MAXFFT1=5376000) real*4 dd(2,nmax) !Input data - complex ca(MAXFFT1) !FFT of input real*8 df type(C_PTR) :: plan1 !Pointer to FFTW plan logical first - common/cacb/ca equivalence (rfilt,cfilt) data first/.true./,npatience/0/ save @@ -20,6 +19,7 @@ subroutine fftbig(dd,nmax) if(nmax.lt.0) go to 900 nfft1=MAXFFT1 + call init_cacb(nfft1) if(first) then nflags=FFTW_ESTIMATE if(npatience.eq.1) nflags=FFTW_ESTIMATE_PATIENT @@ -50,7 +50,9 @@ subroutine fftbig(dd,nmax) call timer('FFTbig ',1) go to 999 -900 call fftwf_destroy_plan(plan1) +900 if(.not.first) call fftwf_destroy_plan(plan1) + call free_cacb() + first=.true. 999 return end subroutine fftbig diff --git a/qmap/libqmap/getcand2.f90 b/qmap/libqmap/getcand2.f90 index 521f97f6..c98c3088 100644 --- a/qmap/libqmap/getcand2.f90 +++ b/qmap/libqmap/getcand2.f90 @@ -16,6 +16,7 @@ subroutine getcand2(ss,savg0,nts_q65,nagain,nhsym,ntx30a,ntx30b, & type(candidate) :: cand(MAX_CANDIDATES) real ss(400,NFFT) !Symbol spectra real savg0(NFFT),savg(NFFT) !Average spectra over whole Rx sequence + save savg !Keep this big array off the stack integer ipk1(1) !Peak index of local portion of spectrum logical sync_ok !True if sync pattern is present logical*1 bAlso30 diff --git a/qmap/libqmap/q65b.f90 b/qmap/libqmap/q65b.f90 index 8409b798..619f785d 100644 --- a/qmap/libqmap/q65b.f90 +++ b/qmap/libqmap/q65b.f90 @@ -6,20 +6,24 @@ subroutine q65b(nutc,nqd,fcenter,nfcal,nfsample,ikhz,mousedf,ntol, & ! This routine provides an interface between QMAP and the Q65 decoder ! in WSJT-X. All arguments are input data obtained from the QMAP GUI. ! Raw Rx data are available as the 96 kHz complex spectrum ca(MAXFFT1) -! in common/cacb. Decoded messages are sent back to the GUI. +! in cacb_mod. Decoded messages are sent back to the GUI. use q65_decode use wavhdr use timer_module, only: timer + use map65_mmdec_mod, only: map65_mmdec + use qmap_decode_ipc, only: max_decode_rows, decode_row_length, & + ndecodes, result, result2 + use iso_fortran_env, only: int16 + use cacb_mod, only: ca, init_cacb parameter (MAXFFT1=5376000) !56*96000 parameter (MAXFFT2=336000) !56*6000 (downsampled by 1/16) parameter (NMAX=60*12000) parameter (RAD=57.2957795) type(hdr) h - integer*2 iwave(60*12000) + integer(int16) iwave(300*12000) integer offset - complex ca(MAXFFT1) !FFT of raw I/Q data from Linrad complex cx(0:MAXFFT2-1),cz(0:MAXFFT2) real*8 fcenter,freq0,freq1 logical*1 bClickDecode @@ -29,17 +33,13 @@ subroutine q65b(nutc,nqd,fcenter,nfcal,nfsample,ikhz,mousedf,ntol, & character*4 grid4 character*3 csubmode character*17 fname - character*72 result,ctmp - character*8 result2 !liveCQ + character(len=decode_row_length) ctmp character*20 datetime,datetime1 - character*1 c1 - common/decodes/ndecodes,ncand2,nQDecoderDone,nWDecoderBusy, & - nWTransmitting,kHzRequested,result(50) - common/decodes2/result2(50) !liveCQ - common/cacb/ca data ifile/0/ save + call init_cacb(MAXFFT1) + if(mycall0(1:1).ne.' ') mycall=mycall0 if(hiscall0(1:1).ne.' ') hiscall=hiscall0 if(hisgrid(1:4).ne.' ') grid4=hisgrid(1:4) @@ -161,7 +161,7 @@ subroutine q65b(nutc,nqd,fcenter,nfcal,nfsample,ikhz,mousedf,ntol, & frx=0.001*k0*df+nkhz_center-48.0+1.0 - 0.001*nfcal fsked=frx - 0.001*ndop00/2.0 - 0.001*offset ctmp=csubmode//' '//trim(msg0) - ndecodes=min(ndecodes+1,50) + ndecodes=min(ndecodes+1,max_decode_rows) write(result(ndecodes),1120) nhhmmss,frx,fsked,xdt0,nsnr0,trim(ctmp) 1120 format(i6.6,f9.3,f7.1,f7.2,i5,2x,a) write(result2(ndecodes),1125) fsked !liveCQ diff --git a/qmap/libqmap/q65c.f90 b/qmap/libqmap/q65c.f90 index 51b4335e..eadf53d7 100644 --- a/qmap/libqmap/q65c.f90 +++ b/qmap/libqmap/q65c.f90 @@ -6,6 +6,7 @@ subroutine q65c use FFTW3 use q65 use q65_decode + use qmap_decode_ipc, only: ndecodes parameter (NFFT=32768) include 'njunk.f90' @@ -20,11 +21,6 @@ subroutine q65c character*12 mycall,hiscall character*6 mygrid,hisgrid character*20 datetime - character*72 result - character*8 result2 !liveCQ - common/decodes/ndecodes,ncand2,nQDecoderDone,nWDecoderBusy, & - nWTransmitting,kHzRequested,result(50) - common/decodes2/result2(50) !liveCQ common/datcom2/dd(2,5760000),ss(400,NFFT),savg(NFFT),nparams0 common/savecom/revision,fname !### REMEMBER that /npar/ is not updated until nparams=nparams0 is executed. ### diff --git a/qmap/libqmap/qmap_decode_ipc.f90 b/qmap/libqmap/qmap_decode_ipc.f90 new file mode 100644 index 00000000..0f8d5d5e --- /dev/null +++ b/qmap/libqmap/qmap_decode_ipc.f90 @@ -0,0 +1,18 @@ +module qmap_decode_ipc + implicit none + + ! Keep row dimensions in sync with qmap/decode_ipc.h. + integer, parameter :: max_decode_rows = 50 + integer, parameter :: decode_row_length = 80 + integer, parameter :: live_cq_row_length = 8 + + integer ndecodes,ncand2,nQDecoderDone,nWDecoderBusy + integer nWTransmitting,kHzRequested + character(len=decode_row_length) result(max_decode_rows) + character(len=live_cq_row_length) result2(max_decode_rows) + + common/decodes/ndecodes,ncand2,nQDecoderDone,nWDecoderBusy, & + nWTransmitting,kHzRequested,result + common/decodes2/result2 + +end module qmap_decode_ipc diff --git a/qmap/libqmap/qmapa.f90 b/qmap/libqmap/qmapa.f90 index 7c299885..2b785622 100644 --- a/qmap/libqmap/qmapa.f90 +++ b/qmap/libqmap/qmapa.f90 @@ -6,6 +6,7 @@ subroutine qmapa(dd,ss,savg,newdat,nutc,fcenter,ntol,nfa,nfb, & ! Processes timf2 data received from Linrad to find and decode Q65 signals. use timer_module, only: timer + use qmap_decode_ipc, only: ndecodes, ncand2 type candidate real :: snr !Relative S/N of sync detection @@ -33,12 +34,7 @@ subroutine qmapa(dd,ss,savg,newdat,nutc,fcenter,ntol,nfa,nfb, & character mycall*12,hiscall*12,hisgrid*6 type(candidate) :: cand(MAX_CANDIDATES) type(good_decode) found(MAX_CANDIDATES) - character*72 result - character*8 result2 !liveCQ character*20 datetime - common/decodes/ndecodes,ncand2,nQDecoderDone,nWDecoderBusy, & - nWTransmitting,kHzRequested,result(50) - common/decodes2/result2(50) !liveCQ save tsec0=sec_midn() diff --git a/qmap/libqmap/read_qm.f90 b/qmap/libqmap/read_qm.f90 index 67e3a0cd..30b02eda 100644 --- a/qmap/libqmap/read_qm.f90 +++ b/qmap/libqmap/read_qm.f90 @@ -7,21 +7,28 @@ subroutine read_qm(fname,iret) real*8 fcenter integer nxtra(15) !For possible future additions integer*1 id1(2,NMAX) + save id1 !Keep this big array off the stack common/datcom/dd(2,5760000),ss(400,NFFT),savg(NFFT), & fcenter,nutc,fselected,mousedf,mousefqso,nagain, & ndepth,ndiskdat,ntx60,newdat,nn1,nn2,nfcal,nfshift, & ntx30a,ntx30b !... open(28,file=trim(fname),status='old',access='stream',err=900) - read(28,end=910) prog_id,mycall,mygrid,fcenter,nutc,ntx30a, & + read(28,end=910,err=910) prog_id,mycall,mygrid,fcenter,nutc,ntx30a, & ntx30b,ndop00,ndop58,ia,ib,fac0,nxtra + + if(.not. ((ia.eq.1 .and. ib.eq.NMAX) .or. & + (ia.eq.1 .and. ib.eq.NMAX/2) .or. & + (ia.eq.NMAX/2+1 .and. ib.eq.NMAX) .or. & + (ia.eq.NMAX/2+1 .and. ib.eq.NMAX/2))) go to 910 + iret=3 if(ib.eq.NMAX/2) iret=1 if(ia.eq.NMAX/2+1) iret=2 fac=1.0 if(fac0.gt.0.0) fac=1.0/fac0 id1=0 - read(28,end=910) id1(1:2,ia:ib) + read(28,end=910,err=910) id1(1:2,ia:ib) dd=0. dd(1:2,ia:ib)=fac*id1(1:2,ia:ib) !Boost back to previous level go to 999 diff --git a/qmap/libqmap/save_qm.f90 b/qmap/libqmap/save_qm.f90 index 282f29b8..94a32b0b 100644 --- a/qmap/libqmap/save_qm.f90 +++ b/qmap/libqmap/save_qm.f90 @@ -15,6 +15,7 @@ subroutine save_qm(fname,revision,mycall,mygrid,dd,ntx30a,ntx30b,fcenter, & ib=NMAX if(ntx30a.gt.5) ia=NMAX/2+1 if(ntx30b.gt.5) ib=NMAX/2 + if(ia.gt.ib) return sq=0. do i=ia,ib @@ -60,4 +61,3 @@ subroutine save_qm(fname,revision,mycall,mygrid,dd,ntx30a,ntx30b,fcenter, & return end subroutine save_qm - diff --git a/qmap/livecq_parser.cpp b/qmap/livecq_parser.cpp new file mode 100644 index 00000000..e43ec5ce --- /dev/null +++ b/qmap/livecq_parser.cpp @@ -0,0 +1,95 @@ +#include "livecq_parser.h" + +#include "../validators/LiveCQCallsign.hpp" + +namespace +{ + bool isReportableMessageType(QString const& messageType) + { + return messageType == "CQ" || messageType == "QRZ" || messageType == "CQV" + || messageType == "CQH" || messageType == "QRT"; + } + + bool parseFrequency(QString const& token, int frequencyOffset, + int& receiveFrequency, int& scheduledFrequency) + { + auto const fields = token.split('.'); + if (fields.size() != 2 || fields.at(0).isEmpty() || fields.at(1).isEmpty()) { + return false; + } + + bool ok = false; + auto const integerPart = fields.at(0).toInt(&ok); + if (!ok) { + return false; + } + auto const fractionalPart = fields.at(1).toInt(&ok); + if (!ok) { + return false; + } + + receiveFrequency = frequencyOffset + fractionalPart; + if (receiveFrequency <= frequencyOffset + 500) { + scheduledFrequency = integerPart; + } else { + scheduledFrequency = integerPart + 1; + receiveFrequency -= 1000; + } + return true; + } +} + +namespace QMapLiveCQ +{ + bool parse(QStringList const& tokens, int frequencyOffset, Record& record) + { + if (tokens.size() < 9 || tokens.size() > 11 + || !isReportableMessageType(tokens.at(6).trimmed())) { + return false; + } + + Record parsed; + parsed.grid = "--"; + auto const messageType = tokens.at(6).trimmed(); + QString frequencyToken; + + if (tokens.size() == 9) { + parsed.callsign = tokens.at(7).trimmed(); + if (!LiveCQ::isValidCallsign(parsed.callsign)) { + return false; + } + parsed.message = messageType + " " + parsed.callsign; + frequencyToken = tokens.at(8); + } else if (tokens.size() == 10) { + auto const firstCandidate = tokens.at(7).trimmed(); + if (LiveCQ::isValidCallsign(firstCandidate)) { + parsed.callsign = firstCandidate; + parsed.grid = tokens.at(8).trimmed(); + parsed.message = messageType + " " + parsed.callsign + " " + parsed.grid; + } else { + parsed.callsign = tokens.at(8).trimmed(); + if (!LiveCQ::isValidCallsign(parsed.callsign)) { + return false; + } + parsed.message = messageType + " " + parsed.callsign; + } + frequencyToken = tokens.at(9); + } else { + parsed.callsign = tokens.at(8).trimmed(); + if (!LiveCQ::isValidCallsign(parsed.callsign)) { + return false; + } + parsed.grid = tokens.at(9).trimmed(); + parsed.message = messageType + " " + parsed.callsign + " " + parsed.grid; + frequencyToken = tokens.at(10); + } + + if (!parseFrequency(frequencyToken, frequencyOffset, + parsed.receiveFrequency, parsed.scheduledFrequency)) { + return false; + } + + record = parsed; + return true; + } +} diff --git a/qmap/livecq_parser.h b/qmap/livecq_parser.h new file mode 100644 index 00000000..aa80bb10 --- /dev/null +++ b/qmap/livecq_parser.h @@ -0,0 +1,21 @@ +#ifndef QMAP_LIVE_CQ_PARSER_H +#define QMAP_LIVE_CQ_PARSER_H + +#include <QString> +#include <QStringList> + +namespace QMapLiveCQ +{ + struct Record + { + QString callsign; + QString grid; + QString message; + int receiveFrequency {0}; + int scheduledFrequency {0}; + }; + + bool parse(QStringList const& tokens, int frequencyOffset, Record& record); +} + +#endif diff --git a/qmap/main.cpp b/qmap/main.cpp index 63a707a0..196b6f4b 100644 --- a/qmap/main.cpp +++ b/qmap/main.cpp @@ -5,9 +5,15 @@ #include <QtGui> #endif #include <QApplication> +#include <QCoreApplication> +#include <QDir> +#include <QFileInfo> +#include <QDebug> +#include <QStandardPaths> #include "revision_utils.hpp" #include "mainwindow.h" +#include "runtime_paths.h" extern "C" { // Fortran procedures we need @@ -21,20 +27,36 @@ extern "C" { int main(int argc, char *argv[]) { - QApplication a {argc, argv}; + QCoreApplication::setApplicationName ("QMAP"); + QString dataDir = QStandardPaths::writableLocation (QStandardPaths::AppLocalDataLocation); + if (dataDir.isEmpty ()) + { + dataDir = QDir::home ().absoluteFilePath (".qmap"); + } -// Initialize libgfortran: - _gfortran_set_args(argc, argv); - _gfortran_set_convert(0); - ftninit_(); + QApplication::setAttribute (Qt::AA_EnableHighDpiScaling); - // Read optional file to disable highDPI scaling - QFile f("DisableHighDpiScaling"); - if (!f.exists()) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication a {argc, argv}; // Override programs executable basename as application name. a.setApplicationName ("QMAP"); - a.setApplicationVersion ("0.6"); + a.setApplicationVersion ("0.7"); + + dataDir = qmapDataDir(); + QFileInfo dataDirInfo {dataDir}; + if (!dataDirInfo.exists() || !dataDirInfo.isDir() || !dataDirInfo.isWritable() + || !QDir::setCurrent(dataDir)) { + QString message {"Unable to use QMAP working directory: " + dataDir}; + qWarning() << message; + QMessageBox::critical(nullptr, QObject::tr("QMAP Startup Error"), message); + return 1; + } + + // QMAP C++ and Fortran code still use relative opens for runtime files. + // Start from the writable data directory before Fortran initializes them. + _gfortran_set_args(argc, argv); + _gfortran_set_convert(0); + ftninit_(); // switch off as we share an Info.plist file with WSJT-X a.setAttribute (Qt::AA_DontUseNativeMenuBar); MainWindow w; diff --git a/qmap/mainwindow.cpp b/qmap/mainwindow.cpp index 47524ad4..7f3b5352 100644 --- a/qmap/mainwindow.cpp +++ b/qmap/mainwindow.cpp @@ -1,21 +1,30 @@ //------------------------------------------------------------------ MainWindow #include "mainwindow.h" +#include <cstring> #include <fftw3.h> #include <QDir> #include <QSettings> #include <QTimer> #include <QToolTip> +#include <QDebug> #include "revision_utils.hpp" #include "qt_helpers.hpp" #include "SettingsGroup.hpp" #include "widgets/MessageBox.hpp" #include "ui_mainwindow.h" +#include "runtime_paths.h" #include "devsetup.h" #include "plotter.h" #include "about.h" #include "astro.h" #include "widegraph.h" +#include "vertwaterfall.h" #include "sleep.h" +#include "livecq_parser.h" +#include "shared_memory_key.h" +#include "qmap_ipc.h" +#include "qmap_decode_record.h" +#include "validators/LiveCQCallsign.hpp" #include <QCoreApplication> //liveCQ #include <QNetworkAccessManager> //liveCQ @@ -27,10 +36,10 @@ #define NFFT 32768 -qint16 id[2*60*96000]; - -QSharedMemory mem_qmap("mem_qmap"); //Memory segment to be shared (optionally) with WSJT-X -int* ipc_wsjtx; +QSharedMemory mem_qmap; //Memory segment to be shared (optionally) with WSJT-X +QMapSharedMemory * ipc_wsjtx {nullptr}; +bool qmap_decoder_region_available {false}; +bool qmap_click_mailbox_available {false}; extern const int RxDataFrequency = 96000; @@ -39,9 +48,11 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_appDir {QApplication::applicationDirPath ()}, - m_settings_filename {m_appDir + "/qmap.ini"}, + m_dataDir {qmapDataDir ()}, + m_settings_filename {qmapSettingsFile (m_appDir, m_dataDir)}, m_astro_window {new Astro {m_settings_filename}}, m_wide_graph_window {new WideGraph {m_settings_filename}}, + m_vert_waterfall_window {new VertWaterfall {m_settings_filename}}, m_gui_timer {new QTimer {this}} { ui->setupUi(this); @@ -72,7 +83,7 @@ MainWindow::MainWindow(QWidget *parent) : ui->actionSave_all->setActionGroup(saveGroup); ui->actionSave_decoded->setActionGroup(saveGroup); - setWindowTitle (program_title ()); + setWindowTitle (branded_program_title ()); connect(&soundInThread, SIGNAL(readyForFFT(int)), this, SLOT(dataSink(int))); connect(&soundInThread, SIGNAL(error(QString)), this, SLOT(showSoundInError(QString))); @@ -106,16 +117,23 @@ MainWindow::MainWindow(QWidget *parent) : xSignalMeter->resize(50, 160); //Attach or create a memory segment to be shared with WSJT-X. - int memSize=4096; + auto const memSize=static_cast<int>(QMapSharedMemorySize); + mem_qmap.setKey (qmap_decode_ipc::shared_memory_key ()); if(!mem_qmap.attach()) { if(!mem_qmap.create(memSize)) { msgBox("Unable to create shared memory segment mem_qmap."); } } - ipc_wsjtx = (int*)mem_qmap.data(); - mem_qmap.lock(); - memset(ipc_wsjtx,0,memSize); //Zero all of shared memory - mem_qmap.unlock(); + auto const mappedSize = mem_qmap.isAttached () + ? static_cast<std::size_t> (mem_qmap.size ()) : 0u; + qmap_decoder_region_available = qmapDecoderRegionAvailable (mappedSize); + qmap_click_mailbox_available = qmapClickMailboxAvailable (mappedSize); + ipc_wsjtx = qmap_decoder_region_available + ? static_cast<QMapSharedMemory *> (mem_qmap.data ()) : nullptr; + if (ipc_wsjtx && mem_qmap.lock ()) { + clearQMapSharedMemory (ipc_wsjtx, mappedSize); + mem_qmap.unlock (); + } // fftwf_import_wisdom_from_filename (QDir {m_appDir}.absoluteFilePath ("qmap_wisdom.dat").toLocal8Bit ()); readSettings(); //Restore user's setup params @@ -134,7 +152,21 @@ MainWindow::MainWindow(QWidget *parent) : border-color: black; min-width: 5em; padding: 3px;}"; on_actionAstro_Data_triggered(); //Create the other windows - on_actionWide_Waterfall_triggered(); + { + // Restore each waterfall's visibility from its last-exit setting. + QSettings settings {m_settings_filename, QSettings::IniFormat}; + bool wideVisible, vertVisible; + { + SettingsGroup g {&settings, "MainWindow"}; + wideVisible = settings.value ("WideGraphVisible", true).toBool (); + } + { + SettingsGroup g {&settings, "VertWaterfall"}; + vertVisible = settings.value ("VertWaterfallVisible", false).toBool (); + } + if (wideVisible) on_actionWide_Waterfall_triggered(); + if (vertVisible) on_actionVertical_Waterfall_triggered(); + } if (m_astro_window) m_astro_window->setFontSize (m_astroFont); if(m_modeQ65==1) on_actionQ65A_triggered(); @@ -182,7 +214,7 @@ MainWindow::MainWindow(QWidget *parent) : // Read items for fAddComboBox ui->fAddComboBox->addItem (0); ui->fAddComboBox->setItemText(0, QString::number(m_fAdd)); - QFile g("fadd.txt"); + QFile g(QDir {m_dataDir}.absoluteFilePath("fadd.txt")); QTextStream stream(&g); if(g.open (QIODevice::ReadOnly | QIODevice::Text)) { while (!stream.atEnd()) { @@ -199,7 +231,11 @@ MainWindow::MainWindow(QWidget *parent) : if(ui->actionBlue->isChecked()) on_actionBlue_triggered(); connect (m_wide_graph_window.get (), &WideGraph::freezeDecode2, this, &MainWindow::freezeDecode); + connect (m_wide_graph_window.get (), &WideGraph::decodeLabelClicked2, this, &MainWindow::decodeLabelClicked); + connect (m_vert_waterfall_window.get (), &VertWaterfall::decodeLabelClicked2, this, &MainWindow::decodeLabelClicked); connect (m_wide_graph_window.get (), &WideGraph::f11f12, this, &MainWindow::bumpDF); + connect (m_wide_graph_window.get (), &WideGraph::spectrumReady, + m_vert_waterfall_window.get (), &VertWaterfall::dataSinkVert); //default freq at startup for Doppler and Tsky datcom_.fcenter = 1296.150; @@ -216,6 +252,12 @@ MainWindow::~MainWindow() writeSettings(); all_done_(); + if (ipc_wsjtx && mem_qmap.isAttached () && mem_qmap.lock ()) { + clearQMapSharedMemory (ipc_wsjtx, + static_cast<std::size_t> (mem_qmap.size ())); + mem_qmap.unlock (); + } + if (soundInThread.isRunning()) { soundInThread.quit(); soundInThread.wait(3000); @@ -273,7 +315,7 @@ void MainWindow::readSettings() { SettingsGroup g {&settings, "MainWindow"}; restoreGeometry(settings.value("geometry").toByteArray()); - m_path = settings.value("MRUdir", m_appDir + "/save").toString(); + m_path = settings.value("MRUdir", QDir {m_dataDir}.absoluteFilePath("save")).toString(); } SettingsGroup g {&settings, "Common"}; @@ -281,10 +323,10 @@ void MainWindow::readSettings() m_myGrid=settings.value("MyGrid","").toString(); m_astroFont=settings.value("AstroFont",18).toInt(); m_myCallColor=settings.value("MyCallColor",1).toInt(); - m_saveDir=settings.value("SaveDir",m_appDir + "/save").toString(); - m_azelDir=settings.value("AzElDir",m_appDir).toString(); + m_saveDir=settings.value("SaveDir", QDir {m_dataDir}.absoluteFilePath("save")).toString(); + m_azelDir=settings.value("AzElDir",m_dataDir).toString(); m_fCal=settings.value("Fcal",0).toInt(); - m_fAdd=settings.value("FAdd",0).toDouble(); + m_fAdd=settings.value("Fadd",0).toDouble(); soundInThread.setFadd(m_fAdd); m_network = settings.value("NetworkInput",true).toBool(); m_dB = settings.value("Scale_dB",0).toInt(); @@ -520,15 +562,24 @@ void MainWindow::on_actionSettings_triggered() void MainWindow::on_monitorButton_clicked() //Monitor { - if(m_monitoring or m_loopall) { - m_monitoring=false; - soundInThread.setMonitoring(false); - m_loopall=false; - } else { - m_monitoring=true; - soundInThread.setMonitoring(true); - m_diskData=false; - } + clearDecodeLabels (); + m_monitoring=true; + soundInThread.setMonitoring(true); + m_diskData=false; +} + +void MainWindow::clearDecodeLabels () +{ + if (m_wide_graph_window) m_wide_graph_window->clearDecodeLabels (); + if (m_vert_waterfall_window) m_vert_waterfall_window->clearDecodeLabels (); +} + +void MainWindow::on_stopButton_clicked() //stopButton +{ + m_monitoring=false; + soundInThread.setMonitoring(m_monitoring); + m_loopall=false; + m_startAnother=false; } void MainWindow::on_actionLinrad_triggered() //Linrad palette @@ -665,9 +716,30 @@ void MainWindow::on_actionExit_triggered() //Exit() void MainWindow::closeEvent (QCloseEvent * e) { if (m_gui_timer) m_gui_timer->stop (); + + // Record whether each waterfall was open, so it can be restored on the + // next startup. Must happen before close() below, since close() hides + // the window and isVisible() would otherwise read back false. Written + // directly here (not from each window's own saveSettings(), which also + // runs again from its destructor after close() -- that second call + // would otherwise clobber this with isVisible()==false). + { + QSettings settings {m_settings_filename, QSettings::IniFormat}; + { + SettingsGroup g {&settings, "MainWindow"}; + settings.setValue ("WideGraphVisible", m_wide_graph_window && m_wide_graph_window->isVisible ()); + } + { + SettingsGroup g {&settings, "VertWaterfall"}; + settings.setValue ("VertWaterfallVisible", m_vert_waterfall_window && m_vert_waterfall_window->isVisible ()); + } + } + m_wide_graph_window->saveSettings(); + if (m_vert_waterfall_window) m_vert_waterfall_window->saveSettings(); if (m_astro_window) m_astro_window->close (); if (m_wide_graph_window) m_wide_graph_window->close (); + if (m_vert_waterfall_window) m_vert_waterfall_window->close (); QMainWindow::closeEvent (e); } @@ -687,6 +759,11 @@ void MainWindow::on_actionWide_Waterfall_triggered() //Display Waterfalls m_wide_graph_window->show(); } +void MainWindow::on_actionVertical_Waterfall_triggered() //Display Vertical Waterfall +{ + if (m_vert_waterfall_window) m_vert_waterfall_window->show(); +} + void MainWindow::on_actionOpen_triggered() //Open File { m_monitoring=false; @@ -702,7 +779,8 @@ void MainWindow::on_actionOpen_triggered() //Open File lab1->setStyleSheet("QLabel{background-color: #66ff66}"); lab1->setText(" " + fname.mid(i,15) + " "); } - if(m_monitoring) on_monitorButton_clicked(); + on_stopButton_clicked(); + clearDecodeLabels (); m_diskData=true; int dbDgrd=0; int iret=4; @@ -738,6 +816,7 @@ void MainWindow::on_actionOpen_next_in_directory_triggered() //Open Next lab1->setStyleSheet("QLabel{background-color: #66ff66}"); lab1->setText(" " + fname.mid(i,len) + " "); } + clearDecodeLabels (); m_diskData=true; int dbDgrd=0; int iret=4; @@ -787,14 +866,12 @@ void MainWindow::decoderFinished() { m_startAnother=m_loopall; decodes_.nQDecoderDone=1; - decodes_.kHzRequested=0; if(m_diskData) decodes_.nQDecoderDone=2; - mem_qmap.lock(); - decodes_.nWDecoderBusy=ipc_wsjtx[3]; //Prevent overwriting values - decodes_.nWTransmitting=ipc_wsjtx[4]; //written here by WSJT-X + if (qmap_decoder_region_available && ipc_wsjtx && mem_qmap.lock ()) { + publishQMapDecodeBlock(*ipc_wsjtx, decodes_); + mem_qmap.unlock (); + } m_bWTransmitting=decodes_.nWTransmitting>0; - memcpy((char*)ipc_wsjtx, &decodes_, sizeof(decodes_)); //Send decodes and flags to WSJT-X - mem_qmap.unlock(); QString t1; t1=t1.asprintf(" %.1f s %d/%d ", 0.15*datcom2_.nhsym, decodes_.ndecodes, decodes_.ncand); lab4->setText(t1); @@ -870,10 +947,12 @@ void MainWindow::on_DecodeButton_clicked() //Decode request void MainWindow::freezeDecode(int n) //freezeDecode() { if(n==3) { + if (!qmap_decoder_region_available || !ipc_wsjtx) return; decodes_.kHzRequested=m_wide_graph_window->QSOfreq(); - mem_qmap.lock(); - ipc_wsjtx[5]=decodes_.kHzRequested; - mem_qmap.unlock(); + if (mem_qmap.lock ()) { + ipc_wsjtx->decodes.kHzRequested=decodes_.kHzRequested; + mem_qmap.unlock (); + } return; } if(n==2) { @@ -892,6 +971,22 @@ void MainWindow::freezeDecode(int n) //freezeDecode() } } +void MainWindow::decodeLabelClicked(QByteArray decodeRow, DecodeClickGesture gesture) +{ + if (!qmap_click_mailbox_available || !ipc_wsjtx + || decodeRow.size () != static_cast<int> (QMapDecodeRowSize)) return; + if (mem_qmap.lock ()) { + std::memcpy(ipc_wsjtx->click.selectedDecode, decodeRow.constData(), QMapDecodeRowSize); + if (gesture == DecodeClickGesture::Press) ipc_wsjtx->click.action = QMapClickAction::Disarm; + else if (gesture == DecodeClickGesture::SingleClick) { + ipc_wsjtx->click.action = QMapClickAction::Select; + } else { + ipc_wsjtx->click.action = QMapClickAction::SelectAndEnableTx; + } + mem_qmap.unlock (); + } +} + void MainWindow::decode() //decode() { if(m_decoderBusy) { @@ -1034,208 +1129,49 @@ void MainWindow::CreateLiveCQ(QStringList cqliveText) //return if cqliveText is empty or data were read from disk. if ((m_diskData && m_myCall.toUpper() != "W3SZ" && m_myCall.toUpper() != "DL3WDG") or (cqliveText.size() == 0)) return; - QStringList cqliveFinalText; - QStringList oldFile; - bool ok; int freqOffset = ui->sbOffset->value(); QStringList bandInfo; bandInfo = ui->labFreq->text().split(".",SkipEmptyParts); QString bandFreq = bandInfo.at(0); QString theDate = ui->labUTC->text().trimmed().mid(0,12); QList<QStringList> decodeList; - bool strOK = false; for (const QString &item : cqliveText) { - QString line = " "; - QStringList thePostLine; - line = line.repeated(100); //.replace("<","").replace(">",""); - QStringList thePieces; - qDebug () << "item is: " << item; - thePieces = item.split(" ",SkipEmptyParts); - int rxFreq = 0.0; - if((thePieces.at(6) == "CQ" || thePieces.at(6) == "QRZ" || thePieces.at(6) == "CQV" || thePieces.at(6) == "CQH" || thePieces.at(6) == "QRT") && m_myCall.length() >=3 && m_myGrid.length()>=4 ) { - try { - //extract Fsked freq and format to 3 digits no decimals - qDebug() << "entered try"; - QString theMsg; - QString theCall; - QString theGrid; - QStringList thekHz; - int nWords=thePieces.length(); - if(nWords==9) { - // Handle CQ CALL messages that do not include a locator - if(thePieces.at(6)==NULL or thePieces.at(7)==NULL or thePieces.at(8)==NULL) continue; - theCall = thePieces.at(7); - bool isCall = testCall(theCall); - qDebug() << "theCall is: " << theCall << " and isCall is: " << isCall; - if(!isCall) continue; - theGrid = "--"; - theMsg = thePieces.at(6) + " " + theCall; - thekHz = thePieces.at(8).split("."); - rxFreq = freqOffset + thekHz.at(1).toInt(&ok); - // int rxFreq = freqOffset + 100 * thekHz.at(1).toInt(&ok); - if (!ok) continue; - } else if(nWords==10) { - // Handle CQ CALL GRID --or-- CQ XXX CALL - if(thePieces.at(6)==NULL or thePieces.at(7)==NULL or thePieces.at(8)==NULL or thePieces.at(9)==NULL) continue; - // Test for callsign at thePieces.at(7) - theCall = thePieces.at(7); - bool isCall = testCall(theCall); - qDebug() << "theCall is: " << theCall << " and isCall is: " << isCall; - // Handle CQ CALL GRID - if(isCall) { - theGrid = thePieces.at(8); - theMsg = thePieces.at(6) + " " + theCall + " " + theGrid; - } - // Handle CQ XXX CALL - else { - theCall = thePieces.at(8); - isCall = testCall(theCall); - qDebug() << "theCall is: " << theCall << " and isCall is: " << isCall; - if(!isCall) continue; - theGrid = "--"; - theMsg = thePieces.at(6) + " " + theCall; - } - thekHz = thePieces.at(9).split("."); - rxFreq = freqOffset + thekHz.at(1).toInt(&ok); - // int rxFreq = freqOffset + 100 * thekHz.at(1).toInt(&ok); - if (!ok) continue; - // Handle CQ XXX CALL GRID - } else if (nWords==11) { - if(thePieces.at(6)==NULL or thePieces.at(7)==NULL or thePieces.at(8)==NULL or thePieces.at(9)==NULL or thePieces.at(10)==NULL) continue; - theCall = thePieces.at(8); - bool isCall = testCall(theCall); - qDebug() << "theCall is: " << theCall << " and isCall is: " << isCall; - if(!isCall) continue; - theGrid = thePieces.at(9); - theMsg = thePieces.at(6) + " " + theCall + " " + theGrid; - thekHz = thePieces.at(10).split("."); - rxFreq = freqOffset + thekHz.at(1).toInt(&ok); - // int rxFreq = freqOffset + 100 * thekHz.at(1).toInt(&ok); - if (!ok) continue; - } - strOK = true; - int skedFreq; - QString skedFreqString; - if (rxFreq <= freqOffset + 500) { - skedFreq = thekHz.at(0).toInt(&ok); - } else { - skedFreq = thekHz.at(0).toInt(&ok) + 1; - rxFreq=rxFreq - 1000; - } - skedFreqString = QString::number(skedFreq).rightJustified(3,'0'); - QString mode = "0 Q65-" + thePieces.at(5); - line.insert(0,bandFreq + "." + skedFreqString); - line.insert(10,QString::number(rxFreq)); - line.insert(15,"0"); - line.insert(18,thePieces.at(0)); - line.insert(26,thePieces.at(3)); - line.insert(32,thePieces.at(4)); - line.insert(36,theMsg); - line.insert(55,mode); - line.insert(67,m_myGrid.toUpper()); - line.insert(74,"Q"); - line.insert(76,theDate); - line.insert(88,m_myCall.toUpper()); - cqliveFinalText << line.trimmed(); - //qDebug () << "cqliveFinalText is: " << cqliveFinalText; - - thePostLine.insert(0, bandFreq + "." + skedFreqString); //skedfreq - thePostLine.insert(1, QString::number(rxFreq)); //rxfreq - thePostLine.insert(2, "--"); //rpol - thePostLine.insert(3,thePieces.at(0)); //utc HHmmSS - thePostLine.insert(4,thePieces.at(3)); //dt - thePostLine.insert(5, thePieces.at(4)); //dB - thePostLine.insert(6, "Q65-" + thePieces.at(5)); //Q65 submode - thePostLine.insert(7, thePieces.at(6)); //msg type - thePostLine.insert(8, theCall); //dx call - thePostLine.insert(9, theGrid); //dx grid - thePostLine.insert(10, m_myGrid.toUpper()); //myGrid - thePostLine.insert(11, theDate); //the date - thePostLine.insert(12, m_myCall.toUpper()); //myCall - thePostLine.insert(13, "--"); //txpol - decodeList.append(thePostLine); - qDebug () << "thePostLine is: " << thePostLine; - } - catch (const std::exception& e) { - // Handle standard C++ exceptions - QMessageBox::critical(this, "Exception", "Exception at line 1116 MainWindow::CreateLiveCQ " + QString::fromStdString(e.what())); - } - catch (...) { - // Handle any other type of exception - QMessageBox::critical(this, "Exception", "Unknown Exception at line 1121 MainWindow::CreateLiveCQ"); - } - } -} - if(strOK) { - sendLiveCQData(decodeList); - } -} - -bool MainWindow::testCall(QString w) -{ -// Check "callsign" to see if it could be a valid standard callsign or a valid -// compound callsign. -// Return a logical "call ok" indicator. - if(w.indexOf('.') >= 0) return false; - if(w.indexOf('+') >= 0) return false; - if(w.indexOf('-') >= 0) return false; - if(w.indexOf('?') >= 0) return false; - w = w.replace('<',""); - w = w.replace('>',""); - int i0=w.indexOf('/'); - int n1=w.length(); - if(n1 > 11) return false; - qDebug() << "Line 1186 w is: " << w << " and i0 is: " << i0 << " and n1 is: " << n1 << " and call is: " << w; - QString bc = QString(); - QStringList wSplit = w.split("/"); - if(wSplit.length() > 1) { - if(wSplit.at(0).length() > wSplit.at(1).length()) { - bc = wSplit.at(0); + QStringList const thePieces = item.split(" ",SkipEmptyParts); + QMapLiveCQ::Record record; + if (!QMapLiveCQ::parse(thePieces, freqOffset, record)) { + continue; } - else { - bc = wSplit.at(1); + qDebug () << "item is: " << item; + if (m_myCall.length() >= 3 && m_myGrid.length() >= 4) { + QString theCall = record.callsign; + QString theGrid = record.grid; + int rxFreq = record.receiveFrequency; + QString skedFreqString = QString::number(record.scheduledFrequency) + .rightJustified(3, '0'); + QStringList thePostLine; + + thePostLine.insert(0, bandFreq + "." + skedFreqString); //skedfreq + thePostLine.insert(1, QString::number(rxFreq)); //rxfreq + thePostLine.insert(2, "--"); //rpol + thePostLine.insert(3,thePieces.at(0)); //utc HHmmSS + thePostLine.insert(4,thePieces.at(3)); //dt + thePostLine.insert(5, thePieces.at(4)); //dB + thePostLine.insert(6, "Q65-" + thePieces.at(5)); //Q65 submode + thePostLine.insert(7, thePieces.at(6)); //msg type + thePostLine.insert(8, theCall); //dx call + thePostLine.insert(9, theGrid); //dx grid + thePostLine.insert(10, m_myGrid.toUpper()); //myGrid + thePostLine.insert(11, theDate); //the date + thePostLine.insert(12, m_myCall.toUpper()); //myCall + thePostLine.insert(13, "--"); //txpol + decodeList.append(thePostLine); + qDebug () << "thePostLine is: " << thePostLine; } } - else { - bc = w; + if (!decodeList.isEmpty()) { + sendLiveCQData(decodeList); } - int nbc=bc.trimmed().length(); - if(nbc > 8) return false; //Base call should have no more than 8 characters e.g. YW18FIFA - qDebug() << "reached line 1201"; - -// One of first two characters (c1 or c2) must be a letter - if((!bc[0].isLetter()) && (!bc[1].isLetter())) return false; - qDebug() << "reached line 1206"; -// Real calls don't start with Q, but we'll allow the placeholder -// callsign QU1RK to be considered a standard call: - if(bc[0]=='Q' && bc.mid(0,5) != "QU1RK") return false; - qDebug() << "reached line 1209"; - -// Must have a digit in 2nd or 3rd or 4th position - int i1=0; - if(bc[1].isDigit()) i1=1; - if(bc[2].isDigit()) i1=2; - if(bc[3].isDigit()) i1=3; - if(i1==0) return false; - qDebug() << "reached line 1217"; - -// Callsign must have a suffix of 1-4 letters e.g. YW18FIFA - if(i1==nbc) return false; - qDebug() << "reached line 1221"; - int n=0; - QChar j=QChar(); - for (int i=i1+1; i<=nbc-1; ++i) { - j=bc[i]; - if(j<QChar('A') || j > QChar('Z')) return false; - qDebug() << "reached line 1227 and n = " << n ; - n=n+1; - } - qDebug() << "reached line 1230"; - if(n >= 1 && n <= 4) return true; - qDebug() << "reached line 1232"; - - return false; } void MainWindow::sendLiveCQData(QList<QStringList>decodeList) @@ -1251,8 +1187,10 @@ void MainWindow::sendLiveCQData(QList<QStringList>decodeList) QNetworkAccessManager *manager = new QNetworkAccessManager(this); QUrl url(theUrl); QNetworkRequest request(url); - request.setRawHeader("User-Agent", "QMAP v0.5"); - request.setRawHeader("X-Custom-User-Agent", "QMAP v0.5"); + QByteArray userAgent = (QCoreApplication::applicationName() + " v" + + QCoreApplication::applicationVersion()).toUtf8(); + request.setRawHeader("User-Agent", userAgent); + request.setRawHeader("X-Custom-User-Agent", userAgent); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); for (const QStringList &thePostLine : decodeList) { @@ -1326,6 +1264,10 @@ void MainWindow::guiUpdate() } m_wide_graph_window->updateFreqLabel(); + if (!m_diskData) { + m_wide_graph_window->pruneDecodeLabels(nsec); + if (m_vert_waterfall_window) m_vert_waterfall_window->pruneDecodeLabels(nsec); + } if(m_startAnother and !m_bDiskDatBusy) { m_startAnother=false; @@ -1336,8 +1278,22 @@ void MainWindow::guiUpdate() if(decodes_.ndecodes > m_fetched) { doLiveCQ = true; while(m_fetched<decodes_.ndecodes) { - QString t=QString::fromLatin1(decodes_.result[m_fetched]); - QString t2=QString::fromLatin1(decodes2_.result2[m_fetched]); + auto const& row=decodes_.result[m_fetched]; + auto const& live_cq_row=decodes2_.result2[m_fetched]; + QString t=QString::fromLatin1(row, + static_cast<int>(qmap_decode_ipc::text_length(row))); + QString t2=QString::fromLatin1(live_cq_row, + static_cast<int>(qmap_decode_ipc::text_length(live_cq_row))); + + if (m_vert_waterfall_window || m_wide_graph_window) { + auto const record = parseQMapDecodeRecord ( + QByteArray {decodes_.result[m_fetched], static_cast<int> (QMapDecodeRowSize)}); + if (record && LiveCQ::isValidCallsign (record->callsign)) { + if (m_vert_waterfall_window) m_vert_waterfall_window->addDecodeLabel(*record); + if (m_wide_graph_window) m_wide_graph_window->addDecodeLabel(*record); + } + } + if(m_UTC0!="" and m_UTC0!=t.left(4)) { t1="-"; ui->decodedTextBrowser->append(t1.repeated(60)); @@ -1382,12 +1338,13 @@ void MainWindow::guiUpdate() m_n60=nsec%60; // See if WSJT-X is transmitting - int itest[5]; - mem_qmap.lock(); - memcpy(&itest, (char*)ipc_wsjtx, 20); - mem_qmap.unlock(); - if(itest[4]>0) { - m_WSJTX_TRperiod=itest[4]; + int transmitting = 0; + if (qmap_decoder_region_available && ipc_wsjtx && mem_qmap.lock ()) { + transmitting=ipc_wsjtx->decodes.nWTransmitting; + mem_qmap.unlock (); + } + if(transmitting>0) { + m_WSJTX_TRperiod=transmitting; m_bWTransmitting=true; if(m_WSJTX_TRperiod==30 and m_n60<30) m_nTx30a++; if(m_WSJTX_TRperiod==30 and m_n60>=30) m_nTx30b++; @@ -1515,6 +1472,16 @@ void MainWindow::on_actionQuick_Start_Guide_to_Q65_triggered() QDesktopServices::openUrl (QUrl {"https://wsjt.sourceforge.io/Q65_Quick_Start.pdf"}); } +void MainWindow::on_actionCopyright_Notice_triggered() +{ + MessageBox::warning_message (this, copyright_notice_text ()); +} + +void MainWindow::on_actionTrademark_Policy_triggered() +{ + QDesktopServices::openUrl (QUrl {"https://wsjtx.github.io/wsjtx/trademark.html"}); +} + void MainWindow::on_actionQuick_Start_Guide_to_WSJT_X_2_7_and_QMAP_triggered() { QDesktopServices::openUrl (QUrl {"https://wsjt.sourceforge.io/Quick_Start_WSJT-X_2.7_QMAP.pdf"}); @@ -1589,7 +1556,8 @@ void MainWindow::on_pbAdd_clicked() { m_fAdd=ui->fAddComboBox->currentText().toDouble(); if (ui->fAddComboBox->currentText() != "") { - QFile g("fadd.txt"); + QString fAddFile = QDir {m_dataDir}.absoluteFilePath("fadd.txt"); + QFile g(fAddFile); if(g.open(QIODevice::Text | QIODevice::Append)) { QString addedEntry = (ui->fAddComboBox->currentText()); QTextStream out(&g); @@ -1599,10 +1567,10 @@ void MainWindow::on_pbAdd_clicked() #else Qt::endl #endif - ; + ; g.close(); if (ui->fAddComboBox->findText(addedEntry) < 0) ui->fAddComboBox->addItem (QString::number(m_fAdd)); - ui->decodedTextBrowser->append("Adding " + QString::number(m_fAdd) + " to file fadd.txt"); + ui->decodedTextBrowser->append("Adding " + QString::number(m_fAdd) + " to file " + fAddFile); } } } diff --git a/qmap/mainwindow.h b/qmap/mainwindow.h index d8895df5..8c71c4d5 100644 --- a/qmap/mainwindow.h +++ b/qmap/mainwindow.h @@ -25,6 +25,8 @@ namespace Ui { class QTimer; class Astro; class WideGraph; +class VertWaterfall; +enum class DecodeClickGesture; class MainWindow : public QMainWindow { @@ -42,6 +44,7 @@ public slots: void diskDat(int iret); void decoderFinished(); void freezeDecode(int n); + void decodeLabelClicked(QByteArray decodeRow, DecodeClickGesture gesture); void guiUpdate(); private: @@ -51,6 +54,7 @@ private: private slots: void on_monitorButton_clicked(); + void on_stopButton_clicked(); void on_actionExit_triggered(); void on_actionAbout_triggered(); void on_actionLinrad_triggered(); @@ -58,6 +62,7 @@ private slots: void on_tolSpinBox_valueChanged(int arg1); void on_actionAstro_Data_triggered(); void on_actionWide_Waterfall_triggered(); + void on_actionVertical_Waterfall_triggered(); void on_actionOpen_triggered(); void on_actionOpen_next_in_directory_triggered(); void on_actionDecode_remaining_files_in_directory_triggered(); @@ -80,6 +85,8 @@ private slots: void on_actionQ65D_triggered(); void on_actionQ65E_triggered(); void on_actionQuick_Start_Guide_to_Q65_triggered(); + void on_actionCopyright_Notice_triggered(); + void on_actionTrademark_Policy_triggered(); void on_actionQuick_Start_Guide_to_WSJT_X_2_7_and_QMAP_triggered(); void on_actionAlso_Q65_30x_toggled(bool b); void on_sbMaxDrift_valueChanged(int arg1); @@ -96,9 +103,11 @@ private slots: private: Ui::MainWindow *ui; QString m_appDir; + QString m_dataDir; QString m_settings_filename; QScopedPointer<Astro> m_astro_window; QScopedPointer<WideGraph> m_wide_graph_window; + QScopedPointer<VertWaterfall> m_vert_waterfall_window; QPointer<QTimer> m_gui_timer; qint32 m_waterfallAvg; qint32 m_DF; @@ -199,9 +208,9 @@ private: void updateStatusBar(); void msgBox(QString t); bool isGrid4(QString g); + void clearDecodeLabels(); void CreateLiveCQ(QStringList cqliveText); //liveCQ void sendLiveCQData(QList<QStringList> decodeList); //liveCQ - bool testCall(QString callsign); //liveCQ }; extern void getfile(QString fname, bool xpol, int idInt); diff --git a/qmap/mainwindow.ui b/qmap/mainwindow.ui index 8f27ebb5..8e1f9fc8 100644 --- a/qmap/mainwindow.ui +++ b/qmap/mainwindow.ui @@ -161,32 +161,52 @@ li.checked::marker { content: "\2612"; } </widget> </item> <item row="1" column="2"> - <widget class="QPushButton" name="monitorButton"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="minimumSize"> - <size> - <width>0</width> - <height>0</height> - </size> - </property> - <property name="maximumSize"> - <size> - <width>16777215</width> - <height>16777215</height> - </size> - </property> - <property name="toolTip"> - <string><html><head/><body><p>Toggle monitoring On/Off. <br/>Yellow when saving .qm files.</p></body></html></string> - </property> - <property name="text"> - <string>&Monitor</string> - </property> - </widget> + <layout class="QHBoxLayout" name="monitorButtonLayout"> + <item> + <widget class="QPushButton" name="stopButton"> + <property name="minimumSize"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + <property name="toolTip"> + <string><html><head/><body><p>Stop monitoring, and break out of a Decode-remaining-files sequence started with Shift+F6.</p></body></html></string> + </property> + <property name="text"> + <string>&Stop</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="monitorButton"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>0</width> + <height>0</height> + </size> + </property> + <property name="maximumSize"> + <size> + <width>16777215</width> + <height>16777215</height> + </size> + </property> + <property name="toolTip"> + <string><html><head/><body><p>Start monitoring. <br/>Yellow when saving .qm files.</p></body></html></string> + </property> + <property name="text"> + <string>&Monitor</string> + </property> + </widget> + </item> + </layout> </item> <item row="5" column="4" colspan="2"> <widget class="QSlider" name="NBslider"> @@ -597,6 +617,7 @@ li.checked::marker { content: "\2612"; } </widget> <addaction name="actionAstro_Data"/> <addaction name="actionWide_Waterfall"/> + <addaction name="actionVertical_Waterfall"/> <addaction name="separator"/> <addaction name="menuWaterfall_palette"/> <addaction name="separator"/> @@ -617,6 +638,10 @@ li.checked::marker { content: "\2612"; } </property> <addaction name="actionQuick_Start_Guide_to_WSJT_X_2_7_and_QMAP"/> <addaction name="actionQuick_Start_Guide_to_Q65"/> + <addaction name="separator"/> + <addaction name="actionCopyright_Notice"/> + <addaction name="actionTrademark_Policy"/> + <addaction name="separator"/> <addaction name="actionAbout"/> </widget> <widget class="QMenu" name="menuMode"> @@ -655,12 +680,22 @@ li.checked::marker { content: "\2612"; } </action> <action name="actionAbout"> <property name="text"> - <string>About QMAP</string> + <string>About QMAP™</string> </property> <property name="shortcut"> <string>Ctrl+F1</string> </property> </action> + <action name="actionCopyright_Notice"> + <property name="text"> + <string>Copyright notice</string> + </property> + </action> + <action name="actionTrademark_Policy"> + <property name="text"> + <string>Trademark policy</string> + </property> + </action> <action name="actionAstro_Data"> <property name="text"> <string>Astro Data</string> @@ -681,7 +716,12 @@ li.checked::marker { content: "\2612"; } </action> <action name="actionWide_Waterfall"> <property name="text"> - <string>Wideband Waterfall</string> + <string>Horizontal Waterfall</string> + </property> + </action> + <action name="actionVertical_Waterfall"> + <property name="text"> + <string>Vertical Waterfall</string> </property> </action> <action name="actionOpen"> @@ -1031,7 +1071,7 @@ li.checked::marker { content: "\2612"; } <customwidget> <class>DisplayText</class> <extends>QTextBrowser</extends> - <header>widgets/displaytext.h</header> + <header>displaytext.h</header> </customwidget> </customwidgets> <resources/> diff --git a/qmap/plotter.cpp b/qmap/plotter.cpp index 0cf1ad17..8977dd92 100644 --- a/qmap/plotter.cpp +++ b/qmap/plotter.cpp @@ -1,5 +1,6 @@ #include "plotter.h" #include <math.h> +#include <algorithm> #include <QDebug> #include <fstream> #include <iostream> @@ -8,7 +9,10 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor - QFrame(parent) + QFrame(parent), + m_decodeClickCoalescer {this, [this] (QByteArray const& decodeRow, DecodeClickGesture gesture) { + emit decodeLabelClicked (decodeRow, gesture); + }} { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setFocusPolicy(Qt::StrongFocus); @@ -18,26 +22,12 @@ CPlotter::CPlotter(QWidget *parent) : //CPlotter Constructor setAttribute(Qt::WA_NoSystemBackground, true); setMouseTracking(true); - m_StartFreq = 100; - m_nSpan=65; //Units: kHz - m_fSpan=(float)m_nSpan; - m_hdivs = HORZ_DIVS; - m_FreqUnits = 1; - m_Running = false; - m_paintEventBusy=false; m_WaterfallPixmap = QPixmap(0,0); m_ZoomWaterfallPixmap = QPixmap(0,0); m_2DPixmap = QPixmap(0,0); m_ScalePixmap = QPixmap(0,0); m_ZoomScalePixmap = QPixmap(0,0); m_Size = QSize(0,0); - m_fQSO = 125; - m_TXkHz = m_fQSO; - m_line = 0; - m_fSample = 96000; - m_paintAllZoom = false; - m_TxDF=0; - m_bDecodeFinished=false; } CPlotter::~CPlotter() { } // Destructor @@ -55,7 +45,20 @@ QSize CPlotter::sizeHint() const void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() { if(!size().isValid()) return; - if( m_Size != size() ) { + applySize(); +} + +void CPlotter::ensureSized(int w, int h) +{ + resize(w, h); + if(!size().isValid()) return; + applySize(); +} + +void CPlotter::applySize() +{ + bool changed = (m_Size != size()); + if(changed) { //if changed, resize pixmaps to new screensize m_Size = size(); int w = m_Size.width(); @@ -66,14 +69,27 @@ void CPlotter::resizeEvent(QResizeEvent* ) //resizeEvent() m_WaterfallPixmap.fill(Qt::black); m_ZoomWaterfallPixmap.fill(Qt::black); m_2DPixmap.fill(Qt::black); - memset(m_zwf,0,32768*h); m_ScalePixmap = QPixmap(w,30); m_ZoomScalePixmap = QPixmap(w,30); //(no change on resize...) m_ScalePixmap.fill(Qt::white); m_ZoomScalePixmap.fill(Qt::yellow); + + // m_zwf (the zoom row's raw per-bin history) is intentionally NOT + // cleared here -- it's sized independently of the widget and already + // holds the real data; only the just-recreated pixmaps above lost + // their pixels. } SetCenterFreq(-1); - DrawOverlay(); + DrawOverlay(); // recomputes m_binsPerPixel/m_fSpan for the new width + if(changed) { + // Repaint both rows from the raw data that survived, now that + // DrawOverlay() above has updated m_fSpan/m_binsPerPixel to match + // the new width -- rebuildWideFromHistory() needs the *current* + // frequency-per-pixel to remap old rows by frequency, not raw index. + rebuildWideFromHistory(); + m_paintAllZoom = true; // forces paintEvent to fully repaint the + // zoom row from m_zwf at the new size + } } void CPlotter::paintEvent(QPaintEvent *) // paintEvent() @@ -87,6 +103,9 @@ void CPlotter::paintEvent(QPaintEvent *) // paintEvent() int h = (m_Size.height()-60)/2; painter.drawPixmap(0,0,m_ScalePixmap); painter.drawPixmap(0,30,m_WaterfallPixmap); + if (!m_decodeLabels.isEmpty()) { + paintDecodeLabels(painter); + } if(m_2Dspec) { painter.drawPixmap(0,h+30,m_ScalePixmap); painter.drawPixmap(0,h+60,m_2DPixmap); @@ -182,6 +201,8 @@ void CPlotter::draw(float s[], int i0, float splot[]) //draw() int i,j,w,h; float y; + if (m_WaterfallPixmap.isNull()) return; // not yet sized (window never shown) + m_i0=i0; w = m_WaterfallPixmap.width(); h = m_WaterfallPixmap.height(); @@ -240,6 +261,22 @@ void CPlotter::draw(float s[], int i0, float splot[]) //draw() } } + // Remember this row (raw, pre-color-map, post-abs), along with the + // frequency-per-pixel it was captured at, so a later resize can repaint + // m_WaterfallPixmap by remapping frequency to the new width instead of + // just blanking it (or, worse, copying pixel index i to pixel index i + // regardless of how many kHz that pixel now represents). + { + QVector<float> row(w); + for (int k=0; k<w; k++) row[k]=s[k]; + WideHistoryLine line; + line.row = row; + line.startFreq = m_StartFreq; + line.df = (w>0) ? m_fSpan/w : 0.0; + m_wideHistory.prepend(line); + if (m_wideHistory.size() > kMaxWideHistory) m_wideHistory.removeLast(); + } + for(i=0; i<32768; i++) { y = 10.0*log10(splot[i]); int y1 = 5.0*gain*(y + 30 - m_plotZero); @@ -261,6 +298,46 @@ void CPlotter::draw(float s[], int i0, float splot[]) //draw() update(); //trigger a new paintEvent } +// Repaints m_WaterfallPixmap from m_wideHistory, for use right after a +// resize recreates it as a blank pixmap. Remaps by frequency (using each +// row's own captured startFreq/df against the *current* m_StartFreq/ +// m_fSpan) rather than by raw pixel index, so a width change rescales +// the preserved data instead of misaligning it. Uses the same +// color-mapping formula as draw()'s main loop; kept as a separate small +// duplicate rather than factored out, since draw()'s loop is also +// entangled with the histogram and 2D-spectrum bookkeeping that don't +// apply here. +void CPlotter::rebuildWideFromHistory() +{ + if (m_WaterfallPixmap.isNull()) return; + int w = m_WaterfallPixmap.width(); + int h = m_WaterfallPixmap.height(); + if (w<=0 || m_fSpan<=0.0) return; + double gain = pow(10.0,0.05*(m_plotGain+7)); + double newDf = m_fSpan/w; // kHz per pixel, current width + + QPainter painter(&m_WaterfallPixmap); + int rows = qMin(h, m_wideHistory.size()); + for (int y=0; y<rows; y++) { + WideHistoryLine const& line = m_wideHistory.at(y); + int n = line.row.size(); + if (n<=0 || line.df<=0.0) continue; + for (int i=0; i<w; i++) { + double freq = m_StartFreq + i*newDf; + int j = int((freq - line.startFreq)/line.df + 0.5); + if (j<0 || j>=n) continue; // outside what this row captured + float sv = line.row.at(j); + double yv = 10.0*log10(sv); + int y1 = 5.0*gain*(yv + 29 - m_plotZero); + if (y1<0) y1=0; + if (y1>254) y1=254; + if (sv>1.e29) y1=255; + painter.setPen(m_ColorTbl[y1]); + painter.drawPoint(i,y); + } + } +} + void CPlotter::UTCstr() { int ihr,imin; @@ -297,45 +374,42 @@ void CPlotter::DrawOverlay() //DrawOverlay() m_binsPerPixel = m_nSpan * 32768.0/(w*0.001*m_fSample) + 0.5; double FreqPerDiv=5.0; double df = m_binsPerPixel*0.001*m_fSample/32768.0; - m_hdivs = w*df/FreqPerDiv + 0.9999; m_fSpan = w*df; m_ScalePixmap.fill(Qt::white); painter0.drawRect(0, 0, w, 30); - //draw tick marks on wideband (upper) scale + // Wideband (upper) scale ticks and labels. Snap the first division to + // the nearest round FreqPerDiv-kHz frequency at or after m_StartFreq, + // rather than starting the grid at the raw left-edge frequency (which + // is generally not a multiple of FreqPerDiv) -- otherwise labels read + // e.g. 34,39,44,... instead of the intended 35,40,45,..., and the + // ticks themselves sit up to FreqPerDiv/2 kHz off from where the + // labels claim, not just a cosmetic mislabeling. Mirrors + // CVertPlotter::drawScale()'s equivalent fix for the vertical + // waterfall's own frequency scale. pixperdiv = FreqPerDiv/df; - for( int i=1; i<m_hdivs; i++) { //major ticks - x = (int)( (float)i*pixperdiv ); + double f0 = ceil(m_StartFreq/FreqPerDiv)*FreqPerDiv; + double x0 = (f0 - m_StartFreq)/df; + int ndivs = qMin(63, (int)((m_StartFreq+m_fSpan-f0)/FreqPerDiv + 1.e-6)); + + for (int i=0; i<=ndivs; i++) { + x = (int)(x0 + i*pixperdiv + 0.5); painter0.drawLine(x,18,x,30); - } - for( int i=1; i<5*m_hdivs; i++) { //minor ticks - x = i*pixperdiv/5.0; - painter0.drawLine(x,24,x,30); + if (i>0) { + for (int k=1; k<5; k++) { //minor ticks between this major and the previous one + int xm = (int)(x0 + (i-1)*pixperdiv + k*pixperdiv/5.0 + 0.5); + painter0.drawLine(xm,24,xm,30); + } + } + m_HDivText[i].setNum((int)(f0 + i*FreqPerDiv + 0.5)); } //draw frequency values - MakeFrequencyStrs(); - for( int i=0; i<=m_hdivs; i++) { - if(0==i) { - //left justify the leftmost text - x = (int)( (float)i*pixperdiv); - rect0.setRect(x,0, (int)pixperdiv, 20); - painter0.drawText(rect0, Qt::AlignLeft|Qt::AlignVCenter, - m_HDivText[i]); - } - else if(m_hdivs == i) { - //right justify the rightmost text - x = (int)( (float)i*pixperdiv - pixperdiv); - rect0.setRect(x,0, (int)pixperdiv, 20); - painter0.drawText(rect0, Qt::AlignRight|Qt::AlignVCenter, - m_HDivText[i]); - } else { - //center justify the rest of the text - x = (int)( (float)i*pixperdiv - pixperdiv/2); - rect0.setRect(x,0, (int)pixperdiv, 20); - painter0.drawText(rect0, Qt::AlignHCenter|Qt::AlignVCenter, - m_HDivText[i]); - } + for (int i=0; i<=ndivs; i++) { + x = (int)(x0 + i*pixperdiv + 0.5); + rect0.setRect(x-(int)(pixperdiv/2),0, (int)pixperdiv, 20); + painter0.drawText(rect0, Qt::AlignHCenter|Qt::AlignVCenter, + m_HDivText[i]); } @@ -491,6 +565,90 @@ float CPlotter::FreqfromX(int x) //FreqfromX() return f; } +void CPlotter::setDecodeLabels(const QList<QMapDecodeLabel>& labels) +{ + m_decodeLabels = labels; + update(); +} + +QVector<CPlotter::DecodeLabelRect> CPlotter::layoutDecodeLabels() +{ + // Sort left-to-right so the stacking pass below assigns rows in order + // of x-position. + QList<QMapDecodeLabel> sorted = m_decodeLabels; + std::sort(sorted.begin(), sorted.end(), + [this](QMapDecodeLabel const& a, QMapDecodeLabel const& b) { + return XfromFreq(static_cast<float>(a.receiveFrequencyKHz)) + < XfromFreq(static_cast<float>(b.receiveFrequencyKHz)); + }); + + QFont font("Arial", 8, QFont::Bold); + QFontMetrics metrics(font); + const int row_height = metrics.height() + 1; + + // Up to 5 stack rows -- plenty for how many simultaneous decoded + // stations typically show up in one wideband span. + constexpr int max_rows = 5; + // Upper-waterfall geometry: paintEvent() draws the scale at y=0..30 + // and the waterfall row starting at y=30, height (m_Size.height()-60)/2. + constexpr int waterfall_top_y = 30; + int row_right_edge[max_rows]; + for (int i = 0; i < max_rows; ++i) row_right_edge[i] = -1000; + + QVector<DecodeLabelRect> out; + for (auto const& l : sorted) { + if (l.receiveFrequencyKHz < m_StartFreq + || l.receiveFrequencyKHz > m_StartFreq + m_fSpan) continue; + const int x = XfromFreq(static_cast<float>(l.receiveFrequencyKHz)); + const int text_w = metrics.horizontalAdvance(l.callsign); + const int rect_w = text_w + 4; + const int rect_x = x - rect_w / 2; + + int row = 0; + for (; row < max_rows; ++row) { + if (rect_x > row_right_edge[row] + 4) break; + } + if (row >= max_rows) continue; + row_right_edge[row] = rect_x + rect_w; + + const int y_top = waterfall_top_y + row_height * row; + out.append({l, QRect(rect_x, y_top, rect_w, row_height)}); + } + return out; +} + +void CPlotter::paintDecodeLabels(QPainter& painter) +{ + QFont font("Arial", 8, QFont::Bold); + painter.setFont(font); + const int row_height = QFontMetrics(font).height() + 1; + + for (auto const& lr : layoutDecodeLabels()) { + painter.fillRect(lr.rect, QColor(0, 0, 0, 180)); + + // Primary (60s) decodes yellow; second-30s-half decodes a distinct + // hue (orange) rather than a shade, so they stay legible at a glance. + const QColor col = lr.label.secondHalf ? QColor(255, 165, 0) : QColor(255, 255, 0); + const int x = XfromFreq(static_cast<float>(lr.label.receiveFrequencyKHz)); + painter.setPen(QColor(col.red(), col.green(), col.blue(), 200)); + // Tick points down into the waterfall trace at the label's exact frequency. + painter.drawLine(x, lr.rect.top() + row_height, x, lr.rect.top() + row_height + 4); + painter.setPen(col); + painter.drawText(lr.rect, Qt::AlignHCenter | Qt::AlignVCenter, lr.label.callsign); + } +} + +bool CPlotter::hitTestDecodeLabel(QPoint const& pos, QMapDecodeLabel& label) +{ + for (auto const& lr : layoutDecodeLabels()) { + if (lr.rect.contains(pos)) { + label = lr.label; + return true; + } + } + return false; +} + void CPlotter::SetRunningState(bool running) //SetRunningState() { m_Running = running; @@ -601,8 +759,15 @@ void CPlotter::mousePressEvent(QMouseEvent *event) //mousePressEvent int button=event->button(); if(y < h+30) { // Wideband waterfall if(button==1) { + QMapDecodeLabel label; + bool const controlClick = event->modifiers() & Qt::ControlModifier; + bool const labelClicked = !controlClick + && hitTestDecodeLabel(QPoint(x,y), label); setFQSO(x,false); - if(event->modifiers() & Qt::ControlModifier) emit freezeDecode1(3); + if (labelClicked) { + m_decodeClickCoalescer.press(label.callsign, label.raw); + } + if(controlClick) emit freezeDecode1(3); } if(button==2 and !m_bLockTxRx) { if(x<0) x=0; // x is pixel number @@ -627,7 +792,14 @@ void CPlotter::mouseDoubleClickEvent(QMouseEvent *event) //mouse2click int y=event->y(); if(y < h+30) { m_DF=0; + QMapDecodeLabel label; + bool const controlClick = event->modifiers() & Qt::ControlModifier; + bool const labelClicked = !controlClick + && hitTestDecodeLabel(QPoint(x,y), label); setFQSO(x,false); + if (labelClicked) { + m_decodeClickCoalescer.doubleClick(label.callsign, label.raw); + } emit freezeDecode1(2); } else { float f = m_ZoomStartFreq + x*m_fSample/32768.0; diff --git a/qmap/plotter.h b/qmap/plotter.h index 36f0bcd0..ce4663b3 100644 --- a/qmap/plotter.h +++ b/qmap/plotter.h @@ -11,8 +11,12 @@ #include <QFrame> #include <QImage> #include <QToolTip> +#include <QVector> +#include <QList> #include <cstring> #include "commons.h" +#include "decode_click_coalescer.h" +#include "decode_label.h" #define VERT_DIVS 7 //specify grid screen divisions #define HORZ_DIVS 20 @@ -26,17 +30,17 @@ public: QSize minimumSizeHint() const override; QSize sizeHint() const override; - QColor m_ColorTbl[256]; - bool m_bDecodeFinished; - int m_plotZero; - int m_plotGain; - float m_fSpan; - qint32 m_nSpan; - qint32 m_binsPerPixel; - qint32 m_fQSO; - qint32 m_DF; - qint32 m_tol; - qint32 m_fCal; + QColor m_ColorTbl[256] {}; + bool m_bDecodeFinished {}; + int m_plotZero {}; + int m_plotGain {}; + float m_fSpan {65.f}; + qint32 m_nSpan {65}; + qint32 m_binsPerPixel {1}; + qint32 m_fQSO {125}; + qint32 m_DF {}; + qint32 m_tol {}; + qint32 m_fCal {}; void draw(float sw[], int i0, float splot[]); //Update the waterfalls void SetRunningState(bool running); @@ -75,65 +79,103 @@ public: double txFreq(); // void updateFreqLabel(); + void setDecodeLabels(const QList<QMapDecodeLabel>& labels); + + // Hidden plotters may not receive an initial resize event, but spectrum production still needs valid geometry. + void ensureSized(int w, int h); + signals: void freezeDecode0(int n); void freezeDecode1(int n); + void decodeLabelClicked(QByteArray decodeRow, DecodeClickGesture gesture); protected: //re-implemented widget event handlers void paintEvent(QPaintEvent *event) override; void resizeEvent(QResizeEvent* event) override; void mouseMoveEvent(QMouseEvent * event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseDoubleClickEvent(QMouseEvent *event) override; private: void MakeFrequencyStrs(); void UTCstr(); + void applySize(); int XfromFreq(float f); float FreqfromX(int x); qint64 RoundFreq(qint64 freq, int resolution); + // Render m_decodeLabels overlay on top of the waterfall pixmap. Stacks + // colliding labels vertically (max 5 rows) so a busy band doesn't paint + // labels on top of each other. + void paintDecodeLabels(QPainter& painter); + + // Painting and hit-testing share the same collision-adjusted bounds. + struct DecodeLabelRect { + QMapDecodeLabel label; + QRect rect; + }; + QVector<DecodeLabelRect> layoutDecodeLabels(); + bool hitTestDecodeLabel(QPoint const& pos, QMapDecodeLabel& label); + + // Raw wideband-row snapshots (post color-mapping input, pre color-map), + // front=newest, so a resize can repaint m_WaterfallPixmap from history + // instead of blanking it. m_zwf already plays this role for the zoom + // row -- this is the wideband row's counterpart. Each row keeps the + // frequency-per-pixel (df) it was captured at, since that changes with + // window width -- rebuildWideFromHistory() remaps by frequency, not by + // raw pixel index, so a width change rescales existing data instead of + // just shifting it to the wrong frequency. + struct WideHistoryLine { + QVector<float> row; + double startFreq; // m_StartFreq at capture time + double df; // kHz per pixel at capture time (m_fSpan/width) + }; + void rebuildWideFromHistory(); + QList<WideHistoryLine> m_wideHistory; + static constexpr int kMaxWideHistory = 2048; + + QList<QMapDecodeLabel> m_decodeLabels; + DecodeClickCoalescer m_decodeClickCoalescer; QPixmap m_WaterfallPixmap; QPixmap m_ZoomWaterfallPixmap; QPixmap m_2DPixmap; - unsigned char m_zwf[32768*400]; + unsigned char m_zwf[32768*400] {}; QPixmap m_ScalePixmap; QPixmap m_ZoomScalePixmap; QSize m_Size; QString m_Str; QString m_HDivText[483]; - bool m_Running; - bool m_paintEventBusy; - bool m_2Dspec; - bool m_paintAllZoom; - bool m_bLockTxRx; - double m_CenterFreq; - double m_fGreen; - double m_TXfreq; - qint64 m_StartFreq; - qint64 m_ZoomStartFreq; - qint64 m_FreqOffset; - qint32 m_dBStepSize; - qint32 m_FreqUnits; - qint32 m_hdivs; - bool m_dataFromDisk; + bool m_Running {}; + bool m_paintEventBusy {}; + bool m_2Dspec {}; + bool m_paintAllZoom {}; + bool m_bLockTxRx {}; + double m_CenterFreq {}; + double m_fGreen {}; + double m_TXfreq {}; + qint64 m_StartFreq {100}; + qint64 m_ZoomStartFreq {}; + qint64 m_FreqOffset {}; + qint32 m_dBStepSize {}; + qint32 m_FreqUnits {1}; + qint32 m_hdivs {HORZ_DIVS}; + bool m_dataFromDisk {}; QString m_sutc; - qint32 m_line; - qint32 m_hist1[256]; - qint32 m_hist2[256]; - qint32 m_z1; - qint32 m_z2; - qint32 m_nkhz; - qint32 m_fSample; - qint32 m_mode65; - qint32 m_i0; - qint32 m_xClick; - qint32 m_TXkHz; - qint32 m_TxDF; - -private slots: - void mousePressEvent(QMouseEvent *event) override; - void mouseDoubleClickEvent(QMouseEvent *event) override; + qint32 m_line {}; + qint32 m_hist1[256] {}; + qint32 m_hist2[256] {}; + qint32 m_z1 {}; + qint32 m_z2 {}; + qint32 m_nkhz {}; + qint32 m_fSample {96000}; + qint32 m_mode65 {}; + qint32 m_i0 {}; + qint32 m_xClick {}; + qint32 m_TXkHz {125}; + qint32 m_TxDF {}; + }; #endif // PLOTTER_H diff --git a/qmap/qmap.pro b/qmap/qmap.pro deleted file mode 100644 index 3bc2b681..00000000 --- a/qmap/qmap.pro +++ /dev/null @@ -1,44 +0,0 @@ -#------------------------------------------------- -# -# Project created by QtCreator 2011-07-07T08:39:24 -# -#------------------------------------------------- - -QT += core gui network -greaterThan(QT_MAJOR_VERSION, 4): QT += widgets -CONFIG += thread -#CONFIG += console - -TARGET = qmap -VERSION = 0.1 -TEMPLATE = app -DEFINES = QT5 - -F90 = gfortran -gfortran.output = ${QMAKE_FILE_BASE}.o -gfortran.commands = $$F90 -c -O2 -o ${QMAKE_FILE_OUT} ${QMAKE_FILE_NAME} -gfortran.input = F90_SOURCES -QMAKE_EXTRA_COMPILERS += gfortran - -win32 { -DEFINES = WIN32 -} - -unix { -DEFINES = UNIX -} - -SOURCES += main.cpp mainwindow.cpp plotter.cpp about.cpp \ - soundin.cpp devsetup.cpp \ - widegraph.cpp getfile.cpp \ - astro.cpp displaytext.cpp getdev.cpp \ - meterwidget.cpp signalmeter.cpp - -HEADERS += mainwindow.h plotter.h soundin.h \ - about.h devsetup.h widegraph.h getfile.h \ - commons.h sleep.h astro.h displaytext.h \ - meterwidget.h signalmeter.h - -FORMS += mainwindow.ui about.ui devsetup.ui widegraph.ui \ - astro.ui txtune.ui - diff --git a/qmap/qmap_click_policy.h b/qmap/qmap_click_policy.h new file mode 100644 index 00000000..d5cedc0f --- /dev/null +++ b/qmap/qmap_click_policy.h @@ -0,0 +1,25 @@ +#ifndef QMAP_CLICK_POLICY_H +#define QMAP_CLICK_POLICY_H + +struct QMapClickPolicy +{ + bool disarmBeforeQsy {}; + bool enableAutoTx {}; + bool disableAutoTx {}; + bool restartTransmission {}; +}; + +constexpr QMapClickPolicy qmapClickPolicy (bool doubleClick, + bool frequencyChanged, + bool autoTxEnabled, + bool transmitting) noexcept +{ + return { + doubleClick && autoTxEnabled, + doubleClick && frequencyChanged, + !doubleClick && autoTxEnabled, + frequencyChanged && transmitting + }; +} + +#endif // QMAP_CLICK_POLICY_H diff --git a/qmap/qmap_decode_record.cpp b/qmap/qmap_decode_record.cpp new file mode 100644 index 00000000..7891bfeb --- /dev/null +++ b/qmap/qmap_decode_record.cpp @@ -0,0 +1,41 @@ +#include "qmap_decode_record.h" + +#include "Decoder/decodedtext.h" + +std::optional<QMapDecodeRecord> parseQMapDecodeRecord (QByteArray const& row) +{ + if (row.size () != static_cast<int> (QMapDecodeRowSize)) return std::nullopt; + + auto text = QString::fromLatin1 (row.constData (), row.size ()); + auto const terminator = text.indexOf (QChar::Null); + if (terminator >= 0) text.truncate (terminator); + + bool timeOk {}; + bool receiveOk {}; + bool scheduledOk {}; + bool snrOk {}; + auto const hhmmss = text.left (6).toInt (&timeOk); + auto const hour = hhmmss / 10000; + auto const minute = (hhmmss / 100) % 100; + auto const second = hhmmss % 100; + + QMapDecodeRecord record; + record.raw = row; + record.time = text.left (6); + record.receiveFrequencyKHz = text.mid (6, 9).toDouble (&receiveOk); + record.scheduledFrequencyKHz = text.mid (15, 7).toDouble (&scheduledOk); + record.snr = text.mid (29, 5).toInt (&snrOk); + record.submode = text.mid (36, 3).trimmed (); + auto const fields = parseDecodedMessage (text.mid (41)); + record.callsign = fields.sender; + record.grid = fields.grid; + record.secondsSinceMidnight = hour * 3600 + minute * 60 + second; + record.secondHalf = second == 30; + record.cq = fields.cq; + + if (!timeOk || !receiveOk || !scheduledOk || !snrOk + || hour > 23 || minute > 59 || second > 59 || record.submode.isEmpty ()) { + return std::nullopt; + } + return record; +} diff --git a/qmap/qmap_decode_record.h b/qmap/qmap_decode_record.h new file mode 100644 index 00000000..1d0f3e03 --- /dev/null +++ b/qmap/qmap_decode_record.h @@ -0,0 +1,28 @@ +#ifndef QMAP_DECODE_RECORD_H +#define QMAP_DECODE_RECORD_H + +#include <optional> + +#include <QByteArray> +#include <QString> + +#include "qmap_ipc.h" + +struct QMapDecodeRecord +{ + QByteArray raw; + QString time; + QString callsign; + QString grid; + QString submode; + double receiveFrequencyKHz {}; + double scheduledFrequencyKHz {}; + int snr {}; + int secondsSinceMidnight {}; + bool secondHalf {}; + bool cq {}; +}; + +std::optional<QMapDecodeRecord> parseQMapDecodeRecord (QByteArray const& row); + +#endif // QMAP_DECODE_RECORD_H diff --git a/qmap/qmap_ipc.h b/qmap/qmap_ipc.h new file mode 100644 index 00000000..2ded811d --- /dev/null +++ b/qmap/qmap_ipc.h @@ -0,0 +1,107 @@ +#ifndef QMAP_IPC_H +#define QMAP_IPC_H + +#include "decode_ipc.h" + +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <type_traits> + +constexpr std::size_t QMapDecodeCapacity = qmap_decode_ipc::max_rows; +constexpr std::size_t QMapDecodeRowSize = qmap_decode_ipc::row_size; + +static_assert (QMapDecodeRowSize == 80, + "QMAP IPC must use the fixed 80-byte decoder row"); + +enum class QMapClickAction : std::int32_t +{ + None = 0, + Disarm = 1, + Select = 2, + SelectAndEnableTx = 3, +}; + +using QMapDecodeBlock = qmap_decode_ipc::DecodeRows; + +struct QMapClickMailbox +{ + char selectedDecode[QMapDecodeRowSize]; + QMapClickAction action; +}; + +struct QMapSharedMemory +{ + QMapDecodeBlock decodes; + QMapClickMailbox click; +}; + +static_assert (sizeof (std::int32_t) == 4, "QMAP IPC requires 32-bit integers"); +static_assert (std::is_standard_layout<QMapClickMailbox>::value, + "QMAP click mailbox must have a stable field layout"); +static_assert (std::is_trivially_copyable<QMapClickMailbox>::value, + "QMAP click mailbox must support byte-for-byte copying"); +static_assert (offsetof (QMapClickMailbox, action) == QMapDecodeRowSize, + "QMAP click request offset changed"); +static_assert (sizeof (QMapClickMailbox) == QMapDecodeRowSize + sizeof (std::int32_t), + "QMAP click mailbox size changed"); +static_assert (std::is_standard_layout<QMapSharedMemory>::value, + "QMAP shared memory must have a stable field layout"); +static_assert (std::is_trivially_copyable<QMapSharedMemory>::value, + "QMAP shared memory must support byte-for-byte copying"); +static_assert (offsetof (QMapSharedMemory, decodes) == 0, + "QMAP decode block must start the shared segment"); +static_assert (offsetof (QMapSharedMemory, click) == sizeof (QMapDecodeBlock), + "QMAP click mailbox offset changed"); +static_assert (sizeof (QMapSharedMemory) == sizeof (QMapDecodeBlock) + sizeof (QMapClickMailbox), + "QMAP IPC wire layout changed"); + +constexpr std::size_t QMapSharedMemorySize { + ((sizeof (QMapSharedMemory) + 15) / 16) * 16 +}; + +static_assert (QMapSharedMemorySize >= qmap_decode_ipc::shared_memory_size, + "QMAP shared memory must preserve the decoder segment size"); +static_assert (sizeof (QMapSharedMemory) <= QMapSharedMemorySize, + "QMAP IPC exceeds the shared-memory segment"); + +constexpr bool qmapDecoderRegionAvailable (std::size_t mappedSize) noexcept +{ + return mappedSize >= qmap_decode_ipc::shared_memory_size; +} + +constexpr bool qmapClickMailboxAvailable (std::size_t mappedSize) noexcept +{ + return mappedSize >= sizeof (QMapSharedMemory); +} + +constexpr std::size_t qmapClearLength (std::size_t mappedSize) noexcept +{ + return std::min (mappedSize, QMapSharedMemorySize); +} + +inline void clearQMapSharedMemory (void * mappedData, + std::size_t mappedSize) noexcept +{ + if (mappedData) std::memset (mappedData, 0, qmapClearLength (mappedSize)); +} + +inline void publishQMapDecodeBlock (QMapSharedMemory& shared, + QMapDecodeBlock& publication) noexcept +{ + publication.nWDecoderBusy = shared.decodes.nWDecoderBusy; + publication.nWTransmitting = shared.decodes.nWTransmitting; + publication.kHzRequested = shared.decodes.kHzRequested; + shared.decodes = publication; +} + +inline bool acknowledgeQMapDecodeBatch (QMapDecodeBlock& shared) noexcept +{ + if (shared.nQDecoderDone == 0) return false; + shared.ndecodes = 0; + shared.nQDecoderDone = 0; + return true; +} + +#endif // QMAP_IPC_H diff --git a/qmap/runtime_paths.cpp b/qmap/runtime_paths.cpp new file mode 100644 index 00000000..b4f2291e --- /dev/null +++ b/qmap/runtime_paths.cpp @@ -0,0 +1,40 @@ +#include "runtime_paths.h" + +#include <QDebug> +#include <QDir> +#include <QFile> +#include <QStandardPaths> + +QString qmapDataDir() +{ + QString dataDir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); + if (dataDir.isEmpty()) { + dataDir = QDir::home().absoluteFilePath(".qmap"); + } + + if (!QDir{}.mkpath(dataDir)) { + qWarning() << "Unable to create QMAP data directory:" << dataDir; + } + + QDir dir {dataDir}; + if (!dir.mkpath("save")) { + qWarning() << "Unable to create QMAP save directory:" << dir.absoluteFilePath("save"); + } + return dataDir; +} + +QString qmapSettingsFile(QString const& appDir, QString const& dataDir) +{ + QString settingsFile = QDir {dataDir}.absoluteFilePath("qmap.ini"); + QString legacySettingsFile = QDir {appDir}.absoluteFilePath("qmap.ini"); + if (!QFile::exists(settingsFile) && QFile::exists(legacySettingsFile)) { + if (QFile::copy(legacySettingsFile, settingsFile)) { + QFile::setPermissions(settingsFile, QFile::ReadOwner | QFile::WriteOwner + | QFile::ReadGroup | QFile::ReadOther); + } else { + qWarning() << "Unable to migrate QMAP settings from" << legacySettingsFile + << "to" << settingsFile; + } + } + return settingsFile; +} diff --git a/qmap/runtime_paths.h b/qmap/runtime_paths.h new file mode 100644 index 00000000..d99eb7af --- /dev/null +++ b/qmap/runtime_paths.h @@ -0,0 +1,9 @@ +#ifndef QMAP_RUNTIME_PATHS_H +#define QMAP_RUNTIME_PATHS_H + +#include <QString> + +QString qmapDataDir(); +QString qmapSettingsFile(QString const& appDir, QString const& dataDir); + +#endif diff --git a/qmap/shared_memory_key.h b/qmap/shared_memory_key.h new file mode 100644 index 00000000..6a0a5cae --- /dev/null +++ b/qmap/shared_memory_key.h @@ -0,0 +1,15 @@ +#ifndef QMAP_SHARED_MEMORY_KEY_H +#define QMAP_SHARED_MEMORY_KEY_H + +#include <QString> + +namespace qmap_decode_ipc +{ + inline QString shared_memory_key () + { + auto const override_key = qEnvironmentVariable ("WSJT_QMAP_SHARED_MEMORY_KEY"); + return override_key.isEmpty () ? QStringLiteral ("mem_qmap") : override_key; + } +} + +#endif diff --git a/qmap/soundin.cpp b/qmap/soundin.cpp index 1b71b9e8..e84911ef 100644 --- a/qmap/soundin.cpp +++ b/qmap/soundin.cpp @@ -12,7 +12,7 @@ extern "C" { - struct + extern struct { double d8[60*96000]; //This is "common/datcom/..." in fortran float ss[400*NFFT]; diff --git a/qmap/vertwaterfall.cpp b/qmap/vertwaterfall.cpp new file mode 100644 index 00000000..ec42549e --- /dev/null +++ b/qmap/vertwaterfall.cpp @@ -0,0 +1,85 @@ +#include "vertwaterfall.h" +#include <QSettings> +#include "SettingsGroup.hpp" +#include "ui_vertwaterfall.h" + +VertWaterfall::VertWaterfall (QString const& settings_filename, QWidget * parent) + : QDialog {parent}, + ui {new Ui::VertWaterfall}, + m_settings_filename {settings_filename}, + m_decodeLabelsEnabled {true} +{ + ui->setupUi(this); + setWindowTitle("Vertical Waterfall"); + setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint); + + QSettings settings {m_settings_filename, QSettings::IniFormat}; + { + SettingsGroup g {&settings, "VertWaterfall"}; + setGeometry (settings.value ("VertWaterfallGeom", QRect {80,80,300,900}).toRect ()); + m_decodeLabelsEnabled = settings.value ("decode_labels_enabled", true).toBool (); + } + ui->cbShowCallsigns->setChecked (m_decodeLabelsEnabled); + + connect (ui->vertPlot, &CVertPlotter::decodeLabelClicked, + this, &VertWaterfall::decodeLabelClicked2); +} + +VertWaterfall::~VertWaterfall() +{ + saveSettings(); + delete ui; +} + +void VertWaterfall::saveSettings() +{ + QSettings settings {m_settings_filename, QSettings::IniFormat}; + SettingsGroup g {&settings, "VertWaterfall"}; + settings.setValue ("VertWaterfallGeom", geometry()); + settings.setValue ("decode_labels_enabled", m_decodeLabelsEnabled); +} + +void VertWaterfall::closeEvent(QCloseEvent * event) +{ + saveSettings(); + QDialog::closeEvent(event); +} + +void VertWaterfall::dataSinkVert(const float swide[], int n, double startFreqKHz, double fSpanKHz, + int plotZero, int plotGain) +{ + ui->vertPlot->draw(swide, n, startFreqKHz, fSpanKHz, plotZero, plotGain); +} + +void VertWaterfall::addDecodeLabel(QMapDecodeRecord const& record) +{ + if (!m_decodeLabelsEnabled) return; + pruneQMapDecodeLabels(m_decodeLabels, record.secondsSinceMidnight); + upsertQMapDecodeLabel(m_decodeLabels, record); + ui->vertPlot->setDecodeLabels(m_decodeLabels); +} + +void VertWaterfall::pruneDecodeLabels(int nowSeconds) +{ + auto const previousSize = m_decodeLabels.size(); + pruneQMapDecodeLabels(m_decodeLabels, nowSeconds); + if (m_decodeLabels.size() != previousSize) { + ui->vertPlot->setDecodeLabels(m_decodeLabels); + } +} + +void VertWaterfall::clearDecodeLabels() +{ + if (m_decodeLabels.isEmpty ()) return; + m_decodeLabels.clear (); + ui->vertPlot->setDecodeLabels (m_decodeLabels); +} + +void VertWaterfall::on_cbShowCallsigns_toggled(bool checked) +{ + m_decodeLabelsEnabled = checked; + if (!checked) { + m_decodeLabels.clear(); + ui->vertPlot->setDecodeLabels(m_decodeLabels); + } +} diff --git a/qmap/vertwaterfall.h b/qmap/vertwaterfall.h new file mode 100644 index 00000000..3a713b5e --- /dev/null +++ b/qmap/vertwaterfall.h @@ -0,0 +1,47 @@ +#ifndef VERTWATERFALL_H +#define VERTWATERFALL_H + +#include <QDialog> +#include <QList> +#include <QString> +#include "vplotter.h" + +namespace Ui { + class VertWaterfall; +} + +class VertWaterfall : public QDialog +{ + Q_OBJECT + +public: + explicit VertWaterfall (QString const& settings_filename, QWidget * parent = nullptr); + ~VertWaterfall(); + + void saveSettings(); + void pruneDecodeLabels(int nowSeconds); + void clearDecodeLabels(); + +public slots: + void dataSinkVert(const float swide[], int n, double startFreqKHz, double fSpanKHz, + int plotZero, int plotGain); + void addDecodeLabel(QMapDecodeRecord const& record); + +signals: + void decodeLabelClicked2(QByteArray decodeRow, DecodeClickGesture gesture); + +protected: + void closeEvent(QCloseEvent * event) override; + +private slots: + void on_cbShowCallsigns_toggled(bool checked); + +private: + Ui::VertWaterfall * ui; + QString m_settings_filename; + + QList<QMapDecodeLabel> m_decodeLabels; + bool m_decodeLabelsEnabled; +}; + +#endif // VERTWATERFALL_H diff --git a/qmap/vertwaterfall.ui b/qmap/vertwaterfall.ui new file mode 100644 index 00000000..4c745dcb --- /dev/null +++ b/qmap/vertwaterfall.ui @@ -0,0 +1,78 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>VertWaterfall</class> + <widget class="QDialog" name="VertWaterfall"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>300</width> + <height>900</height> + </rect> + </property> + <property name="windowTitle"> + <string>Vertical Waterfall</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout" stretch="1,0"> + <item> + <widget class="CVertPlotter" name="vertPlot"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>150</width> + <height>200</height> + </size> + </property> + <property name="frameShape"> + <enum>QFrame::StyledPanel</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Sunken</enum> + </property> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QCheckBox" name="cbShowCallsigns"> + <property name="text"> + <string>Show callsigns</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </widget> + <customwidgets> + <customwidget> + <class>CVertPlotter</class> + <extends>QFrame</extends> + <header>vplotter.h</header> + <container>1</container> + </customwidget> + </customwidgets> + <resources/> + <connections/> +</ui> diff --git a/qmap/vplotter.cpp b/qmap/vplotter.cpp new file mode 100644 index 00000000..91e9b26d --- /dev/null +++ b/qmap/vplotter.cpp @@ -0,0 +1,367 @@ +#include "vplotter.h" +#include <algorithm> +#include <math.h> +#include <QPainter> +#include <QFontMetrics> +#include <QMouseEvent> +#include <QtMath> + +CVertPlotter::CVertPlotter(QWidget *parent) : + QFrame(parent), + m_decodeClickCoalescer {this, [this] (QByteArray const& decodeRow, DecodeClickGesture gesture) { + emit decodeLabelClicked (decodeRow, gesture); + }} +{ + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + setAttribute(Qt::WA_OpaquePaintEvent, false); + setAttribute(Qt::WA_NoSystemBackground, true); + + m_scaleWidth = 40; + m_labelWidth = 90; + m_startFreqKHz = 0.0; + m_fSpanKHz = 1.0; + m_hdivs = 0; + m_size = QSize(0,0); + m_waterfallPixmap = QPixmap(0,0); + m_scalePixmap = QPixmap(0,0); + setPalette("Linrad"); +} + +CVertPlotter::~CVertPlotter() { } + +QSize CVertPlotter::minimumSizeHint() const +{ + return QSize(m_scaleWidth + m_labelWidth + 40, 100); +} + +QSize CVertPlotter::sizeHint() const +{ + return QSize(m_scaleWidth + m_labelWidth + 120, 800); +} + +void CVertPlotter::resizeEvent(QResizeEvent*) +{ + if(!size().isValid()) return; + if(m_size != size()) { + m_size = size(); + int w = qMax(1, m_size.width() - m_scaleWidth - m_labelWidth); + int h = m_size.height(); + m_waterfallPixmap = QPixmap(w,h); + m_waterfallPixmap.fill(Qt::black); + m_scalePixmap = QPixmap(m_scaleWidth,h); + m_scalePixmap.fill(QColor(235,235,230)); + rebuildFromHistory(); + } + drawScale(); +} + +// y=0 is the top of the spectrogram (highest frequency in span); y=h-1 +// is the bottom (lowest frequency), matching "frequency runs bottom to +// top" as requested. +int CVertPlotter::yFromFreq(double freq_khz) const +{ + int h = m_waterfallPixmap.height(); + if(h<=0 || m_fSpanKHz<=0.0) return 0; + double frac = (freq_khz - m_startFreqKHz)/m_fSpanKHz; // 0=bottom .. 1=top + int y = int((1.0 - frac)*h + 0.5); + if(y<0) y=0; + if(y>h-1) y=h-1; + return y; +} + +void CVertPlotter::draw(const float swide[], int n, double startFreqKHz, double fSpanKHz, + int plotZero, int plotGain) +{ + if(n<=0 || m_waterfallPixmap.isNull()) return; + m_startFreqKHz = startFreqKHz; + m_fSpanKHz = fSpanKHz; + + // Remember this column (raw, pre-color-map) so a later resize can + // repaint the spectrogram instead of blanking it. + { + HistoryLine line; + line.swide.resize(n); + for (int k=0; k<n; k++) line.swide[k]=swide[k]; + line.startFreqKHz = startFreqKHz; + line.fSpanKHz = fSpanKHz; + line.plotZero = plotZero; + line.plotGain = plotGain; + m_history.prepend(line); + if (m_history.size() > kMaxHistory) m_history.removeLast(); + } + + int w = m_waterfallPixmap.width(); + int h = m_waterfallPixmap.height(); + double gain = pow(10.0,0.05*(plotGain+7)); + + //move current data left one column (must do this before attaching a QPainter) + m_waterfallPixmap.scroll(-1,0,0,0,w,h); + QPainter painter(&m_waterfallPixmap); + + for(int y=0; y<h; y++) { + // Row y (top=high freq) maps to sample j (increasing index = increasing freq) + int j = int((double)(h-1-y)*(n-1)/qMax(1,h-1) + 0.5); + if(j<0) j=0; + if(j>n-1) j=n-1; + float sv = swide[j]; + if(sv<0) sv=-sv; //strong-signal tag, ignored for color here + double yv = 10.0*log10(sv); + int y1 = int(5.0*gain*(yv + 29 - plotZero)); + if(y1<0) y1=0; + if(y1>254) y1=254; + if(sv>1.e29) y1=255; + painter.setPen(m_ColorTbl[y1]); + painter.drawPoint(w-1,y); + } + + drawScale(); + update(); +} + +// Repaints the spectrogram from m_history, for use right after a resize +// recreates m_waterfallPixmap as blank. Same color-mapping formula as +// draw()'s loop (kept as a separate small duplicate rather than shared, +// same tradeoff as CPlotter::rebuildWideFromHistory). A column narrower +// or wider than the current width is left as-is (each column already +// resamples to the current height independent of its own sample count). +void CVertPlotter::rebuildFromHistory() +{ + if (m_waterfallPixmap.isNull()) return; + int w = m_waterfallPixmap.width(); + int h = m_waterfallPixmap.height(); + m_waterfallPixmap.fill(Qt::black); + QPainter painter(&m_waterfallPixmap); + + int cols = qMin(w, m_history.size()); + for (int age=0; age<cols; age++) { + HistoryLine const& line = m_history.at(age); + int n = line.swide.size(); + if (n<=0) continue; + int x = w-1-age; + double gain = pow(10.0,0.05*(line.plotGain+7)); + for (int y=0; y<h; y++) { + int j = int((double)(h-1-y)*(n-1)/qMax(1,h-1) + 0.5); + if(j<0) j=0; + if(j>n-1) j=n-1; + float sv = line.swide.at(j); + if(sv<0) sv=-sv; + double yv = 10.0*log10(sv); + int y1 = int(5.0*gain*(yv + 29 - line.plotZero)); + if(y1<0) y1=0; + if(y1>254) y1=254; + if(sv>1.e29) y1=255; + painter.setPen(m_ColorTbl[y1]); + painter.drawPoint(x,y); + } + } +} + +// Chooses a round kHz step (5/10/25/50/...) that keeps ticks from +// crowding, then the first (bottom-most) tick frequency at or above +// m_startFreqKHz, and formats the label text for each tick. +void CVertPlotter::makeFrequencyStrs() +{ + m_hdivs = 0; + int h = m_scalePixmap.height(); + if(h<=0 || m_fSpanKHz<=0.0) return; + + static const double steps[] = {5.0,10.0,25.0,50.0,100.0,200.0,500.0,1000.0}; + double pixPerKHz = h/m_fSpanKHz; + m_freqPerDiv = steps[0]; + for (double step : steps) { + m_freqPerDiv = step; + if (step*pixPerKHz >= 24.0) break; + } + + m_freq0 = qCeil(m_startFreqKHz/m_freqPerDiv)*m_freqPerDiv; + m_hdivs = qMin(63, int((m_startFreqKHz+m_fSpanKHz-m_freq0)/m_freqPerDiv + 1.e-6)); + for(int i=0; i<=m_hdivs; i++) { + double f = m_freq0 + i*m_freqPerDiv; + m_HDivText[i] = QString::number(f, 'f', 0); + } +} + +void CVertPlotter::drawScale() +{ + if(m_scalePixmap.isNull()) return; + int w = m_scalePixmap.width(); + + QPainter painter(&m_scalePixmap); + QFont font("Arial"); + font.setPointSize(8); + painter.setFont(font); + m_scalePixmap.fill(QColor(235,235,230)); + painter.setPen(QColor(120,120,115)); + painter.drawLine(0,0,0,m_scalePixmap.height()); // thin rule against the spectrogram edge + + makeFrequencyStrs(); + painter.setPen(Qt::black); + for(int i=0; i<=m_hdivs; i++) { + double f = m_freq0 + i*m_freqPerDiv; + int y = yFromFreq(f); + painter.drawLine(0,y,6,y); + QRect rect0(8, y-8, w-10, 16); + painter.drawText(rect0, Qt::AlignLeft|Qt::AlignVCenter, m_HDivText[i]); + } +} + +void CVertPlotter::setDecodeLabels(const QList<QMapDecodeLabel>& labels) +{ + m_decodeLabels = labels; + update(); +} + +QFont CVertPlotter::labelFont() const +{ + QFont font("Arial"); + font.setPointSize(9); + return font; +} + +// Displace nearby labels downward in frequency order to keep them legible. +QVector<CVertPlotter::LabelLayout> CVertPlotter::computeLayout(QFontMetrics const& fm, int minSpacing) const +{ + int labelX = m_waterfallPixmap.width() + m_scaleWidth; + int indentPx = fm.horizontalAdvance("MM"); + + QVector<LabelLayout> out; + out.reserve(m_decodeLabels.size()); + for (auto const& lab : qAsConst(m_decodeLabels)) { + if (lab.receiveFrequencyKHz < m_startFreqKHz + || lab.receiveFrequencyKHz > m_startFreqKHz + m_fSpanKHz) continue; + LabelLayout ll; + ll.label = lab; + ll.trueY = ll.dispY = yFromFreq(lab.receiveFrequencyKHz); + ll.textX = labelX + 14 + (lab.secondHalf ? indentPx : 0); + out.append(ll); + } + std::sort(out.begin(), out.end(), [](LabelLayout const& a, LabelLayout const& b) { + return a.trueY < b.trueY; + }); + for (int i=1; i<out.size(); ++i) { + if (out[i].dispY < out[i-1].dispY + minSpacing) + out[i].dispY = out[i-1].dispY + minSpacing; + } + for (auto& ll : out) { + int text_w = fm.horizontalAdvance(ll.label.callsign); + ll.rect = QRect(ll.textX - 2, ll.dispY + 4 - fm.ascent(), text_w + 4, fm.height()); + } + return out; +} + +bool CVertPlotter::hitTestDecodeLabel(QPoint const& pos, QMapDecodeLabel& label) +{ + QFontMetrics fm(labelFont()); + for (auto const& ll : computeLayout(fm, fm.height() + 2)) { + if (ll.rect.contains(pos)) { + label = ll.label; + return true; + } + } + return false; +} + +void CVertPlotter::mousePressEvent(QMouseEvent *event) +{ + if (event->button() != Qt::LeftButton) return; + QMapDecodeLabel label; + if (hitTestDecodeLabel(event->pos(), label)) { + m_decodeClickCoalescer.press(label.callsign, label.raw); + } +} + +void CVertPlotter::mouseDoubleClickEvent(QMouseEvent *event) +{ + if (event->button() != Qt::LeftButton) return; + QMapDecodeLabel label; + if (hitTestDecodeLabel(event->pos(), label)) { + m_decodeClickCoalescer.doubleClick(label.callsign, label.raw); + } +} + +void CVertPlotter::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + int w = m_waterfallPixmap.width(); + painter.drawPixmap(0,0,m_waterfallPixmap); + painter.drawPixmap(w,0,m_scalePixmap); + + int labelX = w + m_scaleWidth; + painter.fillRect(labelX, 0, m_labelWidth, height(), QColor(255,255,240)); + + QFont font = labelFont(); + painter.setFont(font); + QFontMetrics fm(font); + int minSpacing = fm.height() + 2; + + QColor dotColor(230,200,40); + QColor leaderColor(150,150,140); + for (auto const& ll : computeLayout(fm, minSpacing)) { + painter.setPen(Qt::NoPen); + painter.setBrush(dotColor); + painter.drawEllipse(QPoint(labelX+5,ll.trueY), 3, 3); + if (ll.dispY != ll.trueY || ll.label.secondHalf) { + painter.setPen(QPen(leaderColor,1)); + painter.drawLine(labelX+8, ll.trueY, ll.textX-2, ll.dispY); + } + painter.setPen(Qt::black); + painter.drawText(ll.textX, ll.dispY+4, ll.label.callsign); + } +} + +void CVertPlotter::setPalette(QString palette) +{ + if(palette=="Linrad") { + float twopi=6.2831853f; + float r,g,b,phi,x; + for(int i=0; i<256; i++) { + r=0.0; + if(i>105 and i<=198) { + phi=(twopi/4.0f) * (i-105.0f)/(198.0f-105.0f); + r=sin(phi); + } else if(i>=198) { + r=1.0; + } + + g=0.0; + if(i>35 and i<198) { + phi=(twopi/4.0f) * (i-35.0f)/(122.5f-35.0f); + g=0.625f*sin(phi); + } else if(i>=198) { + x=(i-186.0f); + g=-0.014f + 0.0144f*x -0.00007f*x*x +0.000002f*x*x*x; + if(g>1.0) g=1.0; + } + + b=0.0; + if(i<=117) { + phi=(twopi/2.0f) * i/117.0f; + b=0.4531f*sin(phi); + } else if(i>186) { + x=(i-186.0f); + b=-0.014f + 0.0144f*x -0.00007f*x*x +0.000002f*x*x*x; + if(b>1.0) b=1.0; + } + m_ColorTbl[i].setRgb(int(255.0*r),int(255.0*g),int(255.0*b)); + } + m_ColorTbl[255].setRgb(255,255,100); + } + + if(palette=="CuteSDR") { + for(int i=0; i<256; i++) { + if( (i<43) ) + m_ColorTbl[i].setRgb( 0,0, 255*(i)/43); + if( (i>=43) && (i<87) ) + m_ColorTbl[i].setRgb( 0, 255*(i-43)/43, 255 ); + if( (i>=87) && (i<120) ) + m_ColorTbl[i].setRgb( 0,255, 255-(255*(i-87)/32)); + if( (i>=120) && (i<154) ) + m_ColorTbl[i].setRgb( (255*(i-120)/33), 255, 0); + if( (i>=154) && (i<217) ) + m_ColorTbl[i].setRgb( 255, 255 - (255*(i-154)/62), 0); + if( (i>=217) ) + m_ColorTbl[i].setRgb( 255, 0, 128*(i-217)/38); + } + m_ColorTbl[255].setRgb(255,255,100); + } +} diff --git a/qmap/vplotter.h b/qmap/vplotter.h new file mode 100644 index 00000000..8d50de01 --- /dev/null +++ b/qmap/vplotter.h @@ -0,0 +1,103 @@ +/////////////////////////////////////////////////////////////////////////// +// Rotated counterpart of plotter.h/CPlotter: frequency runs bottom-to-top +// instead of left-to-right, and spectra scroll to the left instead of +// scrolling down. Used by VertWaterfall, the optional narrow/tall sibling +// of the Horizontal Waterfall (WideGraph/CPlotter). +/////////////////////////////////////////////////////////////////////////// + +#ifndef VPLOTTER_H +#define VPLOTTER_H + +#include <QFrame> +#include <QPixmap> +#include <QList> +#include <QVector> +#include <QString> +#include <QtGlobal> +#include <QRect> +#include <QFont> + +#include "decode_click_coalescer.h" +#include "decode_label.h" + +class QMouseEvent; +class QFontMetrics; + +class CVertPlotter : public QFrame +{ + Q_OBJECT +public: + explicit CVertPlotter(QWidget *parent = nullptr); + ~CVertPlotter(); + + QSize minimumSizeHint() const override; + QSize sizeHint() const override; + + // swide[0..n-1] is the same decimated spectrum WideGraph paints as the + // top row of its waterfall (increasing index = increasing frequency), + // spanning [startFreqKHz, startFreqKHz+fSpanKHz]. plotZero/plotGain are + // WideGraph's current values, so color mapping matches it exactly. + void draw(const float swide[], int n, double startFreqKHz, double fSpanKHz, + int plotZero, int plotGain); + void setPalette(QString palette); + void setDecodeLabels(const QList<QMapDecodeLabel>& labels); + +signals: + void decodeLabelClicked(QByteArray decodeRow, DecodeClickGesture gesture); + +protected: + void paintEvent(QPaintEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseDoubleClickEvent(QMouseEvent *event) override; + +private: + void drawScale(); + int yFromFreq(double freq_khz) const; + void makeFrequencyStrs(); + + // One remembered column (raw, pre-color-map), so a resize can repaint + // the spectrogram from history instead of blanking it. Keeps its own + // freq/gain context, so an old column still renders how it looked when + // captured even if the live settings have since changed. + struct HistoryLine { + QVector<float> swide; + double startFreqKHz; + double fSpanKHz; + int plotZero; + int plotGain; + }; + void rebuildFromHistory(); + QList<HistoryLine> m_history; // front = newest + static constexpr int kMaxHistory = 4096; + + // Painting and hit-testing share the same frequency and displaced text bounds. + struct LabelLayout { + QMapDecodeLabel label; + int trueY; + int dispY; + int textX; + QRect rect; + }; + QVector<LabelLayout> computeLayout(QFontMetrics const& fm, int minSpacing) const; + QFont labelFont() const; + bool hitTestDecodeLabel(QPoint const& pos, QMapDecodeLabel& label); + + QColor m_ColorTbl[256]; + QPixmap m_waterfallPixmap; // spectrogram: x=time (newest at right), y=frequency (high at top) + QPixmap m_scalePixmap; // frequency ticks/labels, drawn just right of the spectrogram + QSize m_size; + int m_scaleWidth; // px reserved for the tick/label strip + int m_labelWidth; // px reserved for decoded-callsign text, right of the scale + double m_startFreqKHz; // frequency at the bottom edge + double m_fSpanKHz; + QString m_HDivText[64]; + int m_hdivs; + double m_freqPerDiv; + double m_freq0; // frequency of the first (bottom-most) tick + + QList<QMapDecodeLabel> m_decodeLabels; + DecodeClickCoalescer m_decodeClickCoalescer; +}; + +#endif // VPLOTTER_H diff --git a/qmap/widegraph.cpp b/qmap/widegraph.cpp index bc64fd50..4290ec7d 100644 --- a/qmap/widegraph.cpp +++ b/qmap/widegraph.cpp @@ -12,7 +12,7 @@ WideGraph::WideGraph (QString const& settings_filename, QWidget * parent) m_settings_filename {settings_filename} { ui->setupUi(this); - setWindowTitle("Wideband Waterfall"); + setWindowTitle("Horizontal Waterfall"); setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint); installEventFilter(parent); //Installing the filter ui->widePlot->setCursor(Qt::CrossCursor); @@ -21,12 +21,16 @@ WideGraph::WideGraph (QString const& settings_filename, QWidget * parent) ui->widePlot->setMaximumHeight(800); connect(ui->widePlot, SIGNAL(freezeDecode1(int)),this, SLOT(wideFreezeDecode(int))); + connect(ui->widePlot, &CPlotter::decodeLabelClicked, + this, &WideGraph::decodeLabelClicked2); //Restore user's settings QSettings settings {m_settings_filename, QSettings::IniFormat}; + QRect geom; { SettingsGroup g {&settings, "MainWindow"}; // historical reasons - setGeometry (settings.value ("WideGraphGeom", QRect {45,30,1023,340}).toRect ()); + geom = settings.value ("WideGraphGeom", QRect {45,30,1023,340}).toRect (); + setGeometry (geom); } SettingsGroup g {&settings, "WideGraph"}; ui->widePlot->setPlotZero(settings.value("PlotZero", 20).toInt()); @@ -41,6 +45,8 @@ WideGraph::WideGraph (QString const& settings_filename, QWidget * parent) ui->widePlot->setBinsPerPixel(nbpp); m_waterfallAvg = settings.value("WaterfallAvg",10).toInt(); ui->waterfallAvgSpinBox->setValue(m_waterfallAvg); + + ui->widePlot->ensureSized(w, qMax(100, geom.height()-60)); } WideGraph::~WideGraph() @@ -109,6 +115,8 @@ void WideGraph::dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, } n=0; + if (ui->widePlot->plotWidth() <= 0) return; // not yet sized (window never shown) + int w=ui->widePlot->plotWidth(); qint64 sf = nkhz - 0.5*w*nbpp*df/1000.0; if(sf != ui->widePlot->startFreq()) ui->widePlot->SetStartFreq(sf); @@ -138,9 +146,34 @@ void WideGraph::dataSink2(float s[], int nkhz, int ihsym, int ndiskdata, } ntrz=ntr; ui->widePlot->draw(swide,i0,splot); + emit spectrumReady(swide, qMin(w,2048), ui->widePlot->startFreq(), ui->widePlot->m_fSpan, + ui->widePlot->getPlotZero(), ui->widePlot->getPlotGain()); + } +} + +void WideGraph::addDecodeLabel(QMapDecodeRecord const& record) +{ + pruneQMapDecodeLabels(m_decodeLabels, record.secondsSinceMidnight); + upsertQMapDecodeLabel(m_decodeLabels, record); + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels(m_decodeLabels); +} + +void WideGraph::pruneDecodeLabels(int nowSeconds) +{ + auto const previousSize = m_decodeLabels.size(); + pruneQMapDecodeLabels(m_decodeLabels, nowSeconds); + if (m_decodeLabels.size() != previousSize && ui && ui->widePlot) { + ui->widePlot->setDecodeLabels(m_decodeLabels); } } +void WideGraph::clearDecodeLabels() +{ + if (m_decodeLabels.isEmpty ()) return; + m_decodeLabels.clear (); + if (ui && ui->widePlot) ui->widePlot->setDecodeLabels (m_decodeLabels); +} + void WideGraph::on_waterfallAvgSpinBox_valueChanged(int n) { m_waterfallAvg = n; diff --git a/qmap/widegraph.h b/qmap/widegraph.h index e678a664..2dc241cc 100644 --- a/qmap/widegraph.h +++ b/qmap/widegraph.h @@ -2,6 +2,9 @@ #define WIDEGRAPH_H #include <QDialog> +#include <QList> +#include "decode_click_coalescer.h" +#include "decode_label.h" namespace Ui { class WideGraph; @@ -36,11 +39,21 @@ public: void updateFreqLabel(); void enableSetRxHardware(bool b); + void addDecodeLabel(QMapDecodeRecord const& record); + void pruneDecodeLabels(int nowSeconds); + void clearDecodeLabels(); + qint32 m_qsoFreq; signals: void freezeDecode2(int n); void f11f12(int n); + void decodeLabelClicked2(QByteArray decodeRow, DecodeClickGesture gesture); + // Emitted once per average cycle, right after the Horizontal Waterfall's + // own top-row draw(), so VertWaterfall can show exactly the same + // spectral data instead of an independently-decimated copy of it. + void spectrumReady(const float swide[], int n, double startFreqKHz, double fSpanKHz, + int plotZero, int plotGain); public slots: void wideFreezeDecode(int n); @@ -68,6 +81,8 @@ private: qint32 m_fSample; qint32 m_mode65; qint32 m_TRperiod=60; + + QList<QMapDecodeLabel> m_decodeLabels; }; #endif // WIDEGRAPH_H diff --git a/qmap/wsjt.ico b/qmap/wsjt.ico Binary files differindex 8a55550f..dcbba2ca 100644 --- a/qmap/wsjt.ico +++ b/qmap/wsjt.ico |
